mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 07:07:31 +00:00
feat(tours): link the track a tour was actually done with, and show its own values (ACT-01)
A planned tour can now be given the track it was actually done with. In the tour's detail, "Add actual track" opens a dialog that asks for the day the tour was done on (or none) and a recording of the trip: an import nobody planned over, or a new one through the existing GPX import, its preview preset to the tour's type. What the choice measures is shown before anything is written, and only "Link" writes. The linked track keeps its own name and source; the detail shows its distance, heights, profile and, only where the file carried time stamps, the time it took, marked as actual values next to the untouched plan. A track can be changed or unlinked again. Server: a tour_activities table points a tour's execution (a day assignment, or none) at a recording of the same trip, and the tours GPX import keeps the first and last time of a track whose every point carries one. The values are read from the recording's own line on every read, so a changed recording updates them while the plan's line, measures and revision stay as they were. Every check runs inside the write: the recording must be an import of this trip not planned over, documenting no other tour; the day must be one of this tour; a refusal names its reason and changes nothing. PUT and DELETE /api/trips/:tripId/tours/:placeId/activities answer the detail, which now carries the actual tracks; the list names them per tour and per recording. MCP: assign_tour_track and unassign_tour_track over the same service and checks, get_tour_plan reads the values without the line. A recording linked as a tour's actual track is no longer counted as a tour of its own in the trip's tour summary, and the GPX preview imports a city walk as one instead of as a hike.
This commit is contained in:
@@ -0,0 +1,14 @@
|
||||
import type { TourActivityAssignRequest, TourDetailResponse } from '@trek/shared';
|
||||
import apiClient from './client';
|
||||
|
||||
/** ACT-01: the recorded tracks of a tour, assigned and taken off; both answer the tour's detail. */
|
||||
export const tourActivitiesApi = {
|
||||
assign: (
|
||||
tripId: number | string,
|
||||
placeId: number | string,
|
||||
body: TourActivityAssignRequest
|
||||
): Promise<TourDetailResponse> =>
|
||||
apiClient.put(`/trips/${tripId}/tours/${placeId}/activities`, body).then((r) => r.data),
|
||||
unassign: (tripId: number | string, placeId: number | string, activityId: number): Promise<TourDetailResponse> =>
|
||||
apiClient.delete(`/trips/${tripId}/tours/${placeId}/activities/${activityId}`).then((r) => r.data),
|
||||
};
|
||||
@@ -316,6 +316,13 @@ describe('TourDetailDialog', () => {
|
||||
expect(screen.getAllByText('T2').length).toBeGreaterThan(0)
|
||||
})
|
||||
|
||||
it('ACT-01: a recording that is the actual track of a tour names that tour in its head', () => {
|
||||
seedStore(useTripStore, { places: [buildPlace({ id: 7, name: 'Lake loop' }), place] })
|
||||
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, has_waypoints: false, origin: 'gpx', activity_of: 7 }} />)
|
||||
|
||||
expect(screen.getByTestId('tour-detail-track-of')).toHaveTextContent('Actual track of Lake loop')
|
||||
})
|
||||
|
||||
it('shows the grade on the tile and no second difficulty scale', () => {
|
||||
render(<TourDetailDialog {...defaultProps} tour={{ ...tour, difficulty: 'easy', max_hiking_difficulty: 1 }} />)
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
FileDown,
|
||||
FileImage,
|
||||
FileText,
|
||||
Footprints,
|
||||
Loader2,
|
||||
Minus,
|
||||
Navigation,
|
||||
@@ -48,6 +49,7 @@ import TrackColorPicker from '../shared/TrackColorPicker';
|
||||
import { markdownLinkComponents } from '../shared/markdownLink';
|
||||
import { TourDayRowAvatar } from './TourDayRowFacts';
|
||||
import { TourGpxExportButton } from './TourGpxExportButton';
|
||||
import TourActivitySection from './activity/TourActivitySection';
|
||||
import { PaddleCheckSection } from './paddle/PaddleCheckSection';
|
||||
import { PaddleWindSection } from './paddle/PaddleWindCard';
|
||||
import { TourProvenanceBlock } from './provenance/TourProvenanceSection';
|
||||
@@ -88,6 +90,8 @@ interface TourDetailDialogProps extends TourPermissionProps {
|
||||
onSourceReimported?: (tour: TourListItem) => Promise<void> | void;
|
||||
/** P2C-07: save this tour again as a new, independent one. */
|
||||
onSaveAsNew?: (tour: TourListItem) => Promise<void> | void;
|
||||
/** ACT-01: a recorded track was assigned, taken off or imported; the lists take in these tours. */
|
||||
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
|
||||
onAssignToDay?: (placeId: number, dayId?: number) => void;
|
||||
onRemoveAssignment?: (dayId: number, assignmentId: number) => void;
|
||||
onDelete?: () => void;
|
||||
@@ -243,6 +247,10 @@ function TourHeadPills({
|
||||
? null
|
||||
: (state.places.find((p) => p.id === tour.derived_from_place_id)?.name ?? null)
|
||||
);
|
||||
// ACT-01: the tour this one is the recorded track of.
|
||||
const documentsName = useTripStore((state) =>
|
||||
tour.activity_of == null ? null : (state.places.find((p) => p.id === tour.activity_of)?.name ?? null)
|
||||
);
|
||||
return (
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5">
|
||||
<span className={HEAD_PILL} style={fs(10.5)}>
|
||||
@@ -285,6 +293,14 @@ function TourHeadPills({
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{documentsName && (
|
||||
<Tooltip label={t('tours.activity.isTrackHint')}>
|
||||
<span data-testid="tour-detail-track-of" className={`${HEAD_PILL} max-w-[220px]`} style={fs(10.5)}>
|
||||
<Footprints size={11} strokeWidth={2} className="flex-none text-success" />
|
||||
<span className="min-w-0 truncate">{t('tours.activity.ofTour', { name: documentsName })}</span>
|
||||
</span>
|
||||
</Tooltip>
|
||||
)}
|
||||
{shownTime != null && (
|
||||
<Tooltip label={timeTooltip}>
|
||||
<span aria-label={timeTooltip} className={HEAD_PILL} style={fs(10.5)}>
|
||||
@@ -483,6 +499,7 @@ export default function TourDetailDialog({
|
||||
onFileUpload,
|
||||
onSourceReimported,
|
||||
onSaveAsNew,
|
||||
onToursChanged,
|
||||
onAssignToDay,
|
||||
onRemoveAssignment,
|
||||
onDelete,
|
||||
@@ -709,6 +726,17 @@ export default function TourDetailDialog({
|
||||
)}
|
||||
{tour.tour_type === 'kayak' && <PaddleCheckSection tour={tour} />}
|
||||
{tour.tour_type === 'kayak' && <PaddleWindSection placeId={place.id} start={placeStart(place)} />}
|
||||
{/* A tour written here offline has no server copy to assign a recording to until it syncs. */}
|
||||
{place.id > 0 && (
|
||||
<TourActivitySection
|
||||
tripId={place.trip_id}
|
||||
tour={tour}
|
||||
days={days}
|
||||
assignments={assignments}
|
||||
canEdit={canEdit}
|
||||
onToursChanged={onToursChanged}
|
||||
/>
|
||||
)}
|
||||
|
||||
{description && (
|
||||
<DialogSection className="flex-none" label={t('places.formDescription')}>
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
// FE-GPX-PREVIEW-001 to FE-GPX-PREVIEW-003
|
||||
// The GPX preview as ACT-01 uses it: preset to the tour's type, a city walk
|
||||
// imported as one, and when a track was recorded shown where it carried times.
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { TourGpxPreviewTrack } from '@trek/shared';
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
import TourGpxPreviewDialog from './TourGpxPreviewDialog';
|
||||
import type { TourGpxImport } from './useTourGpxImport';
|
||||
|
||||
vi.mock('../Map/MapViewAuto', () => ({ MapViewAuto: () => <div data-testid="gpx-preview-map-stub" /> }));
|
||||
|
||||
function track(overrides: Partial<TourGpxPreviewTrack> = {}): TourGpxPreviewTrack {
|
||||
return {
|
||||
name: 'Morning',
|
||||
geometry: [
|
||||
[47, 11],
|
||||
[47.01, 11],
|
||||
],
|
||||
point_count: 2,
|
||||
distance_km: 1.1,
|
||||
elevation_gain_m: null,
|
||||
elevation_loss_m: null,
|
||||
started_at: '2026-07-02T06:10:00.000Z',
|
||||
ended_at: '2026-07-02T07:00:00.000Z',
|
||||
duplicate: false,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
function gpxImport(tracks: TourGpxPreviewTrack[]): TourGpxImport {
|
||||
return {
|
||||
importing: false,
|
||||
preview: [{ file: new File(['<gpx/>'], 'morning.gpx'), tracks }],
|
||||
confirm: vi.fn(),
|
||||
cancel: vi.fn(),
|
||||
pick: vi.fn(),
|
||||
importFiles: vi.fn(),
|
||||
} as unknown as TourGpxImport;
|
||||
}
|
||||
|
||||
describe('TourGpxPreviewDialog (ACT-01)', () => {
|
||||
it('FE-GPX-PREVIEW-001: shows when a track was recorded and how long it took, and nothing for one without times', () => {
|
||||
const tracks = [track(), track({ name: 'Drawn', started_at: null, ended_at: null })];
|
||||
render(<TourGpxPreviewDialog gpxImport={gpxImport(tracks)} />);
|
||||
const recorded = screen.getAllByTestId('gpx-preview-recorded');
|
||||
expect(recorded).toHaveLength(1);
|
||||
expect(recorded[0]).toHaveTextContent('50 min');
|
||||
});
|
||||
|
||||
it('FE-GPX-PREVIEW-002: imports as the preset type, a paddle tour with its boat and water', () => {
|
||||
const current = gpxImport([track()]);
|
||||
render(
|
||||
<TourGpxPreviewDialog
|
||||
gpxImport={current}
|
||||
initial={{ tour_type: 'kayak', boat_type: 'sup', water_context: 'lake' }}
|
||||
/>
|
||||
);
|
||||
fireEvent.click(screen.getByTestId('gpx-preview-import'));
|
||||
expect(current.confirm).toHaveBeenCalledWith({ tour_type: 'kayak', boat_type: 'sup', water_context: 'lake' });
|
||||
});
|
||||
|
||||
it('FE-GPX-PREVIEW-003: a city walk is imported as a city walk, and without a preset as a hike', () => {
|
||||
const walk = gpxImport([track()]);
|
||||
const { unmount } = render(<TourGpxPreviewDialog gpxImport={walk} initial={{ tour_type: 'walk' }} />);
|
||||
fireEvent.click(screen.getByTestId('gpx-preview-import'));
|
||||
expect(walk.confirm).toHaveBeenCalledWith({ tour_type: 'walk' });
|
||||
unmount();
|
||||
|
||||
const hike = gpxImport([track()]);
|
||||
render(<TourGpxPreviewDialog gpxImport={hike} />);
|
||||
fireEvent.click(screen.getByTestId('gpx-preview-import'));
|
||||
expect(hike.confirm).toHaveBeenCalledWith({ tour_type: 'hike' });
|
||||
});
|
||||
});
|
||||
@@ -1,9 +1,11 @@
|
||||
import { AlertTriangle, FileDown } from 'lucide-react';
|
||||
import type { TourGpxImportFields } from '@trek/shared';
|
||||
import { AlertTriangle, Clock, FileDown } from 'lucide-react';
|
||||
import { useId, useMemo } from 'react';
|
||||
import { OFM_POSITRON } from '../../constants/mapDefaults';
|
||||
import { useTileUrl } from '../../hooks/useTileUrl';
|
||||
import { useTranslation } from '../../i18n';
|
||||
import { useSettingsStore } from '../../store/settingsStore';
|
||||
import { formatDate } from '../../utils/formatters';
|
||||
import { formatDistance, formatElevation } from '../../utils/units';
|
||||
import { MapViewAuto } from '../Map/MapViewAuto';
|
||||
import { SoftPill } from '../Planner/planParts';
|
||||
@@ -18,14 +20,30 @@ import {
|
||||
fs,
|
||||
NEUTRAL_TINT,
|
||||
} from '../shared/DialogShell';
|
||||
import { recordedMinutes } from './activity/tourActivityModel';
|
||||
import { importFields, importMissing, useGpxImportChoices } from './gpxImportChoices';
|
||||
import { GpxImportTypeSection } from './GpxImportTypeSection';
|
||||
import { TourNotice } from './tourParts';
|
||||
import { formatPlannedTourDuration } from './tourPresentation';
|
||||
import type { GpxPreviewFile, TourGpxImport } from './useTourGpxImport';
|
||||
|
||||
const BADGE =
|
||||
'inline-flex flex-none items-center rounded-full bg-surface-secondary px-2 font-geist tabular-nums leading-[20px] text-content-secondary';
|
||||
|
||||
/** ACT-01: when a track was recorded and how long it took, where every point carried a time. */
|
||||
function RecordedBadge({ track }: { track: GpxPreviewFile['tracks'][number] }) {
|
||||
const { locale } = useTranslation();
|
||||
const minutes = recordedMinutes(track.started_at, track.ended_at);
|
||||
if (minutes === null || !track.started_at) return null;
|
||||
return (
|
||||
<span className={`${BADGE} gap-1`} data-testid="gpx-preview-recorded">
|
||||
<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />
|
||||
{formatDate(track.started_at.slice(0, 10), locale)}
|
||||
<span className="text-content-faint">{formatPlannedTourDuration(minutes)}</span>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** One track of the file as a row: its name, and what it measures as badges; a track the trip holds says so. */
|
||||
function PreviewTrackRow({ name, track }: { name: string; track: GpxPreviewFile['tracks'][number] }) {
|
||||
const { t } = useTranslation();
|
||||
@@ -54,6 +72,7 @@ function PreviewTrackRow({ name, track }: { name: string; track: GpxPreviewFile[
|
||||
<span className={BADGE}>{t('tours.import.previewNoHeights')}</span>
|
||||
)}
|
||||
<span className={BADGE}>{t('tours.import.previewPoints', { count: track.point_count })}</span>
|
||||
<RecordedBadge track={track} />
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
@@ -66,19 +85,36 @@ function PreviewTrackRow({ name, track }: { name: string; track: GpxPreviewFile[
|
||||
* and water, as a planned paddle tour does, a ski import its discipline
|
||||
* (SKI-02); a ride (HOR-02) says before anything is stored that its line stays
|
||||
* as recorded, gets no riding time and is not checked for access. Closing it
|
||||
* stores nothing.
|
||||
* stores nothing. `initial` presets the type, as a recording imported for a
|
||||
* tour takes that tour's (ACT-01); left out, it is a hike.
|
||||
*/
|
||||
export default function TourGpxPreviewDialog({ gpxImport }: { gpxImport: TourGpxImport }) {
|
||||
export default function TourGpxPreviewDialog({
|
||||
gpxImport,
|
||||
initial,
|
||||
}: {
|
||||
gpxImport: TourGpxImport;
|
||||
initial?: TourGpxImportFields;
|
||||
}) {
|
||||
const { preview } = gpxImport;
|
||||
if (!preview) return null;
|
||||
return <PreviewDialog gpxImport={gpxImport} files={preview} />;
|
||||
return <PreviewDialog gpxImport={gpxImport} files={preview} initial={initial ?? HIKE} />;
|
||||
}
|
||||
|
||||
function PreviewDialog({ gpxImport, files }: { gpxImport: TourGpxImport; files: GpxPreviewFile[] }) {
|
||||
const HIKE: TourGpxImportFields = { tour_type: 'hike' };
|
||||
|
||||
function PreviewDialog({
|
||||
gpxImport,
|
||||
files,
|
||||
initial,
|
||||
}: {
|
||||
gpxImport: TourGpxImport;
|
||||
files: GpxPreviewFile[];
|
||||
initial: TourGpxImportFields;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const labelId = useId();
|
||||
const tileUrl = useTileUrl(OFM_POSITRON);
|
||||
const choices = useGpxImportChoices();
|
||||
const choices = useGpxImportChoices(initial);
|
||||
|
||||
const tracks = files.flatMap((file) => file.tracks.map((track) => ({ file: file.file, track })));
|
||||
const fresh = tracks.filter(({ track }) => !track.duplicate).length;
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useId, type ReactNode } from 'react'
|
||||
import { Eye, EyeOff } from 'lucide-react'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { fs } from '../shared/DialogShell'
|
||||
import { TourCautionBadge, TourDaysBadge, TourGradeTile } from './tourParts'
|
||||
import { TourActivityBadge, TourCautionBadge, TourDaysBadge, TourGradeTile } from './tourParts'
|
||||
import type { Day } from '../../types'
|
||||
import { endPlaceDrag, startPlaceDrag } from '../Map/markerDrag'
|
||||
import { TourDayRowPills } from './TourDayRowFacts'
|
||||
@@ -76,6 +76,7 @@ function TourRowBody({ tour, nameId, tourDays, dimmed }: {
|
||||
className="-mx-0.5 mt-0.5 flex h-6 min-w-0 flex-wrap content-start gap-x-1.5 gap-y-2 overflow-hidden px-0.5 pt-0.5"
|
||||
>
|
||||
<TourCautionBadge tour={tour} />
|
||||
<TourActivityBadge tour={tour} />
|
||||
<TourDayRowPills tour={tour} compact />
|
||||
<TourDaysBadge tourDays={tourDays} />
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// FE-ACT-BADGE-001
|
||||
// ACT-01 on a tour's row: a tour with an actual track and a recording that is
|
||||
// the actual track of a tour each say so with an icon, the tooltip naming which.
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { TourActivityBadge } from '../tourParts';
|
||||
|
||||
describe('TourActivityBadge (ACT-01)', () => {
|
||||
it('FE-ACT-BADGE-001: marks a tour with an actual track and a recording that is one, nothing else', () => {
|
||||
const { rerender } = render(
|
||||
<TourActivityBadge tour={{ activity_tracks: [{ id: 1, track_place_id: 9, assignment_id: null }] }} />
|
||||
);
|
||||
expect(screen.getByTestId('tour-activity-badge')).toHaveAttribute('aria-label', 'tours.activity.badgeHint');
|
||||
|
||||
rerender(<TourActivityBadge tour={{ activity_tracks: [], activity_of: 4 }} />);
|
||||
expect(screen.getByTestId('tour-activity-badge')).toHaveAttribute('aria-label', 'tours.activity.isTrackHint');
|
||||
|
||||
rerender(<TourActivityBadge tour={{ activity_tracks: [], activity_of: null }} />);
|
||||
expect(screen.queryByTestId('tour-activity-badge')).toBeNull();
|
||||
rerender(<TourActivityBadge tour={{}} />);
|
||||
expect(screen.queryByTestId('tour-activity-badge')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,119 @@
|
||||
// FE-ACT-DIALOG-001 to FE-ACT-DIALOG-004
|
||||
// ACT-01, the link dialog: the day, the recordings with one taken by another
|
||||
// tour dimmed, what the choice measures, the GPX import as the second way in,
|
||||
// and only "Link" writing, once a free recording is chosen.
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import TourActivityDialog from './TourActivityDialog';
|
||||
import type { TourActivities } from './useTourActivities';
|
||||
import type { TrackAssignment } from './useTrackAssignment';
|
||||
|
||||
const hook = vi.hoisted(() => ({ assignment: null as unknown }));
|
||||
vi.mock('./useTrackAssignment', () => ({ useTrackAssignment: () => hook.assignment }));
|
||||
vi.mock('../TourGpxPreviewDialog', () => ({ default: () => null }));
|
||||
|
||||
const tour = { place_id: 7, name: 'Ridge', tour_type: 'hike' } as TourListItem;
|
||||
const recording = (placeId: number, name: string) =>
|
||||
({
|
||||
place_id: placeId,
|
||||
name,
|
||||
tour_type: 'hike',
|
||||
origin: 'gpx',
|
||||
has_waypoints: false,
|
||||
distance: 12.4,
|
||||
track_started_at: '2026-07-02T06:10:00Z',
|
||||
track_ended_at: '2026-07-02T09:25:00Z',
|
||||
}) as TourListItem;
|
||||
|
||||
function assignment(overrides: Partial<TrackAssignment> = {}): TrackAssignment {
|
||||
const watch = { tour: recording(20, 'Watch export'), takenBy: null };
|
||||
return {
|
||||
executions: [{ assignmentId: 11, day: { id: 1, date: '2026-07-02', title: null }, index: 0 }],
|
||||
assignmentId: 11,
|
||||
execution: { assignmentId: 11, day: null, index: 0 },
|
||||
chooseExecution: vi.fn(),
|
||||
candidates: [watch, { tour: recording(21, 'Phone export'), takenBy: 'Lake loop' }],
|
||||
selected: 20,
|
||||
choose: vi.fn(),
|
||||
choice: watch,
|
||||
replaces: null,
|
||||
gpxImport: {
|
||||
importing: false,
|
||||
preview: null,
|
||||
pick: vi.fn(),
|
||||
confirm: vi.fn(),
|
||||
cancel: vi.fn(),
|
||||
importFiles: vi.fn(),
|
||||
},
|
||||
importFields: { tour_type: 'hike' },
|
||||
ready: true,
|
||||
...overrides,
|
||||
} as unknown as TrackAssignment;
|
||||
}
|
||||
|
||||
const state = (overrides: Partial<TourActivities> = {}) =>
|
||||
({
|
||||
busy: false,
|
||||
canEdit: true,
|
||||
assigning: {},
|
||||
assign: vi.fn(),
|
||||
closeAssign: vi.fn(),
|
||||
...overrides,
|
||||
}) as unknown as TourActivities;
|
||||
|
||||
const show = (current: TourActivities = state()) =>
|
||||
render(<TourActivityDialog tripId={1} tour={tour} executions={[]} state={current} activities={[]} />);
|
||||
|
||||
beforeEach(() => {
|
||||
hook.assignment = assignment();
|
||||
});
|
||||
|
||||
describe('TourActivityDialog (ACT-01)', () => {
|
||||
it('FE-ACT-DIALOG-001: offers the recordings, the taken one dimmed with its tour, and what the choice measures', () => {
|
||||
show();
|
||||
expect(screen.getByText('tours.activity.dialogEyebrow')).toBeInTheDocument();
|
||||
expect(screen.getByText('tours.activity.dialogHint')).toBeInTheDocument();
|
||||
const [watch, phone] = screen.getAllByTestId('tour-activity-candidate');
|
||||
expect(watch).toHaveAttribute('aria-checked', 'true');
|
||||
expect(phone).toBeDisabled();
|
||||
expect(phone).toHaveTextContent('tours.activity.ofTour');
|
||||
expect(watch).toHaveTextContent('3 h 15 min');
|
||||
expect(screen.getByText('tours.activity.time')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ACT-DIALOG-002: only Link writes, with the chosen recording and day', () => {
|
||||
const current = state();
|
||||
show(current);
|
||||
fireEvent.click(screen.getAllByTestId('tour-activity-candidate')[0] as HTMLElement);
|
||||
expect((hook.assignment as TrackAssignment).choose).toHaveBeenCalledWith(20);
|
||||
expect(current.assign).not.toHaveBeenCalled();
|
||||
fireEvent.click(screen.getByTestId('tour-activity-confirm'));
|
||||
expect(current.assign).toHaveBeenCalledWith(20, 11);
|
||||
});
|
||||
|
||||
it('FE-ACT-DIALOG-003: nothing to link until a free recording is chosen; what it replaces is said', () => {
|
||||
hook.assignment = assignment({ ready: false, choice: null, selected: null, replaces: 'Old export' });
|
||||
const current = state();
|
||||
show(current);
|
||||
expect(screen.getByTestId('tour-activity-confirm')).toBeDisabled();
|
||||
fireEvent.click(screen.getByTestId('tour-activity-confirm'));
|
||||
expect(current.assign).not.toHaveBeenCalled();
|
||||
expect(screen.getByText('tours.activity.replaces')).toBeInTheDocument();
|
||||
expect(screen.queryByText('tours.activity.time')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ACT-DIALOG-004: the GPX import is the way in when the trip has none; a list still loading waits', () => {
|
||||
const empty = assignment({ candidates: [], choice: null, selected: null, ready: false });
|
||||
hook.assignment = empty;
|
||||
const { unmount } = show();
|
||||
expect(screen.getByText('tours.activity.noCandidates')).toBeInTheDocument();
|
||||
fireEvent.click(screen.getByRole('button', { name: /tours.activity.importGpx/ }));
|
||||
expect(empty.gpxImport.pick).toHaveBeenCalled();
|
||||
unmount();
|
||||
|
||||
hook.assignment = assignment({ candidates: null, choice: null, selected: null, ready: false });
|
||||
show();
|
||||
expect(screen.getByLabelText('common.loading')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,284 @@
|
||||
import type { TourActivity, TourListItem } from '@trek/shared';
|
||||
import { AlertTriangle, Check, Clock, FileDown, Footprints, Link2, Loader2, Ruler, Upload } from 'lucide-react';
|
||||
import { useId, useMemo } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import { useTripStore } from '../../../store/tripStore';
|
||||
import { formatDate } from '../../../utils/formatters';
|
||||
import { analyzeRouteGeometry } from '../../../utils/routeGeometry';
|
||||
import { formatDistance } from '../../../utils/units';
|
||||
import { SoftPill } from '../../Planner/planParts';
|
||||
import {
|
||||
DialogButton,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogSection,
|
||||
DialogShell,
|
||||
DialogTile,
|
||||
FooterSpacer,
|
||||
fs,
|
||||
NEUTRAL_TINT,
|
||||
} from '../../shared/DialogShell';
|
||||
import { PillSelect } from '../../shared/dialogParts';
|
||||
import TourGpxPreviewDialog from '../TourGpxPreviewDialog';
|
||||
import { CardAction, TourMetricFields, TourNotice } from '../tourParts';
|
||||
import { formatPlannedTourDuration, hikeSourceBadgeLabel } from '../tourPresentation';
|
||||
import { recordedMinutes, type TourExecution, type TrackCandidate } from './tourActivityModel';
|
||||
import type { TourActivities } from './useTourActivities';
|
||||
import { useTrackAssignment, type TrackAssignment } from './useTrackAssignment';
|
||||
|
||||
/** The value of the execution picker for "no day". */
|
||||
const NO_DAY = 'none';
|
||||
|
||||
/** One recording of the trip to choose: its name and what it is as badges; one taken by another tour is dimmed. */
|
||||
function CandidateRow({
|
||||
candidate,
|
||||
selected,
|
||||
onChoose,
|
||||
}: {
|
||||
candidate: TrackCandidate;
|
||||
selected: boolean;
|
||||
onChoose: () => void;
|
||||
}) {
|
||||
const { t, locale } = useTranslation();
|
||||
const unit = useSettingsStore((store) => store.settings.distance_unit) ?? 'metric';
|
||||
const { tour, takenBy } = candidate;
|
||||
const minutes = recordedMinutes(tour.track_started_at, tour.track_ended_at);
|
||||
const recordedOn = tour.track_started_at ? formatDate(tour.track_started_at.slice(0, 10), locale) : null;
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
role="radio"
|
||||
aria-checked={selected}
|
||||
disabled={takenBy !== null}
|
||||
onClick={onChoose}
|
||||
data-testid="tour-activity-candidate"
|
||||
className={`flex w-full items-center gap-2.5 rounded-[12px] border px-3 py-2.5 text-start transition-colors focus-visible:outline focus-visible:outline-2 focus-visible:outline-accent disabled:cursor-default disabled:opacity-55 ${selected ? 'border-accent bg-surface-card shadow-sm' : 'border-edge-faint bg-surface-card enabled:hover:bg-surface-hover'}`}
|
||||
>
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className={`grid h-5 w-5 flex-none place-items-center rounded-full ring-1 ring-inset ${selected ? 'bg-accent text-accent-text ring-accent' : 'ring-edge'}`}
|
||||
>
|
||||
{selected && <Check size={12} strokeWidth={2.6} />}
|
||||
</span>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="block truncate font-semibold text-content" style={fs(13, 'body')}>
|
||||
{tour.name}
|
||||
</span>
|
||||
<span className="mt-1 flex flex-wrap items-center gap-1">
|
||||
<SoftPill icon={<FileDown size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
|
||||
{hikeSourceBadgeLabel(tour, t)}
|
||||
</SoftPill>
|
||||
{tour.distance != null && (
|
||||
<SoftPill icon={<Ruler size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
|
||||
{formatDistance(tour.distance, unit)}
|
||||
</SoftPill>
|
||||
)}
|
||||
{recordedOn && (
|
||||
<SoftPill icon={<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
|
||||
{minutes === null ? recordedOn : `${recordedOn} ${formatPlannedTourDuration(minutes)}`}
|
||||
</SoftPill>
|
||||
)}
|
||||
{takenBy !== null && <SoftPill tone="warning">{t('tours.activity.ofTour', { name: takenBy })}</SoftPill>}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
/** The recordings to choose from, or what to do while there is none. */
|
||||
function CandidateList({ assignment }: { assignment: TrackAssignment }) {
|
||||
const { t } = useTranslation();
|
||||
const { candidates } = assignment;
|
||||
if (candidates === null) {
|
||||
return (
|
||||
<div className="flex justify-center py-3 text-content-faint">
|
||||
<Loader2 size={16} className="animate-spin" aria-label={t('common.loading')} />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (candidates.length === 0) {
|
||||
return (
|
||||
<TourNotice role="status" icon={<Footprints size={13} strokeWidth={2} />}>
|
||||
{t('tours.activity.noCandidates')}
|
||||
</TourNotice>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<div role="radiogroup" aria-label={t('tours.activity.track')} className="flex flex-col gap-1.5">
|
||||
{candidates.map((candidate) => (
|
||||
<CandidateRow
|
||||
key={candidate.tour.place_id}
|
||||
candidate={candidate}
|
||||
selected={candidate.tour.place_id === assignment.selected}
|
||||
onChoose={() => assignment.choose(candidate.tour.place_id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** What the chosen recording measures, read the way the detail will show it, before anything is written. */
|
||||
function ChoicePreview({ choice }: { choice: TourListItem }) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useSettingsStore((store) => store.settings.distance_unit) ?? 'metric';
|
||||
const line = useTripStore((store) => store.places.find((place) => place.id === choice.place_id)?.route_geometry);
|
||||
const analysis = useMemo(() => analyzeRouteGeometry(line), [line]);
|
||||
const minutes = recordedMinutes(choice.track_started_at, choice.track_ended_at);
|
||||
return (
|
||||
<DialogSection label={t('tours.activity.badge')}>
|
||||
<TourMetricFields
|
||||
analysis={analysis}
|
||||
unit={unit}
|
||||
extra={[
|
||||
{
|
||||
label: t('tours.activity.time'),
|
||||
value: minutes === null ? t('tours.activity.noTime') : formatPlannedTourDuration(minutes),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</DialogSection>
|
||||
);
|
||||
}
|
||||
|
||||
/** The day picker: every day the tour is on, and no day at all. */
|
||||
function ExecutionPicker({ assignment }: { assignment: TrackAssignment }) {
|
||||
const { t, locale } = useTranslation();
|
||||
const options = [
|
||||
...assignment.executions.map((execution: TourExecution) => ({
|
||||
value: String(execution.assignmentId),
|
||||
label: t('dayplan.dayN', { n: execution.index + 1 }),
|
||||
hint: (execution.day && formatDate(execution.day.date, locale)) || undefined,
|
||||
})),
|
||||
{ value: NO_DAY, label: t('tours.activity.noDay') },
|
||||
];
|
||||
return (
|
||||
<PillSelect
|
||||
quiet
|
||||
value={assignment.assignmentId === null ? NO_DAY : String(assignment.assignmentId)}
|
||||
options={options}
|
||||
onChange={(value) => assignment.chooseExecution(value === NO_DAY ? null : Number(value))}
|
||||
label={t('tours.activity.execution')}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface TourActivityDialogProps {
|
||||
tripId: number;
|
||||
tour: TourListItem;
|
||||
executions: readonly TourExecution[];
|
||||
state: TourActivities;
|
||||
activities: readonly TourActivity[];
|
||||
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
|
||||
}
|
||||
|
||||
/**
|
||||
* ACT-01: assigning a recorded track, on purpose and confirmed. The user picks
|
||||
* the day it was done on and a recording of the trip, or imports one through
|
||||
* the GPX import as always, sees what it measures, and only "Assign" writes.
|
||||
* The plan is not touched, and the head says so.
|
||||
*/
|
||||
export default function TourActivityDialog({
|
||||
tripId,
|
||||
tour,
|
||||
executions,
|
||||
state,
|
||||
activities,
|
||||
onToursChanged,
|
||||
}: TourActivityDialogProps) {
|
||||
const { t } = useTranslation();
|
||||
const labelId = useId();
|
||||
const assignment = useTrackAssignment({
|
||||
tripId,
|
||||
tour,
|
||||
executions,
|
||||
activities,
|
||||
target: state.assigning ?? {},
|
||||
canEdit: state.canEdit,
|
||||
onToursChanged,
|
||||
});
|
||||
const { gpxImport, choice, selected } = assignment;
|
||||
const importing = gpxImport.importing || gpxImport.preview !== null;
|
||||
const confirm = () => {
|
||||
if (selected !== null && assignment.ready) void state.assign(selected, assignment.assignmentId);
|
||||
};
|
||||
return (
|
||||
<>
|
||||
<DialogShell
|
||||
onClose={state.closeAssign}
|
||||
labelledBy={labelId}
|
||||
width="detail"
|
||||
align="top"
|
||||
blocked={state.busy || importing}
|
||||
header={
|
||||
<DialogHeader
|
||||
tile={
|
||||
<DialogTile>
|
||||
<Footprints size={20} strokeWidth={2} className="text-content" />
|
||||
</DialogTile>
|
||||
}
|
||||
tint={NEUTRAL_TINT}
|
||||
labelId={labelId}
|
||||
onClose={state.closeAssign}
|
||||
eyebrow={t('tours.activity.dialogEyebrow')}
|
||||
title={tour.name}
|
||||
sub={t('tours.activity.dialogHint')}
|
||||
subWraps
|
||||
/>
|
||||
}
|
||||
footer={
|
||||
<DialogFooter>
|
||||
<FooterSpacer />
|
||||
<DialogButton onClick={state.closeAssign} disabled={state.busy}>
|
||||
{t('common.cancel')}
|
||||
</DialogButton>
|
||||
<DialogButton
|
||||
variant="primary"
|
||||
data-testid="tour-activity-confirm"
|
||||
disabled={!assignment.ready || state.busy || importing}
|
||||
icon={
|
||||
state.busy ? <Loader2 size={14} className="animate-spin" /> : <Link2 size={14} strokeWidth={2} />
|
||||
}
|
||||
onClick={confirm}
|
||||
>
|
||||
{t('tours.activity.confirm')}
|
||||
</DialogButton>
|
||||
</DialogFooter>
|
||||
}
|
||||
>
|
||||
<DialogSection label={t('tours.activity.execution')}>
|
||||
<ExecutionPicker assignment={assignment} />
|
||||
</DialogSection>
|
||||
<DialogSection
|
||||
label={t('tours.activity.track')}
|
||||
action={
|
||||
<CardAction
|
||||
icon={
|
||||
gpxImport.importing ? (
|
||||
<Loader2 size={12} className="animate-spin" />
|
||||
) : (
|
||||
<Upload size={12} strokeWidth={2.2} />
|
||||
)
|
||||
}
|
||||
onClick={gpxImport.pick}
|
||||
disabled={importing}
|
||||
>
|
||||
{t('tours.activity.importGpx')}
|
||||
</CardAction>
|
||||
}
|
||||
>
|
||||
<div className="flex flex-col gap-2">
|
||||
<CandidateList assignment={assignment} />
|
||||
{assignment.replaces && (
|
||||
<TourNotice tone="warning" icon={<AlertTriangle size={13} strokeWidth={2} />}>
|
||||
{t('tours.activity.replaces', { name: assignment.replaces })}
|
||||
</TourNotice>
|
||||
)}
|
||||
</div>
|
||||
</DialogSection>
|
||||
{choice && choice.takenBy === null && <ChoicePreview choice={choice.tour} />}
|
||||
</DialogShell>
|
||||
<TourGpxPreviewDialog gpxImport={gpxImport} initial={assignment.importFields} />
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// FE-ACT-SECTION-001 to FE-ACT-SECTION-005
|
||||
// ACT-01 in the tour's detail, rendered without the translation provider so
|
||||
// every text reads as its key: the actual tracks with their own values marked
|
||||
// as such, a time only where the track measured one, and the actions only for
|
||||
// someone who may change the tour.
|
||||
import { fireEvent, render, screen } from '@testing-library/react';
|
||||
import type { TourActivity, TourListItem } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { Day } from '../../../types';
|
||||
import TourActivitySection from './TourActivitySection';
|
||||
import type { TourActivities } from './useTourActivities';
|
||||
|
||||
const hook = vi.hoisted(() => ({ state: null as unknown }));
|
||||
vi.mock('./useTourActivities', () => ({ useTourActivities: () => hook.state }));
|
||||
vi.mock('./TourActivityDialog', () => ({ default: () => <div data-testid="tour-activity-dialog" /> }));
|
||||
|
||||
const tour = { place_id: 7, name: 'Ridge', tour_type: 'hike' } as TourListItem;
|
||||
const days = [{ id: 1, date: '2026-07-02', title: null }] as unknown as Day[];
|
||||
const assignments = { '1': [{ id: 11, place_id: 7 }] } as never;
|
||||
|
||||
function activity(overrides: Partial<TourActivity['metrics']> = {}, assignmentId: number | null = 11): TourActivity {
|
||||
return {
|
||||
id: 4,
|
||||
assignment_id: assignmentId,
|
||||
day_id: 1,
|
||||
assigned_at: null,
|
||||
track: { place_id: 20, name: 'Watch export', origin: 'gpx', file_name: 'morning.gpx', imported_at: null },
|
||||
metrics: {
|
||||
distance_km: 0.1,
|
||||
elevation_gain_m: 100,
|
||||
elevation_loss_m: 0,
|
||||
started_at: '2026-07-02T06:10:00Z',
|
||||
ended_at: '2026-07-02T09:25:00Z',
|
||||
elapsed_minutes: 195,
|
||||
point_count: 2,
|
||||
...overrides,
|
||||
},
|
||||
geometry: [
|
||||
[47, 11, 600],
|
||||
[47.001, 11, 700],
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
function state(overrides: Partial<TourActivities> = {}): TourActivities {
|
||||
return {
|
||||
activities: [activity()],
|
||||
canEdit: true,
|
||||
busy: false,
|
||||
assigning: null,
|
||||
openAssign: vi.fn(),
|
||||
closeAssign: vi.fn(),
|
||||
assign: vi.fn(),
|
||||
removing: null,
|
||||
askRemove: vi.fn(),
|
||||
cancelRemove: vi.fn(),
|
||||
remove: vi.fn(),
|
||||
...overrides,
|
||||
} as TourActivities;
|
||||
}
|
||||
|
||||
const show = (canEdit = true, item: TourListItem = tour) =>
|
||||
render(<TourActivitySection tripId={1} tour={item} days={days} assignments={assignments} canEdit={canEdit} />);
|
||||
|
||||
beforeEach(() => {
|
||||
hook.state = state();
|
||||
});
|
||||
|
||||
describe('TourActivitySection (ACT-01)', () => {
|
||||
it('FE-ACT-SECTION-001: shows an actual track with its day, its file, its own values and its profile', () => {
|
||||
show();
|
||||
expect(screen.getByText('tours.activity.label')).toBeInTheDocument();
|
||||
expect(screen.getByText('Watch export')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('tour-activity-day')).toHaveTextContent('dayplan.dayN');
|
||||
expect(screen.getByText('morning.gpx')).toBeInTheDocument();
|
||||
expect(screen.getByText('tours.activity.badge')).toBeInTheDocument();
|
||||
expect(screen.getByText('tours.activity.time')).toBeInTheDocument();
|
||||
expect(screen.getByText('3 h 15 min')).toBeInTheDocument();
|
||||
expect(screen.getByText('tours.detail.ascent')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ACT-SECTION-002: a track without times measures no time, and a track without a day says so', () => {
|
||||
hook.state = state({ activities: [activity({ elapsed_minutes: null, started_at: null, ended_at: null }, null)] });
|
||||
show();
|
||||
expect(screen.getByText('tours.activity.noTime')).toBeInTheDocument();
|
||||
expect(screen.getByTestId('tour-activity-day')).toHaveTextContent('tours.activity.noDay');
|
||||
expect(screen.queryByText('tours.activity.recordedOn')).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ACT-SECTION-003: someone who may change the tour links, changes and unlinks; the dialog opens when asked', () => {
|
||||
const current = state();
|
||||
hook.state = current;
|
||||
const { rerender } = show();
|
||||
fireEvent.click(screen.getByRole('button', { name: /tours.activity.assign$/ }));
|
||||
expect(current.openAssign).toHaveBeenCalledWith();
|
||||
fireEvent.click(screen.getByRole('button', { name: /tours.activity.change/ }));
|
||||
expect(current.openAssign).toHaveBeenCalledWith({ assignmentId: 11 });
|
||||
fireEvent.click(screen.getByRole('button', { name: /tours.activity.remove/ }));
|
||||
expect(current.askRemove).toHaveBeenCalledWith(current.activities?.[0]);
|
||||
|
||||
hook.state = state({ assigning: {}, removing: activity() });
|
||||
rerender(<TourActivitySection tripId={1} tour={tour} days={days} assignments={assignments} canEdit />);
|
||||
expect(screen.getByTestId('tour-activity-dialog')).toBeInTheDocument();
|
||||
expect(screen.getByText('tours.activity.removeTitle')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('FE-ACT-SECTION-004: without the right to change it, the values show and no action does', () => {
|
||||
hook.state = state({ canEdit: false });
|
||||
show(false);
|
||||
expect(screen.getByText('Watch export')).toBeInTheDocument();
|
||||
expect(screen.queryByRole('button', { name: /tours.activity.assign$/ })).toBeNull();
|
||||
expect(screen.queryByRole('button', { name: /tours.activity.remove/ })).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ACT-SECTION-005: an empty place for one when it may be linked; nothing while loading, when it cannot, or for a track of another tour', () => {
|
||||
hook.state = state({ activities: [] });
|
||||
const { unmount } = show();
|
||||
expect(screen.getByTestId('tour-activity-empty')).toHaveTextContent('tours.activity.empty');
|
||||
unmount();
|
||||
|
||||
hook.state = state({ activities: [], canEdit: false });
|
||||
const readOnly = show(false);
|
||||
expect(readOnly.container).toBeEmptyDOMElement();
|
||||
readOnly.unmount();
|
||||
|
||||
hook.state = state({ activities: null });
|
||||
const loading = show();
|
||||
expect(loading.container).toBeEmptyDOMElement();
|
||||
loading.unmount();
|
||||
|
||||
hook.state = state();
|
||||
const track = show(true, { ...tour, activity_of: 3 });
|
||||
expect(track.container).toBeEmptyDOMElement();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
import type { TourActivity, TourListItem } from '@trek/shared';
|
||||
import { CalendarDays, Clock, FileDown, Footprints, Plus, RefreshCw, Unlink } from 'lucide-react';
|
||||
import { useMemo } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { useSettingsStore } from '../../../store/settingsStore';
|
||||
import type { AssignmentsMap, Day } from '../../../types';
|
||||
import { formatDate } from '../../../utils/formatters';
|
||||
import { BOX } from '../../Planner/bookings/bookingParts';
|
||||
import { SoftPill } from '../../Planner/planParts';
|
||||
import ConfirmDialog from '../../shared/ConfirmDialog';
|
||||
import { DialogSection, fs } from '../../shared/DialogShell';
|
||||
import ElevationProfile from '../../shared/ElevationProfile';
|
||||
import { Tooltip } from '../../shared/Tooltip';
|
||||
import { dayMenuLabel } from '../tourDays';
|
||||
import { CardAction, TourMetricFields, type TourMetricField } from '../tourParts';
|
||||
import { formatPlannedTourDuration } from '../tourPresentation';
|
||||
import TourActivityDialog from './TourActivityDialog';
|
||||
import { analysisOfLine, executionOf, executionsOf, type TourExecution } from './tourActivityModel';
|
||||
import { useTourActivities, type TourActivities } from './useTourActivities';
|
||||
|
||||
type Translate = (key: string, params?: Record<string, unknown>) => string;
|
||||
|
||||
/** The line and the profile of what was recorded take the colour of done, apart from the plan's track colour. */
|
||||
const RECORDED_COLOR = 'var(--success)';
|
||||
|
||||
/** The recorded time as a field: measured from the track's times, or said to be missing, never estimated. */
|
||||
function timeField(activity: TourActivity, t: Translate): TourMetricField {
|
||||
const minutes = activity.metrics.elapsed_minutes;
|
||||
const label = t('tours.activity.time');
|
||||
return minutes === null
|
||||
? { label, value: t('tours.activity.noTime'), info: { label, description: t('tours.activity.noTimeHint') } }
|
||||
: { label, value: formatPlannedTourDuration(minutes), info: { label, description: t('tours.activity.timeHint') } };
|
||||
}
|
||||
|
||||
/** The tile of a recording: footprints, with a small dot at its foot that says it was recorded. */
|
||||
function RecordedTile() {
|
||||
return (
|
||||
<span className="relative grid h-9 w-9 flex-none place-items-center rounded-full bg-surface-secondary text-content-secondary">
|
||||
<Footprints size={15} strokeWidth={2} aria-hidden="true" />
|
||||
<span
|
||||
aria-hidden="true"
|
||||
className="absolute -bottom-0.5 -end-0.5 h-3 w-3 rounded-full bg-success ring-2 ring-surface-card"
|
||||
/>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
/** Where and when: the execution, the file it came from, the day it was recorded, each a badge of its own. */
|
||||
function ActivityBadges({ activity, execution }: { activity: TourActivity; execution: TourExecution }) {
|
||||
const { t, locale } = useTranslation();
|
||||
const dayLabel = execution.day ? t('dayplan.dayN', { n: execution.index + 1 }) : t('tours.activity.noDay');
|
||||
const dayTitle = execution.day ? dayMenuLabel(execution.day, execution.index, t, locale) : dayLabel;
|
||||
const recordedOn = activity.metrics.started_at ? formatDate(activity.metrics.started_at.slice(0, 10), locale) : null;
|
||||
const source =
|
||||
activity.track.file_name ?? t(activity.track.origin === 'wanderer' ? 'tours.badge.wanderer' : 'tours.badge.gpx');
|
||||
return (
|
||||
<div className="mt-1 flex flex-wrap items-center gap-1">
|
||||
<Tooltip label={dayTitle}>
|
||||
<span className="inline-flex" data-testid="tour-activity-day">
|
||||
<SoftPill icon={<CalendarDays size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
|
||||
{dayLabel}
|
||||
</SoftPill>
|
||||
</span>
|
||||
</Tooltip>
|
||||
<SoftPill
|
||||
className="max-w-[180px]"
|
||||
icon={<FileDown size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}
|
||||
>
|
||||
<span className="min-w-0 truncate">{source}</span>
|
||||
</SoftPill>
|
||||
{recordedOn && (
|
||||
<SoftPill icon={<Clock size={10} strokeWidth={2.2} className="flex-none text-content-faint" />}>
|
||||
{t('tours.activity.recordedOn', { date: recordedOn })}
|
||||
</SoftPill>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/** One recording: who it is, its values marked as recorded, its profile, and what the user can do with it. */
|
||||
function ActivityCard({
|
||||
activity,
|
||||
execution,
|
||||
state,
|
||||
}: {
|
||||
activity: TourActivity;
|
||||
execution: TourExecution;
|
||||
state: TourActivities;
|
||||
}) {
|
||||
const { t } = useTranslation();
|
||||
const unit = useSettingsStore((store) => store.settings.distance_unit) ?? 'metric';
|
||||
const analysis = useMemo(() => analysisOfLine(activity.geometry), [activity.geometry]);
|
||||
return (
|
||||
<article data-testid="tour-activity" className={`${BOX} overflow-hidden`}>
|
||||
<header className="flex items-start gap-2.5 px-3 py-2.5">
|
||||
<RecordedTile />
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate font-semibold text-content" style={fs(13, 'body')}>
|
||||
{activity.track.name}
|
||||
</div>
|
||||
<ActivityBadges activity={activity} execution={execution} />
|
||||
</div>
|
||||
<Tooltip label={t('tours.activity.badgeHint')}>
|
||||
<span className="inline-flex">
|
||||
<SoftPill tone="success" caps>
|
||||
{t('tours.activity.badge')}
|
||||
</SoftPill>
|
||||
</span>
|
||||
</Tooltip>
|
||||
</header>
|
||||
<div className="flex flex-col gap-2 border-t border-edge-faint p-2.5">
|
||||
<TourMetricFields analysis={analysis} unit={unit} extra={[timeField(activity, t)]} />
|
||||
{analysis && analysis.distanceIndexedProfileSamples.length >= 2 && (
|
||||
<ElevationProfile
|
||||
samples={analysis.distanceIndexedProfileSamples}
|
||||
color={RECORDED_COLOR}
|
||||
gradientId={`tour-activity-${activity.id}`}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
{state.canEdit && (
|
||||
<footer className="flex flex-wrap gap-1.5 border-t border-edge-faint px-2.5 py-2">
|
||||
<CardAction
|
||||
icon={<RefreshCw size={12} strokeWidth={2.2} />}
|
||||
onClick={() => state.openAssign({ assignmentId: activity.assignment_id })}
|
||||
disabled={state.busy}
|
||||
>
|
||||
{t('tours.activity.change')}
|
||||
</CardAction>
|
||||
<CardAction
|
||||
icon={<Unlink size={12} strokeWidth={2.2} />}
|
||||
onClick={() => state.askRemove(activity)}
|
||||
disabled={state.busy}
|
||||
>
|
||||
{t('tours.activity.remove')}
|
||||
</CardAction>
|
||||
</footer>
|
||||
)}
|
||||
</article>
|
||||
);
|
||||
}
|
||||
|
||||
/** No recording yet: a quiet line, dimmed rather than hidden, so the place for one is known. */
|
||||
function NoActivity() {
|
||||
const { t } = useTranslation();
|
||||
return (
|
||||
<div
|
||||
data-testid="tour-activity-empty"
|
||||
className={`${BOX} flex items-center gap-2.5 px-3 py-2.5 text-content-faint`}
|
||||
style={fs(12, 'body')}
|
||||
>
|
||||
<span className="grid h-7 w-7 flex-none place-items-center rounded-full border border-dashed border-edge">
|
||||
<Footprints size={13} strokeWidth={2} aria-hidden="true" />
|
||||
</span>
|
||||
{t('tours.activity.empty')}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface TourActivitySectionProps {
|
||||
tripId: number;
|
||||
tour: TourListItem;
|
||||
days: Day[];
|
||||
assignments: AssignmentsMap;
|
||||
canEdit: boolean;
|
||||
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
|
||||
}
|
||||
|
||||
/**
|
||||
* ACT-01 in the tour's detail: the tracks the tour was actually done with,
|
||||
* each with the values its own recording measures and its profile, apart from
|
||||
* the planned values above; and for someone who may change the tour, the way
|
||||
* to assign one, change it or take it off. A tour that is itself the recording
|
||||
* of another shows none: it says so in its head instead.
|
||||
*/
|
||||
export default function TourActivitySection({
|
||||
tripId,
|
||||
tour,
|
||||
days,
|
||||
assignments,
|
||||
canEdit,
|
||||
onToursChanged,
|
||||
}: TourActivitySectionProps) {
|
||||
const { t } = useTranslation();
|
||||
const executions = useMemo(() => executionsOf(tour.place_id, days, assignments), [assignments, days, tour.place_id]);
|
||||
const state = useTourActivities({ tripId, tour, executions, canEdit, onToursChanged });
|
||||
const { activities } = state;
|
||||
if (activities === null || tour.activity_of != null || (activities.length === 0 && !canEdit)) return null;
|
||||
return (
|
||||
<DialogSection
|
||||
className="flex-none"
|
||||
label={t('tours.activity.label')}
|
||||
action={
|
||||
canEdit && (
|
||||
<Tooltip label={t('tours.activity.assignHint')}>
|
||||
<span className="inline-flex">
|
||||
<CardAction
|
||||
icon={<Plus size={12} strokeWidth={2.2} />}
|
||||
onClick={() => state.openAssign()}
|
||||
disabled={state.busy}
|
||||
>
|
||||
{t('tours.activity.assign')}
|
||||
</CardAction>
|
||||
</span>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
>
|
||||
{activities.length === 0 ? (
|
||||
<NoActivity />
|
||||
) : (
|
||||
<div className="flex flex-col gap-2">
|
||||
{activities.map((activity) => (
|
||||
<ActivityCard
|
||||
key={activity.id}
|
||||
activity={activity}
|
||||
execution={executionOf(executions, activity.assignment_id)}
|
||||
state={state}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{state.assigning && (
|
||||
<TourActivityDialog
|
||||
tripId={tripId}
|
||||
tour={tour}
|
||||
executions={executions}
|
||||
state={state}
|
||||
activities={activities}
|
||||
onToursChanged={onToursChanged}
|
||||
/>
|
||||
)}
|
||||
<ConfirmDialog
|
||||
isOpen={state.removing !== null}
|
||||
onClose={state.cancelRemove}
|
||||
onConfirm={() => void state.remove()}
|
||||
title={t('tours.activity.removeTitle')}
|
||||
message={t('tours.activity.removeBody')}
|
||||
confirmLabel={t('tours.activity.remove')}
|
||||
/>
|
||||
</DialogSection>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
// FE-ACT-MODEL-001 to FE-ACT-MODEL-008
|
||||
// ACT-01, the pure half of a tour's actual tracks: its executions, the
|
||||
// recordings that can be linked, the GPX preset, the time and the refusals.
|
||||
import type { TourActivity, TourListItem } from '@trek/shared';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import type { Assignment, AssignmentsMap, Day } from '../../../types';
|
||||
import {
|
||||
analysisOfLine,
|
||||
executionOf,
|
||||
executionsOf,
|
||||
importFieldsFor,
|
||||
inDayOrder,
|
||||
isRecording,
|
||||
recordedMinutes,
|
||||
refusalOf,
|
||||
trackCandidates,
|
||||
} from './tourActivityModel';
|
||||
|
||||
const day = (id: number, date: string | null = null) => ({ id, date, title: null }) as unknown as Day;
|
||||
const days = [day(1, '2026-07-01'), day(2, '2026-07-02'), day(3, '2026-07-03')];
|
||||
const assignments: AssignmentsMap = {
|
||||
'1': [{ id: 11, place_id: 7 } as Assignment, { id: 12, place_id: 8 } as Assignment],
|
||||
'3': [{ id: 31, place_id: 7 } as Assignment],
|
||||
};
|
||||
|
||||
function tour(overrides: Partial<TourListItem> = {}): TourListItem {
|
||||
return {
|
||||
place_id: 7,
|
||||
name: 'Ridge',
|
||||
tour_type: 'hike',
|
||||
distance: 8,
|
||||
elevation_gain: 600,
|
||||
elevation_loss: 600,
|
||||
duration: 180,
|
||||
difficulty: null,
|
||||
wanderer_ref: null,
|
||||
match_confidence: 1,
|
||||
max_hiking_difficulty: 2,
|
||||
planned: true,
|
||||
caution: false,
|
||||
has_waypoints: true,
|
||||
origin: 'trek',
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
const activity = (id: number, assignmentId: number | null) =>
|
||||
({ id, assignment_id: assignmentId }) as unknown as TourActivity;
|
||||
|
||||
describe('executions', () => {
|
||||
it('FE-ACT-MODEL-001: lists the days the tour is on with their assignment, in trip order', () => {
|
||||
const executions = executionsOf(7, days, assignments);
|
||||
expect(executions.map((execution) => [execution.assignmentId, execution.day?.id, execution.index])).toEqual([
|
||||
[11, 1, 0],
|
||||
[31, 3, 2],
|
||||
]);
|
||||
expect(executionOf(executions, 31).index).toBe(2);
|
||||
expect(executionOf(executions, null)).toEqual({ assignmentId: null, day: null, index: -1 });
|
||||
expect(executionOf(executions, 99).day).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ACT-MODEL-002: orders the actual tracks by their days, the ones without a day last', () => {
|
||||
const executions = executionsOf(7, days, assignments);
|
||||
const ordered = inDayOrder([activity(1, null), activity(2, 31), activity(3, 11), activity(4, null)], executions);
|
||||
expect(ordered.map((item) => item.id)).toEqual([3, 2, 1, 4]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('candidates', () => {
|
||||
it('FE-ACT-MODEL-003: a recording is an import nobody planned over', () => {
|
||||
expect(isRecording(tour({ origin: 'gpx', has_waypoints: false }))).toBe(true);
|
||||
expect(isRecording(tour({ origin: 'wanderer', has_waypoints: false }))).toBe(true);
|
||||
expect(isRecording(tour({ origin: 'gpx', has_waypoints: true }))).toBe(false);
|
||||
expect(isRecording(tour({ origin: 'trek', has_waypoints: false }))).toBe(false);
|
||||
expect(isRecording(tour({ origin: undefined, has_waypoints: false }))).toBe(false);
|
||||
});
|
||||
|
||||
it('FE-ACT-MODEL-004: offers the recordings, dims one taken by another tour and leaves out the rest', () => {
|
||||
const tours = [
|
||||
tour(),
|
||||
tour({ place_id: 20, name: 'Watch', origin: 'gpx', has_waypoints: false }),
|
||||
tour({ place_id: 21, name: 'Phone', origin: 'gpx', has_waypoints: false, activity_of: 30 }),
|
||||
tour({ place_id: 22, name: 'Mine', origin: 'gpx', has_waypoints: false, activity_of: 7 }),
|
||||
tour({
|
||||
place_id: 23,
|
||||
name: 'Plan',
|
||||
origin: 'gpx',
|
||||
has_waypoints: false,
|
||||
activity_tracks: [{ id: 1, track_place_id: 24, assignment_id: null }],
|
||||
}),
|
||||
tour({ place_id: 30, name: 'Lake' }),
|
||||
];
|
||||
expect(trackCandidates(tours, 7).map(({ tour: item, takenBy }) => [item.place_id, takenBy])).toEqual([
|
||||
[20, null],
|
||||
[21, 'Lake'],
|
||||
[22, null],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the GPX preset', () => {
|
||||
it('FE-ACT-MODEL-005: imports a recording as the tour’s own type', () => {
|
||||
expect(importFieldsFor(tour({ tour_type: 'bike', bike_profile: 'gravel' }))).toEqual({
|
||||
tour_type: 'bike',
|
||||
bike_profile: 'gravel',
|
||||
});
|
||||
expect(importFieldsFor(tour({ tour_type: 'bike', bike_profile: null }))).toEqual({
|
||||
tour_type: 'bike',
|
||||
bike_profile: 'touring',
|
||||
});
|
||||
expect(importFieldsFor(tour({ tour_type: 'kayak', boat_type: 'sup', water_context: 'lake' }))).toEqual({
|
||||
tour_type: 'kayak',
|
||||
boat_type: 'sup',
|
||||
water_context: 'lake',
|
||||
});
|
||||
expect(importFieldsFor(tour({ tour_type: 'kayak', boat_type: null, water_context: null }))).toEqual({
|
||||
tour_type: 'kayak',
|
||||
});
|
||||
expect(importFieldsFor(tour({ tour_type: 'walk' }))).toEqual({ tour_type: 'walk' });
|
||||
expect(importFieldsFor(tour({ tour_type: 'ski' }))).toEqual({ tour_type: 'hike' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('measures', () => {
|
||||
it('FE-ACT-MODEL-006: the time is only what the track’s times say', () => {
|
||||
expect(recordedMinutes('2026-07-02T06:10:00Z', '2026-07-02T09:25:00Z')).toBe(195);
|
||||
expect(recordedMinutes(null, '2026-07-02T09:25:00Z')).toBeNull();
|
||||
expect(recordedMinutes('2026-07-02T09:25:00Z', '2026-07-02T06:10:00Z')).toBeNull();
|
||||
expect(recordedMinutes('nonsense', undefined)).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ACT-MODEL-007: analyses a line like the plan’s, and nothing of fewer than two points', () => {
|
||||
const analysis = analysisOfLine([
|
||||
[47, 11, 600],
|
||||
[47.01, 11, 700],
|
||||
]);
|
||||
expect(analysis?.gain).toBe(100);
|
||||
expect(analysisOfLine([[47, 11]])).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ACT-MODEL-008: reads the server’s reason for a refusal, and none from anything else', () => {
|
||||
expect(refusalOf({ response: { data: { code: 'activity_track_in_use' } } })).toBe('activity_track_in_use');
|
||||
expect(refusalOf({ response: { data: { code: 'tour_revision_conflict' } } })).toBeNull();
|
||||
expect(refusalOf(new Error('offline'))).toBeNull();
|
||||
expect(refusalOf(null)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,126 @@
|
||||
import {
|
||||
TOUR_ACTIVITY_REFUSALS,
|
||||
type TourActivity,
|
||||
type TourActivityRefusal,
|
||||
type TourGpxImportFields,
|
||||
type TourListItem,
|
||||
} from '@trek/shared';
|
||||
import type { AssignmentsMap, Day } from '../../../types';
|
||||
import { analyzeRouteGeometry, type RouteGeometryAnalysis } from '../../../utils/routeGeometry';
|
||||
|
||||
/**
|
||||
* ACT-01, the pure half of a tour's recorded tracks: the executions a
|
||||
* recording can belong to (the days the tour is on, or none), the recordings
|
||||
* of the trip that can be assigned, and what one of them measures.
|
||||
*/
|
||||
|
||||
/** One execution of a tour: a day it is on, through its day assignment; `null` assignment for none. */
|
||||
export interface TourExecution {
|
||||
assignmentId: number | null;
|
||||
day: Day | null;
|
||||
/** The day's position in the trip, so `index + 1` is the number the plan shows; -1 without a day. */
|
||||
index: number;
|
||||
}
|
||||
|
||||
/** Every day the tour is on, in the order of the trip, each with its assignment. */
|
||||
export function executionsOf(placeId: number, days: readonly Day[], assignments: AssignmentsMap): TourExecution[] {
|
||||
return days.flatMap((day, index) => {
|
||||
const assignment = (assignments[String(day.id)] ?? []).find((item) => item.place_id === placeId);
|
||||
return assignment ? [{ assignmentId: assignment.id, day, index }] : [];
|
||||
});
|
||||
}
|
||||
|
||||
/** The execution an assignment stands for; one whose day is gone reads as none. */
|
||||
export function executionOf(executions: readonly TourExecution[], assignmentId: number | null): TourExecution {
|
||||
return (
|
||||
executions.find((execution) => execution.assignmentId === assignmentId) ?? {
|
||||
assignmentId: null,
|
||||
day: null,
|
||||
index: -1,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/** The recordings in the order of the days they belong to, the ones without a day last. */
|
||||
export function inDayOrder(activities: readonly TourActivity[], executions: readonly TourExecution[]): TourActivity[] {
|
||||
const position = (activity: TourActivity) => {
|
||||
const index = executionOf(executions, activity.assignment_id).index;
|
||||
return index < 0 ? Number.MAX_SAFE_INTEGER : index;
|
||||
};
|
||||
return [...activities].sort((a, b) => position(a) - position(b) || a.id - b.id);
|
||||
}
|
||||
|
||||
/** A tour of the trip that still is the line it was recorded with: an import nobody planned over. */
|
||||
export function isRecording(tour: Pick<TourListItem, 'origin' | 'has_waypoints'>): boolean {
|
||||
return tour.origin !== undefined && tour.origin !== 'trek' && !tour.has_waypoints;
|
||||
}
|
||||
|
||||
/**
|
||||
* What can be offered for this tour: every recording of the trip but the tour
|
||||
* itself and the ones with recordings of their own. One that documents another
|
||||
* tour stays in the list, dimmed, with that tour's name, so the user sees why
|
||||
* it cannot be picked rather than missing it.
|
||||
*/
|
||||
export interface TrackCandidate {
|
||||
tour: TourListItem;
|
||||
/** The other tour this recording documents already; null while it is free or this tour's own. */
|
||||
takenBy: string | null;
|
||||
}
|
||||
|
||||
export function trackCandidates(tours: readonly TourListItem[], placeId: number): TrackCandidate[] {
|
||||
const names = new Map(tours.map((tour) => [tour.place_id, tour.name]));
|
||||
return tours
|
||||
.filter((tour) => tour.place_id !== placeId && isRecording(tour) && !tour.activity_tracks?.length)
|
||||
.map((tour) => {
|
||||
const owner = tour.activity_of ?? null;
|
||||
return { tour, takenBy: owner !== null && owner !== placeId ? (names.get(owner) ?? '') : null };
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The type a recording of this tour is imported as, preset in the GPX
|
||||
* preview: the tour's own, with its bike or run profile or its boat and water where
|
||||
* it has them. A type the import does not offer starts as a hike, as the
|
||||
* preview always did.
|
||||
*/
|
||||
export function importFieldsFor(
|
||||
tour: Pick<TourListItem, 'tour_type' | 'bike_profile' | 'boat_type' | 'water_context'> &
|
||||
Partial<Pick<TourListItem, 'run_profile'>>
|
||||
): TourGpxImportFields {
|
||||
switch (tour.tour_type) {
|
||||
case 'bike':
|
||||
return { tour_type: 'bike', bike_profile: tour.bike_profile ?? 'touring' };
|
||||
case 'run':
|
||||
return { tour_type: 'run', run_profile: tour.run_profile ?? 'running' };
|
||||
case 'horse':
|
||||
return { tour_type: 'horse' };
|
||||
case 'kayak':
|
||||
return {
|
||||
tour_type: 'kayak',
|
||||
...(tour.boat_type ? { boat_type: tour.boat_type } : {}),
|
||||
...(tour.water_context ? { water_context: tour.water_context } : {}),
|
||||
};
|
||||
case 'walk':
|
||||
return { tour_type: 'walk' };
|
||||
default:
|
||||
return { tour_type: 'hike' };
|
||||
}
|
||||
}
|
||||
|
||||
/** A recording's line analysed the way the plan's is, so both read alike. */
|
||||
export function analysisOfLine(geometry: TourActivity['geometry']): RouteGeometryAnalysis | null {
|
||||
return geometry.length >= 2 ? analyzeRouteGeometry(JSON.stringify(geometry)) : null;
|
||||
}
|
||||
|
||||
/** Minutes from a track's first to its last time, pauses included; null unless both are there and in order. */
|
||||
export function recordedMinutes(startedAt?: string | null, endedAt?: string | null): number | null {
|
||||
const start = startedAt ? Date.parse(startedAt) : Number.NaN;
|
||||
const end = endedAt ? Date.parse(endedAt) : Number.NaN;
|
||||
return Number.isFinite(start) && Number.isFinite(end) && end > start ? Math.round((end - start) / 60_000) : null;
|
||||
}
|
||||
|
||||
/** Why the server refused an assignment, when it named a reason this build knows; null for anything else. */
|
||||
export function refusalOf(error: unknown): TourActivityRefusal | null {
|
||||
const code = (error as { response?: { data?: { code?: unknown } } } | null)?.response?.data?.code;
|
||||
return TOUR_ACTIVITY_REFUSALS.find((known) => known === code) ?? null;
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
// FE-ACT-HOOK-001 to FE-ACT-HOOK-005
|
||||
// ACT-01: the actual tracks read with the tour's detail, linked from the
|
||||
// dialog and unlinked after confirming, each write telling the lists and the
|
||||
// user, and a refusal named in the user's words without changing anything.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { TourActivity, TourListItem } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { TourExecution } from './tourActivityModel';
|
||||
import { useTourActivities } from './useTourActivities';
|
||||
|
||||
const repo = vi.hoisted(() => ({ detail: vi.fn(), assignActivity: vi.fn(), unassignActivity: vi.fn() }));
|
||||
const toast = vi.hoisted(() => ({ success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }));
|
||||
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: repo }));
|
||||
vi.mock('../../shared/Toast', () => ({ useToast: () => toast }));
|
||||
|
||||
const tour = { place_id: 7, name: 'Ridge', activity_tracks: [] } as unknown as TourListItem;
|
||||
const executions: TourExecution[] = [{ assignmentId: 11, day: null, index: 0 }];
|
||||
|
||||
function activity(id: number, assignmentId: number | null, trackPlaceId = 20): TourActivity {
|
||||
return {
|
||||
id,
|
||||
assignment_id: assignmentId,
|
||||
day_id: null,
|
||||
assigned_at: null,
|
||||
track: { place_id: trackPlaceId, name: 'Watch', origin: 'gpx', file_name: null, imported_at: null },
|
||||
metrics: {
|
||||
distance_km: 3,
|
||||
elevation_gain_m: null,
|
||||
elevation_loss_m: null,
|
||||
started_at: null,
|
||||
ended_at: null,
|
||||
elapsed_minutes: null,
|
||||
point_count: 2,
|
||||
},
|
||||
geometry: [],
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo.detail.mockResolvedValue({ tour, waypoints: [], activities: [activity(1, null), activity(2, 11, 21)] });
|
||||
});
|
||||
|
||||
function render(canEdit = true, onToursChanged = vi.fn()) {
|
||||
return renderHook(
|
||||
({ current }) => useTourActivities({ tripId: 1, tour: current, executions, canEdit, onToursChanged }),
|
||||
{ initialProps: { current: tour } }
|
||||
);
|
||||
}
|
||||
|
||||
describe('useTourActivities', () => {
|
||||
it('FE-ACT-HOOK-001: reads the actual tracks with the detail, in day order, and again when the list says they changed', async () => {
|
||||
const { result, rerender } = render();
|
||||
expect(result.current.activities).toBeNull();
|
||||
await waitFor(() => expect(result.current.activities?.map((item) => item.id)).toEqual([2, 1]));
|
||||
expect(repo.detail).toHaveBeenCalledWith(1, 7, expect.any(AbortSignal));
|
||||
|
||||
rerender({ current: { ...tour, activity_tracks: [{ id: 3, track_place_id: 22, assignment_id: null }] } });
|
||||
await waitFor(() => expect(repo.detail).toHaveBeenCalledTimes(2));
|
||||
});
|
||||
|
||||
it('FE-ACT-HOOK-002: a detail that cannot be had shows none', async () => {
|
||||
repo.detail.mockRejectedValueOnce(new Error('offline'));
|
||||
const { result } = render();
|
||||
await waitFor(() => expect(result.current.activities).toEqual([]));
|
||||
});
|
||||
|
||||
it('FE-ACT-HOOK-003: links the confirmed track, takes the answer in, tells the lists and closes the dialog', async () => {
|
||||
const onToursChanged = vi.fn();
|
||||
repo.assignActivity.mockResolvedValue({ tour, waypoints: [], activities: [activity(5, 11, 30)] });
|
||||
const { result } = render(true, onToursChanged);
|
||||
await waitFor(() => expect(result.current.activities).not.toBeNull());
|
||||
|
||||
act(() => result.current.openAssign({ assignmentId: 11 }));
|
||||
expect(result.current.assigning).toEqual({ assignmentId: 11 });
|
||||
await act(async () => result.current.assign(30, 11));
|
||||
|
||||
expect(repo.assignActivity).toHaveBeenCalledWith(1, 7, { track_place_id: 30, assignment_id: 11 });
|
||||
expect(result.current.activities?.map((item) => item.id)).toEqual([5]);
|
||||
expect(onToursChanged).toHaveBeenCalledWith([7, 30]);
|
||||
expect(toast.success).toHaveBeenCalledWith('tours.activity.assigned');
|
||||
expect(result.current.assigning).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ACT-HOOK-004: a refusal names its reason, keeps the dialog open and changes nothing', async () => {
|
||||
repo.assignActivity.mockRejectedValue({ response: { status: 409, data: { code: 'activity_track_in_use' } } });
|
||||
const { result } = render();
|
||||
await waitFor(() => expect(result.current.activities).not.toBeNull());
|
||||
act(() => result.current.openAssign());
|
||||
await act(async () => result.current.assign(30, null));
|
||||
expect(toast.error).toHaveBeenCalledWith('tours.activity.refused.activity_track_in_use');
|
||||
expect(result.current.assigning).toEqual({});
|
||||
expect(result.current.activities?.map((item) => item.id)).toEqual([2, 1]);
|
||||
|
||||
repo.assignActivity.mockRejectedValue(new Error('offline'));
|
||||
await act(async () => result.current.assign(30, null));
|
||||
expect(toast.error).toHaveBeenLastCalledWith('tours.activity.failed');
|
||||
act(() => result.current.closeAssign());
|
||||
expect(result.current.assigning).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ACT-HOOK-005: unlinks only after the question, and nothing for someone who may not change the tour', async () => {
|
||||
const onToursChanged = vi.fn();
|
||||
repo.unassignActivity.mockResolvedValue({ tour, waypoints: [], activities: [] });
|
||||
const { result } = render(true, onToursChanged);
|
||||
await waitFor(() => expect(result.current.activities).not.toBeNull());
|
||||
const target = result.current.activities?.[0] as TourActivity;
|
||||
|
||||
act(() => result.current.askRemove(target));
|
||||
expect(result.current.removing).toBe(target);
|
||||
act(() => result.current.cancelRemove());
|
||||
await act(async () => result.current.remove());
|
||||
expect(repo.unassignActivity).not.toHaveBeenCalled();
|
||||
|
||||
act(() => result.current.askRemove(target));
|
||||
await act(async () => result.current.remove());
|
||||
expect(repo.unassignActivity).toHaveBeenCalledWith(1, 7, 2);
|
||||
expect(onToursChanged).toHaveBeenCalledWith([7, 21]);
|
||||
expect(toast.success).toHaveBeenCalledWith('tours.activity.removed');
|
||||
expect(result.current.activities).toEqual([]);
|
||||
|
||||
const readOnly = render(false);
|
||||
await waitFor(() => expect(readOnly.result.current.activities).not.toBeNull());
|
||||
act(() => {
|
||||
readOnly.result.current.openAssign();
|
||||
readOnly.result.current.askRemove(target);
|
||||
});
|
||||
expect(readOnly.result.current.assigning).toBeNull();
|
||||
expect(readOnly.result.current.removing).toBeNull();
|
||||
await act(async () => readOnly.result.current.assign(30, null));
|
||||
expect(repo.assignActivity).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,133 @@
|
||||
import type { TourActivity, TourDetailResponse, TourListItem } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { useTranslation } from '../../../i18n';
|
||||
import { tourRepo } from '../../../repo/tourRepo';
|
||||
import { useToast } from '../../shared/Toast';
|
||||
import { inDayOrder, refusalOf, type TourExecution } from './tourActivityModel';
|
||||
|
||||
interface TourActivitiesOptions {
|
||||
tripId: number;
|
||||
tour: TourListItem;
|
||||
/** The days the tour is on, each an execution a recording can belong to. */
|
||||
executions: readonly TourExecution[];
|
||||
canEdit: boolean;
|
||||
/** Lets the trip's lists take in a change: the tour lists its recordings, a recording the tour it documents. */
|
||||
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
|
||||
}
|
||||
|
||||
/** Which execution the assignment dialog is open for: `undefined` lets it pick the first free one. */
|
||||
export interface AssignTarget {
|
||||
assignmentId?: number | null;
|
||||
}
|
||||
|
||||
/** The refs a list item names, so the detail is read again when another client changed them. */
|
||||
function refsKey(tour: TourListItem): string {
|
||||
return (tour.activity_tracks ?? []).map((ref) => `${ref.id}:${ref.track_place_id}:${ref.assignment_id}`).join(',');
|
||||
}
|
||||
|
||||
/**
|
||||
* ACT-01: the recorded tracks of a tour in its detail, read with the detail
|
||||
* (online from the server, offline from the copy the last detail left), and
|
||||
* the two changes the user can make: open the assignment for an execution,
|
||||
* and take a recording off after confirming it. Both writes are online only,
|
||||
* as the GPX import a recording comes through is; a refused one says why and
|
||||
* changes nothing.
|
||||
*/
|
||||
export function useTourActivities({ tripId, tour, executions, canEdit, onToursChanged }: TourActivitiesOptions) {
|
||||
const { t } = useTranslation();
|
||||
const toast = useToast();
|
||||
const placeId = tour.place_id;
|
||||
const refs = refsKey(tour);
|
||||
const [loaded, setLoaded] = useState<{ placeId: number; activities: TourActivity[] } | null>(null);
|
||||
const [assigning, setAssigning] = useState<AssignTarget | null>(null);
|
||||
const [removing, setRemoving] = useState<TourActivity | null>(null);
|
||||
const [busy, setBusy] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
tourRepo.detail(tripId, placeId, controller.signal).then(
|
||||
(detail) => {
|
||||
if (!controller.signal.aborted) setLoaded({ placeId, activities: detail.activities ?? [] });
|
||||
},
|
||||
() => {
|
||||
if (!controller.signal.aborted) setLoaded({ placeId, activities: [] });
|
||||
}
|
||||
);
|
||||
return () => controller.abort();
|
||||
// `refs` is the list's word that the recordings changed elsewhere.
|
||||
}, [tripId, placeId, refs]);
|
||||
|
||||
const activities = useMemo(
|
||||
() => (loaded?.placeId === placeId ? inDayOrder(loaded.activities, executions) : null),
|
||||
[executions, loaded, placeId]
|
||||
);
|
||||
|
||||
/** One write, its answer taken in, the lists told and the user too; false when it was refused. */
|
||||
const apply = useCallback(
|
||||
async (write: () => Promise<TourDetailResponse>, success: string, changed: number[]): Promise<boolean> => {
|
||||
setBusy(true);
|
||||
try {
|
||||
const detail = await write();
|
||||
setLoaded({ placeId, activities: detail.activities ?? [] });
|
||||
await onToursChanged?.(changed);
|
||||
toast.success(t(success));
|
||||
return true;
|
||||
} catch (error: unknown) {
|
||||
const refusal = refusalOf(error);
|
||||
toast.error(t(refusal ? `tours.activity.refused.${refusal}` : 'tours.activity.failed'));
|
||||
return false;
|
||||
} finally {
|
||||
setBusy(false);
|
||||
}
|
||||
},
|
||||
[onToursChanged, placeId, t, toast]
|
||||
);
|
||||
|
||||
/** The confirmed assignment from the dialog; the dialog closes once it is written. */
|
||||
const assign = useCallback(
|
||||
async (trackPlaceId: number, assignmentId: number | null) => {
|
||||
if (!canEdit || busy) return;
|
||||
const done = await apply(
|
||||
() => tourRepo.assignActivity(tripId, placeId, { track_place_id: trackPlaceId, assignment_id: assignmentId }),
|
||||
'tours.activity.assigned',
|
||||
[placeId, trackPlaceId]
|
||||
);
|
||||
if (done) setAssigning(null);
|
||||
},
|
||||
[apply, busy, canEdit, placeId, tripId]
|
||||
);
|
||||
|
||||
/** The recording asked about, taken off once the user confirmed it. */
|
||||
const remove = useCallback(async () => {
|
||||
const target = removing;
|
||||
if (!canEdit || !target || busy) return;
|
||||
setRemoving(null);
|
||||
await apply(() => tourRepo.unassignActivity(tripId, placeId, target.id), 'tours.activity.removed', [
|
||||
placeId,
|
||||
target.track.place_id,
|
||||
]);
|
||||
}, [apply, busy, canEdit, placeId, removing, tripId]);
|
||||
|
||||
return {
|
||||
/** Null while the detail loads. */
|
||||
activities,
|
||||
canEdit,
|
||||
busy,
|
||||
assigning,
|
||||
openAssign: (target: AssignTarget = {}) => {
|
||||
if (canEdit) setAssigning(target);
|
||||
},
|
||||
closeAssign: () => {
|
||||
if (!busy) setAssigning(null);
|
||||
},
|
||||
assign,
|
||||
removing,
|
||||
askRemove: (activity: TourActivity) => {
|
||||
if (canEdit) setRemoving(activity);
|
||||
},
|
||||
cancelRemove: () => setRemoving(null),
|
||||
remove,
|
||||
};
|
||||
}
|
||||
|
||||
export type TourActivities = ReturnType<typeof useTourActivities>;
|
||||
@@ -0,0 +1,105 @@
|
||||
// FE-ACT-ASSIGN-001 to FE-ACT-ASSIGN-004
|
||||
// ACT-01, the link dialog's state: the day it starts on, the recordings of the
|
||||
// trip to choose from, what a choice replaces, and a recording imported here
|
||||
// chosen for the user but never linked by itself.
|
||||
import { act, renderHook, waitFor } from '@testing-library/react';
|
||||
import type { TourActivity, TourListItem } from '@trek/shared';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
import type { TourExecution } from './tourActivityModel';
|
||||
import { useTrackAssignment } from './useTrackAssignment';
|
||||
|
||||
const repo = vi.hoisted(() => ({ list: vi.fn() }));
|
||||
interface ImportOptions {
|
||||
onImported?: (tours: TourListItem[]) => void;
|
||||
onToursChanged?: (ids?: number[]) => unknown;
|
||||
}
|
||||
const gpx = vi.hoisted(() => ({ options: null as null | ImportOptions }));
|
||||
vi.mock('../../../repo/tourRepo', () => ({ tourRepo: repo }));
|
||||
vi.mock('../useTourGpxImport', () => ({
|
||||
useTourGpxImport: (options: ImportOptions) => {
|
||||
gpx.options = options;
|
||||
return { importing: false, preview: null, pick: vi.fn(), confirm: vi.fn(), cancel: vi.fn(), importFiles: vi.fn() };
|
||||
},
|
||||
}));
|
||||
|
||||
const tour = { place_id: 7, name: 'Ridge', tour_type: 'hike', origin: 'trek', has_waypoints: true } as TourListItem;
|
||||
const recording = (placeId: number, name: string, extra: Partial<TourListItem> = {}) =>
|
||||
({ place_id: placeId, name, tour_type: 'hike', origin: 'gpx', has_waypoints: false, ...extra }) as TourListItem;
|
||||
const executions: TourExecution[] = [
|
||||
{ assignmentId: 11, day: null, index: 0 },
|
||||
{ assignmentId: 31, day: null, index: 2 },
|
||||
];
|
||||
const linked = (assignmentId: number | null, trackPlaceId: number, name: string) =>
|
||||
({
|
||||
id: trackPlaceId,
|
||||
assignment_id: assignmentId,
|
||||
track: { place_id: trackPlaceId, name },
|
||||
}) as unknown as TourActivity;
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
repo.list.mockResolvedValue({ tours: [tour, recording(20, 'Watch'), recording(21, 'Phone', { activity_of: 99 })] });
|
||||
});
|
||||
|
||||
function render(activities: TourActivity[], target: { assignmentId?: number | null } = {}, onToursChanged = vi.fn()) {
|
||||
return renderHook(() =>
|
||||
useTrackAssignment({ tripId: 1, tour, executions, activities, target, canEdit: true, onToursChanged })
|
||||
);
|
||||
}
|
||||
|
||||
describe('useTrackAssignment', () => {
|
||||
it('FE-ACT-ASSIGN-001: starts on the first day without an actual track, or on the day asked for', async () => {
|
||||
expect(render([]).result.current.assignmentId).toBe(11);
|
||||
expect(render([linked(11, 20, 'Watch')]).result.current.assignmentId).toBe(31);
|
||||
expect(render([linked(11, 20, 'Watch'), linked(31, 21, 'Phone')]).result.current.assignmentId).toBe(11);
|
||||
const asked = render([linked(31, 21, 'Phone')], { assignmentId: 31 });
|
||||
expect(asked.result.current.assignmentId).toBe(31);
|
||||
// A change starts on the track the day has, which therefore replaces nothing.
|
||||
expect(asked.result.current.selected).toBe(21);
|
||||
expect(asked.result.current.replaces).toBeNull();
|
||||
await waitFor(() => expect(asked.result.current.candidates).not.toBeNull());
|
||||
});
|
||||
|
||||
it('FE-ACT-ASSIGN-002: lists the recordings of the trip, and only a free one can be linked', async () => {
|
||||
const { result } = render([]);
|
||||
expect(result.current.candidates).toBeNull();
|
||||
expect(result.current.ready).toBe(false);
|
||||
await waitFor(() => expect(result.current.candidates?.map((c) => c.tour.place_id)).toEqual([20, 21]));
|
||||
expect(repo.list).toHaveBeenCalledWith(1);
|
||||
|
||||
act(() => result.current.choose(21));
|
||||
expect(result.current.choice?.takenBy).toBe('');
|
||||
expect(result.current.ready).toBe(false);
|
||||
act(() => result.current.choose(20));
|
||||
expect(result.current.ready).toBe(true);
|
||||
expect(result.current.importFields).toEqual({ tour_type: 'hike' });
|
||||
});
|
||||
|
||||
it('FE-ACT-ASSIGN-003: names the track a choice replaces on its day, and none on a day without one', async () => {
|
||||
const { result } = render([linked(11, 21, 'Phone')], { assignmentId: 11 });
|
||||
await waitFor(() => expect(result.current.candidates).not.toBeNull());
|
||||
act(() => result.current.choose(20));
|
||||
expect(result.current.replaces).toBe('Phone');
|
||||
act(() => result.current.chooseExecution(null));
|
||||
expect(result.current.execution.day).toBeNull();
|
||||
expect(result.current.replaces).toBeNull();
|
||||
});
|
||||
|
||||
it('FE-ACT-ASSIGN-004: a recording imported here is chosen and the list read again; the lists are told', async () => {
|
||||
const onToursChanged = vi.fn();
|
||||
const { result } = render([], {}, onToursChanged);
|
||||
await waitFor(() => expect(result.current.candidates).not.toBeNull());
|
||||
repo.list.mockResolvedValue({ tours: [tour, recording(20, 'Watch'), recording(40, 'Imported')] });
|
||||
|
||||
await act(async () => gpx.options?.onToursChanged?.([40]));
|
||||
expect(onToursChanged).toHaveBeenCalledWith([40]);
|
||||
await act(async () => gpx.options?.onToursChanged?.());
|
||||
expect(onToursChanged).toHaveBeenLastCalledWith([]);
|
||||
act(() => gpx.options?.onImported?.([recording(40, 'Imported')]));
|
||||
expect(result.current.selected).toBe(40);
|
||||
await waitFor(() => expect(result.current.choice?.tour.name).toBe('Imported'));
|
||||
expect(repo.list).toHaveBeenCalledTimes(2);
|
||||
act(() => gpx.options?.onImported?.([]));
|
||||
expect(result.current.selected).toBe(40);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,104 @@
|
||||
import type { TourActivity, TourListItem } from '@trek/shared';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { tourRepo } from '../../../repo/tourRepo';
|
||||
import { useTourGpxImport } from '../useTourGpxImport';
|
||||
import { executionOf, importFieldsFor, trackCandidates, type TourExecution } from './tourActivityModel';
|
||||
import type { AssignTarget } from './useTourActivities';
|
||||
|
||||
interface TrackAssignmentOptions {
|
||||
tripId: number;
|
||||
tour: TourListItem;
|
||||
executions: readonly TourExecution[];
|
||||
/** The recordings the tour has now, to preset a change and to say what a choice replaces. */
|
||||
activities: readonly TourActivity[];
|
||||
target: AssignTarget;
|
||||
canEdit: boolean;
|
||||
onToursChanged?: (placeIds: number[]) => Promise<void> | void;
|
||||
}
|
||||
|
||||
/** The execution the dialog starts on: the one asked for, else the first day without a recording, else none. */
|
||||
function startingExecution(
|
||||
executions: readonly TourExecution[],
|
||||
activities: readonly TourActivity[],
|
||||
target: AssignTarget
|
||||
): number | null {
|
||||
if (target.assignmentId !== undefined) return target.assignmentId;
|
||||
const recorded = new Set(activities.map((activity) => activity.assignment_id));
|
||||
return (executions.find((execution) => !recorded.has(execution.assignmentId)) ?? executions[0])?.assignmentId ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* ACT-01, the dialog that assigns a recording: which execution it was, which
|
||||
* recording of the trip, or a new one through the GPX import (its preview
|
||||
* preset to the tour's type), and what the choice measures before anything is
|
||||
* written. Nothing is stored until the user confirms; a recording imported
|
||||
* here is chosen for them, never assigned.
|
||||
*/
|
||||
export function useTrackAssignment({
|
||||
tripId,
|
||||
tour,
|
||||
executions,
|
||||
activities,
|
||||
target,
|
||||
canEdit,
|
||||
onToursChanged,
|
||||
}: TrackAssignmentOptions) {
|
||||
const [assignmentId, setAssignmentId] = useState<number | null>(() =>
|
||||
startingExecution(executions, activities, target)
|
||||
);
|
||||
const current = activities.find((activity) => activity.assignment_id === assignmentId) ?? null;
|
||||
const [selected, setSelected] = useState<number | null>(() => current?.track.place_id ?? null);
|
||||
const [tours, setTours] = useState<TourListItem[] | null>(null);
|
||||
const [reads, setReads] = useState(0);
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
tourRepo.list(tripId).then(
|
||||
({ tours: listed }) => {
|
||||
if (!cancelled) setTours(listed);
|
||||
},
|
||||
() => {
|
||||
if (!cancelled) setTours([]);
|
||||
}
|
||||
);
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [tripId, reads]);
|
||||
|
||||
const onImported = useCallback((imported: TourListItem[]) => {
|
||||
const first = imported[0];
|
||||
if (first) setSelected(first.place_id);
|
||||
setReads((count) => count + 1);
|
||||
}, []);
|
||||
const gpxImport = useTourGpxImport({
|
||||
tripId,
|
||||
canEdit,
|
||||
onToursChanged: (placeIds) => onToursChanged?.(placeIds ?? []),
|
||||
onImported,
|
||||
});
|
||||
|
||||
const candidates = useMemo(() => (tours ? trackCandidates(tours, tour.place_id) : null), [tour.place_id, tours]);
|
||||
const choice = candidates?.find((candidate) => candidate.tour.place_id === selected) ?? null;
|
||||
// A recording the execution has now, other than the one chosen, gives way to it.
|
||||
const replaces = current && current.track.place_id !== selected ? current.track.name : null;
|
||||
|
||||
return {
|
||||
executions,
|
||||
assignmentId,
|
||||
execution: executionOf(executions, assignmentId),
|
||||
chooseExecution: setAssignmentId,
|
||||
/** Null while the trip's tours load. */
|
||||
candidates,
|
||||
selected,
|
||||
choose: setSelected,
|
||||
choice,
|
||||
replaces,
|
||||
gpxImport,
|
||||
importFields: importFieldsFor(tour),
|
||||
/** A free recording is chosen, so the assignment can be confirmed. */
|
||||
ready: choice !== null && choice.takenBy === null,
|
||||
};
|
||||
}
|
||||
|
||||
export type TrackAssignment = ReturnType<typeof useTrackAssignment>;
|
||||
@@ -23,14 +23,22 @@ export interface GpxImportChoices {
|
||||
ski: SkiChoice;
|
||||
}
|
||||
|
||||
const START: GpxImportChoices = {
|
||||
type: 'hike',
|
||||
boat: null,
|
||||
water: null,
|
||||
bikeProfile: 'touring',
|
||||
runProfile: 'running',
|
||||
ski: NO_SKI_CHOICE,
|
||||
};
|
||||
const HIKE: TourGpxImportFields = { tour_type: 'hike' };
|
||||
|
||||
/** The choices a preview opens with: the fields it was preset to (ACT-01), the rest as a fresh preview has them. */
|
||||
function choicesFrom(initial: TourGpxImportFields): GpxImportChoices {
|
||||
return {
|
||||
type: initial.tour_type,
|
||||
boat: initial.boat_type ?? null,
|
||||
water: initial.water_context ?? null,
|
||||
bikeProfile: initial.bike_profile ?? 'touring',
|
||||
runProfile: initial.run_profile ?? 'running',
|
||||
ski:
|
||||
initial.tour_type === 'ski'
|
||||
? { discipline: initial.ski_discipline ?? null, technique: initial.ski_technique ?? null }
|
||||
: NO_SKI_CHOICE,
|
||||
};
|
||||
}
|
||||
|
||||
/** What the chosen type still lacks before anything can be imported; null when nothing does. */
|
||||
export function importMissing(chosen: GpxImportChoices): 'paddle' | 'ski' | null {
|
||||
@@ -47,6 +55,8 @@ export function importFields(chosen: GpxImportChoices): TourGpxImportFields {
|
||||
if (type === 'bike') return { tour_type: 'bike', bike_profile: chosen.bikeProfile };
|
||||
// RUN-01: a run comes in with its profile and no pace; its time stays unknown until one is planned from it.
|
||||
if (type === 'run') return { tour_type: 'run', run_profile: chosen.runProfile };
|
||||
// ACT-01: a city walk comes in as one, not as a hike.
|
||||
if (type === 'walk') return { tour_type: 'walk' };
|
||||
// HOR-01: a recorded ride comes in as a ride, with nothing of another type.
|
||||
if (type === 'horse') return { tour_type: 'horse' };
|
||||
// SKI-02: a ski track comes in with its discipline and, for cross-country, its technique, and no time.
|
||||
@@ -55,9 +65,9 @@ export function importFields(chosen: GpxImportChoices): TourGpxImportFields {
|
||||
return { tour_type: 'hike' };
|
||||
}
|
||||
|
||||
/** The preview's choices, each field set on its own; a fresh preview starts as a hike. */
|
||||
export function useGpxImportChoices() {
|
||||
const [chosen, setChosen] = useState<GpxImportChoices>(START);
|
||||
/** The preview's choices, each field set on its own; a fresh preview starts as a hike, a preset one as preset. */
|
||||
export function useGpxImportChoices(initial: TourGpxImportFields = HIKE) {
|
||||
const [chosen, setChosen] = useState<GpxImportChoices>(() => choicesFrom(initial));
|
||||
const set =
|
||||
<K extends keyof GpxImportChoices>(key: K) =>
|
||||
(value: GpxImportChoices[K]) =>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useId, useLayoutEffect, useRef, useState, type ReactNode } from 'react'
|
||||
import type { TourListItem } from '@trek/shared'
|
||||
import { AlertTriangle, CalendarDays, ChevronDown, Info, Plus } from 'lucide-react'
|
||||
import { AlertTriangle, CalendarDays, ChevronDown, Footprints, Info, Plus } from 'lucide-react'
|
||||
import { createElement } from 'react'
|
||||
import type { Day, DistanceUnit } from '../../types'
|
||||
import type { RouteGeometryAnalysis } from '../../utils/routeGeometry'
|
||||
@@ -122,6 +122,26 @@ export function TourCautionBadge({ tour }: { tour: Pick<TourListItem, 'caution'>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* ACT-01 on a row, icon only like the caution: a tour that has a recorded
|
||||
* track, or a recording that is the track of a tour. The tooltip says which.
|
||||
*/
|
||||
export function TourActivityBadge({ tour }: { tour: Pick<TourListItem, 'activity_tracks' | 'activity_of'> }) {
|
||||
const { t } = useTranslation()
|
||||
const isTrack = tour.activity_of != null
|
||||
if (!isTrack && !tour.activity_tracks?.length) return null
|
||||
const label = t(isTrack ? 'tours.activity.isTrackHint' : 'tours.activity.badgeHint')
|
||||
return (
|
||||
<Tooltip label={label}>
|
||||
<span data-testid="tour-activity-badge" aria-label={label} className="inline-flex flex-none">
|
||||
<WhiteBadge className="text-success" icon={<Footprints size={10} strokeWidth={2.2} className="flex-none" />}>
|
||||
{null}
|
||||
</WhiteBadge>
|
||||
</span>
|
||||
</Tooltip>
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* The days a tour is on as small pills, "Day 2" each, the date and title in the
|
||||
* tooltip. A tour on many days names the first ones and folds the rest into "+n",
|
||||
|
||||
@@ -77,6 +77,13 @@ describe('tourScopeSummary (STA-01)', () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it('ACT-01: leaves out a recording that is the actual track of a tour, so the tour is not counted twice', () => {
|
||||
const track = { ...GPX_HIKE, place_id: 9, activity_of: HIKE_A.place_id };
|
||||
const scope = tourScopeSummary([HIKE_A, track]);
|
||||
expect(scope.count).toBe(1);
|
||||
expect(scope.types[0].distanceKm).toEqual({ value: 10, known: 1, of: 1 });
|
||||
});
|
||||
|
||||
it('sums what is known and says how much of the whole that is, never a zero for unknown', () => {
|
||||
const [hike] = tourScopeSummary([HIKE_A, HIKE_B, GPX_HIKE]).types;
|
||||
expect(hike.distanceKm).toEqual({ value: 23.5, known: 3, of: 3 });
|
||||
|
||||
@@ -87,10 +87,13 @@ type OnDay = (tour: TourListItem) => boolean;
|
||||
* however many days it is on; the list is the trip's tours, one row each, so
|
||||
* a tour on three days is still one tour and one distance. `onDay` reads the
|
||||
* day lists where the caller has them; the list's own flag is the fallback.
|
||||
* A recording assigned to a tour as its recorded track (ACT-01) is that tour
|
||||
* done, not a tour of its own, so it is not counted twice.
|
||||
*/
|
||||
export function tourScopeSummary(tours: readonly TourListItem[], onDay: OnDay = (tour) => tour.planned): TourScope {
|
||||
const byType = new Map<TourTypeKey, TourListItem[]>();
|
||||
for (const tour of new Map(tours.map((tour) => [tour.place_id, tour])).values()) {
|
||||
const counted = tours.filter((tour) => tour.activity_of == null);
|
||||
for (const tour of new Map(counted.map((tour) => [tour.place_id, tour])).values()) {
|
||||
byType.set(tour.tour_type, [...(byType.get(tour.tour_type) ?? []), tour]);
|
||||
}
|
||||
const types = [...byType.entries()]
|
||||
|
||||
@@ -53,6 +53,31 @@ describe('cacheTourAnswer', () => {
|
||||
expect(await offlineDb.tours.get(40)).toEqual(row);
|
||||
});
|
||||
|
||||
it('CT-ACT-001: the actual tracks of a detail are cached, and kept by an answer without them (ACT-01)', async () => {
|
||||
const activities = [
|
||||
{
|
||||
id: 5,
|
||||
assignment_id: null,
|
||||
day_id: null,
|
||||
assigned_at: null,
|
||||
track: { place_id: 41, name: 'Watch', origin: 'gpx' as const, file_name: null, imported_at: null },
|
||||
metrics: {
|
||||
distance_km: 2,
|
||||
elevation_gain_m: null,
|
||||
elevation_loss_m: null,
|
||||
started_at: null,
|
||||
ended_at: null,
|
||||
elapsed_minutes: null,
|
||||
point_count: 2,
|
||||
},
|
||||
geometry: [] as Array<[number, number]>,
|
||||
},
|
||||
];
|
||||
await cacheTourAnswer(3, { tour: tour({ tour_type: 'hike' }), waypoints, activities });
|
||||
const row = await cacheTourAnswer(3, { tour: tour({ tour_type: 'hike', name: 'Again' }), waypoints });
|
||||
expect(row.activities).toEqual(activities);
|
||||
});
|
||||
|
||||
it('CT-002: an answer without provenance or checklist keeps the cached ones', async () => {
|
||||
const check = obstacleCheck();
|
||||
await cacheTourAnswer(3, { tour: tour(), waypoints, provenance, obstacle_check: check });
|
||||
|
||||
@@ -3,22 +3,24 @@ import { offlineDb, type CachedTour } from './offlineDb';
|
||||
|
||||
/**
|
||||
* A tour as the server answered it, written to the cache with its control
|
||||
* points. Where it came from and a paddle tour's checklist are kept from the
|
||||
* row already there when the answer carries none, so a write answered
|
||||
* without them does not lose them. Safe inside a Dexie transaction that
|
||||
* holds the tours table.
|
||||
* points. Where it came from, a paddle tour's checklist and its recorded
|
||||
* tracks (ACT-01) are kept from the row already there when the answer carries
|
||||
* none, so a write answered without them does not lose them. Safe inside a
|
||||
* Dexie transaction that holds the tours table.
|
||||
*/
|
||||
export async function cacheTourAnswer(tripId: number, answer: TourCreateResponse): Promise<CachedTour> {
|
||||
const previous = await offlineDb.tours.get(answer.tour.place_id);
|
||||
const provenance = answer.provenance ?? previous?.provenance;
|
||||
// Only a paddle tour has a checklist; a tour that stopped being one drops it.
|
||||
const check = answer.tour.tour_type === 'kayak' ? (answer.obstacle_check ?? previous?.obstacle_check) : undefined;
|
||||
const activities = answer.activities ?? previous?.activities;
|
||||
const row: CachedTour = {
|
||||
...answer.tour,
|
||||
trip_id: tripId,
|
||||
waypoints: answer.waypoints,
|
||||
...(provenance ? { provenance } : {}),
|
||||
...(check ? { obstacle_check: check } : {}),
|
||||
...(activities ? { activities } : {}),
|
||||
};
|
||||
await offlineDb.tours.put(row);
|
||||
return row;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { Ferrata, RoadtripPreferences, TourListItem, TourObstacleCheck, TourProvenance, TourVisit, TourWaypoint } from '@trek/shared';
|
||||
import type { Ferrata, RoadtripPreferences, TourActivity, TourListItem, TourObstacleCheck, TourProvenance, TourVisit, TourWaypoint } from '@trek/shared';
|
||||
import Dexie, { type Table } from 'dexie';
|
||||
import type { Trip, Day, Place, PackingItem, TodoItem, BudgetItem, Reservation, TripFile, Accommodation, TripMember, Tag, Category } from '../types';
|
||||
|
||||
@@ -19,6 +19,8 @@ export interface CachedTour extends TourListItem {
|
||||
provenance?: TourProvenance;
|
||||
/** A paddle tour's obstacle checklist as its detail last said; its revision tells whether the list's bench still matches. */
|
||||
obstacle_check?: TourObstacleCheck;
|
||||
/** ACT-01: the recorded tracks its detail last answered, kept while the list names the same ones. */
|
||||
activities?: TourActivity[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -468,6 +470,13 @@ export async function replaceTripRows<T extends { id: number }>(table: TripScope
|
||||
* reads the same: the list carries no waypoints, and a route edited elsewhere
|
||||
* must not open offline with the old ones.
|
||||
*/
|
||||
/** The recorded tracks a cached detail holds, while the list still names the same ones (ACT-01). */
|
||||
function keptActivities(previous: CachedTour | undefined, tour: TourListItem): Pick<CachedTour, 'activities'> {
|
||||
const refs = (item: Pick<TourListItem, 'activity_tracks'>) =>
|
||||
(item.activity_tracks ?? []).map(ref => `${ref.id}:${ref.track_place_id}:${ref.assignment_id}`).join(',')
|
||||
return previous?.activities && refs(previous) === refs(tour) ? { activities: previous.activities } : {}
|
||||
}
|
||||
|
||||
export async function replaceTripTours(tripId: number, tours: TourListItem[]): Promise<void> {
|
||||
await offlineDb.transaction('rw', offlineDb.tours, async () => {
|
||||
const cached = new Map((await offlineDb.tours.where('trip_id').equals(tripId).toArray()).map(t => [t.place_id, t]));
|
||||
@@ -490,6 +499,7 @@ export async function replaceTripTours(tripId: number, tours: TourListItem[]): P
|
||||
...(sameRoute && previous.waypoints ? { waypoints: previous.waypoints } : {}),
|
||||
...(previous?.provenance ? { provenance: previous.provenance } : {}),
|
||||
...(previous?.obstacle_check ? { obstacle_check: previous.obstacle_check } : {}),
|
||||
...keptActivities(previous, tour),
|
||||
};
|
||||
}));
|
||||
});
|
||||
|
||||
@@ -7,8 +7,9 @@ import type { useTripPlanner } from './useTripPlanner';
|
||||
/**
|
||||
* What the tour's detail does beyond a place's: a rename reloads the tours,
|
||||
* a reimport from its source check (MF-03) takes the new snapshot in and opens
|
||||
* it, and "save as new tour" (P2C-07) makes the copy and opens it under a name
|
||||
* that says it is one, so renaming it is the next step.
|
||||
* it, "save as new tour" (P2C-07) makes the copy and opens it under a name
|
||||
* that says it is one, so renaming it is the next step, and a recorded track
|
||||
* assigned or taken off (ACT-01) is taken into the lists.
|
||||
*/
|
||||
export function useTourDetailActions(planner: ReturnType<typeof useTripPlanner>) {
|
||||
const { invalidateTourPlaceIds, reloadTourPlaceIds, t, toast, tripActions, tripId, upsertTour } = planner;
|
||||
@@ -31,6 +32,8 @@ export function useTourDetailActions(planner: ReturnType<typeof useTripPlanner>)
|
||||
await reloadTourPlaceIds();
|
||||
},
|
||||
onSourceReimported: takeIn,
|
||||
/** ACT-01: a recorded track assigned, taken off or imported; the lists read these tours again. */
|
||||
onToursChanged: (placeIds: number[]) => invalidateTourPlaceIds({ placeIds }),
|
||||
/** LIB-02: a tour taken over from another trip; the tours rail opens it in the planner. */
|
||||
onTakenOver: bringIn,
|
||||
onSaveAsNew: async (tour: TourListItem) => {
|
||||
|
||||
@@ -413,6 +413,43 @@ describe('tourRepo provenance and copies (P2C-02, P2C-07)', () => {
|
||||
expect(offline.tour).not.toHaveProperty('provenance')
|
||||
})
|
||||
|
||||
it('FE-REPO-TOUR-022: an actual track is linked and unlinked on the server, and the detail keeps it offline (ACT-01)', async () => {
|
||||
const activity = {
|
||||
id: 5, assignment_id: null, day_id: null, assigned_at: null,
|
||||
track: { place_id: 41, name: 'Watch', origin: 'gpx', file_name: 'watch.gpx', imported_at: null },
|
||||
metrics: { distance_km: 2, elevation_gain_m: null, elevation_loss_m: null, started_at: null, ended_at: null, elapsed_minutes: null, point_count: 2 },
|
||||
geometry: [[47, 11], [47.01, 11]],
|
||||
}
|
||||
let sent: unknown = null
|
||||
server.use(
|
||||
http.put('/api/trips/3/tours/40/activities', async ({ request }) => {
|
||||
sent = await request.json()
|
||||
return HttpResponse.json({ tour: tour({ activity_tracks: [{ id: 5, track_place_id: 41, assignment_id: null }] }), waypoints: body.waypoints, activities: [activity] })
|
||||
}),
|
||||
http.delete('/api/trips/3/tours/40/activities/5', () => HttpResponse.json({ tour: tour(), waypoints: body.waypoints, activities: [] })),
|
||||
)
|
||||
const linked = await tourRepo.assignActivity(3, 40, { track_place_id: 41, assignment_id: null })
|
||||
expect(sent).toEqual({ track_place_id: 41, assignment_id: null })
|
||||
expect(linked.activities).toHaveLength(1)
|
||||
expect((await offlineDb.tours.get(40))?.activities).toEqual([activity])
|
||||
|
||||
// A list naming the same tracks keeps them; offline the detail answers them, the list item stays without them.
|
||||
await replaceTripTours(3, [tour({ activity_tracks: [{ id: 5, track_place_id: 41, assignment_id: null }] })])
|
||||
setOnline(false)
|
||||
const offline = await tourRepo.detail(3, 40)
|
||||
expect(offline.activities).toEqual([activity])
|
||||
expect(offline.tour).not.toHaveProperty('activities')
|
||||
setOnline(true)
|
||||
|
||||
// A list naming other tracks drops the stale copy.
|
||||
await replaceTripTours(3, [tour({ activity_tracks: [] })])
|
||||
expect((await offlineDb.tours.get(40))?.activities).toBeUndefined()
|
||||
|
||||
const unlinked = await tourRepo.unassignActivity(3, 40, 5)
|
||||
expect(unlinked.activities).toEqual([])
|
||||
expect((await offlineDb.tours.get(40))?.activities).toEqual([])
|
||||
})
|
||||
|
||||
it('FE-REPO-TOUR-021: a copy is asked of the server under its name and cached as a tour of the trip', async () => {
|
||||
let sent: unknown = null
|
||||
server.use(http.post('/api/trips/3/tours/40/copy', async ({ request }) => {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { computeTourMetrics, estimatePaddleTime, paddleCheckSummaryOf, paddleLayoutOfTrack, paddleMovingSeconds, recommendedPaddleSpeedKmh, type GeometryPoint, type TourObstacleCheck, type TourObstacleReviewsRequest, type TourPaddlePlanRequest, type TourSkiClassificationRequest, type TourCreateRequest, type TourCreateResponse, type TourDetailResponse, type TourGpxImportFields, type TourGpxPreviewResponse, type TourImportGpxResponse, type TourListItem, type TourWaypoint, walkStationFacts } from '@trek/shared'
|
||||
import { computeTourMetrics, estimatePaddleTime, paddleCheckSummaryOf, paddleLayoutOfTrack, paddleMovingSeconds, recommendedPaddleSpeedKmh, type GeometryPoint, type TourActivityAssignRequest, type TourObstacleCheck, type TourObstacleReviewsRequest, type TourPaddlePlanRequest, type TourSkiClassificationRequest, type TourCreateRequest, type TourCreateResponse, type TourDetailResponse, type TourGpxImportFields, type TourGpxPreviewResponse, type TourImportGpxResponse, type TourListItem, type TourWaypoint, walkStationFacts } from '@trek/shared'
|
||||
import { toursApi } from '../api/client'
|
||||
import { tourGpxApi } from '../api/tourGpx'
|
||||
import { recordedTrackApi } from '../api/recordedTrack'
|
||||
import { tourActivitiesApi } from '../api/tourActivities'
|
||||
import { tourPaddlePlanApi } from '../api/tourPaddlePlan'
|
||||
import { tourSkiApi } from '../api/tourSki'
|
||||
import { tourCopiesApi } from '../api/tourCopies'
|
||||
@@ -16,7 +17,7 @@ import { onlineThenCache } from './withOfflineFallback'
|
||||
import type { Place } from '../types'
|
||||
|
||||
/** The list item a cached row stands for: the cache-only fields stripped. */
|
||||
function toListItem({ trip_id: _tripId, waypoints: _waypoints, provenance: _provenance, obstacle_check: _check, ...tour }: CachedTour): TourListItem {
|
||||
function toListItem({ trip_id: _tripId, waypoints: _waypoints, provenance: _provenance, obstacle_check: _check, activities: _activities, ...tour }: CachedTour): TourListItem {
|
||||
return tour
|
||||
}
|
||||
|
||||
@@ -171,6 +172,7 @@ export const tourRepo = {
|
||||
waypoints,
|
||||
...(cached.provenance ? { provenance: cached.provenance } : {}),
|
||||
...(cached.obstacle_check ? { obstacle_check: cached.obstacle_check } : {}),
|
||||
...(cached.activities ? { activities: cached.activities } : {}),
|
||||
}
|
||||
},
|
||||
)
|
||||
@@ -321,6 +323,25 @@ export const tourRepo = {
|
||||
return result
|
||||
},
|
||||
|
||||
/**
|
||||
* ACT-01, online only like the GPX import a recording comes through: the
|
||||
* assignment points at a recording the server keeps, so it needs the server
|
||||
* to answer. Nothing of the plan changes, so nothing waits in the queue; the
|
||||
* answer keeps the cached detail fresh.
|
||||
*/
|
||||
async assignActivity(tripId: number | string, placeId: number, body: TourActivityAssignRequest): Promise<TourDetailResponse> {
|
||||
const result = await tourActivitiesApi.assign(tripId, placeId, body)
|
||||
await cacheTourAnswer(Number(tripId), result)
|
||||
return result
|
||||
},
|
||||
|
||||
/** ACT-01: a recorded track taken off the tour again; online only, like the assignment. */
|
||||
async unassignActivity(tripId: number | string, placeId: number, activityId: number): Promise<TourDetailResponse> {
|
||||
const result = await tourActivitiesApi.unassign(tripId, placeId, activityId)
|
||||
await cacheTourAnswer(Number(tripId), result)
|
||||
return result
|
||||
},
|
||||
|
||||
/**
|
||||
* 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`
|
||||
|
||||
@@ -108,6 +108,7 @@
|
||||
"Tags": "tags",
|
||||
"TodoCategoryAssignees": "todo",
|
||||
"TodoItems": "todo",
|
||||
"TourActivities": "tours",
|
||||
"TourChangeSteps": "tours",
|
||||
"TourObstacleReviews": "tours",
|
||||
"TourStationVisits": "tours",
|
||||
|
||||
@@ -7,6 +7,7 @@ import { FileLinks } from './FileLinks.entity';
|
||||
import { Places } from './Places.entity';
|
||||
import { Reservations } from './Reservations.entity';
|
||||
import { RoadtripDayBoundaries } from './RoadtripDayBoundaries.entity';
|
||||
import { TourActivities } from './TourActivities.entity';
|
||||
import { TourStationVisits } from './TourStationVisits.entity';
|
||||
|
||||
export class DayAssignments {
|
||||
@@ -34,6 +35,7 @@ export class DayAssignments {
|
||||
reservations_collection = new Collection<Reservations>(this);
|
||||
roadtrip_day_boundaries_collection = new Collection<RoadtripDayBoundaries>(this);
|
||||
roadtrip_day_boundaries_collection1 = new Collection<RoadtripDayBoundaries>(this);
|
||||
tour_activities_collection = new Collection<TourActivities>(this);
|
||||
tour_station_visits_collection = new Collection<TourStationVisits>(this);
|
||||
}
|
||||
|
||||
@@ -64,6 +66,7 @@ export const DayAssignmentsSchema = defineEntity({
|
||||
reservations_collection: () => p.oneToMany(Reservations).mappedBy('assignment').hidden(),
|
||||
roadtrip_day_boundaries_collection: () => p.oneToMany(RoadtripDayBoundaries).mappedBy('fromAssignment').hidden(),
|
||||
roadtrip_day_boundaries_collection1: () => p.oneToMany(RoadtripDayBoundaries).mappedBy('toAssignment').hidden(),
|
||||
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('assignment').hidden(),
|
||||
tour_station_visits_collection: () => p.oneToMany(TourStationVisits).mappedBy('assignment').hidden(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,45 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { TourActivitiesRepository } from '../repositories/TourActivities.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { DayAssignments } from './DayAssignments.entity';
|
||||
import { Tours } from './Tours.entity';
|
||||
import { Users } from './Users.entity';
|
||||
|
||||
export class TourActivities {
|
||||
[EntityRepositoryType]?: TourActivitiesRepository;
|
||||
id!: number & Opt;
|
||||
place!: Ref<Tours>;
|
||||
place_id!: number;
|
||||
trackPlace!: Ref<Tours>;
|
||||
track_place_id!: number;
|
||||
assignment?: Ref<DayAssignments> | null;
|
||||
assignment_id?: number | null;
|
||||
assigned_by?: number | null;
|
||||
assigned_at!: string & Opt;
|
||||
assignedByRef?: Ref<Users> | null;
|
||||
}
|
||||
|
||||
export const TourActivitiesSchema = defineEntity({
|
||||
class: TourActivities,
|
||||
repository: () => TourActivitiesRepository,
|
||||
uniques: [
|
||||
{ properties: ['trackPlace'] },
|
||||
{
|
||||
name: 'idx_tour_activities_assignment',
|
||||
where: 'assignment_id IS NOT NULL',
|
||||
properties: ['assignment'],
|
||||
},
|
||||
],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
place: () => p.manyToOne(Tours).ref().name('place_id').deleteRule('cascade').hidden().index('idx_tour_activities_place'),
|
||||
place_id: p.integer().persist(false).index('idx_tour_activities_place'),
|
||||
trackPlace: () => p.manyToOne(Tours).ref().name('track_place_id').deleteRule('cascade').hidden(),
|
||||
track_place_id: p.integer().persist(false),
|
||||
assignment: () => p.manyToOne(DayAssignments).ref().nullable().hidden(),
|
||||
assignment_id: p.integer().nullable().persist(false),
|
||||
assigned_by: p.integer().nullable().persist(false).index('idx_tour_activities_assigned_by'),
|
||||
assigned_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
assignedByRef: () => p.manyToOne(Users).ref().joinColumn('assigned_by').nullable().hidden().index('idx_tour_activities_assigned_by'),
|
||||
},
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { ToursRepository } from '../repositories/Tours.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { Places } from './Places.entity';
|
||||
import { TourActivities } from './TourActivities.entity';
|
||||
import { TourChangeSteps } from './TourChangeSteps.entity';
|
||||
import { TourObstacleReviews } from './TourObstacleReviews.entity';
|
||||
import { TourSources } from './TourSources.entity';
|
||||
@@ -45,7 +47,11 @@ export class Tours {
|
||||
run_pace_seconds_per_km?: number | null;
|
||||
ski_discipline?: TToursSkiDiscipline | null;
|
||||
ski_technique?: TToursSkiTechnique | null;
|
||||
track_started_at?: string | null;
|
||||
track_ended_at?: string | null;
|
||||
tourTypeRef!: Ref<TourTypes>;
|
||||
tour_activities_collection = new Collection<TourActivities>(this);
|
||||
tour_activities_collection1 = new Collection<TourActivities>(this);
|
||||
tour_change_steps_collection = new Collection<TourChangeSteps>(this);
|
||||
tour_obstacle_reviews_collection = new Collection<TourObstacleReviews>(this);
|
||||
tour_sources: Ref<TourSources> | null = null;
|
||||
@@ -176,7 +182,11 @@ export const ToursSchema = defineEntity({
|
||||
run_pace_seconds_per_km: p.integer().nullable(),
|
||||
ski_discipline: p.enum(() => ToursSkiDiscipline).nullable(),
|
||||
ski_technique: p.enum(() => ToursSkiTechnique).nullable(),
|
||||
track_started_at: p.type(DbTimestampType).nullable(),
|
||||
track_ended_at: p.type(DbTimestampType).nullable(),
|
||||
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
|
||||
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('place').hidden(),
|
||||
tour_activities_collection1: () => p.oneToMany(TourActivities).mappedBy('trackPlace').hidden(),
|
||||
tour_change_steps_collection: () => p.oneToMany(TourChangeSteps).mappedBy('place').hidden(),
|
||||
tour_obstacle_reviews_collection: () => p.oneToMany(TourObstacleReviews).mappedBy('place').hidden(),
|
||||
tour_sources: () => p.oneToOne(TourSources).ref().mappedBy('place').hidden(),
|
||||
|
||||
@@ -51,6 +51,7 @@ import { ShareTokens } from './ShareTokens.entity';
|
||||
import { Tags } from './Tags.entity';
|
||||
import { TodoCategoryAssignees } from './TodoCategoryAssignees.entity';
|
||||
import { TodoItems } from './TodoItems.entity';
|
||||
import { TourActivities } from './TourActivities.entity';
|
||||
import { TourSources } from './TourSources.entity';
|
||||
import { TrekPhotos } from './TrekPhotos.entity';
|
||||
import { TripAlbumLinks } from './TripAlbumLinks.entity';
|
||||
@@ -178,6 +179,7 @@ export class Users {
|
||||
tags_collection = new Collection<Tags>(this);
|
||||
todo_category_assignees_collection = new Collection<TodoCategoryAssignees>(this);
|
||||
todo_items_collection = new Collection<TodoItems>(this);
|
||||
tour_activities_collection = new Collection<TourActivities>(this);
|
||||
tour_sources_collection = new Collection<TourSources>(this);
|
||||
trek_photos_collection = new Collection<TrekPhotos>(this);
|
||||
trip_album_links_collection = new Collection<TripAlbumLinks>(this);
|
||||
@@ -323,6 +325,7 @@ export const UsersSchema = defineEntity({
|
||||
tags_collection: () => p.oneToMany(Tags).mappedBy('user').hidden(),
|
||||
todo_category_assignees_collection: () => p.oneToMany(TodoCategoryAssignees).mappedBy('user').hidden(),
|
||||
todo_items_collection: () => p.oneToMany(TodoItems).mappedBy('assignedUser').hidden(),
|
||||
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('assignedByRef').hidden(),
|
||||
tour_sources_collection: () => p.oneToMany(TourSources).mappedBy('importedByRef').hidden(),
|
||||
trek_photos_collection: () => p.oneToMany(TrekPhotos).mappedBy('owner').hidden(),
|
||||
trip_album_links_collection: () => p.oneToMany(TripAlbumLinks).mappedBy('user').hidden(),
|
||||
|
||||
@@ -107,6 +107,7 @@ import { ShareTokensSchema } from './ShareTokens.entity';
|
||||
import { TagsSchema } from './Tags.entity';
|
||||
import { TodoCategoryAssigneesSchema } from './TodoCategoryAssignees.entity';
|
||||
import { TodoItemsSchema } from './TodoItems.entity';
|
||||
import { TourActivitiesSchema } from './TourActivities.entity';
|
||||
import { TourChangeStepsSchema } from './TourChangeSteps.entity';
|
||||
import { TourObstacleReviewsSchema } from './TourObstacleReviews.entity';
|
||||
import { TourSourcesSchema } from './TourSources.entity';
|
||||
@@ -253,6 +254,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
|
||||
TagsSchema,
|
||||
TodoCategoryAssigneesSchema,
|
||||
TodoItemsSchema,
|
||||
TourActivitiesSchema,
|
||||
TourChangeStepsSchema,
|
||||
TourObstacleReviewsSchema,
|
||||
TourSourcesSchema,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface TourActivitiesTable {
|
||||
id: InsertOptional<number>;
|
||||
place_id: number;
|
||||
track_place_id: number;
|
||||
assignment_id: InsertOptional<number | null>;
|
||||
assigned_by: InsertOptional<number | null>;
|
||||
assigned_at: InsertOptional<string>;
|
||||
}
|
||||
@@ -36,4 +36,6 @@ export interface ToursTable {
|
||||
run_pace_seconds_per_km: InsertOptional<number | null>;
|
||||
ski_discipline: InsertOptional<string | null>;
|
||||
ski_technique: InsertOptional<string | null>;
|
||||
track_started_at: InsertOptional<string | null>;
|
||||
track_ended_at: InsertOptional<string | null>;
|
||||
}
|
||||
|
||||
@@ -113,6 +113,7 @@ import type { ShareTokensTable } from './ShareTokens.table';
|
||||
import type { TagsTable } from './Tags.table';
|
||||
import type { TodoCategoryAssigneesTable } from './TodoCategoryAssignees.table';
|
||||
import type { TodoItemsTable } from './TodoItems.table';
|
||||
import type { TourActivitiesTable } from './TourActivities.table';
|
||||
import type { TourChangeStepsTable } from './TourChangeSteps.table';
|
||||
import type { TourObstacleReviewsTable } from './TourObstacleReviews.table';
|
||||
import type { TourSourcesTable } from './TourSources.table';
|
||||
@@ -265,6 +266,7 @@ export interface DB {
|
||||
tags: TagsTable;
|
||||
todo_category_assignees: TodoCategoryAssigneesTable;
|
||||
todo_items: TodoItemsTable;
|
||||
tour_activities: TourActivitiesTable;
|
||||
tour_change_steps: TourChangeStepsTable;
|
||||
tour_obstacle_reviews: TourObstacleReviewsTable;
|
||||
tour_sources: TourSourcesTable;
|
||||
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* ACT-01: a tour can be given the track it was actually done with. The
|
||||
* recording is a tour of the same trip that came in through the GPX import
|
||||
* (or from wanderer); `tour_activities` only points at it, so it keeps its own
|
||||
* name and provenance, and the planned tour keeps its line, measures and times
|
||||
* untouched. `assignment_id` is the execution, the day assignment of the tour
|
||||
* the recording belongs to; NULL for a tour done without a day. One recording
|
||||
* documents one tour (`track_place_id UNIQUE`) and an execution has one
|
||||
* recording (the partial unique index); an execution without a day is held to
|
||||
* one by the service, which also refuses a tour as its own recording. Taking
|
||||
* the tour off a day keeps the recording and only forgets the day; deleting
|
||||
* either tour takes the assignment with it.
|
||||
* `assigned_by` names who assigned it, kept as unknown when that account goes.
|
||||
*
|
||||
* Not to be confused with `tours.recorded_route_geometry`: that is the line an
|
||||
* import was planned over from, this is what was walked.
|
||||
*
|
||||
* `track_started_at` and `track_ended_at` are the first and last time on the
|
||||
* points of a track the GPX import read, NULL unless every point carried one;
|
||||
* every tour imported before stays NULL, its times unknown.
|
||||
*/
|
||||
export class Migration20200101045900_a_tour_keeps_the_track_it_was_done_with extends Migration {
|
||||
override name = 'Migration20200101045900_a_tour_keeps_the_track_it_was_done_with';
|
||||
|
||||
override up(): void {
|
||||
this.addSql('ALTER TABLE tours ADD COLUMN track_started_at DATETIME');
|
||||
this.addSql('ALTER TABLE tours ADD COLUMN track_ended_at DATETIME');
|
||||
this.addSql(`
|
||||
CREATE TABLE IF NOT EXISTS tour_activities (
|
||||
id INTEGER PRIMARY KEY,
|
||||
place_id INTEGER NOT NULL REFERENCES tours(place_id) ON DELETE CASCADE,
|
||||
track_place_id INTEGER NOT NULL UNIQUE REFERENCES tours(place_id) ON DELETE CASCADE,
|
||||
assignment_id INTEGER REFERENCES day_assignments(id) ON DELETE SET NULL,
|
||||
assigned_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
assigned_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
`);
|
||||
this.addSql('CREATE INDEX IF NOT EXISTS idx_tour_activities_place ON tour_activities(place_id)');
|
||||
this.addSql(
|
||||
'CREATE UNIQUE INDEX IF NOT EXISTS idx_tour_activities_assignment ON tour_activities(assignment_id) WHERE assignment_id IS NOT NULL',
|
||||
);
|
||||
this.addSql('CREATE INDEX IF NOT EXISTS idx_tour_activities_assigned_by ON tour_activities(assigned_by)');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import type { TourActivities } from '../entities/TourActivities.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type ActivitiesDB = Pick<DB, 'tour_activities' | 'tours' | 'places' | 'day_assignments'>;
|
||||
|
||||
/** One assignment of a recording to a tour, as the trip's tour list names it. */
|
||||
export interface TourActivityRefRow {
|
||||
id: number;
|
||||
place_id: number;
|
||||
track_place_id: number;
|
||||
assignment_id: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One assignment with what the detail shows of its recording: the name and
|
||||
* provenance it has in the trip, its line (the place's, or the line it kept
|
||||
* when it was planned over since), and the times the import read off it.
|
||||
*/
|
||||
export interface TourActivityRow extends TourActivityRefRow {
|
||||
day_id: number | null;
|
||||
assigned_at: string;
|
||||
track_name: string;
|
||||
track_origin: string;
|
||||
track_file_name: string | null;
|
||||
track_created_at: string | null;
|
||||
track_route_geometry: string | null;
|
||||
track_recorded_route_geometry: string | null;
|
||||
track_started_at: string | null;
|
||||
track_ended_at: string | null;
|
||||
}
|
||||
|
||||
/** What an assignment writes: the tour, its recording, the execution and who confirmed it. */
|
||||
interface TourActivityInsert {
|
||||
place_id: number;
|
||||
track_place_id: number;
|
||||
assignment_id: number | null;
|
||||
assigned_by: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `tour_activities` (ACT-01): the recordings assigned to the tours of a trip.
|
||||
* Every read here is scoped to one trip through both tours' places, so a row
|
||||
* never reaches across trips even if an id does. Kysely throughout: the reads
|
||||
* join the tours and places of both sides.
|
||||
*/
|
||||
export class TourActivitiesRepository extends TrekRepository<TourActivities> {
|
||||
private db() {
|
||||
return this.kysely<ActivitiesDB>();
|
||||
}
|
||||
|
||||
/** The assignments of one tour of the trip, with their recordings, oldest first. */
|
||||
async listForPlace(trip_id: number, place_id: number): Promise<TourActivityRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('tour_activities as a')
|
||||
.innerJoin('places as p', 'p.id', 'a.place_id')
|
||||
.innerJoin('places as tp', 'tp.id', 'a.track_place_id')
|
||||
.innerJoin('tours as tt', 'tt.place_id', 'a.track_place_id')
|
||||
.leftJoin('day_assignments as da', 'da.id', 'a.assignment_id')
|
||||
.select([
|
||||
'a.id as id',
|
||||
'a.place_id as place_id',
|
||||
'a.track_place_id as track_place_id',
|
||||
'a.assignment_id as assignment_id',
|
||||
'da.day_id as day_id',
|
||||
'a.assigned_at as assigned_at',
|
||||
'tp.name as track_name',
|
||||
'tt.origin as track_origin',
|
||||
'tt.origin_file_name as track_file_name',
|
||||
'tt.created_at as track_created_at',
|
||||
'tp.route_geometry as track_route_geometry',
|
||||
'tt.recorded_route_geometry as track_recorded_route_geometry',
|
||||
'tt.track_started_at as track_started_at',
|
||||
'tt.track_ended_at as track_ended_at',
|
||||
])
|
||||
.where('a.place_id', '=', place_id)
|
||||
.where('p.trip_id', '=', trip_id)
|
||||
.where('tp.trip_id', '=', trip_id)
|
||||
.orderBy('a.id', 'asc')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Every assignment between tours of the trip, for its tour list. */
|
||||
async listForTrip(trip_id: number): Promise<TourActivityRefRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('tour_activities as a')
|
||||
.innerJoin('places as p', 'p.id', 'a.place_id')
|
||||
.select(['a.id', 'a.place_id', 'a.track_place_id', 'a.assignment_id'])
|
||||
.where('p.trip_id', '=', trip_id)
|
||||
.orderBy('a.id', 'asc')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** The assignment a recording is part of, whichever tour it documents; undefined while it documents none. */
|
||||
async findByTrack(track_place_id: number): Promise<TourActivityRefRow | undefined> {
|
||||
return await this.db()
|
||||
.selectFrom('tour_activities')
|
||||
.select(['id', 'place_id', 'track_place_id', 'assignment_id'])
|
||||
.where('track_place_id', '=', track_place_id)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
/** Whether a tour has any recording assigned to it. */
|
||||
async hasActivities(place_id: number): Promise<boolean> {
|
||||
const row = await this.db()
|
||||
.selectFrom('tour_activities')
|
||||
.select('id')
|
||||
.where('place_id', '=', place_id)
|
||||
.executeTakeFirst();
|
||||
return !!row;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clears the way for a new assignment of `track_place_id` to this execution
|
||||
* of the tour: the recording the execution had, and the execution this
|
||||
* recording had on the same tour. Inside the caller's transaction, before
|
||||
* {@link insertActivity}.
|
||||
*/
|
||||
async clearFor(place_id: number, track_place_id: number, assignment_id: number | null): Promise<void> {
|
||||
await this.db()
|
||||
.deleteFrom('tour_activities')
|
||||
.where('place_id', '=', place_id)
|
||||
.where((eb) =>
|
||||
eb.or([
|
||||
assignment_id === null ? eb('assignment_id', 'is', null) : eb('assignment_id', '=', assignment_id),
|
||||
eb('track_place_id', '=', track_place_id),
|
||||
]),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Writes one assignment and answers its id. */
|
||||
async insertActivity(input: TourActivityInsert): Promise<number> {
|
||||
const row = await this.db().insertInto('tour_activities').values(input).returning('id').executeTakeFirstOrThrow();
|
||||
return row.id;
|
||||
}
|
||||
|
||||
/** Removes one assignment of this tour; answers whether there was one. */
|
||||
async removeFromPlace(place_id: number, id: number): Promise<boolean> {
|
||||
const result = await this.db()
|
||||
.deleteFrom('tour_activities')
|
||||
.where('id', '=', id)
|
||||
.where('place_id', '=', place_id)
|
||||
.executeTakeFirst();
|
||||
return Number(result.numDeletedRows ?? 0) > 0;
|
||||
}
|
||||
}
|
||||
@@ -63,6 +63,9 @@ export interface TourListRow {
|
||||
revision: number;
|
||||
/** MF-08: a hike's routing preferences, still JSON text. */
|
||||
hiking_preferences: string | null;
|
||||
/** ACT-01: the first and last time on an imported track's points; NULL without times. */
|
||||
track_started_at: string | null;
|
||||
track_ended_at: string | null;
|
||||
}
|
||||
|
||||
/** LIB-02: a tour of another trip as the take-over list reads it, with the trip it is in. */
|
||||
@@ -119,6 +122,8 @@ export interface TourRow {
|
||||
run_pace_seconds_per_km: number | null;
|
||||
ski_discipline: string | null;
|
||||
ski_technique: string | null;
|
||||
track_started_at: string | null;
|
||||
track_ended_at: string | null;
|
||||
}
|
||||
const _tourRowKeys: AssertRowKeys<TourRow, Tours> = true;
|
||||
|
||||
@@ -299,6 +304,8 @@ export class ToursRepository extends TrekRepository<Tours> {
|
||||
't.track_marks as track_marks',
|
||||
't.revision as revision',
|
||||
't.hiking_preferences as hiking_preferences',
|
||||
't.track_started_at as track_started_at',
|
||||
't.track_ended_at as track_ended_at',
|
||||
eb('t.recorded_route_geometry', 'is not', null).as('has_recorded_track'),
|
||||
eb('p.route_geometry', 'is', null).as('route_missing'),
|
||||
eb
|
||||
@@ -637,6 +644,9 @@ export class ToursRepository extends TrekRepository<Tours> {
|
||||
track_marks?: string | null;
|
||||
taken_over_from_trip_title?: string | null;
|
||||
taken_over_from_tour_name?: string | null;
|
||||
/** ACT-01: the times the import read off the track's points, canonical DATETIME text. */
|
||||
track_started_at?: string | null;
|
||||
track_ended_at?: string | null;
|
||||
},
|
||||
): Promise<void> {
|
||||
await this.insert({
|
||||
@@ -670,6 +680,8 @@ export class ToursRepository extends TrekRepository<Tours> {
|
||||
hiking_preferences: input.hiking_preferences ?? null,
|
||||
taken_over_from_trip_title: input.taken_over_from_trip_title ?? null,
|
||||
taken_over_from_tour_name: input.taken_over_from_tour_name ?? null,
|
||||
track_started_at: input.track_started_at ?? null,
|
||||
track_ended_at: input.track_ended_at ?? null,
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -13,6 +13,11 @@ export interface PreparedGpxPlace {
|
||||
lng: number;
|
||||
description: string | null;
|
||||
routeGeometry?: string;
|
||||
/**
|
||||
* ACT-01: when a track was recorded, ISO 8601 in UTC: its first and last
|
||||
* point's time, only when every point carries one. Never on a route.
|
||||
*/
|
||||
trackTimes?: { startedAt: string; endedAt: string };
|
||||
}
|
||||
|
||||
export interface GpxImportOptions {
|
||||
|
||||
@@ -208,6 +208,29 @@ export function gpxFilename(tripTitle: string, fallback = 'trip'): string {
|
||||
return `${[...base].slice(0, 60).join('') || fallback}.gpx`;
|
||||
}
|
||||
|
||||
/** A time written with its zone (`Z` or an offset); one without is local to an unknown clock and reads as none. */
|
||||
const ZONED_TIME = /(?:Z|[+-]\d{2}:?\d{2})$/i;
|
||||
|
||||
/**
|
||||
* ACT-01: when a track was recorded, from the times on its points: the first
|
||||
* and the last, only when every point carries one with its zone and they never
|
||||
* run backwards, so a track drawn on a map or stitched from pieces never reads
|
||||
* as recorded. Undefined otherwise.
|
||||
*/
|
||||
export function trackTimeSpan(times: readonly unknown[]): { startedAt: string; endedAt: string } | undefined {
|
||||
let first: number | undefined;
|
||||
let last = Number.NEGATIVE_INFINITY;
|
||||
for (const raw of times) {
|
||||
const text = typeof raw === 'string' ? raw.trim() : '';
|
||||
const at = ZONED_TIME.test(text) ? Date.parse(text) : Number.NaN;
|
||||
if (!Number.isFinite(at) || at < last) return undefined;
|
||||
first ??= at;
|
||||
last = at;
|
||||
}
|
||||
if (first === undefined || last <= first) return undefined;
|
||||
return { startedAt: new Date(first).toISOString(), endedAt: new Date(last).toISOString() };
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a GPX file into the places an import would create, without writing
|
||||
* anything. Waypoints become places, each route and each track becomes one
|
||||
@@ -282,12 +305,14 @@ function prepareGpxRows(fileBuffer: Buffer, opts: GpxImportOptions = {}): Prepar
|
||||
if (importTracks) {
|
||||
for (const trk of gpx.trk ?? []) {
|
||||
const trackPoints: { lat: number; lng: number; ele: number | null }[] = [];
|
||||
const times: unknown[] = [];
|
||||
for (const seg of trk.trkseg ?? []) {
|
||||
for (const pt of seg.trkpt ?? []) {
|
||||
const lat = num(pt['@_lat']);
|
||||
const lng = num(pt['@_lon']);
|
||||
if (lat === null || lng === null) continue;
|
||||
trackPoints.push({ lat, lng, ele: num(pt.ele) });
|
||||
times.push(pt.time);
|
||||
}
|
||||
}
|
||||
if (trackPoints.length === 0) continue;
|
||||
@@ -300,6 +325,7 @@ function prepareGpxRows(fileBuffer: Buffer, opts: GpxImportOptions = {}): Prepar
|
||||
name: geoName(str(trk.name), 'GPX Track'),
|
||||
description: str(trk.desc),
|
||||
routeGeometry: JSON.stringify(routeGeometry),
|
||||
...withTrackTimes(trackTimeSpan(times)),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -307,6 +333,11 @@ function prepareGpxRows(fileBuffer: Buffer, opts: GpxImportOptions = {}): Prepar
|
||||
return waypoints;
|
||||
}
|
||||
|
||||
/** The times as a row carries them: left out, not undefined, when the track has none. */
|
||||
function withTrackTimes(span: ReturnType<typeof trackTimeSpan>): Pick<PreparedGpxPlace, 'trackTimes'> {
|
||||
return span ? { trackTimes: span } : {};
|
||||
}
|
||||
|
||||
/** The GPX source: a trip file in, a trip file out. */
|
||||
@Injectable()
|
||||
export class GpxProvider {
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { tourActivityAssignRequestSchema } from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
|
||||
export class TourActivityAssignDto extends createZodDto(tourActivityAssignRequestSchema) {}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { TourActivityAssignDto } from './dto/tour-activity.dto';
|
||||
import { TourActivitiesService } from './tour-activities.service';
|
||||
import { Body, Controller, Delete, Headers, Param, ParseIntPipe, Put, UseGuards } from '@nestjs/common';
|
||||
import { tourDetailResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* ACT-01: the recorded tracks of a tour. PUT
|
||||
* /api/trips/:tripId/tours/:placeId/activities assigns a recording of the trip
|
||||
* to one execution of the tour (a day it is on, or none); DELETE
|
||||
* .../activities/:activityId takes it off again. Both answer the tour as its
|
||||
* detail reads it and need 'place_edit', like every other change of a tour.
|
||||
* Reading them is the tour's detail.
|
||||
*/
|
||||
@Controller('api/trips/:tripId/tours/:placeId/activities')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
|
||||
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
|
||||
export class TourActivitiesController {
|
||||
constructor(private readonly activities: TourActivitiesService) {}
|
||||
|
||||
@RequirePermission('place_edit')
|
||||
@Put()
|
||||
@ResponseContract(tourDetailResponseSchema)
|
||||
async assign(
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('placeId') placeId: string,
|
||||
@Body() body: TourActivityAssignDto,
|
||||
@CurrentUser() user: User,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return await this.activities.assign(tripId, placeId, body, user.id, socketId);
|
||||
}
|
||||
|
||||
@RequirePermission('place_edit')
|
||||
@Delete(':activityId')
|
||||
@ResponseContract(tourDetailResponseSchema)
|
||||
async unassign(
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('placeId') placeId: string,
|
||||
@Param('activityId', ParseIntPipe) activityId: number,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return await this.activities.unassign(tripId, placeId, activityId, socketId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
/**
|
||||
* ACT-01: the pure half of a tour's recorded tracks. What a recording measures
|
||||
* is read from its own line every time it is asked, so the answer follows the
|
||||
* recording and never touches the plan; what an assignment row says about the
|
||||
* two tours it joins is mapped here for the list and the detail.
|
||||
*/
|
||||
import type { TourActivityRefRow, TourActivityRow } from '../../db/repositories/TourActivities.repository';
|
||||
import { dbNow, parseDbTimestamp, utcSuffix, type DbTimestamp } from '../../db/types';
|
||||
import type { PreparedGpxPlace } from '../place-import/place-import.types';
|
||||
import { computeTourMetrics, parseRouteGeometry } from './tours.helpers';
|
||||
import type { TourActivity, TourListItem, TourOrigin } from '@trek/shared';
|
||||
|
||||
/** Minutes from the first to the last time of a track, pauses included; null unless both are there and in order. */
|
||||
export function elapsedMinutes(startedAt: string | null, endedAt: string | null): number | null {
|
||||
const start = parseDbTimestamp(startedAt);
|
||||
const end = parseDbTimestamp(endedAt);
|
||||
if (!start || !end || end.getTime() <= start.getTime()) return null;
|
||||
return Math.round((end.getTime() - start.getTime()) / 60_000);
|
||||
}
|
||||
|
||||
/**
|
||||
* One assignment as the detail answers it. The recording's line is the one it
|
||||
* kept when someone planned over it since, otherwise its place's own: either
|
||||
* way the line it was recorded with, never a plan.
|
||||
*/
|
||||
export function toActivity(row: TourActivityRow): TourActivity {
|
||||
const geometry = parseRouteGeometry(row.track_recorded_route_geometry ?? row.track_route_geometry);
|
||||
const metrics = computeTourMetrics(geometry);
|
||||
return {
|
||||
id: row.id,
|
||||
assignment_id: row.assignment_id,
|
||||
day_id: row.day_id,
|
||||
assigned_at: utcSuffix(row.assigned_at),
|
||||
track: {
|
||||
place_id: row.track_place_id,
|
||||
name: row.track_name,
|
||||
origin: row.track_origin as TourOrigin,
|
||||
file_name: row.track_file_name,
|
||||
imported_at: utcSuffix(row.track_created_at),
|
||||
},
|
||||
metrics: {
|
||||
distance_km: geometry.length >= 2 ? metrics.distanceKm : null,
|
||||
elevation_gain_m: metrics.elevationGainM,
|
||||
elevation_loss_m: metrics.elevationLossM,
|
||||
started_at: utcSuffix(row.track_started_at),
|
||||
ended_at: utcSuffix(row.track_ended_at),
|
||||
elapsed_minutes: elapsedMinutes(row.track_started_at, row.track_ended_at),
|
||||
point_count: geometry.length,
|
||||
},
|
||||
geometry,
|
||||
};
|
||||
}
|
||||
|
||||
/** An assignment as an MCP tool answers it: everything but the recorded line, which runs to thousands of points. */
|
||||
export function withoutLine({ geometry: _line, ...activity }: TourActivity): Omit<TourActivity, 'geometry'> {
|
||||
return activity;
|
||||
}
|
||||
|
||||
/** What the list says of a tour's assignments: the recordings it has, and the tour it documents itself. */
|
||||
export function activityFacts(
|
||||
placeId: number,
|
||||
refs: readonly TourActivityRefRow[],
|
||||
): Pick<TourListItem, 'activity_tracks' | 'activity_of'> {
|
||||
return {
|
||||
activity_tracks: refs
|
||||
.filter((ref) => ref.place_id === placeId)
|
||||
.map(({ id, track_place_id, assignment_id }) => ({ id, track_place_id, assignment_id })),
|
||||
activity_of: refs.find((ref) => ref.track_place_id === placeId)?.place_id ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The times an import stores for a track, as the DATETIME columns hold them; NULL without. */
|
||||
function storedTimes(row: PreparedGpxPlace | undefined): { started: DbTimestamp | null; ended: DbTimestamp | null } {
|
||||
const times = row?.trackTimes;
|
||||
return times
|
||||
? { started: dbNow(new Date(times.startedAt)), ended: dbNow(new Date(times.endedAt)) }
|
||||
: { started: null, ended: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* The times of each imported place, found by the row it was made from: the
|
||||
* same name and start, the first row not taken yet. The import skips a
|
||||
* duplicate, so the places are not the rows one by one.
|
||||
*/
|
||||
export function trackTimesFor(
|
||||
rows: readonly PreparedGpxPlace[],
|
||||
places: ReadonlyArray<{ id: number; name: string; lat: number | null; lng: number | null }>,
|
||||
): Map<number, { started: DbTimestamp | null; ended: DbTimestamp | null }> {
|
||||
const taken = new Set<number>();
|
||||
const byPlace = new Map<number, { started: DbTimestamp | null; ended: DbTimestamp | null }>();
|
||||
for (const place of places) {
|
||||
const index = rows.findIndex(
|
||||
(row, at) => !taken.has(at) && row.name === place.name && row.lat === place.lat && row.lng === place.lng,
|
||||
);
|
||||
if (index >= 0) taken.add(index);
|
||||
byPlace.set(place.id, storedTimes(rows[index]));
|
||||
}
|
||||
return byPlace;
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
errorResult,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { withoutLine } from './tour-activities.helpers';
|
||||
import { TourActivitiesService } from './tour-activities.service';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
import {
|
||||
idSchema,
|
||||
tourActivityAssignRequestSchema,
|
||||
type TourActivityAssignRequest,
|
||||
type TourDetailResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
const assign = tourActivityAssignRequestSchema.shape;
|
||||
|
||||
/** The tour after the change, its recordings without their lines. */
|
||||
function answer(detail: TourDetailResponse) {
|
||||
return { ...detail, activities: (detail.activities ?? []).map(withoutLine) };
|
||||
}
|
||||
|
||||
/**
|
||||
* ACT-01: assigning a recorded track to a tour and taking it off, over the
|
||||
* same service and the same checks as REST: access to the trip, then
|
||||
* 'place_edit' on it. What a tour's recordings measure is read with
|
||||
* get_tour_plan.
|
||||
*/
|
||||
@McpController()
|
||||
export class TourActivitiesMcp {
|
||||
constructor(
|
||||
private readonly activities: TourActivitiesService,
|
||||
private readonly access: TripAccessService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
/** The checks every tool here runs first: the trip is the user's to see, and theirs to change tours in. */
|
||||
private async refusal(tripId: number, userId: number) {
|
||||
if (!(await this.access.findAccessible(tripId, userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, userId))) return permissionDenied();
|
||||
return null;
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'assign_tour_track',
|
||||
description:
|
||||
'Assign a recorded track to a saved tour, as the way the tour was actually done, once the user has chosen the track and confirmed it. The track is another tour of the same trip that came in through the GPX import or from wanderer and was not planned over (list_tours: origin gpx or wanderer, has_waypoints false); it keeps its own name and source. assignment_id is the execution, one of the day assignments of the tour (find_tours_for_day and get_tour_plan show its days), or null for none; an execution that already has a track gets this one instead, and the track moves there if it was on another execution of the same tour. A track documents one tour only. The planned line, measures and times of the tour stay exactly as they are; what the recording measures (distance, ascent, descent, and the time from its first to its last point, only where the file carried times) is answered under activities and read again with get_tour_plan. Never assign a track the user did not pick.',
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
placeId: idSchema.describe('The place id of the planned tour, as list_tours gives it'),
|
||||
track_place_id: assign.track_place_id.describe('The place id of the recorded track, a tour of the same trip'),
|
||||
assignment_id: assign.assignment_id.describe('The day assignment of the tour it was done on, or null'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async assignTourTrack(
|
||||
{ tripId, placeId, ...body }: { tripId: number; placeId: number } & TourActivityAssignRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
const refusal = await this.refusal(tripId, ctx.userId);
|
||||
if (refusal) return refusal;
|
||||
try {
|
||||
return ok(answer(await this.activities.assign(String(tripId), String(placeId), body, ctx.userId)));
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NotFoundException) return errorResult('Tour or recorded track not found.');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'unassign_tour_track',
|
||||
description:
|
||||
'Take a recorded track off a saved tour again, by the id get_tour_plan lists it under activities. The track stays in the trip as the import it is, and nothing of the tour changes.',
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
placeId: idSchema.describe('The place id of the planned tour, as list_tours gives it'),
|
||||
activityId: idSchema.describe('The id of the assignment, from get_tour_plan activities'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
})
|
||||
async unassignTourTrack(
|
||||
{ tripId, placeId, activityId }: { tripId: number; placeId: number; activityId: number },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
const refusal = await this.refusal(tripId, ctx.userId);
|
||||
if (refusal) return refusal;
|
||||
try {
|
||||
return ok(answer(await this.activities.unassign(String(tripId), String(placeId), activityId)));
|
||||
} catch (err: unknown) {
|
||||
if (err instanceof NotFoundException) return errorResult('Recorded track not found.');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { TourActivities } from '../../db/entities/TourActivities.entity';
|
||||
import { TourStationVisits } from '../../db/entities/TourStationVisits.entity';
|
||||
import { Tours } from '../../db/entities/Tours.entity';
|
||||
import type { TourActivitiesRepository } from '../../db/repositories/TourActivities.repository';
|
||||
import type { TourStationVisitsRepository } from '../../db/repositories/TourStationVisits.repository';
|
||||
import type { ToursRepository } from '../../db/repositories/Tours.repository';
|
||||
import { DomainError } from '../common/domain-error';
|
||||
import { toRowId } from '../common/row-id';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { ToursService } from './tours.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable, NotFoundException } from '@nestjs/common';
|
||||
import type { TourActivityAssignRequest, TourActivityRefusal, TourDetailResponse } from '@trek/shared';
|
||||
|
||||
/** A refusal with its code in the body, so the app can say what went wrong in its own words. */
|
||||
function refused(status: 400 | 409, code: TourActivityRefusal, message: string): DomainError {
|
||||
return new DomainError(status, message, { code, details: { code } });
|
||||
}
|
||||
|
||||
/**
|
||||
* ACT-01: assigning a recorded track to a tour, and taking it off again. The
|
||||
* recording is a tour of the same trip that still holds the line it was
|
||||
* recorded with; the assignment points at it for one execution of the tour (a
|
||||
* day it is on, or none) and changes nothing of either tour's plan, so it does
|
||||
* not raise the tour's revision either: an open draft of the plan stays valid.
|
||||
* Every check runs inside the write, so a recording assigned or a day removed
|
||||
* meanwhile is refused rather than written over, and a refused write leaves
|
||||
* everything as it was. Both surfaces (REST and MCP) call these two methods.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TourActivitiesService {
|
||||
constructor(
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly tours: ToursService,
|
||||
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
|
||||
@InjectRepository(TourActivities) private readonly activitiesRepo: TourActivitiesRepository,
|
||||
@InjectRepository(TourStationVisits) private readonly visitsRepo: TourStationVisitsRepository,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The recording becomes the track this execution of the tour was done with,
|
||||
* in place of the one it had; a recording already on another execution of
|
||||
* the same tour moves here. Answers the tour as the detail reads it.
|
||||
*/
|
||||
async assign(
|
||||
tripId: string,
|
||||
placeId: string,
|
||||
input: TourActivityAssignRequest,
|
||||
userId: number,
|
||||
socketId?: string,
|
||||
): Promise<TourDetailResponse> {
|
||||
const { tid, pid } = this.ids(tripId, placeId);
|
||||
const trackId = input.track_place_id;
|
||||
await this.uow.transactional(async () => {
|
||||
if (!(await this.toursRepo.findInTrip(tid, pid))) throw new NotFoundException('Tour not found');
|
||||
await this.checkTrack(tid, pid, trackId);
|
||||
await this.checkAssignment(tid, pid, input.assignment_id);
|
||||
await this.activitiesRepo.clearFor(pid, trackId, input.assignment_id);
|
||||
await this.activitiesRepo.insertActivity({
|
||||
place_id: pid,
|
||||
track_place_id: trackId,
|
||||
assignment_id: input.assignment_id,
|
||||
assigned_by: userId,
|
||||
});
|
||||
});
|
||||
this.tours.broadcastToursChanged(tripId, [pid, trackId], socketId);
|
||||
return await this.tours.getTour(tripId, placeId);
|
||||
}
|
||||
|
||||
/** The recording is no longer this tour's; it stays in the trip as the import it is. */
|
||||
async unassign(tripId: string, placeId: string, activityId: number, socketId?: string): Promise<TourDetailResponse> {
|
||||
const { tid, pid } = this.ids(tripId, placeId);
|
||||
const activity = (await this.activitiesRepo.listForPlace(tid, pid)).find((row) => row.id === activityId);
|
||||
if (!activity || !(await this.activitiesRepo.removeFromPlace(pid, activityId))) {
|
||||
throw new NotFoundException('Recorded track not found');
|
||||
}
|
||||
this.tours.broadcastToursChanged(tripId, [pid, activity.track_place_id], socketId);
|
||||
return await this.tours.getTour(tripId, placeId);
|
||||
}
|
||||
|
||||
private ids(tripId: string, placeId: string): { tid: number; pid: number } {
|
||||
const tid = toRowId(tripId);
|
||||
const pid = toRowId(placeId);
|
||||
if (tid === null || pid === null) throw new NotFoundException('Tour not found');
|
||||
return { tid, pid };
|
||||
}
|
||||
|
||||
/**
|
||||
* What may be assigned: a tour of this trip that came in as a recording and
|
||||
* still is one, that is neither this tour nor one with recordings of its own,
|
||||
* and that documents no other tour; and this tour must not be the recording
|
||||
* of another. A tour of another trip reads as missing, as any id would.
|
||||
*/
|
||||
private async checkTrack(tripId: number, placeId: number, trackId: number): Promise<void> {
|
||||
if (trackId === placeId) throw refused(400, 'activity_track_is_tour', 'A tour cannot be its own recorded track');
|
||||
const track = await this.toursRepo.findInTrip(tripId, trackId);
|
||||
if (!track) throw new NotFoundException('Recorded track not found');
|
||||
if (track.origin === 'trek' || track.has_waypoints) {
|
||||
throw refused(400, 'activity_track_not_recorded', 'Only an import that was not planned over can be assigned');
|
||||
}
|
||||
if (await this.activitiesRepo.hasActivities(trackId)) {
|
||||
throw refused(400, 'activity_track_is_tour', 'A tour with recorded tracks of its own cannot be one');
|
||||
}
|
||||
const used = await this.activitiesRepo.findByTrack(trackId);
|
||||
if (used && used.place_id !== placeId) {
|
||||
throw refused(409, 'activity_track_in_use', 'This recorded track is assigned to another tour');
|
||||
}
|
||||
if (await this.activitiesRepo.findByTrack(placeId)) {
|
||||
throw refused(400, 'activity_tour_is_track', 'A recorded track of another tour cannot have recorded tracks');
|
||||
}
|
||||
}
|
||||
|
||||
/** The execution, when one is named, is a day assignment of this very tour in this trip. */
|
||||
private async checkAssignment(tripId: number, placeId: number, assignmentId: number | null): Promise<void> {
|
||||
if (assignmentId === null) return;
|
||||
const assignment = await this.visitsRepo.assignmentInTrip(assignmentId, tripId);
|
||||
if (assignment?.place_id !== placeId) {
|
||||
throw refused(400, 'activity_assignment_not_of_tour', 'The day is not one this tour is on');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, errorResult, ok, type M
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { withoutLine } from './tour-activities.helpers';
|
||||
import { TourGpxExportService } from './tour-gpx-export.service';
|
||||
import { derivedFields, planLegs, planLine, planPoints, planRun } from './tour-plan-read';
|
||||
import { TourPoiSearchService } from './tour-poi-search.service';
|
||||
@@ -41,8 +42,9 @@ interface PlanRead {
|
||||
/**
|
||||
* MCP-T01: the plan of one saved tour as an assistant reads it: the detail the
|
||||
* app reads, its days, the legs between its control points, its saved line in
|
||||
* brief, for a city walk the visits of the day asked for, and the fields that
|
||||
* were worked out on reading rather than stored.
|
||||
* brief, the recorded tracks assigned to it (ACT-01), for a city walk the
|
||||
* visits of the day asked for, and the fields that were worked out on reading
|
||||
* rather than stored.
|
||||
*/
|
||||
function planOf({ detail, days, line, names }: PlanRead, run: WalkProgress | null) {
|
||||
const named = detail.waypoints.map((point) =>
|
||||
@@ -57,6 +59,8 @@ function planOf({ detail, days, line, names }: PlanRead, run: WalkProgress | nul
|
||||
...detail,
|
||||
tour: withDays(detail.tour, days),
|
||||
waypoints: planPoints(detail.tour.tour_type, named, run),
|
||||
// ACT-01: the recorded tracks assigned to the tour, with their values and without their lines.
|
||||
activities: (detail.activities ?? []).map(withoutLine),
|
||||
legs: planLegs(detail.waypoints, { recorded }),
|
||||
line: saved,
|
||||
...(isWalk ? { run: run ? planRun(run) : null } : {}),
|
||||
@@ -97,7 +101,7 @@ export class ToursMcp {
|
||||
@Tool({
|
||||
name: 'list_tours',
|
||||
description:
|
||||
'List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours, rides on horseback and ski tracks planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, horse for a ride, or ski for a ski track; a ride has no riding time worked out, so its duration is null), 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) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the winter label of a hike (winter_activity: winter_hike or snowshoe, null for none; a label the travellers chose, while the route and its time are planned as for any hike, never a statement that a way can be walked in winter or anything about snow or avalanches), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the classification of a ski track (ski_discipline: alpine, snowboard, cross_country or touring for ski touring; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a ski track is imported from a GPX file and kept as recorded, never routed, its distance and heights come from the file, it has no ski time worked out, and nothing in it says anything about snow, avalanches or whether a run or trail is open), 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), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), the revision (raised by every saved change of the tour), and the days of the trip each tour is on.',
|
||||
'List the saved tours of a trip (hikes, city walks, runs, bike tours, paddle tours, rides on horseback and ski tracks planned or imported in the Tours addon): name, type (hike, walk for a city walk, run, bike, kayak for a paddle tour, horse for a ride, or ski for a ski track; a ride has no riding time worked out, so its duration is null), 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) and its route choices (hiking_preferences: avoid_climbs for gentler ways, avoid_steps, avoid_ferries; weightings, never a grade of the path), the profile a bike tour is routed for (bike_profile: touring for paved cycle paths and quiet roads, road for asphalt, gravel for gravel and farm tracks, mtb for rough tracks; a routing preference, never a statement that a way is rideable or safe), the winter label of a hike (winter_activity: winter_hike or snowshoe, null for none; a label the travellers chose, while the route and its time are planned as for any hike, never a statement that a way can be walked in winter or anything about snow or avalanches), the profile and pace of a run (run_profile: running for runnable, mostly paved ways in towns and parks, trail for forest tracks and natural paths up to mountain paths (T2); a routing preference, never a statement that a way can be run; run_pace_seconds_per_km, the pace the runners planned with, null while they entered none; its duration is the distance at that pace and nothing else, no climb, descent or difficulty is in it, and it is a plan, never a recorded time), the classification of a ski track (ski_discipline: alpine, snowboard, cross_country or touring for ski touring; ski_technique for cross-country only: classic, skating or unknown when the travellers did not know; a ski track is imported from a GPX file and kept as recorded, never routed, its distance and heights come from the file, it has no ski time worked out, and nothing in it says anything about snow, avalanches or whether a run or trail is open), 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), for a city walk the number of its stations (station_count: its points without the shaping points and the way back of a loop), their stays as far as entered (station_stay_minutes) and how many have none (station_stays_unknown), whether a tour still waits for its way to be planned (route_pending: saved with its points only, so its distance and walking time stay null until someone opens it in the planner and saves it), the revision (raised by every saved change of the tour), the recorded tracks assigned to a tour (activity_tracks) and, for a recorded track, the tour it documents (activity_of), when an imported track was recorded (track_started_at, track_ended_at; null when the file carried no times), and the days of the trip each tour is on.',
|
||||
inputSchema: { tripId: idSchema },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.TOURS),
|
||||
@@ -112,7 +116,7 @@ export class ToursMcp {
|
||||
@Tool({
|
||||
name: 'get_tour_plan',
|
||||
description:
|
||||
'Read one saved tour of a trip as the travellers saved it: its facts (tour: place_id, name, tour_type, distance, heights and walking time as stored, null when not known; the routing options as list_tours describes them; revision, raised by every saved change; the days it is on), its ordered control points (start, via and end, each with its sequence and its key, the same across saves; an import without its own shows the two ends of its track), where it came from (provenance) and its legs. Drafts in a browser are never visible: only saved tours exist here, and reading changes nothing, not the tour, its revision nor any visit. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. legs lists every step from one control point to the next (from_sequence, to_sequence, from_key, to_key) with its kind: routed (planned by the router), track (part of a recorded line, an import without control points of its own, which no router planned), ferrata (follows a via ferrata, name gives it), free (drawn by hand and checked by nothing), portage (a paddle tour carried over land) or horse_route (a ride only: a section of a signposted horse route from OpenStreetMap in the direction the rider chose; the fixed_leg of its control point says signposted, with or against the direction the route is signposted in, null where it is not signposted one way, and access, the metres of each horse=* value its ways carried when it was taken, unknown where untagged; being on a horse route is no permission to ride it); length_km is the length of the line a fixed leg keeps and null for a routed or track leg, whose length is not stored apart. line gives the saved line in brief: point_count, has_heights and a preview thinned to 200 points; null while the tour waits for its way to be planned. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. A city walk (tour_type walk) has stations for control points, shaping points and the way back of a loop aside, each with every field spelled out: key (the visits of a day are kept by it), name, stay_minutes (the stay in minutes; 0 for a point only passed through, null when not known), importance (optional or must; null for a normal station), protected (true for a station any change you propose has to keep where it is: neither removed, replaced nor moved; the travellers can still edit it themselves in the app), opening_hours (as OpenStreetMap writes them; a hint to check, never a promise; null when none is known) and visit_status. Visits belong to one day of the walk: name that day with dayId (one of its days) to read the status of each station that day (planned, visited or skipped) and run (the day, its assignment and what is still open); without dayId visit_status and run are null. A station visited or skipped that day is done: do not ask about it again or move it to another day. dayId is for a city walk only. derived names the fields worked out on reading rather than stored with the tour: never present them as saved facts.',
|
||||
'Read one saved tour of a trip as the travellers saved it: its facts (tour: place_id, name, tour_type, distance, heights and walking time as stored, null when not known; the routing options as list_tours describes them; revision, raised by every saved change; the days it is on), its ordered control points (start, via and end, each with its sequence and its key, the same across saves; an import without its own shows the two ends of its track), where it came from (provenance) and its legs. Drafts in a browser are never visible: only saved tours exist here, and reading changes nothing, not the tour, its revision nor any visit. A control point with linked_place_id stands for that place of the trip (linked_place_name names it); it keeps its own coordinates. legs lists every step from one control point to the next (from_sequence, to_sequence, from_key, to_key) with its kind: routed (planned by the router), track (part of a recorded line, an import without control points of its own, which no router planned), ferrata (follows a via ferrata, name gives it), free (drawn by hand and checked by nothing), portage (a paddle tour carried over land) or horse_route (a ride only: a section of a signposted horse route from OpenStreetMap in the direction the rider chose; the fixed_leg of its control point says signposted, with or against the direction the route is signposted in, null where it is not signposted one way, and access, the metres of each horse=* value its ways carried when it was taken, unknown where untagged; being on a horse route is no permission to ride it); length_km is the length of the line a fixed leg keeps and null for a routed or track leg, whose length is not stored apart. line gives the saved line in brief: point_count, has_heights and a preview thinned to 200 points; null while the tour waits for its way to be planned. A paddle tour also carries its obstacle checklist (obstacle_check): the obstacles of the OpenStreetMap data along its line, the decisions the travellers made about them and their own portages and locks; a planning aid, never a safety or legal clearance. A city walk (tour_type walk) has stations for control points, shaping points and the way back of a loop aside, each with every field spelled out: key (the visits of a day are kept by it), name, stay_minutes (the stay in minutes; 0 for a point only passed through, null when not known), importance (optional or must; null for a normal station), protected (true for a station any change you propose has to keep where it is: neither removed, replaced nor moved; the travellers can still edit it themselves in the app), opening_hours (as OpenStreetMap writes them; a hint to check, never a promise; null when none is known) and visit_status. Visits belong to one day of the walk: name that day with dayId (one of its days) to read the status of each station that day (planned, visited or skipped) and run (the day, its assignment and what is still open); without dayId visit_status and run are null. A station visited or skipped that day is done: do not ask about it again or move it to another day. dayId is for a city walk only. The recorded tracks assigned to the tour (activities, ACT-01) each name their execution (assignment_id and day_id, null for none), the recording (track: its tour in the trip, origin, file name, when it came in) and what the recording measures (metrics: distance_km, elevation_gain_m and elevation_loss_m, null without heights; started_at, ended_at and elapsed_minutes from the first to the last time on its points, pauses included, null when the file carried no times, never estimated); these are the values of the recording, the planned values of the tour stay apart and unchanged. derived names the fields worked out on reading rather than stored with the tour: never present them as saved facts.',
|
||||
inputSchema: {
|
||||
tripId: idSchema,
|
||||
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { TourActivities } from '../../db/entities/TourActivities.entity';
|
||||
import { TourChangeSteps } from '../../db/entities/TourChangeSteps.entity';
|
||||
import { TourObstacleReviews } from '../../db/entities/TourObstacleReviews.entity';
|
||||
import { TourSources } from '../../db/entities/TourSources.entity';
|
||||
@@ -20,6 +21,9 @@ import { WandererModule } from '../wanderer/wanderer.module';
|
||||
import { CityWalkBriefingService } from './city-walk-briefing.service';
|
||||
import { CityWalkFootWayService } from './city-walk-foot-way.service';
|
||||
import { CityWalkMcp } from './city-walk.mcp';
|
||||
import { TourActivitiesController } from './tour-activities.controller';
|
||||
import { TourActivitiesMcp } from './tour-activities.mcp';
|
||||
import { TourActivitiesService } from './tour-activities.service';
|
||||
import { TourChangePreviewService } from './tour-change-preview.service';
|
||||
import { TourChangeSaveService } from './tour-change-save.service';
|
||||
import { TourChangeUndoMcp } from './tour-change-undo.mcp';
|
||||
@@ -69,7 +73,9 @@ import { Module } from '@nestjs/common';
|
||||
* assistant prepares for review is laid onto its saved points and planned on
|
||||
* foot by the same router, and saves nothing (MCP-T02); once the traveller
|
||||
* confirmed it, it is saved through the tour's own write, which records the
|
||||
* step for a later undo (MCP-T03).
|
||||
* step for a later undo (MCP-T03). The recorded tracks assigned to a tour
|
||||
* (ACT-01) are read with its detail and written through
|
||||
* TourActivitiesService, over the day assignments the visits repository reads.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -99,12 +105,14 @@ import { Module } from '@nestjs/common';
|
||||
TourObstacleReviews,
|
||||
TourStationVisits,
|
||||
TourChangeSteps,
|
||||
TourActivities,
|
||||
Places,
|
||||
]),
|
||||
],
|
||||
controllers: [
|
||||
TourHorseRoutesController,
|
||||
TourTakeOverController,
|
||||
TourActivitiesController,
|
||||
TourPoiSearchController,
|
||||
TourSkiController,
|
||||
TourTrailGradeController,
|
||||
@@ -135,12 +143,14 @@ import { Module } from '@nestjs/common';
|
||||
TourChangePreviewService,
|
||||
TourChangeSaveService,
|
||||
TourChangeUndoService,
|
||||
TourActivitiesService,
|
||||
ToursMcp,
|
||||
TourLibraryMcp,
|
||||
TourWalkImportMcp,
|
||||
CityWalkMcp,
|
||||
TourChangeMcp,
|
||||
TourChangeUndoMcp,
|
||||
TourActivitiesMcp,
|
||||
],
|
||||
})
|
||||
export class ToursModule {}
|
||||
|
||||
@@ -1,10 +1,12 @@
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { TourActivities } from '../../db/entities/TourActivities.entity';
|
||||
import { TourStationVisits } from '../../db/entities/TourStationVisits.entity';
|
||||
import { TourTypes } from '../../db/entities/TourTypes.entity';
|
||||
import { TourWaypoints } from '../../db/entities/TourWaypoints.entity';
|
||||
import { Tours } from '../../db/entities/Tours.entity';
|
||||
import { TOUR_HIKING_PREFERENCES, TOUR_TRACK_MARKS } from '../../db/json-columns';
|
||||
import type { PlacesRepository } from '../../db/repositories/Places.repository';
|
||||
import type { TourActivitiesRepository, TourActivityRefRow } from '../../db/repositories/TourActivities.repository';
|
||||
import type { TourStationVisitsRepository } from '../../db/repositories/TourStationVisits.repository';
|
||||
import type { TourTypesRepository } from '../../db/repositories/TourTypes.repository';
|
||||
import type {
|
||||
@@ -19,12 +21,14 @@ import type {
|
||||
ToursRepository,
|
||||
TourUpdate,
|
||||
} from '../../db/repositories/Tours.repository';
|
||||
import { utcSuffix } from '../../db/types';
|
||||
import { decodeJson, encodeJson } from '../../utils/json-column';
|
||||
import { badRequest, DomainError } from '../common/domain-error';
|
||||
import { toRowId } from '../common/row-id';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { PlaceImportService } from '../place-import/place-import.service';
|
||||
import { PlacesService } from '../places/places.service';
|
||||
import { activityFacts, toActivity, trackTimesFor } from './tour-activities.helpers';
|
||||
import { TourPaddleCheckService } from './tour-paddle-check.service';
|
||||
import { advanceTourRevision } from './tour-revision';
|
||||
import { toVisit } from './tour-visits.service';
|
||||
@@ -160,12 +164,20 @@ export class ToursService {
|
||||
@InjectRepository(TourWaypoints) private readonly waypointsRepo: TourWaypointsRepository,
|
||||
@InjectRepository(TourStationVisits) private readonly visitsRepo: TourStationVisitsRepository,
|
||||
@InjectRepository(Places) private readonly placesRepo: PlacesRepository,
|
||||
@InjectRepository(TourActivities) private readonly activitiesRepo: TourActivitiesRepository,
|
||||
private readonly placeImport: PlaceImportService,
|
||||
private readonly paddleChecks: TourPaddleCheckService,
|
||||
) {}
|
||||
|
||||
/** A tour as it is listed; a city walk with the stations its points make and their stays (CW-02, CW-03). */
|
||||
private toItem(r: TourListRow, points: readonly TourWaypointRow[] = []): TourListItem {
|
||||
/**
|
||||
* A tour as it is listed; a city walk with the stations its points make and their stays (CW-02, CW-03),
|
||||
* every tour with the recordings assigned to it and the tour it documents itself (ACT-01).
|
||||
*/
|
||||
private toItem(
|
||||
r: TourListRow,
|
||||
points: readonly TourWaypointRow[] = [],
|
||||
activities: readonly TourActivityRefRow[] = [],
|
||||
): TourListItem {
|
||||
return {
|
||||
place_id: r.place_id,
|
||||
name: r.name,
|
||||
@@ -204,6 +216,9 @@ export class ToursService {
|
||||
hiking_preferences: decodeJson(TOUR_HIKING_PREFERENCES, r.hiking_preferences, 'tour'),
|
||||
...walkStationFacts(r.tour_type, points),
|
||||
route_pending: Boolean(r.route_missing) && Boolean(r.has_waypoints),
|
||||
track_started_at: utcSuffix(r.track_started_at),
|
||||
track_ended_at: utcSuffix(r.track_ended_at),
|
||||
...activityFacts(r.place_id, activities),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -287,9 +302,10 @@ export class ToursService {
|
||||
if (tid === null) return [];
|
||||
const rows = await this.toursRepo.listForTrip(tid);
|
||||
const walkPoints = await this.walkPointsByPlace(rows);
|
||||
const activities = await this.activitiesRepo.listForTrip(tid);
|
||||
return await this.paddleChecks.forTrip(
|
||||
tid,
|
||||
rows.map((r) => this.toItem(r, walkPoints.get(r.place_id) ?? [])),
|
||||
rows.map((r) => this.toItem(r, walkPoints.get(r.place_id) ?? [], activities)),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -352,12 +368,21 @@ export class ToursService {
|
||||
}
|
||||
}
|
||||
|
||||
const checked = await this.paddleChecks.forTour(this.toItem(row, stored), stored, place?.route_geometry ?? null);
|
||||
// ACT-01: the recordings assigned to this tour, and the assignment this tour is the recording of.
|
||||
const activities = await this.activitiesRepo.listForPlace(tid, row.place_id);
|
||||
const documents = await this.activitiesRepo.findByTrack(row.place_id);
|
||||
const refs = documents ? [...activities, documents] : activities;
|
||||
const checked = await this.paddleChecks.forTour(
|
||||
this.toItem(row, stored, refs),
|
||||
stored,
|
||||
place?.route_geometry ?? null,
|
||||
);
|
||||
return {
|
||||
tour: checked.item,
|
||||
waypoints,
|
||||
provenance: await this.provenanceOf(tid, row.place_id),
|
||||
...(checked.obstacle_check ? { obstacle_check: checked.obstacle_check } : {}),
|
||||
activities: activities.map(toActivity),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -673,6 +698,9 @@ export class ToursService {
|
||||
// A copy of a copy names where the first one came from.
|
||||
taken_over_from_trip_title: how.takenOverFrom?.tripTitle ?? provenance.taken_over_from_trip_title,
|
||||
taken_over_from_tour_name: how.takenOverFrom?.tourName ?? provenance.taken_over_from_tour_name,
|
||||
// A copy of a recording was recorded when it was; the assignments stay with the tours they joined.
|
||||
track_started_at: row.track_started_at,
|
||||
track_ended_at: row.track_ended_at,
|
||||
});
|
||||
// A stop standing for a place of the source trip stands for nothing in another trip.
|
||||
await this.waypointsRepo.insertForPlace(
|
||||
@@ -890,7 +918,9 @@ export class ToursService {
|
||||
const result = await this.uow.transactional(async () => {
|
||||
// A nested transactional, so the places and their facets commit together.
|
||||
const imported = await this.places.importPreparedGpx(tripId, rows);
|
||||
const times = trackTimesFor(rows, imported.places);
|
||||
for (const place of imported.places) {
|
||||
const recorded = times.get(place.id);
|
||||
const metrics = computeTourMetrics(parseRouteGeometry(place.route_geometry));
|
||||
const matchConfidence = metrics.hasElevation ? 1 : 0.3;
|
||||
await this.toursRepo.insertTour({
|
||||
@@ -907,6 +937,8 @@ export class ToursService {
|
||||
max_hiking_difficulty: null,
|
||||
origin: 'gpx',
|
||||
origin_file_name: gpxFileName(fileName),
|
||||
track_started_at: recorded?.started ?? null,
|
||||
track_ended_at: recorded?.ended ?? null,
|
||||
});
|
||||
tours.push(
|
||||
this.toItem({
|
||||
@@ -938,6 +970,8 @@ export class ToursService {
|
||||
revision: 1,
|
||||
hiking_preferences: null,
|
||||
winter_activity: null,
|
||||
track_started_at: recorded?.started ?? null,
|
||||
track_ended_at: recorded?.ended ?? null,
|
||||
}),
|
||||
);
|
||||
}
|
||||
@@ -980,6 +1014,8 @@ export class ToursService {
|
||||
distance_km: metrics.distanceKm,
|
||||
elevation_gain_m: metrics.elevationGainM,
|
||||
elevation_loss_m: metrics.elevationLossM,
|
||||
started_at: row.trackTimes?.startedAt ?? null,
|
||||
ended_at: row.trackTimes?.endedAt ?? null,
|
||||
duplicate: duplicates[index] ?? false,
|
||||
};
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,285 @@
|
||||
/**
|
||||
* ACT-01 e2e: a recorded track assigned to a tour, through the real
|
||||
* JwtAuthGuard, AddonGuard and TripAccessGuard against a real migrated temp
|
||||
* SQLite db. The recording comes in through the existing GPX import, is
|
||||
* assigned on purpose to one execution of a planned tour, read with the
|
||||
* tour's detail and taken off again; the plan stays as it was all along.
|
||||
*
|
||||
* Fixtures: user 1 owns trip 5 (two days), user 2 is a member whom the
|
||||
* permission spy denies 'place_edit', user 3 has no access.
|
||||
*/
|
||||
import { db } from '../../src/db/database';
|
||||
import { Days } from '../../src/db/entities/Days.entity';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { TourActivities } from '../../src/db/entities/TourActivities.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
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 { makeDayAssignment } from '../helpers/factories/itinerary';
|
||||
import { countRows, deleteRows, findRow, insertRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { addTripMember } from '../helpers/factories/trips';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, 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(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const journeyHooks = {
|
||||
reconcileTripSkeletons: vi.fn().mockResolvedValue(undefined),
|
||||
onPlaceCreated: vi.fn().mockResolvedValue(undefined),
|
||||
onPlaceUpdated: vi.fn().mockResolvedValue(undefined),
|
||||
onPlaceDeleted: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
|
||||
const realtime = new FakeRealtimeService();
|
||||
const OWNER = 1;
|
||||
const VIEWER = 2;
|
||||
const OUTSIDER = 3;
|
||||
const TRIP = 5;
|
||||
|
||||
const PLAN = [
|
||||
[47, 11, 600],
|
||||
[47.01, 11.01, 700],
|
||||
[47.02, 11.02, 650],
|
||||
];
|
||||
const tourBody = {
|
||||
name: 'Ridge walk',
|
||||
route_geometry: PLAN,
|
||||
waypoints: [
|
||||
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
|
||||
{ lat: 47.02, lng: 11.02, role: 'end', sequence: 1 },
|
||||
],
|
||||
max_hiking_difficulty: 3,
|
||||
duration_seconds: 3600,
|
||||
};
|
||||
|
||||
const WATCH_GPX = `<?xml version="1.0"?>
|
||||
<gpx version="1.1" creator="e2e"><trk><name>Watch export</name><trkseg>
|
||||
<trkpt lat="47" lon="11"><ele>600</ele><time>2026-07-02T06:10:00Z</time></trkpt>
|
||||
<trkpt lat="47.012" lon="11.008"><ele>720</ele><time>2026-07-02T07:40:00Z</time></trkpt>
|
||||
<trkpt lat="47.02" lon="11.02"><ele>660</ele><time>2026-07-02T09:25:00Z</time></trkpt>
|
||||
</trkseg></trk></gpx>`;
|
||||
const PHONE_GPX = `<?xml version="1.0"?>
|
||||
<gpx version="1.1" creator="e2e"><trk><name>Phone export</name><trkseg>
|
||||
<trkpt lat="47.5" lon="11.5"/><trkpt lat="47.51" lon="11.51"/>
|
||||
</trkseg></trk></gpx>`;
|
||||
|
||||
describe('Tour activities e2e (ACT-01)', () => {
|
||||
let orm: TestOrm;
|
||||
let server: Server;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let checkPermission: MockInstance;
|
||||
let assignmentIds: number[];
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
await TestUnitOfWorkModule.forRoot(db),
|
||||
await createTestMikroOrmModule(db),
|
||||
RealtimeModule,
|
||||
ToursModule,
|
||||
],
|
||||
})
|
||||
.overrideProvider(RealtimeService)
|
||||
.useValue(realtime)
|
||||
.overrideProvider(JourneyDomainService)
|
||||
.useValue(journeyHooks)
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
|
||||
const createTour = async () => {
|
||||
const res = await request(server).post(`/api/trips/${TRIP}/tours`).set(as(OWNER)).send(tourBody);
|
||||
expect(res.status).toBe(201);
|
||||
return res.body.tour.place_id as number;
|
||||
};
|
||||
|
||||
/** A recording through the one GPX import there is. */
|
||||
const importTrack = async (xml: string, name: string) => {
|
||||
const res = await request(server)
|
||||
.post(`/api/trips/${TRIP}/tours/import/gpx`)
|
||||
.set(as(OWNER))
|
||||
.attach('file', Buffer.from(xml), { filename: name, contentType: 'application/gpx+xml' });
|
||||
expect(res.status).toBe(201);
|
||||
return res.body.tours[0] as { place_id: number; track_started_at: string | null };
|
||||
};
|
||||
|
||||
const assign = (placeId: number, body: unknown, userId = OWNER) =>
|
||||
request(server).put(`/api/trips/${TRIP}/tours/${placeId}/activities`).set(as(userId)).send(body);
|
||||
const unassign = (placeId: number, activityId: number, userId = OWNER) =>
|
||||
request(server).delete(`/api/trips/${TRIP}/tours/${placeId}/activities/${activityId}`).set(as(userId));
|
||||
|
||||
/** The tour on both days of the trip; answers its two day assignments. */
|
||||
const onBothDays = async (placeId: number) => [
|
||||
(await makeDayAssignment(orm, 3, placeId)).id,
|
||||
(await makeDayAssignment(orm, 4, placeId)).id,
|
||||
];
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(db);
|
||||
await makeUser(orm, { id: 1, username: 'owner', email: 'owner@example.test', role: 'user', password_version: 0 });
|
||||
await makeUser(orm, { id: 2, username: 'viewer', email: 'viewer@example.test', role: 'user', password_version: 0 });
|
||||
await makeUser(orm, { id: 3, username: 'outsider', email: 'out@example.test', role: 'user', password_version: 0 });
|
||||
await insertRows(orm, Trips, [{ id: TRIP, user: 1, title: 'Alps' }]);
|
||||
await addTripMember(orm, TRIP, 2);
|
||||
await insertRows(orm, Days, [
|
||||
{ id: 3, trip: TRIP, day_number: 1 },
|
||||
{ id: 4, trip: TRIP, day_number: 2 },
|
||||
]);
|
||||
app = await build();
|
||||
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
checkPermission.mockImplementation(
|
||||
(action: string, _role: string, _owner: number, userId: number) =>
|
||||
!(action === 'place_edit' && userId === VIEWER),
|
||||
);
|
||||
await setAddonEnabled(orm, 'tours', true);
|
||||
realtime.broadcastMock.mockClear();
|
||||
await deleteRows(orm, Places);
|
||||
assignmentIds = [];
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
it('ACT-E2E-001: a GPX recording assigned to a day of a planned tour shows its own values; the plan stays', async () => {
|
||||
const tour = await createTour();
|
||||
assignmentIds = await onBothDays(tour);
|
||||
const watch = await importTrack(WATCH_GPX, 'watch.gpx');
|
||||
expect(watch.track_started_at).toBe('2026-07-02T06:10:00Z');
|
||||
const before = (await request(server).get(`/api/trips/${TRIP}/tours/${tour}`).set(as(OWNER))).body;
|
||||
|
||||
const res = await assign(tour, { track_place_id: watch.place_id, assignment_id: assignmentIds[1] });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.activities).toHaveLength(1);
|
||||
expect(res.body.activities[0]).toMatchObject({
|
||||
assignment_id: assignmentIds[1],
|
||||
day_id: 4,
|
||||
track: { place_id: watch.place_id, name: 'Watch export', origin: 'gpx', file_name: 'watch.gpx' },
|
||||
metrics: {
|
||||
elevation_gain_m: 120,
|
||||
elevation_loss_m: 60,
|
||||
started_at: '2026-07-02T06:10:00Z',
|
||||
ended_at: '2026-07-02T09:25:00Z',
|
||||
elapsed_minutes: 195,
|
||||
point_count: 3,
|
||||
},
|
||||
});
|
||||
expect(res.body.activities[0].geometry).toHaveLength(3);
|
||||
// The planned values, line and revision are what they were.
|
||||
for (const key of ['distance', 'elevation_gain', 'elevation_loss', 'duration', 'revision']) {
|
||||
expect(res.body.tour[key]).toEqual(before.tour[key]);
|
||||
}
|
||||
expect(await findRow(orm, Places, { id: tour })).toMatchObject({ route_geometry: JSON.stringify(PLAN) });
|
||||
expect(realtime.broadcastMock).toHaveBeenCalledWith(
|
||||
String(TRIP),
|
||||
'tours:changed',
|
||||
{ placeIds: [tour, watch.place_id] },
|
||||
undefined,
|
||||
);
|
||||
|
||||
const listed = (await request(server).get(`/api/trips/${TRIP}/tours`).set(as(OWNER))).body.tours;
|
||||
expect(listed.find((item: { place_id: number }) => item.place_id === tour).activity_tracks).toEqual([
|
||||
{ id: res.body.activities[0].id, track_place_id: watch.place_id, assignment_id: assignmentIds[1] },
|
||||
]);
|
||||
expect(listed.find((item: { place_id: number }) => item.place_id === watch.place_id).activity_of).toBe(tour);
|
||||
});
|
||||
|
||||
it('ACT-E2E-002: a track without times measures no time, and taking it off leaves it in the trip', async () => {
|
||||
const tour = await createTour();
|
||||
const phone = await importTrack(PHONE_GPX, 'phone.gpx');
|
||||
const res = await assign(tour, { track_place_id: phone.place_id, assignment_id: null });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.activities[0].metrics).toMatchObject({
|
||||
elevation_gain_m: null,
|
||||
started_at: null,
|
||||
ended_at: null,
|
||||
elapsed_minutes: null,
|
||||
});
|
||||
|
||||
const removed = await unassign(tour, res.body.activities[0].id);
|
||||
expect(removed.status).toBe(200);
|
||||
expect(removed.body.activities).toEqual([]);
|
||||
expect(await countRows(orm, TourActivities)).toBe(0);
|
||||
expect(await findRow(orm, Places, { id: phone.place_id })).not.toBeNull();
|
||||
expect((await unassign(tour, res.body.activities[0].id)).status).toBe(404);
|
||||
});
|
||||
|
||||
it('ACT-E2E-003: a refused assignment names why and changes nothing', async () => {
|
||||
const tour = await createTour();
|
||||
const other = await createTour();
|
||||
const watch = await importTrack(WATCH_GPX, 'watch.gpx');
|
||||
const otherAssignment = (await makeDayAssignment(orm, 3, other)).id;
|
||||
|
||||
const planned = await assign(tour, { track_place_id: other, assignment_id: null });
|
||||
expect(planned.status).toBe(400);
|
||||
expect(planned.body).toEqual({
|
||||
error: 'Only an import that was not planned over can be assigned',
|
||||
code: 'activity_track_not_recorded',
|
||||
});
|
||||
const foreignDay = await assign(tour, { track_place_id: watch.place_id, assignment_id: otherAssignment });
|
||||
expect(foreignDay.status).toBe(400);
|
||||
expect(foreignDay.body.code).toBe('activity_assignment_not_of_tour');
|
||||
expect((await assign(tour, { track_place_id: watch.place_id })).status).toBe(400);
|
||||
expect((await assign(tour, { track_place_id: 999_999, assignment_id: null })).status).toBe(404);
|
||||
|
||||
expect((await assign(tour, { track_place_id: watch.place_id, assignment_id: null })).status).toBe(200);
|
||||
const taken = await assign(other, { track_place_id: watch.place_id, assignment_id: null });
|
||||
expect(taken.status).toBe(409);
|
||||
expect(taken.body.code).toBe('activity_track_in_use');
|
||||
expect(await countRows(orm, TourActivities)).toBe(1);
|
||||
});
|
||||
|
||||
it('ACT-E2E-004: the gates: 401 without a session, 404 without access or the addon, 403 without place_edit', async () => {
|
||||
const tour = await createTour();
|
||||
const watch = await importTrack(WATCH_GPX, 'watch.gpx');
|
||||
const body = { track_place_id: watch.place_id, assignment_id: null };
|
||||
|
||||
expect((await request(server).put(`/api/trips/${TRIP}/tours/${tour}/activities`).send(body)).status).toBe(401);
|
||||
expect((await assign(tour, body, OUTSIDER)).status).toBe(404);
|
||||
expect((await unassign(tour, 1, OUTSIDER)).status).toBe(404);
|
||||
expect((await assign(tour, body, VIEWER)).status).toBe(403);
|
||||
expect((await unassign(tour, 1, VIEWER)).status).toBe(403);
|
||||
await setAddonEnabled(orm, 'tours', false);
|
||||
const off = await assign(tour, body);
|
||||
expect(off.status).toBe(404);
|
||||
expect(off.body).toEqual({ error: 'Tours addon is not enabled' });
|
||||
expect(await countRows(orm, TourActivities)).toBe(0);
|
||||
});
|
||||
});
|
||||
@@ -1,8 +1,9 @@
|
||||
import { TourActivities } from '../../../src/db/entities/TourActivities.entity';
|
||||
import { TourStationVisits, type TTourStationVisitsStatus } from '../../../src/db/entities/TourStationVisits.entity';
|
||||
import { TourWaypoints, type TTourWaypointsImportance } from '../../../src/db/entities/TourWaypoints.entity';
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import type { FactoryOrm } from './context';
|
||||
import { findRow, insertRow, insertRows } from './rows';
|
||||
import { createRow, findRow, insertRow, insertRows } from './rows';
|
||||
import type { EntityData, EntityDTO } from '@mikro-orm/core';
|
||||
|
||||
export type TourRow = EntityDTO<Tours>;
|
||||
@@ -71,3 +72,15 @@ export async function markStationVisit(
|
||||
): Promise<void> {
|
||||
await insertRow(orm, TourStationVisits, { assignment: assignmentId, station_key: stationKey, status });
|
||||
}
|
||||
|
||||
type TourActivityRow = EntityDTO<TourActivities>;
|
||||
|
||||
/** ACT-01: the recording `trackPlaceId` assigned to the tour, on no day unless `assignment` names one. */
|
||||
export function makeTourActivity(
|
||||
orm: FactoryOrm,
|
||||
placeId: number,
|
||||
trackPlaceId: number,
|
||||
overrides: EntityData<TourActivities> = {},
|
||||
): Promise<TourActivityRow> {
|
||||
return createRow(orm, TourActivities, { place: placeId, trackPlace: trackPlaceId }, overrides);
|
||||
}
|
||||
|
||||
@@ -2,8 +2,10 @@
|
||||
* A TourPaddleCheckService for suites that build ToursService by hand and are
|
||||
* not about paddle checks: the list and the detail pass through as they are.
|
||||
* It takes nothing in its constructor, so lint:test-new-service does not count
|
||||
* it; the paddle checks have their own suites over the real service.
|
||||
* it; the paddle checks have their own suites over the real service. Beside it
|
||||
* the recorded tracks (ACT-01) of a trip that has none, for the same suites.
|
||||
*/
|
||||
import type { TourActivitiesRepository } from '../../src/db/repositories/TourActivities.repository';
|
||||
import type { TourPaddleCheckService } from '../../src/nest/tours/tour-paddle-check.service';
|
||||
import type { TourListItem } from '@trek/shared';
|
||||
|
||||
@@ -21,3 +23,12 @@ export class NoPaddleChecks {
|
||||
export function noPaddleChecks(): TourPaddleCheckService {
|
||||
return new NoPaddleChecks() as unknown as TourPaddleCheckService;
|
||||
}
|
||||
|
||||
/** The reads of a trip without recorded tracks, as the repository ToursService takes. */
|
||||
export function noActivities(): TourActivitiesRepository {
|
||||
return {
|
||||
listForTrip: async () => [],
|
||||
listForPlace: async () => [],
|
||||
findByTrack: async () => undefined,
|
||||
} as unknown as TourActivitiesRepository;
|
||||
}
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { TourActivities } from '../../src/db/entities/TourActivities.entity';
|
||||
import { TourStationVisits } from '../../src/db/entities/TourStationVisits.entity';
|
||||
import { TourTypes } from '../../src/db/entities/TourTypes.entity';
|
||||
import { TourWaypoints } from '../../src/db/entities/TourWaypoints.entity';
|
||||
import { Tours } from '../../src/db/entities/Tours.entity';
|
||||
import type { TourActivitiesRepository } from '../../src/db/repositories/TourActivities.repository';
|
||||
import type { TourStationVisitsRepository } from '../../src/db/repositories/TourStationVisits.repository';
|
||||
import type { TourTypesRepository } from '../../src/db/repositories/TourTypes.repository';
|
||||
import type { TourWaypointsRepository } from '../../src/db/repositories/TourWaypoints.repository';
|
||||
@@ -32,6 +34,10 @@ export function createTestTourStationVisitsRepo(db: Database.Database): Promise<
|
||||
return sharedTestOrm(db).then((t) => t.repo(TourStationVisits));
|
||||
}
|
||||
|
||||
export function createTestTourActivitiesRepo(db: Database.Database): Promise<TourActivitiesRepository> {
|
||||
return sharedTestOrm(db).then((t) => t.repo(TourActivities));
|
||||
}
|
||||
|
||||
/** A `tours` row for an existing place, with the defaults a GPX import writes. */
|
||||
export function createTour(
|
||||
db: Database.Database,
|
||||
|
||||
@@ -41,14 +41,15 @@ describe('ALL_ENTITIES', () => {
|
||||
* + trip_journal_links and trip_journal_link_members, the journal a trip shows and who it is open to
|
||||
* + paddle_water_graphs and paddle_region_requests, a region's water network and the regions that wait for an admin
|
||||
* + tour_station_visits, how far a city walk got on one of its days
|
||||
* + tour_change_steps, the changes to a tour saved from a confirmed proposal)
|
||||
* + tour_change_steps, the changes to a tour saved from a confirmed proposal
|
||||
* + tour_activities, the recorded tracks assigned to a tour)
|
||||
* is registered, and no two share a class name (a silent duplicate would
|
||||
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
|
||||
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
|
||||
* which de-duplicates by class name).
|
||||
*/
|
||||
it('ENT-003: exactly 144 entities, every class name unique', () => {
|
||||
expect(ALL_ENTITIES.length).toBe(144);
|
||||
it('ENT-003: exactly 145 entities, every class name unique', () => {
|
||||
expect(ALL_ENTITIES.length).toBe(145);
|
||||
const names = ALL_ENTITIES.map((s) => s.meta.className);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
});
|
||||
|
||||
@@ -38,7 +38,8 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
// day plan that checks a city walk's station off).
|
||||
// + tour_change_steps: id, place_id, proposal_id, base_revision, revision, changes, before_state (a step is
|
||||
// only ever written whole, by the save of a confirmed change).
|
||||
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 504;
|
||||
// + tour_activities: id, place_id, track_place_id (an assignment always names its tour and its recording).
|
||||
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 507;
|
||||
|
||||
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
|
||||
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {
|
||||
|
||||
@@ -72,6 +72,7 @@ const UNNUMBERED = [
|
||||
'Migration20200101045600_a_tour_can_be_ridden_on_horseback',
|
||||
'Migration20200101045700_a_tour_records_the_changes_saved_from_a_proposal',
|
||||
'Migration20200101045710_a_saved_tour_change_can_be_taken_back',
|
||||
'Migration20200101045900_a_tour_keeps_the_track_it_was_done_with',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
/**
|
||||
* `TourActivitiesRepository` (ACT-01): the recordings assigned to the tours
|
||||
* of a trip. Seeded through the ORM factories over the migrated snapshot
|
||||
* schema; every read is held to one trip through both tours' places.
|
||||
*/
|
||||
import { DayAssignments } from '../../../../src/db/entities/DayAssignments.entity';
|
||||
import { Places } from '../../../../src/db/entities/Places.entity';
|
||||
import { TourActivities } from '../../../../src/db/entities/TourActivities.entity';
|
||||
import type { TourActivitiesRepository } from '../../../../src/db/repositories/TourActivities.repository';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makeDayAssignment } from '../../../helpers/factories/itinerary';
|
||||
import { makePlace } from '../../../helpers/factories/places';
|
||||
import { countRows, deleteRows, findRow } from '../../../helpers/factories/rows';
|
||||
import { makeTour, makeTourActivity } from '../../../helpers/factories/tours';
|
||||
import { makeDay, makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repo: TourActivitiesRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repo = t.repo(TourActivities);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
const LINE = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.01, 11, 700],
|
||||
]);
|
||||
|
||||
/** A planned hike on two days, two GPX recordings, and a tour with a recording of its own in another trip. */
|
||||
async function fixture() {
|
||||
const { user } = await makeUser(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const day1 = await makeDay(t, trip.id, { day_number: 1 });
|
||||
const day2 = await makeDay(t, trip.id, { day_number: 2 });
|
||||
const hike = await makePlace(t, trip.id, { name: 'Ridge' });
|
||||
await makeTour(t, hike.id);
|
||||
const onDay1 = await makeDayAssignment(t, day1.id, hike.id);
|
||||
const onDay2 = await makeDayAssignment(t, day2.id, hike.id);
|
||||
const watch = await makePlace(t, trip.id, { name: 'Watch export', route_geometry: LINE });
|
||||
await makeTour(t, watch.id, {
|
||||
origin: 'gpx',
|
||||
origin_file_name: 'morning.gpx',
|
||||
track_started_at: '2026-07-02 06:10:00',
|
||||
track_ended_at: '2026-07-02 08:10:00',
|
||||
});
|
||||
const phone = await makePlace(t, trip.id, { name: 'Phone export', route_geometry: LINE });
|
||||
await makeTour(t, phone.id, { origin: 'gpx' });
|
||||
|
||||
const other = await makeTrip(t, user.id);
|
||||
const elsewhere = await makePlace(t, other.id, { name: 'Elsewhere' });
|
||||
await makeTour(t, elsewhere.id);
|
||||
const elsewhereTrack = await makePlace(t, other.id, { name: 'Elsewhere track' });
|
||||
await makeTour(t, elsewhereTrack.id, { origin: 'gpx' });
|
||||
await makeTourActivity(t, elsewhere.id, elsewhereTrack.id);
|
||||
return { user, trip, day1, hike, onDay1, onDay2, watch, phone, other, elsewhere, elsewhereTrack };
|
||||
}
|
||||
|
||||
describe('TourActivitiesRepository', () => {
|
||||
it('ACT-REPO-001: insertActivity writes an assignment and listForPlace reads it with its recording and day', async () => {
|
||||
const { user, trip, day1, hike, onDay1, watch } = await fixture();
|
||||
const id = await repo.insertActivity({
|
||||
place_id: hike.id,
|
||||
track_place_id: watch.id,
|
||||
assignment_id: onDay1.id,
|
||||
assigned_by: user.id,
|
||||
});
|
||||
const [row, ...rest] = await repo.listForPlace(trip.id, hike.id);
|
||||
expect(rest).toEqual([]);
|
||||
expect(row).toMatchObject({
|
||||
id,
|
||||
place_id: hike.id,
|
||||
track_place_id: watch.id,
|
||||
assignment_id: onDay1.id,
|
||||
day_id: day1.id,
|
||||
track_name: 'Watch export',
|
||||
track_origin: 'gpx',
|
||||
track_file_name: 'morning.gpx',
|
||||
track_route_geometry: LINE,
|
||||
track_recorded_route_geometry: null,
|
||||
track_started_at: '2026-07-02 06:10:00',
|
||||
track_ended_at: '2026-07-02 08:10:00',
|
||||
});
|
||||
expect(row?.assigned_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
|
||||
expect(row?.track_created_at).toBeTruthy();
|
||||
expect(await findRow(t, TourActivities, { id })).toMatchObject({ assigned_by: user.id });
|
||||
});
|
||||
|
||||
it('ACT-REPO-002: listForPlace stays inside the trip, and an assignment without a day has none', async () => {
|
||||
const { trip, hike, watch, other, elsewhere } = await fixture();
|
||||
await makeTourActivity(t, hike.id, watch.id);
|
||||
expect((await repo.listForPlace(trip.id, hike.id)).map((row) => row.day_id)).toEqual([null]);
|
||||
expect(await repo.listForPlace(other.id, hike.id)).toEqual([]);
|
||||
expect(await repo.listForPlace(trip.id, elsewhere.id)).toEqual([]);
|
||||
});
|
||||
|
||||
it('ACT-REPO-003: listForTrip lists the trip’s assignments only, oldest first', async () => {
|
||||
const { trip, hike, onDay2, watch, phone } = await fixture();
|
||||
const first = await makeTourActivity(t, hike.id, watch.id);
|
||||
const second = await makeTourActivity(t, hike.id, phone.id, { assignment: onDay2.id });
|
||||
expect(await repo.listForTrip(trip.id)).toEqual([
|
||||
{ id: first.id, place_id: hike.id, track_place_id: watch.id, assignment_id: null },
|
||||
{ id: second.id, place_id: hike.id, track_place_id: phone.id, assignment_id: onDay2.id },
|
||||
]);
|
||||
});
|
||||
|
||||
it('ACT-REPO-004: findByTrack and hasActivities answer for one recording and one tour', async () => {
|
||||
const { hike, watch, phone } = await fixture();
|
||||
const activity = await makeTourActivity(t, hike.id, watch.id);
|
||||
expect(await repo.findByTrack(watch.id)).toEqual({
|
||||
id: activity.id,
|
||||
place_id: hike.id,
|
||||
track_place_id: watch.id,
|
||||
assignment_id: null,
|
||||
});
|
||||
expect(await repo.findByTrack(phone.id)).toBeUndefined();
|
||||
expect(await repo.hasActivities(hike.id)).toBe(true);
|
||||
expect(await repo.hasActivities(watch.id)).toBe(false);
|
||||
});
|
||||
|
||||
it('ACT-REPO-005: clearFor removes the execution’s recording and the recording’s other execution, nothing else', async () => {
|
||||
const { trip, hike, onDay1, onDay2, watch, phone, elsewhere } = await fixture();
|
||||
await makeTourActivity(t, hike.id, watch.id, { assignment: onDay1.id });
|
||||
await makeTourActivity(t, hike.id, phone.id, { assignment: onDay2.id });
|
||||
|
||||
// Day 1 gets the phone export: day 1's watch export goes, and so does the phone export's day 2.
|
||||
await repo.clearFor(hike.id, phone.id, onDay1.id);
|
||||
expect(await repo.listForPlace(trip.id, hike.id)).toEqual([]);
|
||||
|
||||
await makeTourActivity(t, hike.id, watch.id);
|
||||
await makeTourActivity(t, hike.id, phone.id, { assignment: onDay2.id });
|
||||
// No day: only the assignment without a day goes.
|
||||
await repo.clearFor(hike.id, 999_999, null);
|
||||
expect((await repo.listForPlace(trip.id, hike.id)).map((row) => row.track_place_id)).toEqual([phone.id]);
|
||||
expect(await repo.hasActivities(elsewhere.id)).toBe(true);
|
||||
});
|
||||
|
||||
it('ACT-REPO-006: removeFromPlace removes one assignment of that tour only', async () => {
|
||||
const { hike, watch, elsewhere } = await fixture();
|
||||
const activity = await makeTourActivity(t, hike.id, watch.id);
|
||||
expect(await repo.removeFromPlace(elsewhere.id, activity.id)).toBe(false);
|
||||
expect(await repo.removeFromPlace(hike.id, activity.id)).toBe(true);
|
||||
expect(await repo.removeFromPlace(hike.id, activity.id)).toBe(false);
|
||||
});
|
||||
|
||||
it('ACT-REPO-007: taking the tour off a day keeps the recording without its day; deleting a tour takes it along', async () => {
|
||||
const { trip, hike, onDay1, watch, phone } = await fixture();
|
||||
await makeTourActivity(t, hike.id, watch.id, { assignment: onDay1.id });
|
||||
await makeTourActivity(t, hike.id, phone.id);
|
||||
|
||||
await deleteRows(t, DayAssignments, { id: onDay1.id });
|
||||
expect((await repo.listForPlace(trip.id, hike.id)).map((row) => row.assignment_id)).toEqual([null, null]);
|
||||
|
||||
await deleteRows(t, Places, { id: watch.id });
|
||||
expect(await countRows(t, TourActivities, { place: hike.id })).toBe(1);
|
||||
});
|
||||
});
|
||||
@@ -110,6 +110,8 @@ describe('ToursRepository reads', () => {
|
||||
run_pace_seconds_per_km: null,
|
||||
ski_discipline: null,
|
||||
ski_technique: null,
|
||||
track_started_at: null,
|
||||
track_ended_at: null,
|
||||
},
|
||||
{
|
||||
place_id: older.id,
|
||||
@@ -147,6 +149,8 @@ describe('ToursRepository reads', () => {
|
||||
run_pace_seconds_per_km: null,
|
||||
ski_discipline: null,
|
||||
ski_technique: null,
|
||||
track_started_at: null,
|
||||
track_ended_at: null,
|
||||
},
|
||||
]);
|
||||
expect((await repo.listForTrip(trip.id)).map((r) => r.place_id)).not.toContain(plain.id);
|
||||
@@ -265,6 +269,8 @@ describe('ToursRepository writes', () => {
|
||||
run_pace_seconds_per_km: null,
|
||||
ski_discipline: null,
|
||||
ski_technique: null,
|
||||
track_started_at: null,
|
||||
track_ended_at: null,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -414,6 +420,8 @@ describe('ToursRepository writes', () => {
|
||||
run_pace_seconds_per_km: null,
|
||||
ski_discipline: null,
|
||||
ski_technique: null,
|
||||
track_started_at: null,
|
||||
track_ended_at: null,
|
||||
taken_over_from_trip_title: null,
|
||||
taken_over_from_tour_name: null,
|
||||
},
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
import {
|
||||
buildGpx,
|
||||
buildTourGpx,
|
||||
GpxProvider,
|
||||
gpxFilename,
|
||||
trackTimeSpan,
|
||||
type GpxExportPlace,
|
||||
type GpxExportDay,
|
||||
} from '../../../../src/nest/place-import/providers/gpx.provider';
|
||||
@@ -348,3 +350,42 @@ describe('buildTourGpx (PR1-06A)', () => {
|
||||
expect(gpxFilename('Grat <Ost>', 'tour')).toBe('Grat-Ost.gpx');
|
||||
});
|
||||
});
|
||||
|
||||
describe('track times (ACT-01)', () => {
|
||||
it('GPX-TIME-001: the first and last time of a track whose every point carries one, in order', () => {
|
||||
expect(trackTimeSpan(['2026-07-02T06:10:00Z', '2026-07-02T06:10:00Z', ' 2026-07-02T09:00:00+02:00 '])).toEqual({
|
||||
startedAt: '2026-07-02T06:10:00.000Z',
|
||||
endedAt: '2026-07-02T07:00:00.000Z',
|
||||
});
|
||||
});
|
||||
|
||||
it('GPX-TIME-002: no times at all when one is missing, has no zone, runs backwards or none passes', () => {
|
||||
expect(trackTimeSpan(['2026-07-02T06:10:00Z', undefined])).toBeUndefined();
|
||||
expect(trackTimeSpan(['2026-07-02T06:10:00', '2026-07-02T07:10:00'])).toBeUndefined();
|
||||
expect(trackTimeSpan(['2026-07-02T07:10:00Z', '2026-07-02T06:10:00Z'])).toBeUndefined();
|
||||
expect(trackTimeSpan(['2026-07-02T06:10:00Z', '2026-07-02T06:10:00Z'])).toBeUndefined();
|
||||
expect(trackTimeSpan(['not a time Z'])).toBeUndefined();
|
||||
expect(trackTimeSpan([])).toBeUndefined();
|
||||
});
|
||||
|
||||
it('GPX-TIME-003: the reader hands a track its times and never a route', () => {
|
||||
const xml = `<?xml version="1.0"?>
|
||||
<gpx version="1.1" creator="unit">
|
||||
<rte><name>Plan</name><rtept lat="1" lon="2"><time>2026-07-02T06:00:00Z</time></rtept><rtept lat="1.1" lon="2"><time>2026-07-02T07:00:00Z</time></rtept></rte>
|
||||
<trk><name>Walked</name><trkseg>
|
||||
<trkpt lat="1" lon="2"><time>2026-07-02T06:00:00Z</time></trkpt>
|
||||
</trkseg><trkseg>
|
||||
<trkpt lat="1.1" lon="2"><time>2026-07-02T08:30:00Z</time></trkpt>
|
||||
</trkseg></trk>
|
||||
<trk><name>Drawn</name><trkseg><trkpt lat="3" lon="4"/><trkpt lat="3.1" lon="4"/></trkseg></trk>
|
||||
</gpx>`;
|
||||
const rows = new GpxProvider().read(Buffer.from(xml), { importWaypoints: false });
|
||||
const byName = new Map(rows.map((row) => [row.name, row]));
|
||||
expect(byName.get('Plan')?.trackTimes).toBeUndefined();
|
||||
expect(byName.get('Walked')?.trackTimes).toEqual({
|
||||
startedAt: '2026-07-02T06:00:00.000Z',
|
||||
endedAt: '2026-07-02T08:30:00.000Z',
|
||||
});
|
||||
expect(byName.get('Drawn')).not.toHaveProperty('trackTimes');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* TourActivitiesController (ACT-01): route metadata and delegation. The
|
||||
* checks themselves live in TourActivitiesService, which the MCP tools call
|
||||
* too, so REST and MCP refuse the same assignments with the same codes; the
|
||||
* service suite and the e2e suite hold those.
|
||||
*/
|
||||
import 'reflect-metadata';
|
||||
|
||||
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
|
||||
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 { TourActivitiesController } from '../../../src/nest/tours/tour-activities.controller';
|
||||
import type { TourActivitiesService } from '../../../src/nest/tours/tour-activities.service';
|
||||
import type { User } from '../../../src/types';
|
||||
import { RequestMethod } from '@nestjs/common';
|
||||
import { GUARDS_METADATA, HTTP_CODE_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
|
||||
import { tourActivityAssignRequestSchema } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../../src/nest/permissions/permissions.service', () => ({ PermissionsService: class {} }));
|
||||
vi.mock('../../../src/nest/addons/addons.service', () => ({ AddonsService: class {} }));
|
||||
vi.mock('../../../src/nest/tours/tour-activities.service', () => ({ TourActivitiesService: class {} }));
|
||||
vi.mock('../../../src/nest/auth-core/jwt-verify', () => ({ extractToken: vi.fn(), verifyJwtAndLoadUser: vi.fn() }));
|
||||
|
||||
const detail = { tour: { place_id: 4 }, waypoints: [], activities: [] };
|
||||
|
||||
describe('TourActivitiesController', () => {
|
||||
it('ACT-CTL-001: sits behind the addon, auth and trip guards, under the tour', () => {
|
||||
expect(Reflect.getMetadata(PATH_METADATA, TourActivitiesController)).toBe(
|
||||
'api/trips/:tripId/tours/:placeId/activities',
|
||||
);
|
||||
expect(Reflect.getMetadata(GUARDS_METADATA, TourActivitiesController)).toEqual([
|
||||
AddonGuard,
|
||||
JwtAuthGuard,
|
||||
TripAccessGuard,
|
||||
]);
|
||||
expect(Reflect.getMetadata(REQUIRE_ADDON, TourActivitiesController)).toEqual({ addonId: 'tours', label: 'Tours' });
|
||||
});
|
||||
|
||||
it('ACT-CTL-002: both routes change a tour, so both need place_edit and answer 200', () => {
|
||||
const routes = [
|
||||
['assign', RequestMethod.PUT, '/'],
|
||||
['unassign', RequestMethod.DELETE, ':activityId'],
|
||||
] as const;
|
||||
for (const [handler, method, path] of routes) {
|
||||
const fn = TourActivitiesController.prototype[handler];
|
||||
expect(Reflect.getMetadata(METHOD_METADATA, fn)).toBe(method);
|
||||
expect(Reflect.getMetadata(PATH_METADATA, fn)).toBe(path);
|
||||
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, fn)).toBe('place_edit');
|
||||
expect(Reflect.getMetadata(HTTP_CODE_METADATA, fn)).toBeUndefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('ACT-CTL-003: PUT hands the validated body, the user and the socket id to the service', async () => {
|
||||
const service = { assign: vi.fn().mockResolvedValue(detail) } as unknown as TourActivitiesService;
|
||||
const body = tourActivityAssignRequestSchema.parse({ track_place_id: 9, assignment_id: 12 });
|
||||
|
||||
expect(await new TourActivitiesController(service).assign('7', '4', body, { id: 3 } as User, 'socket-1')).toBe(
|
||||
detail,
|
||||
);
|
||||
expect(service.assign).toHaveBeenCalledWith('7', '4', body, 3, 'socket-1');
|
||||
});
|
||||
|
||||
it('ACT-CTL-004: DELETE hands the assignment and the socket id to the service', async () => {
|
||||
const service = { unassign: vi.fn().mockResolvedValue(detail) } as unknown as TourActivitiesService;
|
||||
|
||||
expect(await new TourActivitiesController(service).unassign('7', '4', 5, 'socket-2')).toBe(detail);
|
||||
expect(service.unassign).toHaveBeenCalledWith('7', '4', 5, 'socket-2');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,165 @@
|
||||
/**
|
||||
* The pure half of ACT-01: what a recording measures, read from its own line;
|
||||
* how long it took, only from times it carried; what the list says of the
|
||||
* assignments; and which imported place gets which times.
|
||||
*/
|
||||
import type { TourActivityRow } from '../../../src/db/repositories/TourActivities.repository';
|
||||
import {
|
||||
activityFacts,
|
||||
elapsedMinutes,
|
||||
toActivity,
|
||||
trackTimesFor,
|
||||
withoutLine,
|
||||
} from '../../../src/nest/tours/tour-activities.helpers';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const LINE = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.01, 11, 700],
|
||||
[47.02, 11, 650],
|
||||
]);
|
||||
|
||||
const row = (overrides: Partial<TourActivityRow> = {}): TourActivityRow => ({
|
||||
id: 4,
|
||||
place_id: 1,
|
||||
track_place_id: 9,
|
||||
assignment_id: 12,
|
||||
day_id: 3,
|
||||
assigned_at: '2026-07-02 18:00:00',
|
||||
track_name: 'Watch export',
|
||||
track_origin: 'gpx',
|
||||
track_file_name: 'morning.gpx',
|
||||
track_created_at: '2026-07-02 17:58:00',
|
||||
track_route_geometry: LINE,
|
||||
track_recorded_route_geometry: null,
|
||||
track_started_at: '2026-07-02 06:10:00',
|
||||
track_ended_at: '2026-07-02 11:40:30',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
describe('elapsedMinutes', () => {
|
||||
it('ACT-HLP-001: counts from the first to the last time, to the minute', () => {
|
||||
expect(elapsedMinutes('2026-07-02 06:10:00', '2026-07-02 11:40:30')).toBe(331);
|
||||
});
|
||||
|
||||
it('ACT-HLP-002: knows nothing without both times or with times out of order', () => {
|
||||
expect(elapsedMinutes(null, '2026-07-02 11:40:00')).toBeNull();
|
||||
expect(elapsedMinutes('2026-07-02 06:10:00', null)).toBeNull();
|
||||
expect(elapsedMinutes('2026-07-02 11:40:00', '2026-07-02 06:10:00')).toBeNull();
|
||||
expect(elapsedMinutes('garbage', '2026-07-02 06:10:00')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('toActivity', () => {
|
||||
it('ACT-HLP-003: answers the recording, its execution and what its own line measures', () => {
|
||||
const activity = toActivity(row());
|
||||
expect(activity).toMatchObject({
|
||||
id: 4,
|
||||
assignment_id: 12,
|
||||
day_id: 3,
|
||||
assigned_at: '2026-07-02T18:00:00Z',
|
||||
track: {
|
||||
place_id: 9,
|
||||
name: 'Watch export',
|
||||
origin: 'gpx',
|
||||
file_name: 'morning.gpx',
|
||||
imported_at: '2026-07-02T17:58:00Z',
|
||||
},
|
||||
metrics: {
|
||||
elevation_gain_m: 100,
|
||||
elevation_loss_m: 50,
|
||||
started_at: '2026-07-02T06:10:00Z',
|
||||
ended_at: '2026-07-02T11:40:30Z',
|
||||
elapsed_minutes: 331,
|
||||
point_count: 3,
|
||||
},
|
||||
});
|
||||
expect(activity.metrics.distance_km).toBeGreaterThan(2);
|
||||
expect(activity.geometry).toHaveLength(3);
|
||||
});
|
||||
|
||||
it('ACT-HLP-004: reads the line a recording kept when it was planned over since, never the plan', () => {
|
||||
const kept = JSON.stringify([
|
||||
[48, 12],
|
||||
[48.01, 12],
|
||||
]);
|
||||
const activity = toActivity(row({ track_recorded_route_geometry: kept }));
|
||||
expect(activity.geometry).toEqual([
|
||||
[48, 12],
|
||||
[48.01, 12],
|
||||
]);
|
||||
expect(activity.metrics).toMatchObject({ elevation_gain_m: null, elevation_loss_m: null, point_count: 2 });
|
||||
});
|
||||
|
||||
it('ACT-HLP-005: leaves what the recording does not carry unknown', () => {
|
||||
const activity = toActivity(
|
||||
row({ track_route_geometry: null, track_started_at: null, track_ended_at: null, track_created_at: null }),
|
||||
);
|
||||
expect(activity.metrics).toEqual({
|
||||
distance_km: null,
|
||||
elevation_gain_m: null,
|
||||
elevation_loss_m: null,
|
||||
started_at: null,
|
||||
ended_at: null,
|
||||
elapsed_minutes: null,
|
||||
point_count: 0,
|
||||
});
|
||||
expect(activity.track.imported_at).toBeNull();
|
||||
});
|
||||
|
||||
it('ACT-HLP-006: an MCP answer leaves the line out', () => {
|
||||
const { geometry: _line, ...rest } = toActivity(row());
|
||||
expect(withoutLine(toActivity(row()))).toEqual(rest);
|
||||
});
|
||||
});
|
||||
|
||||
describe('activityFacts', () => {
|
||||
const refs = [
|
||||
{ id: 1, place_id: 10, track_place_id: 20, assignment_id: 5 },
|
||||
{ id: 2, place_id: 10, track_place_id: 21, assignment_id: null },
|
||||
];
|
||||
|
||||
it('ACT-HLP-007: a tour lists its recordings, a recording names the tour it documents', () => {
|
||||
expect(activityFacts(10, refs)).toEqual({
|
||||
activity_tracks: [
|
||||
{ id: 1, track_place_id: 20, assignment_id: 5 },
|
||||
{ id: 2, track_place_id: 21, assignment_id: null },
|
||||
],
|
||||
activity_of: null,
|
||||
});
|
||||
expect(activityFacts(21, refs)).toEqual({ activity_tracks: [], activity_of: 10 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('trackTimesFor', () => {
|
||||
const rows = [
|
||||
{
|
||||
name: 'Loop',
|
||||
lat: 47,
|
||||
lng: 11,
|
||||
description: null,
|
||||
trackTimes: { startedAt: '2026-07-02T06:10:00.000Z', endedAt: '2026-07-02T08:00:00.000Z' },
|
||||
},
|
||||
{ name: 'Loop', lat: 47, lng: 11, description: null },
|
||||
{ name: 'Route', lat: 46, lng: 10, description: null },
|
||||
];
|
||||
|
||||
it('ACT-HLP-008: gives each imported place the times of the row it was made from, in canonical text', () => {
|
||||
const times = trackTimesFor(rows, [
|
||||
{ id: 1, name: 'Loop', lat: 47, lng: 11 },
|
||||
{ id: 2, name: 'Loop', lat: 47, lng: 11 },
|
||||
{ id: 3, name: 'Route', lat: 46, lng: 10 },
|
||||
]);
|
||||
expect(times.get(1)).toEqual({ started: '2026-07-02 06:10:00', ended: '2026-07-02 08:00:00' });
|
||||
expect(times.get(2)).toEqual({ started: null, ended: null });
|
||||
expect(times.get(3)).toEqual({ started: null, ended: null });
|
||||
});
|
||||
|
||||
it('ACT-HLP-009: a place without a row of its own stays without times', () => {
|
||||
expect(trackTimesFor(rows, [{ id: 7, name: 'Elsewhere', lat: null, lng: null }]).get(7)).toEqual({
|
||||
started: null,
|
||||
ended: null,
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,138 @@
|
||||
/**
|
||||
* TourActivitiesMcp (ACT-01): assigning a recorded track to a tour and taking
|
||||
* it off over MCP, through the same service and the same checks as REST
|
||||
* (trip access, then 'place_edit'), and get_tour_plan reading what the
|
||||
* recordings measure. Answers leave the recorded line out. The suite takes its
|
||||
* subject from the container over a snapshot test db.
|
||||
*/
|
||||
import { TourActivities } from '../../../src/db/entities/TourActivities.entity';
|
||||
import type { McpContext } from '../../../src/nest-mcp';
|
||||
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
|
||||
import { TourActivitiesMcp } from '../../../src/nest/tours/tour-activities.mcp';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { ToursMcp } from '../../../src/nest/tours/tours.mcp';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makeDayAssignment } from '../../helpers/factories/itinerary';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
import { countRows } from '../../helpers/factories/rows';
|
||||
import { makeTour, makeTourActivity } from '../../helpers/factories/tours';
|
||||
import { makeDay, makeTrip } from '../../helpers/factories/trips';
|
||||
import { makeUser } from '../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let mcp: TourActivitiesMcp;
|
||||
let toursMcp: ToursMcp;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({ db, imports: [ToursModule] });
|
||||
mcp = t.get(TourActivitiesMcp);
|
||||
toursMcp = t.get(ToursMcp);
|
||||
});
|
||||
beforeEach(() => resetTestDb(db));
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const ctx = (userId: number) => ({ userId }) as McpContext;
|
||||
|
||||
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
|
||||
const text = result.content[0]?.text ?? '';
|
||||
return result.isError ? { error: text } : JSON.parse(text);
|
||||
}
|
||||
|
||||
const LINE = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.01, 11, 700],
|
||||
]);
|
||||
|
||||
async function fixture() {
|
||||
const { user } = await makeUser(orm());
|
||||
const { user: outsider } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
const day = await makeDay(orm(), trip.id, { day_number: 1 });
|
||||
const hike = await makePlace(orm(), trip.id, { name: 'Ridge', route_geometry: LINE });
|
||||
await makeTour(orm(), hike.id);
|
||||
const onDay = await makeDayAssignment(orm(), day.id, hike.id);
|
||||
const watch = await makePlace(orm(), trip.id, { name: 'Watch export', route_geometry: LINE });
|
||||
await makeTour(orm(), watch.id, { origin: 'gpx', origin_file_name: 'morning.gpx' });
|
||||
return { user, outsider, trip, day, hike, onDay, watch };
|
||||
}
|
||||
|
||||
describe('TourActivitiesMcp', () => {
|
||||
it('ACT-MCP-001: assign_tour_track assigns the chosen recording and answers it without its line', async () => {
|
||||
const { user, trip, day, hike, onDay, watch } = await fixture();
|
||||
const result = read(
|
||||
await mcp.assignTourTrack(
|
||||
{ tripId: trip.id, placeId: hike.id, track_place_id: watch.id, assignment_id: onDay.id },
|
||||
ctx(user.id),
|
||||
),
|
||||
);
|
||||
expect(result.activities).toHaveLength(1);
|
||||
expect(result.activities[0]).toMatchObject({
|
||||
assignment_id: onDay.id,
|
||||
day_id: day.id,
|
||||
track: { place_id: watch.id, file_name: 'morning.gpx' },
|
||||
metrics: { elevation_gain_m: 100, elapsed_minutes: null, started_at: null },
|
||||
});
|
||||
expect(result.activities[0].geometry).toBeUndefined();
|
||||
|
||||
// get_tour_plan reads the same, also without the line.
|
||||
const plan = read(await toursMcp.getTourPlan({ tripId: trip.id, placeId: hike.id }, ctx(user.id)));
|
||||
expect(plan.activities[0]).toMatchObject({ track: { place_id: watch.id } });
|
||||
expect(plan.activities[0].geometry).toBeUndefined();
|
||||
});
|
||||
|
||||
it('ACT-MCP-002: unassign_tour_track takes it off again; one that is not there is not found', async () => {
|
||||
const { user, trip, hike, watch } = await fixture();
|
||||
const activity = await makeTourActivity(orm(), hike.id, watch.id);
|
||||
const result = read(
|
||||
await mcp.unassignTourTrack({ tripId: trip.id, placeId: hike.id, activityId: activity.id }, ctx(user.id)),
|
||||
);
|
||||
expect(result.activities).toEqual([]);
|
||||
expect(
|
||||
read(await mcp.unassignTourTrack({ tripId: trip.id, placeId: hike.id, activityId: activity.id }, ctx(user.id))),
|
||||
).toEqual({ error: 'Recorded track not found.' });
|
||||
});
|
||||
|
||||
it('ACT-MCP-003: refuses a trip the user cannot open and a track that is not of the trip, as REST does', async () => {
|
||||
const { user, outsider, trip, hike, watch } = await fixture();
|
||||
const input = { tripId: trip.id, placeId: hike.id, track_place_id: watch.id, assignment_id: null };
|
||||
expect(read(await mcp.assignTourTrack(input, ctx(outsider.id)))).toEqual({
|
||||
error: 'Trip not found or access denied.',
|
||||
});
|
||||
expect(
|
||||
read(await mcp.unassignTourTrack({ tripId: trip.id, placeId: hike.id, activityId: 1 }, ctx(outsider.id))),
|
||||
).toEqual({ error: 'Trip not found or access denied.' });
|
||||
expect(read(await mcp.assignTourTrack({ ...input, track_place_id: 999_999 }, ctx(user.id)))).toEqual({
|
||||
error: 'Tour or recorded track not found.',
|
||||
});
|
||||
expect(await countRows(orm(), TourActivities)).toBe(0);
|
||||
});
|
||||
|
||||
it('ACT-MCP-004: without place_edit nothing is assigned or taken off', async () => {
|
||||
const { user, trip, hike, watch } = await fixture();
|
||||
const activity = await makeTourActivity(orm(), hike.id, watch.id);
|
||||
const denied = vi.spyOn(t.get(McpToolGuardsService), 'hasTripPermission').mockResolvedValue(false);
|
||||
const assigned = await mcp.assignTourTrack(
|
||||
{ tripId: trip.id, placeId: hike.id, track_place_id: watch.id, assignment_id: null },
|
||||
ctx(user.id),
|
||||
);
|
||||
const removed = await mcp.unassignTourTrack(
|
||||
{ tripId: trip.id, placeId: hike.id, activityId: activity.id },
|
||||
ctx(user.id),
|
||||
);
|
||||
expect(assigned.isError).toBe(true);
|
||||
expect(removed.isError).toBe(true);
|
||||
expect(denied).toHaveBeenCalledWith('place_edit', trip.id, user.id);
|
||||
expect(await countRows(orm(), TourActivities)).toBe(1);
|
||||
denied.mockRestore();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* TourActivitiesService and the ACT-01 parts of ToursService: a recording of
|
||||
* the trip assigned to a tour on purpose, for one execution, with every check
|
||||
* inside the write; what the recording measures read from its own line; the
|
||||
* plan left exactly as it was; and the GPX import keeping when a track was
|
||||
* recorded. The services come out of ToursModule over a snapshot test db, rows
|
||||
* are seeded through the ORM factories and broadcasts go to a FakeRealtimeService.
|
||||
*/
|
||||
import { Places } from '../../../src/db/entities/Places.entity';
|
||||
import { TourActivities } from '../../../src/db/entities/TourActivities.entity';
|
||||
import { TourWaypoints } from '../../../src/db/entities/TourWaypoints.entity';
|
||||
import { Tours } from '../../../src/db/entities/Tours.entity';
|
||||
import { DomainError } from '../../../src/nest/common/domain-error';
|
||||
import { TourActivitiesService } from '../../../src/nest/tours/tour-activities.service';
|
||||
import { ToursModule } from '../../../src/nest/tours/tours.module';
|
||||
import { ToursService } from '../../../src/nest/tours/tours.service';
|
||||
import { createSnapshotTestDb } from '../../helpers/db-mock';
|
||||
import { makeDayAssignment } from '../../helpers/factories/itinerary';
|
||||
import { makePlace } from '../../helpers/factories/places';
|
||||
import { countRows, deleteRows, findRow, updateRows } from '../../helpers/factories/rows';
|
||||
import { addTourWaypoints, makeTour, makeTourActivity } from '../../helpers/factories/tours';
|
||||
import { makeDay, makeTrip } from '../../helpers/factories/trips';
|
||||
import { makeUser } from '../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let activities: TourActivitiesService;
|
||||
let tours: ToursService;
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({ db, imports: [ToursModule] });
|
||||
activities = t.get(TourActivitiesService);
|
||||
tours = t.get(ToursService);
|
||||
});
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
t.realtime.broadcastMock.mockClear();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const PLAN = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.02, 11, 900],
|
||||
]);
|
||||
const RECORDED = JSON.stringify([
|
||||
[47, 11, 600],
|
||||
[47.01, 11.005, 760],
|
||||
[47.02, 11, 880],
|
||||
]);
|
||||
|
||||
/** The refusal a write threw, as REST and MCP report it. */
|
||||
async function refusal(write: Promise<unknown>): Promise<{ status: number; code: string }> {
|
||||
try {
|
||||
await write;
|
||||
} catch (error) {
|
||||
expect(error).toBeInstanceOf(DomainError);
|
||||
const domain = error as DomainError;
|
||||
return { status: domain.getStatus(), code: domain.code };
|
||||
}
|
||||
throw new Error('the write was not refused');
|
||||
}
|
||||
|
||||
/**
|
||||
* A planned hike on two days with its waypoints, two GPX recordings (one
|
||||
* with times), a tour planned in TREK, an import planned over, and a
|
||||
* recording in another trip.
|
||||
*/
|
||||
async function fixture() {
|
||||
const { user } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
const day1 = await makeDay(orm(), trip.id, { day_number: 1 });
|
||||
const day2 = await makeDay(orm(), trip.id, { day_number: 2 });
|
||||
const hike = await makePlace(orm(), trip.id, { name: 'Ridge', route_geometry: PLAN });
|
||||
await makeTour(orm(), hike.id, { distance: 2.2, elevation_gain: 300, elevation_loss: 0, duration: 120 });
|
||||
await addTourWaypoints(orm(), hike.id, [
|
||||
{ lat: 47, lng: 11 },
|
||||
{ lat: 47.02, lng: 11 },
|
||||
]);
|
||||
const onDay1 = await makeDayAssignment(orm(), day1.id, hike.id);
|
||||
const onDay2 = await makeDayAssignment(orm(), day2.id, hike.id);
|
||||
const watch = await makePlace(orm(), trip.id, { name: 'Watch export', route_geometry: RECORDED });
|
||||
await makeTour(orm(), watch.id, {
|
||||
origin: 'gpx',
|
||||
origin_file_name: 'morning.gpx',
|
||||
track_started_at: '2026-07-02 06:10:00',
|
||||
track_ended_at: '2026-07-02 09:25:00',
|
||||
});
|
||||
const phone = await makePlace(orm(), trip.id, { name: 'Phone export', route_geometry: RECORDED });
|
||||
await makeTour(orm(), phone.id, { origin: 'gpx' });
|
||||
const drawn = await makePlace(orm(), trip.id, { name: 'Drawn', route_geometry: PLAN });
|
||||
await makeTour(orm(), drawn.id);
|
||||
const replanned = await makePlace(orm(), trip.id, { name: 'Replanned', route_geometry: PLAN });
|
||||
await makeTour(orm(), replanned.id, { origin: 'gpx', recorded_route_geometry: RECORDED });
|
||||
await addTourWaypoints(orm(), replanned.id, [
|
||||
{ lat: 47, lng: 11 },
|
||||
{ lat: 47.02, lng: 11 },
|
||||
]);
|
||||
const other = await makeTrip(orm(), user.id);
|
||||
const elsewhere = await makePlace(orm(), other.id, { name: 'Elsewhere', route_geometry: RECORDED });
|
||||
await makeTour(orm(), elsewhere.id, { origin: 'gpx' });
|
||||
return { user, trip, day1, hike, onDay1, onDay2, watch, phone, drawn, replanned, elsewhere };
|
||||
}
|
||||
|
||||
describe('TourActivitiesService.assign', () => {
|
||||
it('ACT-SVC-001: assigns a recording to an execution and answers what it measures, the plan untouched', async () => {
|
||||
const { user, trip, day1, hike, onDay1, watch } = await fixture();
|
||||
const before = await findRow(orm(), Tours, { place: hike.id });
|
||||
const tripId = String(trip.id);
|
||||
|
||||
const detail = await activities.assign(
|
||||
tripId,
|
||||
String(hike.id),
|
||||
{ track_place_id: watch.id, assignment_id: onDay1.id },
|
||||
user.id,
|
||||
'sock-1',
|
||||
);
|
||||
|
||||
expect(detail.activities).toHaveLength(1);
|
||||
expect(detail.activities?.[0]).toMatchObject({
|
||||
assignment_id: onDay1.id,
|
||||
day_id: day1.id,
|
||||
track: { place_id: watch.id, name: 'Watch export', origin: 'gpx', file_name: 'morning.gpx' },
|
||||
metrics: {
|
||||
elevation_gain_m: 280,
|
||||
elevation_loss_m: 0,
|
||||
started_at: '2026-07-02T06:10:00Z',
|
||||
ended_at: '2026-07-02T09:25:00Z',
|
||||
elapsed_minutes: 195,
|
||||
point_count: 3,
|
||||
},
|
||||
});
|
||||
// The plan keeps its values, its line and its revision: an open draft stays valid.
|
||||
expect(detail.tour).toMatchObject({
|
||||
distance: 2.2,
|
||||
elevation_gain: 300,
|
||||
duration: 120,
|
||||
revision: before?.revision,
|
||||
activity_tracks: [{ track_place_id: watch.id, assignment_id: onDay1.id }],
|
||||
activity_of: null,
|
||||
});
|
||||
expect(await findRow(orm(), Places, { id: hike.id })).toMatchObject({ route_geometry: PLAN });
|
||||
expect(await findRow(orm(), TourActivities, { trackPlace: watch.id })).toMatchObject({ assigned_by: user.id });
|
||||
expect(t.realtime.broadcastMock).toHaveBeenCalledWith(
|
||||
tripId,
|
||||
'tours:changed',
|
||||
{ placeIds: [hike.id, watch.id] },
|
||||
'sock-1',
|
||||
);
|
||||
// The recording says whose it is, in the list and in its own detail.
|
||||
const listed = await tours.listTours(tripId);
|
||||
expect(listed.find((tour) => tour.place_id === watch.id)).toMatchObject({
|
||||
activity_of: hike.id,
|
||||
activity_tracks: [],
|
||||
track_started_at: '2026-07-02T06:10:00Z',
|
||||
track_ended_at: '2026-07-02T09:25:00Z',
|
||||
});
|
||||
expect((await tours.getTour(tripId, String(watch.id))).tour.activity_of).toBe(hike.id);
|
||||
});
|
||||
|
||||
it('ACT-SVC-002: an execution takes a new recording in place of its old one; a recording moves between executions', async () => {
|
||||
const { user, trip, hike, onDay1, onDay2, watch, phone } = await fixture();
|
||||
const tripId = String(trip.id);
|
||||
const placeId = String(hike.id);
|
||||
await activities.assign(tripId, placeId, { track_place_id: watch.id, assignment_id: onDay1.id }, user.id);
|
||||
await activities.assign(tripId, placeId, { track_place_id: phone.id, assignment_id: onDay1.id }, user.id);
|
||||
let detail = await tours.getTour(tripId, placeId);
|
||||
expect(detail.activities?.map((a) => [a.track.place_id, a.assignment_id])).toEqual([[phone.id, onDay1.id]]);
|
||||
|
||||
detail = await activities.assign(tripId, placeId, { track_place_id: phone.id, assignment_id: onDay2.id }, user.id);
|
||||
expect(detail.activities?.map((a) => [a.track.place_id, a.assignment_id])).toEqual([[phone.id, onDay2.id]]);
|
||||
|
||||
// Without a day it is one recording too: a second one replaces the first.
|
||||
await activities.assign(tripId, placeId, { track_place_id: watch.id, assignment_id: null }, user.id);
|
||||
detail = await activities.assign(tripId, placeId, { track_place_id: watch.id, assignment_id: null }, user.id);
|
||||
expect(detail.activities?.map((a) => [a.track.place_id, a.assignment_id])).toEqual([
|
||||
[phone.id, onDay2.id],
|
||||
[watch.id, null],
|
||||
]);
|
||||
});
|
||||
|
||||
it('ACT-SVC-003: refuses what is no recording, and a tour as its own', async () => {
|
||||
const { user, trip, hike, drawn, replanned } = await fixture();
|
||||
const tripId = String(trip.id);
|
||||
const assign = (track: number, place = hike.id) =>
|
||||
activities.assign(tripId, String(place), { track_place_id: track, assignment_id: null }, user.id);
|
||||
expect(await refusal(assign(drawn.id))).toEqual({ status: 400, code: 'activity_track_not_recorded' });
|
||||
expect(await refusal(assign(replanned.id))).toEqual({ status: 400, code: 'activity_track_not_recorded' });
|
||||
expect(await refusal(assign(hike.id))).toEqual({ status: 400, code: 'activity_track_is_tour' });
|
||||
expect(await countRows(orm(), TourActivities)).toBe(0);
|
||||
});
|
||||
|
||||
it('ACT-SVC-004: a recording documents one tour, and a recording or a tour with recordings is no candidate the other way', async () => {
|
||||
const { user, trip, hike, watch, phone, drawn } = await fixture();
|
||||
const tripId = String(trip.id);
|
||||
await makeTourActivity(orm(), hike.id, watch.id);
|
||||
const assign = (place: number, track: number) =>
|
||||
activities.assign(tripId, String(place), { track_place_id: track, assignment_id: null }, user.id);
|
||||
|
||||
expect(await refusal(assign(drawn.id, watch.id))).toEqual({ status: 409, code: 'activity_track_in_use' });
|
||||
expect(await refusal(assign(watch.id, phone.id))).toEqual({ status: 400, code: 'activity_tour_is_track' });
|
||||
// The hike has a recording of its own, so it is nobody's recording.
|
||||
await updateRows(orm(), Tours, { place: hike.id }, { origin: 'gpx' });
|
||||
await deleteRows(orm(), TourWaypoints, { place: hike.id });
|
||||
expect(await refusal(assign(drawn.id, hike.id))).toEqual({ status: 400, code: 'activity_track_is_tour' });
|
||||
expect(await countRows(orm(), TourActivities)).toBe(1);
|
||||
});
|
||||
|
||||
it('ACT-SVC-005: an execution must be a day of this tour, and every id must be of this trip', async () => {
|
||||
const { user, trip, hike, onDay1, watch, drawn, elsewhere } = await fixture();
|
||||
const tripId = String(trip.id);
|
||||
const onDrawnDay = await makeDayAssignment(orm(), (await makeDay(orm(), trip.id)).id, drawn.id);
|
||||
expect(
|
||||
await refusal(
|
||||
activities.assign(tripId, String(hike.id), { track_place_id: watch.id, assignment_id: onDrawnDay.id }, user.id),
|
||||
),
|
||||
).toEqual({ status: 400, code: 'activity_assignment_not_of_tour' });
|
||||
await expect(
|
||||
activities.assign(tripId, String(hike.id), { track_place_id: elsewhere.id, assignment_id: null }, user.id),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(
|
||||
activities.assign(tripId, String(elsewhere.id), { track_place_id: watch.id, assignment_id: onDay1.id }, user.id),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
await expect(
|
||||
activities.assign('nope', String(hike.id), { track_place_id: watch.id, assignment_id: null }, user.id),
|
||||
).rejects.toBeInstanceOf(NotFoundException);
|
||||
expect(await countRows(orm(), TourActivities)).toBe(0);
|
||||
expect(t.realtime.broadcastMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('TourActivitiesService.unassign', () => {
|
||||
it('ACT-SVC-006: takes a recording off the tour; the recording stays in the trip', async () => {
|
||||
const { trip, hike, watch } = await fixture();
|
||||
const activity = await makeTourActivity(orm(), hike.id, watch.id);
|
||||
const tripId = String(trip.id);
|
||||
|
||||
const detail = await activities.unassign(tripId, String(hike.id), activity.id, 'sock-2');
|
||||
expect(detail.activities).toEqual([]);
|
||||
expect(detail.tour.activity_tracks).toEqual([]);
|
||||
expect(await findRow(orm(), Tours, { place: watch.id })).not.toBeNull();
|
||||
expect(t.realtime.broadcastMock).toHaveBeenCalledWith(
|
||||
tripId,
|
||||
'tours:changed',
|
||||
{ placeIds: [hike.id, watch.id] },
|
||||
'sock-2',
|
||||
);
|
||||
});
|
||||
|
||||
it('ACT-SVC-007: 404 for an assignment of another tour, or one that is gone', async () => {
|
||||
const { trip, hike, watch, drawn } = await fixture();
|
||||
const activity = await makeTourActivity(orm(), hike.id, watch.id);
|
||||
await expect(activities.unassign(String(trip.id), String(drawn.id), activity.id)).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
await expect(activities.unassign(String(trip.id), String(hike.id), 999_999)).rejects.toBeInstanceOf(
|
||||
NotFoundException,
|
||||
);
|
||||
expect(await countRows(orm(), TourActivities)).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('ToursService and ACT-01', () => {
|
||||
const TIMED = `<?xml version="1.0"?>
|
||||
<gpx version="1.1" creator="unit"><trk><name>Morning</name><trkseg>
|
||||
<trkpt lat="47" lon="11"><ele>600</ele><time>2026-07-02T06:10:00Z</time></trkpt>
|
||||
<trkpt lat="47.01" lon="11"><ele>700</ele><time>2026-07-02T07:00:00Z</time></trkpt>
|
||||
</trkseg></trk><trk><name>Untimed</name><trkseg>
|
||||
<trkpt lat="46" lon="10"/><trkpt lat="46.01" lon="10"/>
|
||||
</trkseg></trk></gpx>`;
|
||||
|
||||
it('ACT-SVC-008: the preview shows when a track was recorded, and the import keeps it; a track without times stays unknown', async () => {
|
||||
const { trip } = await fixture();
|
||||
const tripId = String(trip.id);
|
||||
const preview = await tours.previewGpx(tripId, Buffer.from(TIMED), 'morning.gpx');
|
||||
expect(preview?.tracks.map((track) => [track.name, track.started_at, track.ended_at])).toEqual([
|
||||
['Morning', '2026-07-02T06:10:00.000Z', '2026-07-02T07:00:00.000Z'],
|
||||
['Untimed', null, null],
|
||||
]);
|
||||
|
||||
const imported = await tours.importGpxAsTour(tripId, Buffer.from(TIMED), 'morning.gpx');
|
||||
const byName = new Map(imported?.tours.map((tour) => [tour.name, tour]));
|
||||
expect(byName.get('Morning')).toMatchObject({
|
||||
track_started_at: '2026-07-02T06:10:00Z',
|
||||
track_ended_at: '2026-07-02T07:00:00Z',
|
||||
});
|
||||
expect(byName.get('Untimed')).toMatchObject({ track_started_at: null, track_ended_at: null });
|
||||
const morning = byName.get('Morning')?.place_id ?? 0;
|
||||
expect(await findRow(orm(), Tours, { place: morning })).toMatchObject({
|
||||
track_started_at: '2026-07-02 06:10:00',
|
||||
track_ended_at: '2026-07-02 07:00:00',
|
||||
});
|
||||
});
|
||||
|
||||
it('ACT-SVC-009: a copy of a recording keeps when it was recorded; a copy of a tour leaves its recordings behind', async () => {
|
||||
const { trip, hike, watch } = await fixture();
|
||||
await makeTourActivity(orm(), hike.id, watch.id);
|
||||
const tripId = String(trip.id);
|
||||
|
||||
const recordingCopy = await tours.copyTour(tripId, String(watch.id), 'Watch again');
|
||||
expect(recordingCopy.tour).toMatchObject({ track_started_at: '2026-07-02T06:10:00Z', activity_of: null });
|
||||
const tourCopy = await tours.copyTour(tripId, String(hike.id), 'Ridge again');
|
||||
expect(tourCopy.activities).toEqual([]);
|
||||
expect(tourCopy.tour.activity_tracks).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -60,6 +60,7 @@ import {
|
||||
sharedTestOrm,
|
||||
} from '../../helpers/test-uow';
|
||||
import {
|
||||
createTestTourActivitiesRepo,
|
||||
createTestToursRepo,
|
||||
createTestTourStationVisitsRepo,
|
||||
createTestTourTypesRepo,
|
||||
@@ -172,6 +173,7 @@ beforeAll(async () => {
|
||||
await createTestTourWaypointsRepo(testDb),
|
||||
await createTestTourStationVisitsRepo(testDb),
|
||||
await createTestPlacesRepo(testDb),
|
||||
await createTestTourActivitiesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
noPaddleChecks(),
|
||||
);
|
||||
|
||||
@@ -25,7 +25,7 @@ import type { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import type { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
import { ToursService } from '../../../src/nest/tours/tours.service';
|
||||
import type { User } from '../../../src/types';
|
||||
import { noPaddleChecks } from '../../helpers/fake-paddle-checks';
|
||||
import { noActivities, noPaddleChecks } from '../../helpers/fake-paddle-checks';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { keyed } from '../../helpers/tour-keys';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
@@ -310,6 +310,7 @@ function tourRepositoryFixture(ownerTripId: number) {
|
||||
waypointsRepo as unknown as TourWaypointsRepository,
|
||||
{ dropStationsNotIn: vi.fn(async () => []) } as unknown as TourStationVisitsRepository,
|
||||
placesRepo as unknown as PlacesRepository,
|
||||
noActivities(),
|
||||
buildPlaceImportService(),
|
||||
noPaddleChecks(),
|
||||
);
|
||||
|
||||
@@ -13,7 +13,7 @@ import type { TourProvenanceRow, ToursRepository } from '../../../src/db/reposit
|
||||
import type { UnitOfWork } from '../../../src/nest/database/unit-of-work';
|
||||
import type { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { ToursService } from '../../../src/nest/tours/tours.service';
|
||||
import { noPaddleChecks } from '../../helpers/fake-paddle-checks';
|
||||
import { noActivities, noPaddleChecks } from '../../helpers/fake-paddle-checks';
|
||||
import { buildPlaceImportService } from '../../helpers/place-import';
|
||||
import { keyed } from '../../helpers/tour-keys';
|
||||
import { NotFoundException } from '@nestjs/common';
|
||||
@@ -145,6 +145,7 @@ function makeService() {
|
||||
waypointsRepo as unknown as TourWaypointsRepository,
|
||||
visitsRepo as unknown as TourStationVisitsRepository,
|
||||
placesRepo as unknown as PlacesRepository,
|
||||
noActivities(),
|
||||
buildPlaceImportService(),
|
||||
noPaddleChecks(),
|
||||
);
|
||||
|
||||
@@ -22,6 +22,7 @@ import { resetTestDb } from '../../helpers/test-db';
|
||||
import { createTestPlacesRepo, createTestUnitOfWork, sharedTestOrm } from '../../helpers/test-uow';
|
||||
import { keyed } from '../../helpers/tour-keys';
|
||||
import {
|
||||
createTestTourActivitiesRepo,
|
||||
createTestToursRepo,
|
||||
createTestTourStationVisitsRepo,
|
||||
createTestTourTypesRepo,
|
||||
@@ -86,6 +87,7 @@ beforeAll(async () => {
|
||||
await createTestTourWaypointsRepo(testDb),
|
||||
await createTestTourStationVisitsRepo(testDb),
|
||||
await createTestPlacesRepo(testDb),
|
||||
await createTestTourActivitiesRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
noPaddleChecks(),
|
||||
);
|
||||
|
||||
@@ -1211,5 +1211,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'الوصول غير مُتحقق منه',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'لا يتحقق الاستيراد مما إذا كان يُسمح بركوب الطرق. العبرة باللافتات في المكان.',
|
||||
'tours.activity.label': 'المسار الفعلي',
|
||||
'tours.activity.assign': 'إضافة المسار الفعلي',
|
||||
'tours.activity.assignHint': 'اربط المسار الذي سلكته فعلًا، من هذه الرحلة أو من ملف GPX',
|
||||
'tours.activity.empty': 'لا يوجد مسار فعلي بعد',
|
||||
'tours.activity.badge': 'فعلي',
|
||||
'tours.activity.badgeHint': 'قيم المسار الذي سلكته فعلًا، لا قيم الخطة',
|
||||
'tours.activity.isTrackHint': 'المسار الفعلي لجولة في هذه الرحلة',
|
||||
'tours.activity.ofTour': 'المسار الفعلي لـ {name}',
|
||||
'tours.activity.noDay': 'بلا يوم',
|
||||
'tours.activity.time': 'الوقت المستغرق',
|
||||
'tours.activity.timeHint': 'من أول طابع زمني في المسار إلى آخره، مع فترات الاستراحة',
|
||||
'tours.activity.noTime': 'لا طوابع زمنية',
|
||||
'tours.activity.noTimeHint': 'لا يحتوي المسار على طوابع زمنية، لذا لم يُقَس أي وقت',
|
||||
'tours.activity.recordedOn': 'سُجّل في {date}',
|
||||
'tours.activity.change': 'تغيير',
|
||||
'tours.activity.remove': 'فك الربط',
|
||||
'tours.activity.removeTitle': 'فك ربط المسار الفعلي؟',
|
||||
'tours.activity.removeBody': 'يبقى المسار في الرحلة كملف مستورد. لا تتغير الجولة المخطط لها.',
|
||||
'tours.activity.assigned': 'تم ربط المسار الفعلي',
|
||||
'tours.activity.removed': 'تم فك ربط المسار الفعلي',
|
||||
'tours.activity.failed': 'تعذّر تغيير المسار الفعلي',
|
||||
'tours.activity.dialogEyebrow': 'إضافة المسار الفعلي',
|
||||
'tours.activity.dialogHint': 'تبقى الخطة كما هي. يُربط المسار فقط.',
|
||||
'tours.activity.execution': 'نُفّذت في',
|
||||
'tours.activity.track': 'تسجيل',
|
||||
'tours.activity.importGpx': 'استيراد GPX',
|
||||
'tours.activity.noCandidates': 'لا يوجد بعد مسار في هذه الرحلة لربطه. استورد ملف GPX.',
|
||||
'tours.activity.replaces': 'يحل محل {name} في هذا اليوم',
|
||||
'tours.activity.confirm': 'ربط',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'لا يمكن ربط إلا ملف مستورد لم يُعَد تخطيطه',
|
||||
'tours.activity.refused.activity_track_in_use': 'هذا المسار مرتبط بالفعل بجولة أخرى',
|
||||
'tours.activity.refused.activity_track_is_tour': 'لهذا المسار مسارات فعلية خاصة به',
|
||||
'tours.activity.refused.activity_tour_is_track': 'هذه الجولة هي نفسها المسار الفعلي لجولة أخرى',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'لم تعد الجولة في ذلك اليوم',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1179,5 +1179,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Giriş yoxlanılmayıb',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'İdxal yollarda at sürməyə icazə olub-olmadığını yoxlamır. Yerdəki lövhələr əsasdır.',
|
||||
'tours.activity.label': 'Faktiki iz',
|
||||
'tours.activity.assign': 'Faktiki iz əlavə et',
|
||||
'tours.activity.assignHint': 'Həqiqətən keçdiyin izi bu səyahətdən və ya GPX faylından bağla',
|
||||
'tours.activity.empty': 'Hələ faktiki iz yoxdur',
|
||||
'tours.activity.badge': 'Faktiki',
|
||||
'tours.activity.badgeHint': 'Planın deyil, həqiqətən keçdiyin izin göstəriciləri',
|
||||
'tours.activity.isTrackHint': 'Bu səyahətdəki turun faktiki izi',
|
||||
'tours.activity.ofTour': '{name} turunun faktiki izi',
|
||||
'tours.activity.noDay': 'Gün yoxdur',
|
||||
'tours.activity.time': 'Sərf olunan vaxt',
|
||||
'tours.activity.timeHint': 'İzin ilk vaxt möhüründən sonuncusuna qədər, fasilələr daxil',
|
||||
'tours.activity.noTime': 'Vaxt möhürü yoxdur',
|
||||
'tours.activity.noTimeHint': 'İzdə vaxt möhürü yoxdur, buna görə vaxt ölçülməyib',
|
||||
'tours.activity.recordedOn': 'Qeydə alınıb: {date}',
|
||||
'tours.activity.change': 'Dəyiş',
|
||||
'tours.activity.remove': 'Əlaqəni sil',
|
||||
'tours.activity.removeTitle': 'Faktiki izin əlaqəsi silinsin?',
|
||||
'tours.activity.removeBody': 'İz səyahətdə idxal kimi qalır. Planlaşdırılmış tur dəyişmir.',
|
||||
'tours.activity.assigned': 'Faktiki iz bağlandı',
|
||||
'tours.activity.removed': 'Faktiki izin əlaqəsi silindi',
|
||||
'tours.activity.failed': 'Faktiki izi dəyişmək mümkün olmadı',
|
||||
'tours.activity.dialogEyebrow': 'Faktiki iz əlavə et',
|
||||
'tours.activity.dialogHint': 'Plan olduğu kimi qalır. İz sadəcə bağlanır.',
|
||||
'tours.activity.execution': 'Keçirildiyi gün',
|
||||
'tours.activity.track': 'Qeyd',
|
||||
'tours.activity.importGpx': 'GPX idxal et',
|
||||
'tours.activity.noCandidates': 'Bu səyahətdə hələ bağlanacaq iz yoxdur. GPX faylı idxal et.',
|
||||
'tours.activity.replaces': 'Bu gündə {name} əvəzinə keçir',
|
||||
'tours.activity.confirm': 'Bağla',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Yalnız yenidən planlaşdırılmamış idxal bağlana bilər',
|
||||
'tours.activity.refused.activity_track_in_use': 'Bu iz artıq başqa tura aiddir',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Bu izin öz faktiki izləri var',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Bu tur özü başqa turun faktiki izidir',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Tur artıq o gündə deyil',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1191,5 +1191,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Acesso não verificado',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'A importação não verifica se as vias podem ser percorridas a cavalo. Valem as placas no local.',
|
||||
'tours.activity.label': 'Trilha real',
|
||||
'tours.activity.assign': 'Adicionar trilha real',
|
||||
'tours.activity.assignHint': 'Vincule a trilha que você realmente fez, desta viagem ou de um arquivo GPX',
|
||||
'tours.activity.empty': 'Ainda sem trilha real',
|
||||
'tours.activity.badge': 'Real',
|
||||
'tours.activity.badgeHint': 'Valores da trilha que você realmente fez, não do plano',
|
||||
'tours.activity.isTrackHint': 'Trilha real de um passeio desta viagem',
|
||||
'tours.activity.ofTour': 'Trilha real de {name}',
|
||||
'tours.activity.noDay': 'Sem dia',
|
||||
'tours.activity.time': 'Tempo gasto',
|
||||
'tours.activity.timeHint': 'Do primeiro ao último registro de horário da trilha, pausas incluídas',
|
||||
'tours.activity.noTime': 'Sem registros de horário',
|
||||
'tours.activity.noTimeHint': 'A trilha não tem registros de horário, então nenhum tempo foi medido',
|
||||
'tours.activity.recordedOn': 'Gravada em {date}',
|
||||
'tours.activity.change': 'Alterar',
|
||||
'tours.activity.remove': 'Desvincular',
|
||||
'tours.activity.removeTitle': 'Desvincular a trilha real?',
|
||||
'tours.activity.removeBody': 'A trilha continua na viagem como importação. O passeio planejado não muda.',
|
||||
'tours.activity.assigned': 'Trilha real vinculada',
|
||||
'tours.activity.removed': 'Trilha real desvinculada',
|
||||
'tours.activity.failed': 'Não foi possível alterar a trilha real',
|
||||
'tours.activity.dialogEyebrow': 'Adicionar trilha real',
|
||||
'tours.activity.dialogHint': 'O plano continua como está. A trilha é apenas vinculada.',
|
||||
'tours.activity.execution': 'Feito em',
|
||||
'tours.activity.track': 'Gravação',
|
||||
'tours.activity.importGpx': 'Importar GPX',
|
||||
'tours.activity.noCandidates': 'Ainda não há trilha nesta viagem para vincular. Importe um arquivo GPX.',
|
||||
'tours.activity.replaces': 'Substitui {name} neste dia',
|
||||
'tours.activity.confirm': 'Vincular',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Só uma importação que não foi replanejada pode ser vinculada',
|
||||
'tours.activity.refused.activity_track_in_use': 'Esta trilha já pertence a outro passeio',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Esta trilha tem trilhas reais próprias',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Este passeio é a trilha real de outro passeio',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'O passeio não está mais nesse dia',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1197,5 +1197,40 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Accés sense comprovar',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'La importació no comprova si es pot anar a cavall pels camins. Valen els senyals sobre el terreny.',
|
||||
'tours.activity.label': 'Traç real',
|
||||
'tours.activity.assign': 'Afegeix el traç real',
|
||||
'tours.activity.assignHint': 'Vincula el traç que vas fer realment, d’aquest viatge o d’un fitxer GPX',
|
||||
'tours.activity.empty': 'Encara no hi ha traç real',
|
||||
'tours.activity.badge': 'Real',
|
||||
'tours.activity.badgeHint': 'Valors del traç que vas fer realment, no del pla',
|
||||
'tours.activity.isTrackHint': 'Traç real d’una ruta d’aquest viatge',
|
||||
'tours.activity.ofTour': 'Traç real de {name}',
|
||||
'tours.activity.noDay': 'Sense dia',
|
||||
'tours.activity.time': 'Temps emprat',
|
||||
'tours.activity.timeHint': 'Des de la primera fins a l’última marca de temps del traç, pauses incloses',
|
||||
'tours.activity.noTime': 'Sense marques de temps',
|
||||
'tours.activity.noTimeHint': 'El traç no té marques de temps, així que no s’ha mesurat cap temps',
|
||||
'tours.activity.recordedOn': 'Enregistrat el {date}',
|
||||
'tours.activity.change': 'Canvia',
|
||||
'tours.activity.remove': 'Desvincula',
|
||||
'tours.activity.removeTitle': 'Vols desvincular el traç real?',
|
||||
'tours.activity.removeBody': 'El traç es queda al viatge com a importació. La ruta planificada no canvia.',
|
||||
'tours.activity.assigned': 'Traç real vinculat',
|
||||
'tours.activity.removed': 'Traç real desvinculat',
|
||||
'tours.activity.failed': 'No s’ha pogut canviar el traç real',
|
||||
'tours.activity.dialogEyebrow': 'Afegeix el traç real',
|
||||
'tours.activity.dialogHint': 'El pla es queda com està. El traç només es vincula.',
|
||||
'tours.activity.execution': 'Feta el',
|
||||
'tours.activity.track': 'Enregistrament',
|
||||
'tours.activity.importGpx': 'Importa GPX',
|
||||
'tours.activity.noCandidates': 'Encara no hi ha cap traç en aquest viatge per vincular. Importa un fitxer GPX.',
|
||||
'tours.activity.replaces': 'Substitueix {name} aquest dia',
|
||||
'tours.activity.confirm': 'Vincula',
|
||||
'tours.activity.refused.activity_track_not_recorded':
|
||||
'Només es pot vincular una importació que no s’hagi replanificat',
|
||||
'tours.activity.refused.activity_track_in_use': 'Aquest traç ja pertany a una altra ruta',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Aquest traç té traços reals propis',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Aquesta ruta és alhora el traç real d’una altra ruta',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'La ruta ja no és en aquell dia',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1177,5 +1177,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Přístup neověřen',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Import neověřuje, zda se po cestách smí jezdit na koni. Platí značení na místě.',
|
||||
'tours.activity.label': 'Skutečná trasa',
|
||||
'tours.activity.assign': 'Přidat skutečnou trasu',
|
||||
'tours.activity.assignHint': 'Propoj trasu, kterou jsi opravdu ušel, z této cesty nebo ze souboru GPX',
|
||||
'tours.activity.empty': 'Zatím žádná skutečná trasa',
|
||||
'tours.activity.badge': 'Skutečnost',
|
||||
'tours.activity.badgeHint': 'Hodnoty skutečně ušlé trasy, ne plánu',
|
||||
'tours.activity.isTrackHint': 'Skutečná trasa túry této cesty',
|
||||
'tours.activity.ofTour': 'Skutečná trasa: {name}',
|
||||
'tours.activity.noDay': 'Bez dne',
|
||||
'tours.activity.time': 'Potřebný čas',
|
||||
'tours.activity.timeHint': 'Od prvního do posledního časového razítka trasy, včetně přestávek',
|
||||
'tours.activity.noTime': 'Bez časových razítek',
|
||||
'tours.activity.noTimeHint': 'Trasa nemá časová razítka, proto nebyl změřen žádný čas',
|
||||
'tours.activity.recordedOn': 'Zaznamenáno {date}',
|
||||
'tours.activity.change': 'Změnit',
|
||||
'tours.activity.remove': 'Odpojit',
|
||||
'tours.activity.removeTitle': 'Odpojit skutečnou trasu?',
|
||||
'tours.activity.removeBody': 'Trasa zůstane v cestě jako import. Plánovaná túra se nezmění.',
|
||||
'tours.activity.assigned': 'Skutečná trasa propojena',
|
||||
'tours.activity.removed': 'Skutečná trasa odpojena',
|
||||
'tours.activity.failed': 'Skutečnou trasu se nepodařilo změnit',
|
||||
'tours.activity.dialogEyebrow': 'Přidat skutečnou trasu',
|
||||
'tours.activity.dialogHint': 'Plán zůstává, jak je. Trasa se jen propojí.',
|
||||
'tours.activity.execution': 'Uskutečněno',
|
||||
'tours.activity.track': 'Záznam',
|
||||
'tours.activity.importGpx': 'Importovat GPX',
|
||||
'tours.activity.noCandidates': 'V této cestě zatím není žádná trasa k propojení. Importuj soubor GPX.',
|
||||
'tours.activity.replaces': 'Nahradí {name} v tento den',
|
||||
'tours.activity.confirm': 'Propojit',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Propojit lze jen import, který nebyl přeplánován',
|
||||
'tours.activity.refused.activity_track_in_use': 'Tato trasa už patří k jiné túře',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Tato trasa má vlastní skutečné trasy',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Tato túra je sama skutečnou trasou jiné túry',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Túra už v tento den není',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1203,6 +1203,41 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Zugang nicht geprüft',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Der Import prüft nicht, ob die Wege geritten werden dürfen. Es gilt die Beschilderung vor Ort.',
|
||||
'tours.activity.label': 'Ist-Track',
|
||||
'tours.activity.assign': 'Ist-Track hinzufügen',
|
||||
'tours.activity.assignHint': 'Den tatsächlich gegangenen Track verknüpfen, aus dieser Reise oder einer GPX-Datei',
|
||||
'tours.activity.empty': 'Noch kein Ist-Track',
|
||||
'tours.activity.badge': 'Ist',
|
||||
'tours.activity.badgeHint': 'Werte des tatsächlich gegangenen Tracks, nicht der Planung',
|
||||
'tours.activity.isTrackHint': 'Ist-Track einer Tour dieser Reise',
|
||||
'tours.activity.ofTour': 'Ist-Track von {name}',
|
||||
'tours.activity.noDay': 'Ohne Tag',
|
||||
'tours.activity.time': 'Benötigte Zeit',
|
||||
'tours.activity.timeHint': 'Vom ersten bis zum letzten Zeitstempel des Tracks, Pausen eingeschlossen',
|
||||
'tours.activity.noTime': 'Keine Zeitstempel',
|
||||
'tours.activity.noTimeHint': 'Der Track enthält keine Zeitstempel, daher wurde keine Zeit gemessen',
|
||||
'tours.activity.recordedOn': 'Aufgezeichnet am {date}',
|
||||
'tours.activity.change': 'Ändern',
|
||||
'tours.activity.remove': 'Lösen',
|
||||
'tours.activity.removeTitle': 'Ist-Track lösen?',
|
||||
'tours.activity.removeBody': 'Der Track bleibt als Import in der Reise. Die geplante Tour ändert sich nicht.',
|
||||
'tours.activity.assigned': 'Ist-Track verknüpft',
|
||||
'tours.activity.removed': 'Ist-Track gelöst',
|
||||
'tours.activity.failed': 'Der Ist-Track konnte nicht geändert werden',
|
||||
'tours.activity.dialogEyebrow': 'Ist-Track hinzufügen',
|
||||
'tours.activity.dialogHint': 'Die Planung bleibt, wie sie ist. Der Track wird nur verknüpft.',
|
||||
'tours.activity.execution': 'Durchgeführt am',
|
||||
'tours.activity.track': 'Aufzeichnung',
|
||||
'tours.activity.importGpx': 'GPX importieren',
|
||||
'tours.activity.noCandidates': 'Noch kein Track in dieser Reise zum Verknüpfen. Importiere eine GPX-Datei.',
|
||||
'tours.activity.replaces': 'Ersetzt {name} an diesem Tag',
|
||||
'tours.activity.confirm': 'Verknüpfen',
|
||||
'tours.activity.refused.activity_track_not_recorded':
|
||||
'Nur ein Import, der nicht überplant wurde, kann verknüpft werden',
|
||||
'tours.activity.refused.activity_track_in_use': 'Dieser Track gehört bereits zu einer anderen Tour',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Dieser Track hat selbst Ist-Tracks',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Diese Tour ist selbst der Ist-Track einer anderen Tour',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Die Tour ist nicht mehr an diesem Tag',
|
||||
};
|
||||
|
||||
export default tours;
|
||||
|
||||
@@ -1166,5 +1166,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Access not checked',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'The import does not check whether the ways may be ridden. The signs on site count.',
|
||||
'tours.activity.label': 'Actual track',
|
||||
'tours.activity.assign': 'Add actual track',
|
||||
'tours.activity.assignHint': 'Link the track you actually took, from this trip or a GPX file',
|
||||
'tours.activity.empty': 'No actual track yet',
|
||||
'tours.activity.badge': 'Actual',
|
||||
'tours.activity.badgeHint': 'Values of the track you actually took, not of the plan',
|
||||
'tours.activity.isTrackHint': 'Actual track of a tour in this trip',
|
||||
'tours.activity.ofTour': 'Actual track of {name}',
|
||||
'tours.activity.noDay': 'No day',
|
||||
'tours.activity.time': 'Time taken',
|
||||
'tours.activity.timeHint': 'From the first to the last time stamp in the track, breaks included',
|
||||
'tours.activity.noTime': 'No time stamps',
|
||||
'tours.activity.noTimeHint': 'The track carries no time stamps, so no time was measured',
|
||||
'tours.activity.recordedOn': 'Recorded {date}',
|
||||
'tours.activity.change': 'Change',
|
||||
'tours.activity.remove': 'Unlink',
|
||||
'tours.activity.removeTitle': 'Unlink the actual track?',
|
||||
'tours.activity.removeBody': 'The track stays in the trip as an import. The planned tour does not change.',
|
||||
'tours.activity.assigned': 'Actual track linked',
|
||||
'tours.activity.removed': 'Actual track unlinked',
|
||||
'tours.activity.failed': 'The actual track could not be changed',
|
||||
'tours.activity.dialogEyebrow': 'Add actual track',
|
||||
'tours.activity.dialogHint': 'The plan stays as it is. The track is only linked.',
|
||||
'tours.activity.execution': 'Done on',
|
||||
'tours.activity.track': 'Track',
|
||||
'tours.activity.importGpx': 'Import GPX',
|
||||
'tours.activity.noCandidates': 'No track in this trip to link yet. Import a GPX file.',
|
||||
'tours.activity.replaces': 'Replaces {name} on this day',
|
||||
'tours.activity.confirm': 'Link',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Only an import that was not planned over can be linked',
|
||||
'tours.activity.refused.activity_track_in_use': 'This track already belongs to another tour',
|
||||
'tours.activity.refused.activity_track_is_tour': 'This track has actual tracks of its own',
|
||||
'tours.activity.refused.activity_tour_is_track': 'This tour is itself the actual track of another tour',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'The tour is no longer on that day',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1190,5 +1190,40 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Acceso sin comprobar',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'La importación no comprueba si se puede ir a caballo por las vías. Valen las señales sobre el terreno.',
|
||||
'tours.activity.label': 'Track real',
|
||||
'tours.activity.assign': 'Añadir track real',
|
||||
'tours.activity.assignHint': 'Vincula el track que realmente hiciste, de este viaje o de un archivo GPX',
|
||||
'tours.activity.empty': 'Aún no hay track real',
|
||||
'tours.activity.badge': 'Real',
|
||||
'tours.activity.badgeHint': 'Valores del track que realmente hiciste, no del plan',
|
||||
'tours.activity.isTrackHint': 'Track real de una ruta de este viaje',
|
||||
'tours.activity.ofTour': 'Track real de {name}',
|
||||
'tours.activity.noDay': 'Sin día',
|
||||
'tours.activity.time': 'Tiempo empleado',
|
||||
'tours.activity.timeHint': 'Desde la primera hasta la última marca de tiempo del track, pausas incluidas',
|
||||
'tours.activity.noTime': 'Sin marcas de tiempo',
|
||||
'tours.activity.noTimeHint': 'El track no tiene marcas de tiempo, así que no se midió ningún tiempo',
|
||||
'tours.activity.recordedOn': 'Grabado el {date}',
|
||||
'tours.activity.change': 'Cambiar',
|
||||
'tours.activity.remove': 'Desvincular',
|
||||
'tours.activity.removeTitle': '¿Desvincular el track real?',
|
||||
'tours.activity.removeBody': 'El track queda en el viaje como importación. La ruta planificada no cambia.',
|
||||
'tours.activity.assigned': 'Track real vinculado',
|
||||
'tours.activity.removed': 'Track real desvinculado',
|
||||
'tours.activity.failed': 'No se pudo cambiar el track real',
|
||||
'tours.activity.dialogEyebrow': 'Añadir track real',
|
||||
'tours.activity.dialogHint': 'El plan queda como está. El track solo se vincula.',
|
||||
'tours.activity.execution': 'Hecha el',
|
||||
'tours.activity.track': 'Grabación',
|
||||
'tours.activity.importGpx': 'Importar GPX',
|
||||
'tours.activity.noCandidates': 'Todavía no hay ningún track en este viaje para vincular. Importa un archivo GPX.',
|
||||
'tours.activity.replaces': 'Sustituye a {name} en este día',
|
||||
'tours.activity.confirm': 'Vincular',
|
||||
'tours.activity.refused.activity_track_not_recorded':
|
||||
'Solo se puede vincular una importación que no se haya replanificado',
|
||||
'tours.activity.refused.activity_track_in_use': 'Este track ya pertenece a otra ruta',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Este track tiene sus propios tracks reales',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Esta ruta es a su vez el track real de otra ruta',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'La ruta ya no está en ese día',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1175,5 +1175,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Ligipääs kontrollimata',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Import ei kontrolli, kas teedel tohib ratsutada. Kohapeal kehtivad sildid.',
|
||||
'tours.activity.label': 'Tegelik rada',
|
||||
'tours.activity.assign': 'Lisa tegelik rada',
|
||||
'tours.activity.assignHint': 'Seo päriselt läbitud rada, sellest reisist või GPX-failist',
|
||||
'tours.activity.empty': 'Tegelikku rada veel pole',
|
||||
'tours.activity.badge': 'Tegelik',
|
||||
'tours.activity.badgeHint': 'Päriselt läbitud raja väärtused, mitte plaani omad',
|
||||
'tours.activity.isTrackHint': 'Selle reisi ühe matka tegelik rada',
|
||||
'tours.activity.ofTour': 'Matka {name} tegelik rada',
|
||||
'tours.activity.noDay': 'Päevata',
|
||||
'tours.activity.time': 'Kulunud aeg',
|
||||
'tours.activity.timeHint': 'Raja esimesest viimase ajatemplini, pausid kaasa arvatud',
|
||||
'tours.activity.noTime': 'Ajatemplid puuduvad',
|
||||
'tours.activity.noTimeHint': 'Rajal pole ajatempleid, seega aega ei mõõdetud',
|
||||
'tours.activity.recordedOn': 'Salvestatud {date}',
|
||||
'tours.activity.change': 'Muuda',
|
||||
'tours.activity.remove': 'Eemalda seos',
|
||||
'tours.activity.removeTitle': 'Kas eemaldada tegeliku raja seos?',
|
||||
'tours.activity.removeBody': 'Rada jääb reisi importina alles. Planeeritud matk ei muutu.',
|
||||
'tours.activity.assigned': 'Tegelik rada seotud',
|
||||
'tours.activity.removed': 'Tegeliku raja seos eemaldatud',
|
||||
'tours.activity.failed': 'Tegelikku rada ei õnnestunud muuta',
|
||||
'tours.activity.dialogEyebrow': 'Lisa tegelik rada',
|
||||
'tours.activity.dialogHint': 'Plaan jääb samaks. Rada ainult seotakse.',
|
||||
'tours.activity.execution': 'Läbitud',
|
||||
'tours.activity.track': 'Salvestis',
|
||||
'tours.activity.importGpx': 'Impordi GPX',
|
||||
'tours.activity.noCandidates': 'Selles reisis pole veel rada, mida siduda. Impordi GPX-fail.',
|
||||
'tours.activity.replaces': 'Asendab sel päeval raja {name}',
|
||||
'tours.activity.confirm': 'Seo',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Siduda saab ainult importi, mida pole üle planeeritud',
|
||||
'tours.activity.refused.activity_track_in_use': 'See rada kuulub juba teisele matkale',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Sellel rajal on oma tegelikud rajad',
|
||||
'tours.activity.refused.activity_tour_is_track': 'See matk on ise teise matka tegelik rada',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Matk pole enam sellel päeval',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1215,5 +1215,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Accès non vérifié',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
"L'import ne vérifie pas si les voies peuvent être empruntées à cheval. Les panneaux sur place font foi.",
|
||||
'tours.activity.label': 'Trace réelle',
|
||||
'tours.activity.assign': 'Ajouter la trace réelle',
|
||||
'tours.activity.assignHint': 'Lier la trace réellement parcourue, de ce voyage ou d’un fichier GPX',
|
||||
'tours.activity.empty': 'Pas encore de trace réelle',
|
||||
'tours.activity.badge': 'Réel',
|
||||
'tours.activity.badgeHint': 'Valeurs de la trace réellement parcourue, pas du plan',
|
||||
'tours.activity.isTrackHint': 'Trace réelle d’une sortie de ce voyage',
|
||||
'tours.activity.ofTour': 'Trace réelle de {name}',
|
||||
'tours.activity.noDay': 'Sans jour',
|
||||
'tours.activity.time': 'Temps mis',
|
||||
'tours.activity.timeHint': 'Du premier au dernier horodatage de la trace, pauses comprises',
|
||||
'tours.activity.noTime': 'Aucun horodatage',
|
||||
'tours.activity.noTimeHint': 'La trace ne contient aucun horodatage, aucun temps n’a donc été mesuré',
|
||||
'tours.activity.recordedOn': 'Enregistrée le {date}',
|
||||
'tours.activity.change': 'Modifier',
|
||||
'tours.activity.remove': 'Délier',
|
||||
'tours.activity.removeTitle': 'Délier la trace réelle ?',
|
||||
'tours.activity.removeBody': 'La trace reste dans le voyage comme import. La sortie planifiée ne change pas.',
|
||||
'tours.activity.assigned': 'Trace réelle liée',
|
||||
'tours.activity.removed': 'Trace réelle déliée',
|
||||
'tours.activity.failed': 'La trace réelle n’a pas pu être modifiée',
|
||||
'tours.activity.dialogEyebrow': 'Ajouter la trace réelle',
|
||||
'tours.activity.dialogHint': 'Le plan reste tel quel. La trace est seulement liée.',
|
||||
'tours.activity.execution': 'Réalisée le',
|
||||
'tours.activity.track': 'Enregistrement',
|
||||
'tours.activity.importGpx': 'Importer un GPX',
|
||||
'tours.activity.noCandidates': 'Aucune trace à lier dans ce voyage pour l’instant. Importez un fichier GPX.',
|
||||
'tours.activity.replaces': 'Remplace {name} ce jour-là',
|
||||
'tours.activity.confirm': 'Lier',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Seul un import qui n’a pas été replanifié peut être lié',
|
||||
'tours.activity.refused.activity_track_in_use': 'Cette trace appartient déjà à une autre sortie',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Cette trace a elle-même des traces réelles',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Cette sortie est elle-même la trace réelle d’une autre sortie',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'La sortie n’est plus prévue ce jour-là',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1216,5 +1216,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Πρόσβαση χωρίς έλεγχο',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Η εισαγωγή δεν ελέγχει αν επιτρέπεται η ιππασία στους δρόμους. Ισχύουν οι πινακίδες επί τόπου.',
|
||||
'tours.activity.label': 'Πραγματική διαδρομή',
|
||||
'tours.activity.assign': 'Προσθήκη πραγματικής διαδρομής',
|
||||
'tours.activity.assignHint': 'Σύνδεσε τη διαδρομή που έκανες πραγματικά, από αυτό το ταξίδι ή από αρχείο GPX',
|
||||
'tours.activity.empty': 'Δεν υπάρχει ακόμη πραγματική διαδρομή',
|
||||
'tours.activity.badge': 'Πραγματικό',
|
||||
'tours.activity.badgeHint': 'Τιμές της διαδρομής που έκανες πραγματικά, όχι του σχεδίου',
|
||||
'tours.activity.isTrackHint': 'Πραγματική διαδρομή μιας εκδρομής αυτού του ταξιδιού',
|
||||
'tours.activity.ofTour': 'Πραγματική διαδρομή της {name}',
|
||||
'tours.activity.noDay': 'Χωρίς ημέρα',
|
||||
'tours.activity.time': 'Χρόνος που χρειάστηκε',
|
||||
'tours.activity.timeHint': 'Από την πρώτη έως την τελευταία χρονοσήμανση της διαδρομής, μαζί με τα διαλείμματα',
|
||||
'tours.activity.noTime': 'Χωρίς χρονοσημάνσεις',
|
||||
'tours.activity.noTimeHint': 'Η διαδρομή δεν έχει χρονοσημάνσεις, οπότε δεν μετρήθηκε χρόνος',
|
||||
'tours.activity.recordedOn': 'Καταγράφηκε {date}',
|
||||
'tours.activity.change': 'Αλλαγή',
|
||||
'tours.activity.remove': 'Αποσύνδεση',
|
||||
'tours.activity.removeTitle': 'Αποσύνδεση της πραγματικής διαδρομής;',
|
||||
'tours.activity.removeBody': 'Η διαδρομή μένει στο ταξίδι ως εισαγωγή. Η σχεδιασμένη εκδρομή δεν αλλάζει.',
|
||||
'tours.activity.assigned': 'Η πραγματική διαδρομή συνδέθηκε',
|
||||
'tours.activity.removed': 'Η πραγματική διαδρομή αποσυνδέθηκε',
|
||||
'tours.activity.failed': 'Δεν ήταν δυνατή η αλλαγή της πραγματικής διαδρομής',
|
||||
'tours.activity.dialogEyebrow': 'Προσθήκη πραγματικής διαδρομής',
|
||||
'tours.activity.dialogHint': 'Το σχέδιο μένει ως έχει. Η διαδρομή απλώς συνδέεται.',
|
||||
'tours.activity.execution': 'Έγινε στις',
|
||||
'tours.activity.track': 'Καταγραφή',
|
||||
'tours.activity.importGpx': 'Εισαγωγή GPX',
|
||||
'tours.activity.noCandidates': 'Δεν υπάρχει ακόμη διαδρομή για σύνδεση σε αυτό το ταξίδι. Εισήγαγε ένα αρχείο GPX.',
|
||||
'tours.activity.replaces': 'Αντικαθιστά την {name} αυτή την ημέρα',
|
||||
'tours.activity.confirm': 'Σύνδεση',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Μόνο μια εισαγωγή που δεν επανασχεδιάστηκε μπορεί να συνδεθεί',
|
||||
'tours.activity.refused.activity_track_in_use': 'Αυτή η διαδρομή ανήκει ήδη σε άλλη εκδρομή',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Αυτή η διαδρομή έχει δικές της πραγματικές διαδρομές',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Αυτή η εκδρομή είναι η ίδια πραγματική διαδρομή άλλης εκδρομής',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Η εκδρομή δεν είναι πια σε εκείνη την ημέρα',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1194,5 +1194,40 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Hozzáférés ellenőrizetlen',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Az importálás nem ellenőrzi, hogy szabad-e lovagolni az utakon. A helyszíni táblák a mérvadók.',
|
||||
'tours.activity.label': 'Tényleges nyomvonal',
|
||||
'tours.activity.assign': 'Tényleges nyomvonal hozzáadása',
|
||||
'tours.activity.assignHint':
|
||||
'Kapcsold össze a ténylegesen bejárt nyomvonalat, ebből az utazásból vagy egy GPX-fájlból',
|
||||
'tours.activity.empty': 'Még nincs tényleges nyomvonal',
|
||||
'tours.activity.badge': 'Tényleges',
|
||||
'tours.activity.badgeHint': 'A ténylegesen bejárt nyomvonal értékei, nem a terv értékei',
|
||||
'tours.activity.isTrackHint': 'Egy túra tényleges nyomvonala ebben az utazásban',
|
||||
'tours.activity.ofTour': '{name} tényleges nyomvonala',
|
||||
'tours.activity.noDay': 'Nap nélkül',
|
||||
'tours.activity.time': 'Eltelt idő',
|
||||
'tours.activity.timeHint': 'A nyomvonal első és utolsó időbélyege között, a szünetekkel együtt',
|
||||
'tours.activity.noTime': 'Nincsenek időbélyegek',
|
||||
'tours.activity.noTimeHint': 'A nyomvonal nem tartalmaz időbélyeget, ezért időt sem mértünk',
|
||||
'tours.activity.recordedOn': 'Rögzítve: {date}',
|
||||
'tours.activity.change': 'Módosítás',
|
||||
'tours.activity.remove': 'Leválasztás',
|
||||
'tours.activity.removeTitle': 'Leválasztod a tényleges nyomvonalat?',
|
||||
'tours.activity.removeBody': 'A nyomvonal importként az utazásban marad. A tervezett túra nem változik.',
|
||||
'tours.activity.assigned': 'Tényleges nyomvonal összekapcsolva',
|
||||
'tours.activity.removed': 'Tényleges nyomvonal leválasztva',
|
||||
'tours.activity.failed': 'A tényleges nyomvonalat nem sikerült módosítani',
|
||||
'tours.activity.dialogEyebrow': 'Tényleges nyomvonal hozzáadása',
|
||||
'tours.activity.dialogHint': 'A terv változatlan marad. A nyomvonalat csak összekapcsoljuk.',
|
||||
'tours.activity.execution': 'Teljesítve',
|
||||
'tours.activity.track': 'Felvétel',
|
||||
'tours.activity.importGpx': 'GPX importálása',
|
||||
'tours.activity.noCandidates': 'Ebben az utazásban még nincs összekapcsolható nyomvonal. Importálj egy GPX-fájlt.',
|
||||
'tours.activity.replaces': 'Ezen a napon lecseréli ezt: {name}',
|
||||
'tours.activity.confirm': 'Összekapcsolás',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Csak olyan import kapcsolható össze, amelyet nem terveztek át',
|
||||
'tours.activity.refused.activity_track_in_use': 'Ez a nyomvonal már egy másik túráé',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Ennek a nyomvonalnak saját tényleges nyomvonalai vannak',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Ez a túra maga is egy másik túra tényleges nyomvonala',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'A túra már nem szerepel azon a napon',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1176,5 +1176,40 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Akses belum diperiksa',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Impor tidak memeriksa apakah jalan boleh dilalui dengan berkuda. Rambu di lokasi yang berlaku.',
|
||||
'tours.activity.label': 'Jejak aktual',
|
||||
'tours.activity.assign': 'Tambah jejak aktual',
|
||||
'tours.activity.assignHint': 'Tautkan jejak yang benar-benar kamu tempuh, dari perjalanan ini atau file GPX',
|
||||
'tours.activity.empty': 'Belum ada jejak aktual',
|
||||
'tours.activity.badge': 'Aktual',
|
||||
'tours.activity.badgeHint': 'Nilai jejak yang benar-benar kamu tempuh, bukan dari rencana',
|
||||
'tours.activity.isTrackHint': 'Jejak aktual sebuah tur di perjalanan ini',
|
||||
'tours.activity.ofTour': 'Jejak aktual {name}',
|
||||
'tours.activity.noDay': 'Tanpa hari',
|
||||
'tours.activity.time': 'Waktu tempuh',
|
||||
'tours.activity.timeHint': 'Dari cap waktu pertama hingga terakhir pada jejak, termasuk istirahat',
|
||||
'tours.activity.noTime': 'Tanpa cap waktu',
|
||||
'tours.activity.noTimeHint': 'Jejak tidak memiliki cap waktu, jadi tidak ada waktu yang diukur',
|
||||
'tours.activity.recordedOn': 'Direkam {date}',
|
||||
'tours.activity.change': 'Ubah',
|
||||
'tours.activity.remove': 'Lepaskan',
|
||||
'tours.activity.removeTitle': 'Lepaskan jejak aktual?',
|
||||
'tours.activity.removeBody': 'Jejak tetap ada di perjalanan sebagai impor. Tur yang direncanakan tidak berubah.',
|
||||
'tours.activity.assigned': 'Jejak aktual ditautkan',
|
||||
'tours.activity.removed': 'Jejak aktual dilepaskan',
|
||||
'tours.activity.failed': 'Jejak aktual tidak dapat diubah',
|
||||
'tours.activity.dialogEyebrow': 'Tambah jejak aktual',
|
||||
'tours.activity.dialogHint': 'Rencana tetap seperti semula. Jejak hanya ditautkan.',
|
||||
'tours.activity.execution': 'Dilakukan pada',
|
||||
'tours.activity.track': 'Rekaman',
|
||||
'tours.activity.importGpx': 'Impor GPX',
|
||||
'tours.activity.noCandidates': 'Belum ada jejak di perjalanan ini untuk ditautkan. Impor file GPX.',
|
||||
'tours.activity.replaces': 'Menggantikan {name} pada hari ini',
|
||||
'tours.activity.confirm': 'Tautkan',
|
||||
'tours.activity.refused.activity_track_not_recorded':
|
||||
'Hanya impor yang belum direncanakan ulang yang dapat ditautkan',
|
||||
'tours.activity.refused.activity_track_in_use': 'Jejak ini sudah milik tur lain',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Jejak ini memiliki jejak aktualnya sendiri',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Tur ini sendiri adalah jejak aktual tur lain',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Tur ini sudah tidak ada di hari itu',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1205,5 +1205,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Accesso non verificato',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'L’importazione non verifica se le strade si possono percorrere a cavallo. Valgono i cartelli sul posto.',
|
||||
'tours.activity.label': 'Traccia effettiva',
|
||||
'tours.activity.assign': 'Aggiungi traccia effettiva',
|
||||
'tours.activity.assignHint': 'Collega la traccia percorsa davvero, da questo viaggio o da un file GPX',
|
||||
'tours.activity.empty': 'Ancora nessuna traccia effettiva',
|
||||
'tours.activity.badge': 'Effettivo',
|
||||
'tours.activity.badgeHint': 'Valori della traccia percorsa davvero, non del piano',
|
||||
'tours.activity.isTrackHint': 'Traccia effettiva di un tour di questo viaggio',
|
||||
'tours.activity.ofTour': 'Traccia effettiva di {name}',
|
||||
'tours.activity.noDay': 'Nessun giorno',
|
||||
'tours.activity.time': 'Tempo impiegato',
|
||||
'tours.activity.timeHint': 'Dal primo all’ultimo orario registrato nella traccia, pause comprese',
|
||||
'tours.activity.noTime': 'Nessun orario',
|
||||
'tours.activity.noTimeHint': 'La traccia non contiene orari, quindi non è stato misurato alcun tempo',
|
||||
'tours.activity.recordedOn': 'Registrata il {date}',
|
||||
'tours.activity.change': 'Modifica',
|
||||
'tours.activity.remove': 'Scollega',
|
||||
'tours.activity.removeTitle': 'Scollegare la traccia effettiva?',
|
||||
'tours.activity.removeBody': 'La traccia resta nel viaggio come importazione. Il tour pianificato non cambia.',
|
||||
'tours.activity.assigned': 'Traccia effettiva collegata',
|
||||
'tours.activity.removed': 'Traccia effettiva scollegata',
|
||||
'tours.activity.failed': 'Non è stato possibile modificare la traccia effettiva',
|
||||
'tours.activity.dialogEyebrow': 'Aggiungi traccia effettiva',
|
||||
'tours.activity.dialogHint': 'Il piano resta com’è. La traccia viene solo collegata.',
|
||||
'tours.activity.execution': 'Svolto il',
|
||||
'tours.activity.track': 'Registrazione',
|
||||
'tours.activity.importGpx': 'Importa GPX',
|
||||
'tours.activity.noCandidates': 'Ancora nessuna traccia da collegare in questo viaggio. Importa un file GPX.',
|
||||
'tours.activity.replaces': 'Sostituisce {name} in questo giorno',
|
||||
'tours.activity.confirm': 'Collega',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Si può collegare solo un’importazione non ripianificata',
|
||||
'tours.activity.refused.activity_track_in_use': 'Questa traccia appartiene già a un altro tour',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Questa traccia ha a sua volta tracce effettive',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Questo tour è a sua volta la traccia effettiva di un altro tour',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Il tour non è più in quel giorno',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1141,5 +1141,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': '通行可否は未確認',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'インポートでは、道を馬で通れるかどうかを確認しません。現地の標識が優先されます。',
|
||||
'tours.activity.label': '実際のトラック',
|
||||
'tours.activity.assign': '実際のトラックを追加',
|
||||
'tours.activity.assignHint': 'このトリップまたはGPXファイルから、実際に歩いたトラックをリンクします',
|
||||
'tours.activity.empty': '実際のトラックはまだありません',
|
||||
'tours.activity.badge': '実績',
|
||||
'tours.activity.badgeHint': '計画ではなく、実際に歩いたトラックの値です',
|
||||
'tours.activity.isTrackHint': 'このトリップのツアーの実際のトラック',
|
||||
'tours.activity.ofTour': '{name}の実際のトラック',
|
||||
'tours.activity.noDay': '日なし',
|
||||
'tours.activity.time': '所要時間',
|
||||
'tours.activity.timeHint': 'トラックの最初から最後のタイムスタンプまで(休憩を含む)',
|
||||
'tours.activity.noTime': 'タイムスタンプなし',
|
||||
'tours.activity.noTimeHint': 'トラックにタイムスタンプがないため、時間は測定されていません',
|
||||
'tours.activity.recordedOn': '{date}に記録',
|
||||
'tours.activity.change': '変更',
|
||||
'tours.activity.remove': 'リンク解除',
|
||||
'tours.activity.removeTitle': '実際のトラックのリンクを解除しますか?',
|
||||
'tours.activity.removeBody': 'トラックはインポートとしてトリップに残ります。計画したツアーは変わりません。',
|
||||
'tours.activity.assigned': '実際のトラックをリンクしました',
|
||||
'tours.activity.removed': '実際のトラックのリンクを解除しました',
|
||||
'tours.activity.failed': '実際のトラックを変更できませんでした',
|
||||
'tours.activity.dialogEyebrow': '実際のトラックを追加',
|
||||
'tours.activity.dialogHint': '計画はそのままです。トラックをリンクするだけです。',
|
||||
'tours.activity.execution': '実施日',
|
||||
'tours.activity.track': '記録',
|
||||
'tours.activity.importGpx': 'GPXをインポート',
|
||||
'tours.activity.noCandidates': 'このトリップにはまだリンクできるトラックがありません。GPXファイルをインポートしてください。',
|
||||
'tours.activity.replaces': 'この日の{name}を置き換えます',
|
||||
'tours.activity.confirm': 'リンク',
|
||||
'tours.activity.refused.activity_track_not_recorded': '上書きで計画されていないインポートのみリンクできます',
|
||||
'tours.activity.refused.activity_track_in_use': 'このトラックはすでに別のツアーのものです',
|
||||
'tours.activity.refused.activity_track_is_tour': 'このトラックには独自の実際のトラックがあります',
|
||||
'tours.activity.refused.activity_tour_is_track': 'このツアー自体が別のツアーの実際のトラックです',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'このツアーはもうその日にありません',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1139,5 +1139,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': '통행 여부 미확인',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'가져오기는 길을 말로 지나가도 되는지 확인하지 않습니다. 현장 표지판을 따르세요.',
|
||||
'tours.activity.label': '실제 트랙',
|
||||
'tours.activity.assign': '실제 트랙 추가',
|
||||
'tours.activity.assignHint': '이 여행이나 GPX 파일에서 실제로 걸은 트랙을 연결하세요',
|
||||
'tours.activity.empty': '아직 실제 트랙이 없습니다',
|
||||
'tours.activity.badge': '실제',
|
||||
'tours.activity.badgeHint': '계획이 아니라 실제로 걸은 트랙의 값입니다',
|
||||
'tours.activity.isTrackHint': '이 여행에 있는 투어의 실제 트랙',
|
||||
'tours.activity.ofTour': '{name}의 실제 트랙',
|
||||
'tours.activity.noDay': '날짜 없음',
|
||||
'tours.activity.time': '소요 시간',
|
||||
'tours.activity.timeHint': '트랙의 첫 번째부터 마지막 타임스탬프까지, 휴식 포함',
|
||||
'tours.activity.noTime': '타임스탬프 없음',
|
||||
'tours.activity.noTimeHint': '트랙에 타임스탬프가 없어 시간을 측정하지 않았습니다',
|
||||
'tours.activity.recordedOn': '{date}에 기록',
|
||||
'tours.activity.change': '변경',
|
||||
'tours.activity.remove': '연결 해제',
|
||||
'tours.activity.removeTitle': '실제 트랙 연결을 해제할까요?',
|
||||
'tours.activity.removeBody': '트랙은 가져오기로 여행에 남습니다. 계획한 투어는 바뀌지 않습니다.',
|
||||
'tours.activity.assigned': '실제 트랙을 연결했습니다',
|
||||
'tours.activity.removed': '실제 트랙 연결을 해제했습니다',
|
||||
'tours.activity.failed': '실제 트랙을 변경할 수 없습니다',
|
||||
'tours.activity.dialogEyebrow': '실제 트랙 추가',
|
||||
'tours.activity.dialogHint': '계획은 그대로입니다. 트랙만 연결됩니다.',
|
||||
'tours.activity.execution': '진행일',
|
||||
'tours.activity.track': '기록',
|
||||
'tours.activity.importGpx': 'GPX 가져오기',
|
||||
'tours.activity.noCandidates': '이 여행에는 아직 연결할 트랙이 없습니다. GPX 파일을 가져오세요.',
|
||||
'tours.activity.replaces': '이 날의 {name}을(를) 대체합니다',
|
||||
'tours.activity.confirm': '연결',
|
||||
'tours.activity.refused.activity_track_not_recorded': '덮어서 다시 계획하지 않은 가져오기만 연결할 수 있습니다',
|
||||
'tours.activity.refused.activity_track_in_use': '이 트랙은 이미 다른 투어에 속해 있습니다',
|
||||
'tours.activity.refused.activity_track_is_tour': '이 트랙에는 자체 실제 트랙이 있습니다',
|
||||
'tours.activity.refused.activity_tour_is_track': '이 투어는 다른 투어의 실제 트랙입니다',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': '이 투어는 더 이상 그날에 없습니다',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1197,5 +1197,40 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Toegang niet gecontroleerd',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'De import controleert niet of de wegen bereden mogen worden. Ter plekke gelden de borden.',
|
||||
'tours.activity.label': 'Werkelijke track',
|
||||
'tours.activity.assign': 'Werkelijke track toevoegen',
|
||||
'tours.activity.assignHint': 'Koppel de track die je echt hebt afgelegd, uit deze reis of een GPX-bestand',
|
||||
'tours.activity.empty': 'Nog geen werkelijke track',
|
||||
'tours.activity.badge': 'Werkelijk',
|
||||
'tours.activity.badgeHint': 'Waarden van de track die je echt hebt afgelegd, niet van de planning',
|
||||
'tours.activity.isTrackHint': 'Werkelijke track van een tocht in deze reis',
|
||||
'tours.activity.ofTour': 'Werkelijke track van {name}',
|
||||
'tours.activity.noDay': 'Geen dag',
|
||||
'tours.activity.time': 'Benodigde tijd',
|
||||
'tours.activity.timeHint': 'Van de eerste tot de laatste tijdstempel van de track, pauzes inbegrepen',
|
||||
'tours.activity.noTime': 'Geen tijdstempels',
|
||||
'tours.activity.noTimeHint': 'De track bevat geen tijdstempels, dus er is geen tijd gemeten',
|
||||
'tours.activity.recordedOn': 'Opgenomen op {date}',
|
||||
'tours.activity.change': 'Wijzigen',
|
||||
'tours.activity.remove': 'Ontkoppelen',
|
||||
'tours.activity.removeTitle': 'Werkelijke track ontkoppelen?',
|
||||
'tours.activity.removeBody': 'De track blijft als import in de reis. De geplande tocht verandert niet.',
|
||||
'tours.activity.assigned': 'Werkelijke track gekoppeld',
|
||||
'tours.activity.removed': 'Werkelijke track ontkoppeld',
|
||||
'tours.activity.failed': 'De werkelijke track kon niet worden gewijzigd',
|
||||
'tours.activity.dialogEyebrow': 'Werkelijke track toevoegen',
|
||||
'tours.activity.dialogHint': 'De planning blijft zoals ze is. De track wordt alleen gekoppeld.',
|
||||
'tours.activity.execution': 'Gedaan op',
|
||||
'tours.activity.track': 'Opname',
|
||||
'tours.activity.importGpx': 'GPX importeren',
|
||||
'tours.activity.noCandidates': 'Nog geen track in deze reis om te koppelen. Importeer een GPX-bestand.',
|
||||
'tours.activity.replaces': 'Vervangt {name} op deze dag',
|
||||
'tours.activity.confirm': 'Koppelen',
|
||||
'tours.activity.refused.activity_track_not_recorded':
|
||||
'Alleen een import die niet is overgepland, kan worden gekoppeld',
|
||||
'tours.activity.refused.activity_track_in_use': 'Deze track hoort al bij een andere tocht',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Deze track heeft zelf werkelijke tracks',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Deze tocht is zelf de werkelijke track van een andere tocht',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'De tocht staat niet meer op die dag',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1219,5 +1219,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Dostęp niesprawdzony',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Import nie sprawdza, czy po drogach wolno jeździć konno. Obowiązują znaki na miejscu.',
|
||||
'tours.activity.label': 'Rzeczywista trasa',
|
||||
'tours.activity.assign': 'Dodaj rzeczywistą trasę',
|
||||
'tours.activity.assignHint': 'Połącz trasę, którą naprawdę przeszedłeś, z tej podróży lub z pliku GPX',
|
||||
'tours.activity.empty': 'Brak rzeczywistej trasy',
|
||||
'tours.activity.badge': 'Rzeczywiste',
|
||||
'tours.activity.badgeHint': 'Wartości trasy naprawdę przebytej, nie planu',
|
||||
'tours.activity.isTrackHint': 'Rzeczywista trasa wycieczki z tej podróży',
|
||||
'tours.activity.ofTour': 'Rzeczywista trasa: {name}',
|
||||
'tours.activity.noDay': 'Bez dnia',
|
||||
'tours.activity.time': 'Czas przejścia',
|
||||
'tours.activity.timeHint': 'Od pierwszego do ostatniego znacznika czasu trasy, łącznie z przerwami',
|
||||
'tours.activity.noTime': 'Brak znaczników czasu',
|
||||
'tours.activity.noTimeHint': 'Trasa nie zawiera znaczników czasu, więc nie zmierzono czasu',
|
||||
'tours.activity.recordedOn': 'Zarejestrowano {date}',
|
||||
'tours.activity.change': 'Zmień',
|
||||
'tours.activity.remove': 'Odłącz',
|
||||
'tours.activity.removeTitle': 'Odłączyć rzeczywistą trasę?',
|
||||
'tours.activity.removeBody': 'Trasa zostaje w podróży jako import. Zaplanowana wycieczka się nie zmienia.',
|
||||
'tours.activity.assigned': 'Połączono rzeczywistą trasę',
|
||||
'tours.activity.removed': 'Odłączono rzeczywistą trasę',
|
||||
'tours.activity.failed': 'Nie udało się zmienić rzeczywistej trasy',
|
||||
'tours.activity.dialogEyebrow': 'Dodaj rzeczywistą trasę',
|
||||
'tours.activity.dialogHint': 'Plan pozostaje bez zmian. Trasa jest tylko połączona.',
|
||||
'tours.activity.execution': 'Odbyta dnia',
|
||||
'tours.activity.track': 'Zapis',
|
||||
'tours.activity.importGpx': 'Importuj GPX',
|
||||
'tours.activity.noCandidates': 'W tej podróży nie ma jeszcze trasy do połączenia. Zaimportuj plik GPX.',
|
||||
'tours.activity.replaces': 'Zastępuje {name} w tym dniu',
|
||||
'tours.activity.confirm': 'Połącz',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Połączyć można tylko import, który nie został przeplanowany',
|
||||
'tours.activity.refused.activity_track_in_use': 'Ta trasa należy już do innej wycieczki',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Ta trasa ma własne rzeczywiste trasy',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Ta wycieczka jest sama rzeczywistą trasą innej wycieczki',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Wycieczki nie ma już w tym dniu',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1225,5 +1225,40 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Доступ не проверен',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Импорт не проверяет, можно ли ехать по этим дорогам верхом. На месте действуют знаки.',
|
||||
'tours.activity.label': 'Фактический трек',
|
||||
'tours.activity.assign': 'Добавить фактический трек',
|
||||
'tours.activity.assignHint': 'Привяжите трек, по которому вы на самом деле прошли, из этой поездки или из файла GPX',
|
||||
'tours.activity.empty': 'Фактического трека пока нет',
|
||||
'tours.activity.badge': 'Факт',
|
||||
'tours.activity.badgeHint': 'Значения фактически пройденного трека, а не плана',
|
||||
'tours.activity.isTrackHint': 'Фактический трек маршрута этой поездки',
|
||||
'tours.activity.ofTour': 'Фактический трек: {name}',
|
||||
'tours.activity.noDay': 'Без дня',
|
||||
'tours.activity.time': 'Затраченное время',
|
||||
'tours.activity.timeHint': 'От первой до последней отметки времени в треке, включая перерывы',
|
||||
'tours.activity.noTime': 'Нет отметок времени',
|
||||
'tours.activity.noTimeHint': 'В треке нет отметок времени, поэтому время не измерено',
|
||||
'tours.activity.recordedOn': 'Записан {date}',
|
||||
'tours.activity.change': 'Изменить',
|
||||
'tours.activity.remove': 'Отвязать',
|
||||
'tours.activity.removeTitle': 'Отвязать фактический трек?',
|
||||
'tours.activity.removeBody': 'Трек остаётся в поездке как импорт. Запланированный маршрут не меняется.',
|
||||
'tours.activity.assigned': 'Фактический трек привязан',
|
||||
'tours.activity.removed': 'Фактический трек отвязан',
|
||||
'tours.activity.failed': 'Не удалось изменить фактический трек',
|
||||
'tours.activity.dialogEyebrow': 'Добавить фактический трек',
|
||||
'tours.activity.dialogHint': 'План остаётся прежним. Трек только привязывается.',
|
||||
'tours.activity.execution': 'Пройден',
|
||||
'tours.activity.track': 'Запись',
|
||||
'tours.activity.importGpx': 'Импортировать GPX',
|
||||
'tours.activity.noCandidates': 'В этой поездке пока нет трека для привязки. Импортируйте файл GPX.',
|
||||
'tours.activity.replaces': 'Заменяет {name} в этот день',
|
||||
'tours.activity.confirm': 'Привязать',
|
||||
'tours.activity.refused.activity_track_not_recorded':
|
||||
'Привязать можно только импорт, поверх которого не строили план',
|
||||
'tours.activity.refused.activity_track_in_use': 'Этот трек уже относится к другому маршруту',
|
||||
'tours.activity.refused.activity_track_is_tour': 'У этого трека есть собственные фактические треки',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Этот маршрут сам является фактическим треком другого маршрута',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Маршрута больше нет в этот день',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1181,5 +1181,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Prístup neoverený',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Import neoveruje, či sa po cestách smie jazdiť na koni. Platí značenie na mieste.',
|
||||
'tours.activity.label': 'Skutočná trasa',
|
||||
'tours.activity.assign': 'Pridať skutočnú trasu',
|
||||
'tours.activity.assignHint': 'Prepoj trasu, ktorú si naozaj prešiel, z tohto výletu alebo zo súboru GPX',
|
||||
'tours.activity.empty': 'Zatiaľ žiadna skutočná trasa',
|
||||
'tours.activity.badge': 'Skutočnosť',
|
||||
'tours.activity.badgeHint': 'Hodnoty naozaj prejdenej trasy, nie plánu',
|
||||
'tours.activity.isTrackHint': 'Skutočná trasa túry tohto výletu',
|
||||
'tours.activity.ofTour': 'Skutočná trasa: {name}',
|
||||
'tours.activity.noDay': 'Bez dňa',
|
||||
'tours.activity.time': 'Potrebný čas',
|
||||
'tours.activity.timeHint': 'Od prvej po poslednú časovú pečiatku trasy, vrátane prestávok',
|
||||
'tours.activity.noTime': 'Bez časových pečiatok',
|
||||
'tours.activity.noTimeHint': 'Trasa nemá časové pečiatky, preto sa nezmeral žiadny čas',
|
||||
'tours.activity.recordedOn': 'Zaznamenané {date}',
|
||||
'tours.activity.change': 'Zmeniť',
|
||||
'tours.activity.remove': 'Odpojiť',
|
||||
'tours.activity.removeTitle': 'Odpojiť skutočnú trasu?',
|
||||
'tours.activity.removeBody': 'Trasa zostane vo výlete ako import. Plánovaná túra sa nezmení.',
|
||||
'tours.activity.assigned': 'Skutočná trasa prepojená',
|
||||
'tours.activity.removed': 'Skutočná trasa odpojená',
|
||||
'tours.activity.failed': 'Skutočnú trasu sa nepodarilo zmeniť',
|
||||
'tours.activity.dialogEyebrow': 'Pridať skutočnú trasu',
|
||||
'tours.activity.dialogHint': 'Plán zostáva, ako je. Trasa sa len prepojí.',
|
||||
'tours.activity.execution': 'Uskutočnené',
|
||||
'tours.activity.track': 'Záznam',
|
||||
'tours.activity.importGpx': 'Importovať GPX',
|
||||
'tours.activity.noCandidates': 'V tomto výlete zatiaľ nie je žiadna trasa na prepojenie. Importuj súbor GPX.',
|
||||
'tours.activity.replaces': 'Nahradí {name} v tento deň',
|
||||
'tours.activity.confirm': 'Prepojiť',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Prepojiť sa dá len import, ktorý nebol preplánovaný',
|
||||
'tours.activity.refused.activity_track_in_use': 'Táto trasa už patrí k inej túre',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Táto trasa má vlastné skutočné trasy',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Táto túra je sama skutočnou trasou inej túry',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Túra už v tento deň nie je',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1170,5 +1170,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Tillträde okontrollerat',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Importen kontrollerar inte om vägarna får ridas. Skyltarna på plats gäller.',
|
||||
'tours.activity.label': 'Faktiskt spår',
|
||||
'tours.activity.assign': 'Lägg till faktiskt spår',
|
||||
'tours.activity.assignHint': 'Koppla spåret du faktiskt gick, från den här resan eller en GPX-fil',
|
||||
'tours.activity.empty': 'Inget faktiskt spår ännu',
|
||||
'tours.activity.badge': 'Faktiskt',
|
||||
'tours.activity.badgeHint': 'Värden från spåret du faktiskt gick, inte från planen',
|
||||
'tours.activity.isTrackHint': 'Faktiskt spår för en tur i den här resan',
|
||||
'tours.activity.ofTour': 'Faktiskt spår för {name}',
|
||||
'tours.activity.noDay': 'Ingen dag',
|
||||
'tours.activity.time': 'Tidsåtgång',
|
||||
'tours.activity.timeHint': 'Från första till sista tidsstämpeln i spåret, pauser inräknade',
|
||||
'tours.activity.noTime': 'Inga tidsstämplar',
|
||||
'tours.activity.noTimeHint': 'Spåret saknar tidsstämplar, så ingen tid har mätts',
|
||||
'tours.activity.recordedOn': 'Inspelat {date}',
|
||||
'tours.activity.change': 'Ändra',
|
||||
'tours.activity.remove': 'Koppla bort',
|
||||
'tours.activity.removeTitle': 'Koppla bort det faktiska spåret?',
|
||||
'tours.activity.removeBody': 'Spåret finns kvar i resan som import. Den planerade turen ändras inte.',
|
||||
'tours.activity.assigned': 'Faktiskt spår kopplat',
|
||||
'tours.activity.removed': 'Faktiskt spår bortkopplat',
|
||||
'tours.activity.failed': 'Det faktiska spåret kunde inte ändras',
|
||||
'tours.activity.dialogEyebrow': 'Lägg till faktiskt spår',
|
||||
'tours.activity.dialogHint': 'Planen förblir som den är. Spåret kopplas bara.',
|
||||
'tours.activity.execution': 'Genomförd',
|
||||
'tours.activity.track': 'Inspelning',
|
||||
'tours.activity.importGpx': 'Importera GPX',
|
||||
'tours.activity.noCandidates': 'Inget spår att koppla i den här resan ännu. Importera en GPX-fil.',
|
||||
'tours.activity.replaces': 'Ersätter {name} den här dagen',
|
||||
'tours.activity.confirm': 'Koppla',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Bara en import som inte har planerats om kan kopplas',
|
||||
'tours.activity.refused.activity_track_in_use': 'Det här spåret hör redan till en annan tur',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Det här spåret har egna faktiska spår',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Den här turen är själv det faktiska spåret för en annan tur',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Turen ligger inte längre på den dagen',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1122,5 +1122,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'ยังไม่ตรวจสอบสิทธิ์ผ่าน',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'การนำเข้าไม่ได้ตรวจสอบว่าขี่ม้าผ่านเส้นทางได้หรือไม่ ให้ถือป้ายในพื้นที่เป็นหลัก',
|
||||
'tours.activity.label': 'เส้นทางจริง',
|
||||
'tours.activity.assign': 'เพิ่มเส้นทางจริง',
|
||||
'tours.activity.assignHint': 'เชื่อมเส้นทางที่คุณเดินจริง จากทริปนี้หรือจากไฟล์ GPX',
|
||||
'tours.activity.empty': 'ยังไม่มีเส้นทางจริง',
|
||||
'tours.activity.badge': 'จริง',
|
||||
'tours.activity.badgeHint': 'ค่าของเส้นทางที่คุณเดินจริง ไม่ใช่ของแผน',
|
||||
'tours.activity.isTrackHint': 'เส้นทางจริงของทัวร์ในทริปนี้',
|
||||
'tours.activity.ofTour': 'เส้นทางจริงของ {name}',
|
||||
'tours.activity.noDay': 'ไม่มีวัน',
|
||||
'tours.activity.time': 'เวลาที่ใช้',
|
||||
'tours.activity.timeHint': 'ตั้งแต่เวลาที่บันทึกแรกถึงสุดท้ายของเส้นทาง รวมช่วงพัก',
|
||||
'tours.activity.noTime': 'ไม่มีการบันทึกเวลา',
|
||||
'tours.activity.noTimeHint': 'เส้นทางไม่มีการบันทึกเวลา จึงไม่ได้วัดเวลา',
|
||||
'tours.activity.recordedOn': 'บันทึกเมื่อ {date}',
|
||||
'tours.activity.change': 'เปลี่ยน',
|
||||
'tours.activity.remove': 'ยกเลิกการเชื่อม',
|
||||
'tours.activity.removeTitle': 'ยกเลิกการเชื่อมเส้นทางจริงหรือไม่',
|
||||
'tours.activity.removeBody': 'เส้นทางยังอยู่ในทริปในฐานะไฟล์นำเข้า ทัวร์ที่วางแผนไว้ไม่เปลี่ยนแปลง',
|
||||
'tours.activity.assigned': 'เชื่อมเส้นทางจริงแล้ว',
|
||||
'tours.activity.removed': 'ยกเลิกการเชื่อมเส้นทางจริงแล้ว',
|
||||
'tours.activity.failed': 'ไม่สามารถเปลี่ยนเส้นทางจริงได้',
|
||||
'tours.activity.dialogEyebrow': 'เพิ่มเส้นทางจริง',
|
||||
'tours.activity.dialogHint': 'แผนยังคงเหมือนเดิม เส้นทางถูกเชื่อมเท่านั้น',
|
||||
'tours.activity.execution': 'ทำเมื่อ',
|
||||
'tours.activity.track': 'การบันทึก',
|
||||
'tours.activity.importGpx': 'นำเข้า GPX',
|
||||
'tours.activity.noCandidates': 'ทริปนี้ยังไม่มีเส้นทางให้เชื่อม นำเข้าไฟล์ GPX',
|
||||
'tours.activity.replaces': 'แทนที่ {name} ในวันนี้',
|
||||
'tours.activity.confirm': 'เชื่อม',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'เชื่อมได้เฉพาะไฟล์นำเข้าที่ยังไม่ถูกวางแผนทับ',
|
||||
'tours.activity.refused.activity_track_in_use': 'เส้นทางนี้เป็นของทัวร์อื่นแล้ว',
|
||||
'tours.activity.refused.activity_track_is_tour': 'เส้นทางนี้มีเส้นทางจริงของตัวเอง',
|
||||
'tours.activity.refused.activity_tour_is_track': 'ทัวร์นี้เป็นเส้นทางจริงของทัวร์อื่น',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'ทัวร์ไม่ได้อยู่ในวันนั้นแล้ว',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -20,7 +20,7 @@ const tokens = (value: string) => [...value.matchAll(/\{[^{}]+\}/g)].map((match)
|
||||
// placeholder spec; here only the general keys are.
|
||||
const groups = pluralGroups(Object.keys(english));
|
||||
const generalKeys = (keys: string[]) => keys.filter((key) => !pluralFormOf(key, groups));
|
||||
const GENERAL_KEY_COUNT = 1064;
|
||||
const GENERAL_KEY_COUNT = 1098;
|
||||
|
||||
function literalKeys(source: string): string[] {
|
||||
const tree = ts.createSourceFile('locale.ts', source, ts.ScriptTarget.Latest, true);
|
||||
|
||||
@@ -1176,5 +1176,40 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Erişim denetlenmedi',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'İçe aktarma, yollarda ata binilip binilemeyeceğini denetlemez. Yerindeki tabelalar geçerlidir.',
|
||||
'tours.activity.label': 'Gerçek iz',
|
||||
'tours.activity.assign': 'Gerçek iz ekle',
|
||||
'tours.activity.assignHint': 'Gerçekten yürüdüğün izi bu geziden ya da bir GPX dosyasından bağla',
|
||||
'tours.activity.empty': 'Henüz gerçek iz yok',
|
||||
'tours.activity.badge': 'Gerçek',
|
||||
'tours.activity.badgeHint': 'Planın değil, gerçekten yürüdüğün izin değerleri',
|
||||
'tours.activity.isTrackHint': 'Bu gezideki bir turun gerçek izi',
|
||||
'tours.activity.ofTour': '{name} turunun gerçek izi',
|
||||
'tours.activity.noDay': 'Gün yok',
|
||||
'tours.activity.time': 'Geçen süre',
|
||||
'tours.activity.timeHint': 'İzdeki ilk zaman damgasından sonuncusuna kadar, molalar dahil',
|
||||
'tours.activity.noTime': 'Zaman damgası yok',
|
||||
'tours.activity.noTimeHint': 'İzde zaman damgası yok, bu yüzden süre ölçülmedi',
|
||||
'tours.activity.recordedOn': 'Kaydedildi: {date}',
|
||||
'tours.activity.change': 'Değiştir',
|
||||
'tours.activity.remove': 'Bağlantıyı kaldır',
|
||||
'tours.activity.removeTitle': 'Gerçek izin bağlantısı kaldırılsın mı?',
|
||||
'tours.activity.removeBody': 'İz, içe aktarma olarak gezide kalır. Planlanan tur değişmez.',
|
||||
'tours.activity.assigned': 'Gerçek iz bağlandı',
|
||||
'tours.activity.removed': 'Gerçek izin bağlantısı kaldırıldı',
|
||||
'tours.activity.failed': 'Gerçek iz değiştirilemedi',
|
||||
'tours.activity.dialogEyebrow': 'Gerçek iz ekle',
|
||||
'tours.activity.dialogHint': 'Plan olduğu gibi kalır. İz yalnızca bağlanır.',
|
||||
'tours.activity.execution': 'Yapıldığı gün',
|
||||
'tours.activity.track': 'Kayıt',
|
||||
'tours.activity.importGpx': 'GPX içe aktar',
|
||||
'tours.activity.noCandidates': 'Bu gezide henüz bağlanacak iz yok. Bir GPX dosyası içe aktar.',
|
||||
'tours.activity.replaces': 'Bu günde {name} yerine geçer',
|
||||
'tours.activity.confirm': 'Bağla',
|
||||
'tours.activity.refused.activity_track_not_recorded':
|
||||
'Yalnızca üzerinden yeniden planlanmamış bir içe aktarma bağlanabilir',
|
||||
'tours.activity.refused.activity_track_in_use': 'Bu iz zaten başka bir tura ait',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Bu izin kendi gerçek izleri var',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Bu tur zaten başka bir turun gerçek izi',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Tur artık o günde değil',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1212,5 +1212,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Доступ не перевірено',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Імпорт не перевіряє, чи можна їхати цими дорогами верхи. На місці діють знаки.',
|
||||
'tours.activity.label': 'Фактичний трек',
|
||||
'tours.activity.assign': 'Додати фактичний трек',
|
||||
'tours.activity.assignHint': 'Прив’яжіть трек, яким ви справді пройшли, з цієї подорожі або з файлу GPX',
|
||||
'tours.activity.empty': 'Фактичного треку ще немає',
|
||||
'tours.activity.badge': 'Факт',
|
||||
'tours.activity.badgeHint': 'Значення фактично пройденого треку, а не плану',
|
||||
'tours.activity.isTrackHint': 'Фактичний трек маршруту цієї подорожі',
|
||||
'tours.activity.ofTour': 'Фактичний трек: {name}',
|
||||
'tours.activity.noDay': 'Без дня',
|
||||
'tours.activity.time': 'Витрачений час',
|
||||
'tours.activity.timeHint': 'Від першої до останньої позначки часу в треку, з перервами включно',
|
||||
'tours.activity.noTime': 'Немає позначок часу',
|
||||
'tours.activity.noTimeHint': 'У треку немає позначок часу, тож час не виміряно',
|
||||
'tours.activity.recordedOn': 'Записано {date}',
|
||||
'tours.activity.change': 'Змінити',
|
||||
'tours.activity.remove': 'Відв’язати',
|
||||
'tours.activity.removeTitle': 'Відв’язати фактичний трек?',
|
||||
'tours.activity.removeBody': 'Трек залишається в подорожі як імпорт. Запланований маршрут не змінюється.',
|
||||
'tours.activity.assigned': 'Фактичний трек прив’язано',
|
||||
'tours.activity.removed': 'Фактичний трек відв’язано',
|
||||
'tours.activity.failed': 'Не вдалося змінити фактичний трек',
|
||||
'tours.activity.dialogEyebrow': 'Додати фактичний трек',
|
||||
'tours.activity.dialogHint': 'План лишається незмінним. Трек лише прив’язується.',
|
||||
'tours.activity.execution': 'Пройдено',
|
||||
'tours.activity.track': 'Запис',
|
||||
'tours.activity.importGpx': 'Імпортувати GPX',
|
||||
'tours.activity.noCandidates': 'У цій подорожі ще немає треку для прив’язки. Імпортуйте файл GPX.',
|
||||
'tours.activity.replaces': 'Замінює {name} цього дня',
|
||||
'tours.activity.confirm': 'Прив’язати',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Прив’язати можна лише імпорт, поверх якого не будували план',
|
||||
'tours.activity.refused.activity_track_in_use': 'Цей трек уже належить іншому маршруту',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Цей трек має власні фактичні треки',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Цей маршрут сам є фактичним треком іншого маршруту',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Маршруту вже немає цього дня',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1165,5 +1165,40 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.accessUnchecked': 'Chưa kiểm tra quyền đi',
|
||||
'tours.horse.recorded.accessUncheckedInfo':
|
||||
'Việc nhập không kiểm tra liệu có được cưỡi ngựa trên các con đường hay không. Biển báo tại chỗ mới là căn cứ.',
|
||||
'tours.activity.label': 'Lộ trình thực tế',
|
||||
'tours.activity.assign': 'Thêm lộ trình thực tế',
|
||||
'tours.activity.assignHint': 'Liên kết lộ trình bạn thực sự đã đi, từ chuyến đi này hoặc tệp GPX',
|
||||
'tours.activity.empty': 'Chưa có lộ trình thực tế',
|
||||
'tours.activity.badge': 'Thực tế',
|
||||
'tours.activity.badgeHint': 'Số liệu của lộ trình bạn thực sự đã đi, không phải của kế hoạch',
|
||||
'tours.activity.isTrackHint': 'Lộ trình thực tế của một tour trong chuyến đi này',
|
||||
'tours.activity.ofTour': 'Lộ trình thực tế của {name}',
|
||||
'tours.activity.noDay': 'Không có ngày',
|
||||
'tours.activity.time': 'Thời gian đã đi',
|
||||
'tours.activity.timeHint': 'Từ mốc thời gian đầu tiên đến cuối cùng của lộ trình, kể cả nghỉ',
|
||||
'tours.activity.noTime': 'Không có mốc thời gian',
|
||||
'tours.activity.noTimeHint': 'Lộ trình không có mốc thời gian, nên không đo được thời gian',
|
||||
'tours.activity.recordedOn': 'Ghi lại ngày {date}',
|
||||
'tours.activity.change': 'Thay đổi',
|
||||
'tours.activity.remove': 'Bỏ liên kết',
|
||||
'tours.activity.removeTitle': 'Bỏ liên kết lộ trình thực tế?',
|
||||
'tours.activity.removeBody':
|
||||
'Lộ trình vẫn ở trong chuyến đi dưới dạng tệp nhập. Tour đã lên kế hoạch không thay đổi.',
|
||||
'tours.activity.assigned': 'Đã liên kết lộ trình thực tế',
|
||||
'tours.activity.removed': 'Đã bỏ liên kết lộ trình thực tế',
|
||||
'tours.activity.failed': 'Không thể thay đổi lộ trình thực tế',
|
||||
'tours.activity.dialogEyebrow': 'Thêm lộ trình thực tế',
|
||||
'tours.activity.dialogHint': 'Kế hoạch giữ nguyên. Lộ trình chỉ được liên kết.',
|
||||
'tours.activity.execution': 'Thực hiện vào',
|
||||
'tours.activity.track': 'Bản ghi',
|
||||
'tours.activity.importGpx': 'Nhập GPX',
|
||||
'tours.activity.noCandidates': 'Chuyến đi này chưa có lộ trình để liên kết. Hãy nhập tệp GPX.',
|
||||
'tours.activity.replaces': 'Thay thế {name} vào ngày này',
|
||||
'tours.activity.confirm': 'Liên kết',
|
||||
'tours.activity.refused.activity_track_not_recorded': 'Chỉ có thể liên kết tệp nhập chưa được lập kế hoạch lại',
|
||||
'tours.activity.refused.activity_track_in_use': 'Lộ trình này đã thuộc về tour khác',
|
||||
'tours.activity.refused.activity_track_is_tour': 'Lộ trình này có lộ trình thực tế riêng',
|
||||
'tours.activity.refused.activity_tour_is_track': 'Tour này chính là lộ trình thực tế của tour khác',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': 'Tour không còn ở ngày đó',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1082,5 +1082,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.noTimeInfo': 'TREK 不為騎馬遊計算騎乘時間:節奏取決於馬和騎手。',
|
||||
'tours.horse.recorded.accessUnchecked': '通行未經檢查',
|
||||
'tours.horse.recorded.accessUncheckedInfo': '匯入不會檢查這些道路是否允許騎馬通行。以現場標誌為準。',
|
||||
'tours.activity.label': '實際軌跡',
|
||||
'tours.activity.assign': '新增實際軌跡',
|
||||
'tours.activity.assignHint': '連結你實際走過的軌跡,可來自本趟旅程或 GPX 檔案',
|
||||
'tours.activity.empty': '還沒有實際軌跡',
|
||||
'tours.activity.badge': '實際',
|
||||
'tours.activity.badgeHint': '實際走過的軌跡的數值,而非計畫數值',
|
||||
'tours.activity.isTrackHint': '本趟旅程中某條路線的實際軌跡',
|
||||
'tours.activity.ofTour': '{name} 的實際軌跡',
|
||||
'tours.activity.noDay': '無日期',
|
||||
'tours.activity.time': '花費時間',
|
||||
'tours.activity.timeHint': '從軌跡的第一個到最後一個時間戳記,含休息',
|
||||
'tours.activity.noTime': '無時間戳記',
|
||||
'tours.activity.noTimeHint': '此軌跡沒有時間戳記,因此未測量時間',
|
||||
'tours.activity.recordedOn': '記錄於 {date}',
|
||||
'tours.activity.change': '變更',
|
||||
'tours.activity.remove': '取消連結',
|
||||
'tours.activity.removeTitle': '要取消連結實際軌跡嗎?',
|
||||
'tours.activity.removeBody': '軌跡會以匯入的形式保留在旅程中。計畫的路線不會改變。',
|
||||
'tours.activity.assigned': '已連結實際軌跡',
|
||||
'tours.activity.removed': '已取消連結實際軌跡',
|
||||
'tours.activity.failed': '無法變更實際軌跡',
|
||||
'tours.activity.dialogEyebrow': '新增實際軌跡',
|
||||
'tours.activity.dialogHint': '計畫維持不變,只會連結軌跡。',
|
||||
'tours.activity.execution': '完成於',
|
||||
'tours.activity.track': '紀錄',
|
||||
'tours.activity.importGpx': '匯入 GPX',
|
||||
'tours.activity.noCandidates': '本趟旅程中還沒有可連結的軌跡。請匯入 GPX 檔案。',
|
||||
'tours.activity.replaces': '取代當天的 {name}',
|
||||
'tours.activity.confirm': '連結',
|
||||
'tours.activity.refused.activity_track_not_recorded': '只能連結未被重新規劃覆蓋的匯入',
|
||||
'tours.activity.refused.activity_track_in_use': '此軌跡已屬於另一條路線',
|
||||
'tours.activity.refused.activity_track_is_tour': '此軌跡有自己的實際軌跡',
|
||||
'tours.activity.refused.activity_tour_is_track': '此路線本身是另一條路線的實際軌跡',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': '此路線已不在那一天',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -1083,5 +1083,39 @@ const tours: TranslationStrings = {
|
||||
'tours.horse.recorded.noTimeInfo': 'TREK 不为骑马游计算骑行时间:节奏取决于马和骑手。',
|
||||
'tours.horse.recorded.accessUnchecked': '通行未经检查',
|
||||
'tours.horse.recorded.accessUncheckedInfo': '导入不会检查这些道路是否允许骑马通行。以现场标志为准。',
|
||||
'tours.activity.label': '实际轨迹',
|
||||
'tours.activity.assign': '添加实际轨迹',
|
||||
'tours.activity.assignHint': '关联你实际走过的轨迹,可来自本次旅行或 GPX 文件',
|
||||
'tours.activity.empty': '还没有实际轨迹',
|
||||
'tours.activity.badge': '实际',
|
||||
'tours.activity.badgeHint': '实际走过的轨迹的数值,而非计划数值',
|
||||
'tours.activity.isTrackHint': '本次旅行中某条路线的实际轨迹',
|
||||
'tours.activity.ofTour': '{name} 的实际轨迹',
|
||||
'tours.activity.noDay': '无日期',
|
||||
'tours.activity.time': '用时',
|
||||
'tours.activity.timeHint': '从轨迹的第一个到最后一个时间戳,含休息',
|
||||
'tours.activity.noTime': '无时间戳',
|
||||
'tours.activity.noTimeHint': '该轨迹没有时间戳,因此未测量时间',
|
||||
'tours.activity.recordedOn': '记录于 {date}',
|
||||
'tours.activity.change': '更改',
|
||||
'tours.activity.remove': '取消关联',
|
||||
'tours.activity.removeTitle': '取消关联实际轨迹?',
|
||||
'tours.activity.removeBody': '轨迹会作为导入保留在旅行中。计划的路线不会改变。',
|
||||
'tours.activity.assigned': '已关联实际轨迹',
|
||||
'tours.activity.removed': '已取消关联实际轨迹',
|
||||
'tours.activity.failed': '无法更改实际轨迹',
|
||||
'tours.activity.dialogEyebrow': '添加实际轨迹',
|
||||
'tours.activity.dialogHint': '计划保持不变,只关联轨迹。',
|
||||
'tours.activity.execution': '完成于',
|
||||
'tours.activity.track': '记录',
|
||||
'tours.activity.importGpx': '导入 GPX',
|
||||
'tours.activity.noCandidates': '本次旅行中还没有可关联的轨迹。请导入 GPX 文件。',
|
||||
'tours.activity.replaces': '替换当天的 {name}',
|
||||
'tours.activity.confirm': '关联',
|
||||
'tours.activity.refused.activity_track_not_recorded': '只能关联未被重新规划覆盖的导入',
|
||||
'tours.activity.refused.activity_track_in_use': '该轨迹已属于另一条路线',
|
||||
'tours.activity.refused.activity_track_is_tour': '该轨迹有自己的实际轨迹',
|
||||
'tours.activity.refused.activity_tour_is_track': '该路线本身是另一条路线的实际轨迹',
|
||||
'tours.activity.refused.activity_assignment_not_of_tour': '该路线已不在那一天',
|
||||
};
|
||||
export default tours;
|
||||
|
||||
@@ -58,6 +58,7 @@ export * from './tours/tours.schema';
|
||||
export * from './tours/run-pace';
|
||||
export * from './tours/ski.schema';
|
||||
export * from './tours/tour-provenance.schema';
|
||||
export * from './tours/tour-activity.schema';
|
||||
export * from './tours/tour-library.schema';
|
||||
export * from './tours/tour-poi-search.schema';
|
||||
export * from './tours/tour-trail-grade.schema';
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { tourActivityAssignRequestSchema, tourActivitySchema } from './tour-activity.schema';
|
||||
import { tourDetailResponseSchema, tourListItemSchema } from './tours.schema';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const activity = {
|
||||
id: 4,
|
||||
assignment_id: 12,
|
||||
day_id: 3,
|
||||
assigned_at: '2026-07-02T18:00:00Z',
|
||||
track: { place_id: 9, name: 'Watch export', origin: 'gpx', file_name: 'morning.gpx', imported_at: '2026-07-02 17:58:00' },
|
||||
metrics: {
|
||||
distance_km: 12.4,
|
||||
elevation_gain_m: 640,
|
||||
elevation_loss_m: 610,
|
||||
started_at: '2026-07-02T06:10:00Z',
|
||||
ended_at: '2026-07-02T11:40:00Z',
|
||||
elapsed_minutes: 330,
|
||||
point_count: 2,
|
||||
},
|
||||
geometry: [
|
||||
[47.1, 11.2, 900],
|
||||
[47.2, 11.3, 930],
|
||||
],
|
||||
};
|
||||
|
||||
describe('ACT-01 tour activity contract', () => {
|
||||
it('ACT-SCHEMA-001: reads an assignment with its recording, its measures and its line', () => {
|
||||
expect(tourActivitySchema.parse(activity)).toEqual(activity);
|
||||
});
|
||||
|
||||
it('ACT-SCHEMA-002: keeps what a track lacks unknown instead of zero', () => {
|
||||
const bare = {
|
||||
...activity,
|
||||
assignment_id: null,
|
||||
day_id: null,
|
||||
metrics: {
|
||||
distance_km: 3,
|
||||
elevation_gain_m: null,
|
||||
elevation_loss_m: null,
|
||||
started_at: null,
|
||||
ended_at: null,
|
||||
elapsed_minutes: null,
|
||||
point_count: 2,
|
||||
},
|
||||
};
|
||||
expect(tourActivitySchema.parse(bare).metrics.elapsed_minutes).toBeNull();
|
||||
});
|
||||
|
||||
it('ACT-SCHEMA-003: an assignment names a recording and an execution, nothing else', () => {
|
||||
expect(tourActivityAssignRequestSchema.parse({ track_place_id: 9, assignment_id: null })).toEqual({
|
||||
track_place_id: 9,
|
||||
assignment_id: null,
|
||||
});
|
||||
expect(() => tourActivityAssignRequestSchema.parse({ track_place_id: 9 })).toThrow();
|
||||
expect(() => tourActivityAssignRequestSchema.parse({ track_place_id: 0, assignment_id: null })).toThrow();
|
||||
expect(() =>
|
||||
tourActivityAssignRequestSchema.parse({ track_place_id: 9, assignment_id: null, distance_km: 3 }),
|
||||
).toThrow();
|
||||
});
|
||||
|
||||
it('ACT-SCHEMA-004: a list item and a detail cached before ACT-01 still read', () => {
|
||||
const item = {
|
||||
place_id: 1,
|
||||
tour_type: 'hike',
|
||||
distance: 1,
|
||||
elevation_gain: null,
|
||||
elevation_loss: null,
|
||||
duration: null,
|
||||
difficulty: null,
|
||||
wanderer_ref: null,
|
||||
match_confidence: 1,
|
||||
max_hiking_difficulty: 2,
|
||||
name: 'Ridge',
|
||||
planned: false,
|
||||
caution: false,
|
||||
};
|
||||
expect(tourListItemSchema.parse(item).activity_tracks).toBeUndefined();
|
||||
const detail = tourDetailResponseSchema.parse({ tour: item, waypoints: [], activities: [activity] });
|
||||
expect(detail.activities).toHaveLength(1);
|
||||
expect(
|
||||
tourListItemSchema.parse({ ...item, activity_tracks: [{ id: 4, track_place_id: 9, assignment_id: null }] })
|
||||
.activity_tracks,
|
||||
).toEqual([{ id: 4, track_place_id: 9, assignment_id: null }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,102 @@
|
||||
import { idSchema } from '../common/primitives.schema';
|
||||
import { tourOriginSchema } from './tour-provenance.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* ACT-01: a recorded track assigned to a tour, the way the tour was actually
|
||||
* done. The plan stays what it is: its line, its measures and its times are
|
||||
* never touched by an assignment. The recording is a tour of the same trip
|
||||
* that came in through the GPX import (or from wanderer) and still holds the
|
||||
* line it was recorded with; it keeps its own identity and provenance, and
|
||||
* the assignment only points at it. One assignment per execution: a day the
|
||||
* tour is on, or no day at all.
|
||||
*
|
||||
* This is not the track an import planned over in place keeps
|
||||
* (`has_recorded_track`, `plannedOver`): that one is where a plan came from,
|
||||
* this one is what was walked.
|
||||
*/
|
||||
|
||||
/** The recording an assignment points at, as it is named in the trip. */
|
||||
export const tourActivityTrackSchema = z.object({
|
||||
place_id: idSchema,
|
||||
name: z.string(),
|
||||
/** How the recording came into the trip; never `trek`, a planned line is no recording. */
|
||||
origin: tourOriginSchema,
|
||||
/** The GPX file it was read from; null for a wanderer trail and an import from before TREK kept the name. */
|
||||
file_name: z.string().nullable(),
|
||||
/** When it came into the trip. */
|
||||
imported_at: z.string().nullable(),
|
||||
});
|
||||
export type TourActivityTrack = z.infer<typeof tourActivityTrackSchema>;
|
||||
|
||||
/**
|
||||
* What the recording measures, read from its own line every time, so a
|
||||
* recording that changes changes these and nothing of the plan. A value the
|
||||
* track does not carry stays null: no heights without heights on every point,
|
||||
* no time without a time on every point.
|
||||
*/
|
||||
export const tourActivityMetricsSchema = z.object({
|
||||
distance_km: z.number().nullable(),
|
||||
elevation_gain_m: z.number().nullable(),
|
||||
elevation_loss_m: z.number().nullable(),
|
||||
/** The first and last time the track carries, ISO 8601 in UTC. */
|
||||
started_at: z.string().nullable(),
|
||||
ended_at: z.string().nullable(),
|
||||
/** From the first to the last time, pauses included; null without times on the track. */
|
||||
elapsed_minutes: z.number().int().nonnegative().nullable(),
|
||||
point_count: z.number().int().nonnegative(),
|
||||
});
|
||||
export type TourActivityMetrics = z.infer<typeof tourActivityMetricsSchema>;
|
||||
|
||||
const activityPointSchema = z.union([z.tuple([z.number(), z.number()]), z.tuple([z.number(), z.number(), z.number()])]);
|
||||
|
||||
export const tourActivitySchema = z.object({
|
||||
id: idSchema,
|
||||
/** The execution: the day assignment of the tour it was done on; null for none. */
|
||||
assignment_id: idSchema.nullable(),
|
||||
/** The day of that assignment, for a reader without the day lists. */
|
||||
day_id: idSchema.nullable(),
|
||||
assigned_at: z.string().nullable(),
|
||||
track: tourActivityTrackSchema,
|
||||
metrics: tourActivityMetricsSchema,
|
||||
/** The recorded line, every point, for the profile; the MCP tools leave it out. */
|
||||
geometry: z.array(activityPointSchema),
|
||||
});
|
||||
export type TourActivity = z.infer<typeof tourActivitySchema>;
|
||||
|
||||
/** What a tour list item says about its assignments: which recordings, on which execution. */
|
||||
export const tourActivityRefSchema = z.object({
|
||||
id: idSchema,
|
||||
track_place_id: idSchema,
|
||||
assignment_id: idSchema.nullable(),
|
||||
});
|
||||
export type TourActivityRef = z.infer<typeof tourActivityRefSchema>;
|
||||
|
||||
/**
|
||||
* Assigning a recording to a tour, confirmed by the user. An execution that
|
||||
* already has one gets this one instead; the recording named must not document
|
||||
* another tour.
|
||||
*/
|
||||
export const tourActivityAssignRequestSchema = z
|
||||
.object({
|
||||
track_place_id: idSchema,
|
||||
assignment_id: idSchema.nullable(),
|
||||
})
|
||||
.strict();
|
||||
export type TourActivityAssignRequest = z.infer<typeof tourActivityAssignRequestSchema>;
|
||||
|
||||
/**
|
||||
* Why an assignment was refused, as the 4xx body's `code` names it: the track
|
||||
* is no recording (planned in TREK, or planned over since), it documents
|
||||
* another tour already, it is the tour itself or has recordings of its own, the
|
||||
* tour is itself the recording of another, or the execution is not this tour's.
|
||||
*/
|
||||
export const TOUR_ACTIVITY_REFUSALS = [
|
||||
'activity_track_not_recorded',
|
||||
'activity_track_in_use',
|
||||
'activity_track_is_tour',
|
||||
'activity_tour_is_track',
|
||||
'activity_assignment_not_of_tour',
|
||||
] as const;
|
||||
export type TourActivityRefusal = (typeof TOUR_ACTIVITY_REFUSALS)[number];
|
||||
@@ -27,6 +27,13 @@ export const tourGpxPreviewTrackSchema = z.object({
|
||||
/** Null when the file carries no heights: unknown, never zero. */
|
||||
elevation_gain_m: z.number().nullable(),
|
||||
elevation_loss_m: z.number().nullable(),
|
||||
/**
|
||||
* ACT-01: the first and last time on the track's points (ISO 8601, UTC);
|
||||
* null unless every point carries one, so a route or a drawn track never
|
||||
* reads as recorded.
|
||||
*/
|
||||
started_at: z.string().nullable().optional(),
|
||||
ended_at: z.string().nullable().optional(),
|
||||
/** Already in the trip under the same name and start: the import skips it, as it always has. */
|
||||
duplicate: z.boolean(),
|
||||
});
|
||||
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
} from './paddle-plan.schema';
|
||||
import { runPaceSecondsPerKmSchema } from './run-pace';
|
||||
import { skiDisciplineSchema, skiTechniqueSchema } from './ski.schema';
|
||||
import { tourActivityRefSchema, tourActivitySchema } from './tour-activity.schema';
|
||||
import { tourPoiCategorySchema } from './tour-poi-category';
|
||||
import { tourOriginSchema, tourProvenanceSchema } from './tour-provenance.schema';
|
||||
|
||||
@@ -293,6 +294,17 @@ export const tourListItemSchema = tourSchema.extend({
|
||||
* opened, and a save keeps it. Absent in a list cached before it existed.
|
||||
*/
|
||||
route_pending: z.boolean().optional(),
|
||||
/**
|
||||
* ACT-01: when the track an import read was recorded, from the times on its
|
||||
* points (ISO 8601, UTC); null when the file carried none and for a planned
|
||||
* tour. Absent in a list cached before it existed.
|
||||
*/
|
||||
track_started_at: z.string().nullable().optional(),
|
||||
track_ended_at: z.string().nullable().optional(),
|
||||
/** ACT-01: the recordings assigned to this tour, one per execution. Absent in a list cached before it existed. */
|
||||
activity_tracks: z.array(tourActivityRefSchema).optional(),
|
||||
/** ACT-01: the tour this recording documents, when it is assigned to one; null otherwise. */
|
||||
activity_of: z.number().int().positive().nullable().optional(),
|
||||
});
|
||||
export type TourListItem = z.infer<typeof tourListItemSchema>;
|
||||
|
||||
@@ -676,6 +688,8 @@ export const tourCreateResponseSchema = z.object({
|
||||
provenance: tourProvenanceSchema.optional(),
|
||||
/** PAD-06: a paddle tour's obstacle checklist; dropped, never refused, when this build cannot read it. */
|
||||
obstacle_check: tourObstacleCheckSchema.optional().catch(undefined),
|
||||
/** ACT-01: the recorded tracks assigned to the tour; absent only in a detail cached before TREK sent them. */
|
||||
activities: z.array(tourActivitySchema).optional(),
|
||||
});
|
||||
export type TourCreateResponse = z.infer<typeof tourCreateResponseSchema>;
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user