From d0cc6fc2f469d5c87bff8c84d5293d9530999f16 Mon Sep 17 00:00:00 2001 From: Maurice Date: Tue, 20 Oct 2026 12:42:33 +0200 Subject: [PATCH] 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. --- client/src/api/tourActivities.ts | 14 + .../Tours/TourDetailDialog.test.tsx | 7 + .../src/components/Tours/TourDetailDialog.tsx | 28 ++ .../Tours/TourGpxPreviewDialog.test.tsx | 74 ++++ .../components/Tours/TourGpxPreviewDialog.tsx | 48 ++- client/src/components/Tours/TourListRow.tsx | 3 +- .../Tours/activity/TourActivityBadge.test.tsx | 23 ++ .../activity/TourActivityDialog.test.tsx | 119 +++++++ .../Tours/activity/TourActivityDialog.tsx | 284 ++++++++++++++++ .../activity/TourActivitySection.test.tsx | 135 ++++++++ .../Tours/activity/TourActivitySection.tsx | 243 ++++++++++++++ .../Tours/activity/tourActivityModel.test.ts | 147 ++++++++ .../Tours/activity/tourActivityModel.ts | 126 +++++++ .../Tours/activity/useTourActivities.test.ts | 133 ++++++++ .../Tours/activity/useTourActivities.ts | 133 ++++++++ .../Tours/activity/useTrackAssignment.test.ts | 105 ++++++ .../Tours/activity/useTrackAssignment.ts | 104 ++++++ .../src/components/Tours/gpxImportChoices.ts | 32 +- client/src/components/Tours/tourParts.tsx | 22 +- .../src/components/Tours/tourScope.test.tsx | 7 + client/src/components/Tours/tourScope.ts | 5 +- client/src/db/cacheTour.test.ts | 25 ++ client/src/db/cacheTour.ts | 10 +- client/src/db/offlineDb.ts | 12 +- .../pages/tripPlanner/useTourDetailActions.ts | 7 +- client/src/repo/tourRepo.test.ts | 37 ++ client/src/repo/tourRepo.ts | 25 +- server/scripts/repository-owners.json | 1 + .../src/db/entities/DayAssignments.entity.ts | 3 + .../src/db/entities/TourActivities.entity.ts | 45 +++ server/src/db/entities/Tours.entity.ts | 10 + server/src/db/entities/Users.entity.ts | 3 + server/src/db/entities/index.ts | 2 + server/src/db/kysely/TourActivities.table.ts | 12 + server/src/db/kysely/Tours.table.ts | 2 + server/src/db/kysely/db.ts | 2 + ...a_tour_keeps_the_track_it_was_done_with.ts | 46 +++ .../repositories/TourActivities.repository.ts | 147 ++++++++ .../src/db/repositories/Tours.repository.ts | 12 + .../nest/place-import/place-import.types.ts | 5 + .../place-import/providers/gpx.provider.ts | 31 ++ .../src/nest/tours/dto/tour-activity.dto.ts | 5 + .../nest/tours/tour-activities.controller.ts | 52 +++ .../src/nest/tours/tour-activities.helpers.ts | 99 ++++++ server/src/nest/tours/tour-activities.mcp.ts | 110 ++++++ .../src/nest/tours/tour-activities.service.ts | 121 +++++++ server/src/nest/tours/tours.mcp.ts | 12 +- server/src/nest/tours/tours.module.ts | 12 +- server/src/nest/tours/tours.service.ts | 44 ++- server/tests/e2e/tours-activity.e2e.test.ts | 285 ++++++++++++++++ server/tests/helpers/factories/tours.ts | 15 +- server/tests/helpers/fake-paddle-checks.ts | 13 +- server/tests/helpers/tours-repos.ts | 6 + server/tests/unit/db/entities-index.test.ts | 7 +- .../tests/unit/db/entity-class-fields.test.ts | 3 +- server/tests/unit/db/legacy-baseline.test.ts | 1 + .../TourActivities.repository.test.ts | 171 ++++++++++ .../db/repositories/Tours.repository.test.ts | 8 + .../nest/place-import/gpx.provider.test.ts | 41 +++ .../nest/tour-activities.controller.test.ts | 72 ++++ .../unit/nest/tour-activities.helpers.test.ts | 165 +++++++++ .../unit/nest/tour-activities.mcp.test.ts | 138 ++++++++ .../unit/nest/tour-activities.service.test.ts | 315 ++++++++++++++++++ .../tests/unit/nest/tours.gpx.atomic.test.ts | 2 + ...s.permissions.boundaries.mock-only.test.ts | 3 +- .../nest/tours.service.permissions.test.ts | 3 +- server/tests/unit/nest/tours.service.test.ts | 2 + shared/src/i18n/ar/tours.ts | 34 ++ shared/src/i18n/az/tours.ts | 34 ++ shared/src/i18n/br/tours.ts | 34 ++ shared/src/i18n/ca/tours.ts | 35 ++ shared/src/i18n/cs/tours.ts | 34 ++ shared/src/i18n/de/tours.ts | 35 ++ shared/src/i18n/en/tours.ts | 34 ++ shared/src/i18n/es/tours.ts | 35 ++ shared/src/i18n/et/tours.ts | 34 ++ shared/src/i18n/fr/tours.ts | 34 ++ shared/src/i18n/gr/tours.ts | 34 ++ shared/src/i18n/hu/tours.ts | 35 ++ shared/src/i18n/id/tours.ts | 35 ++ shared/src/i18n/it/tours.ts | 34 ++ shared/src/i18n/ja/tours.ts | 34 ++ shared/src/i18n/ko/tours.ts | 34 ++ shared/src/i18n/nl/tours.ts | 35 ++ shared/src/i18n/pl/tours.ts | 34 ++ shared/src/i18n/ru/tours.ts | 35 ++ shared/src/i18n/sk/tours.ts | 34 ++ shared/src/i18n/sv/tours.ts | 34 ++ shared/src/i18n/th/tours.ts | 34 ++ shared/src/i18n/tours-locales.spec.ts | 2 +- shared/src/i18n/tr/tours.ts | 35 ++ shared/src/i18n/uk/tours.ts | 34 ++ shared/src/i18n/vi/tours.ts | 35 ++ shared/src/i18n/zh-TW/tours.ts | 34 ++ shared/src/i18n/zh/tours.ts | 34 ++ shared/src/index.ts | 1 + shared/src/tours/tour-activity.schema.spec.ts | 86 +++++ shared/src/tours/tour-activity.schema.ts | 102 ++++++ shared/src/tours/tour-gpx-import.schema.ts | 7 + shared/src/tours/tours.schema.ts | 14 + wiki/MCP-Addon-Tools.md | 8 +- 101 files changed, 5031 insertions(+), 50 deletions(-) create mode 100644 client/src/api/tourActivities.ts create mode 100644 client/src/components/Tours/TourGpxPreviewDialog.test.tsx create mode 100644 client/src/components/Tours/activity/TourActivityBadge.test.tsx create mode 100644 client/src/components/Tours/activity/TourActivityDialog.test.tsx create mode 100644 client/src/components/Tours/activity/TourActivityDialog.tsx create mode 100644 client/src/components/Tours/activity/TourActivitySection.test.tsx create mode 100644 client/src/components/Tours/activity/TourActivitySection.tsx create mode 100644 client/src/components/Tours/activity/tourActivityModel.test.ts create mode 100644 client/src/components/Tours/activity/tourActivityModel.ts create mode 100644 client/src/components/Tours/activity/useTourActivities.test.ts create mode 100644 client/src/components/Tours/activity/useTourActivities.ts create mode 100644 client/src/components/Tours/activity/useTrackAssignment.test.ts create mode 100644 client/src/components/Tours/activity/useTrackAssignment.ts create mode 100644 server/src/db/entities/TourActivities.entity.ts create mode 100644 server/src/db/kysely/TourActivities.table.ts create mode 100644 server/src/db/migrations/Migration20200101045900_a_tour_keeps_the_track_it_was_done_with.ts create mode 100644 server/src/db/repositories/TourActivities.repository.ts create mode 100644 server/src/nest/tours/dto/tour-activity.dto.ts create mode 100644 server/src/nest/tours/tour-activities.controller.ts create mode 100644 server/src/nest/tours/tour-activities.helpers.ts create mode 100644 server/src/nest/tours/tour-activities.mcp.ts create mode 100644 server/src/nest/tours/tour-activities.service.ts create mode 100644 server/tests/e2e/tours-activity.e2e.test.ts create mode 100644 server/tests/unit/db/repositories/TourActivities.repository.test.ts create mode 100644 server/tests/unit/nest/tour-activities.controller.test.ts create mode 100644 server/tests/unit/nest/tour-activities.helpers.test.ts create mode 100644 server/tests/unit/nest/tour-activities.mcp.test.ts create mode 100644 server/tests/unit/nest/tour-activities.service.test.ts create mode 100644 shared/src/tours/tour-activity.schema.spec.ts create mode 100644 shared/src/tours/tour-activity.schema.ts diff --git a/client/src/api/tourActivities.ts b/client/src/api/tourActivities.ts new file mode 100644 index 000000000..c101f0b0c --- /dev/null +++ b/client/src/api/tourActivities.ts @@ -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 => + apiClient.put(`/trips/${tripId}/tours/${placeId}/activities`, body).then((r) => r.data), + unassign: (tripId: number | string, placeId: number | string, activityId: number): Promise => + apiClient.delete(`/trips/${tripId}/tours/${placeId}/activities/${activityId}`).then((r) => r.data), +}; diff --git a/client/src/components/Tours/TourDetailDialog.test.tsx b/client/src/components/Tours/TourDetailDialog.test.tsx index abfce8d52..abddc35dd 100644 --- a/client/src/components/Tours/TourDetailDialog.test.tsx +++ b/client/src/components/Tours/TourDetailDialog.test.tsx @@ -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() + + 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() diff --git a/client/src/components/Tours/TourDetailDialog.tsx b/client/src/components/Tours/TourDetailDialog.tsx index a0b7292ef..3071dd169 100644 --- a/client/src/components/Tours/TourDetailDialog.tsx +++ b/client/src/components/Tours/TourDetailDialog.tsx @@ -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; /** P2C-07: save this tour again as a new, independent one. */ onSaveAsNew?: (tour: TourListItem) => Promise | void; + /** ACT-01: a recorded track was assigned, taken off or imported; the lists take in these tours. */ + onToursChanged?: (placeIds: number[]) => Promise | 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 (
@@ -285,6 +293,14 @@ function TourHeadPills({ )} + {documentsName && ( + + + + {t('tours.activity.ofTour', { name: documentsName })} + + + )} {shownTime != null && ( @@ -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' && } {tour.tour_type === 'kayak' && } + {/* A tour written here offline has no server copy to assign a recording to until it syncs. */} + {place.id > 0 && ( + + )} {description && ( diff --git a/client/src/components/Tours/TourGpxPreviewDialog.test.tsx b/client/src/components/Tours/TourGpxPreviewDialog.test.tsx new file mode 100644 index 000000000..eac73169c --- /dev/null +++ b/client/src/components/Tours/TourGpxPreviewDialog.test.tsx @@ -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: () =>
})); + +function track(overrides: Partial = {}): 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([''], '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(); + 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( + + ); + 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(); + fireEvent.click(screen.getByTestId('gpx-preview-import')); + expect(walk.confirm).toHaveBeenCalledWith({ tour_type: 'walk' }); + unmount(); + + const hike = gpxImport([track()]); + render(); + fireEvent.click(screen.getByTestId('gpx-preview-import')); + expect(hike.confirm).toHaveBeenCalledWith({ tour_type: 'hike' }); + }); +}); diff --git a/client/src/components/Tours/TourGpxPreviewDialog.tsx b/client/src/components/Tours/TourGpxPreviewDialog.tsx index 57402d2c4..7df48539d 100644 --- a/client/src/components/Tours/TourGpxPreviewDialog.tsx +++ b/client/src/components/Tours/TourGpxPreviewDialog.tsx @@ -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 ( + + + {formatDate(track.started_at.slice(0, 10), locale)} + {formatPlannedTourDuration(minutes)} + + ); +} + /** 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[ {t('tours.import.previewNoHeights')} )} {t('tours.import.previewPoints', { count: track.point_count })} +
); @@ -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 ; + return ; } -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; diff --git a/client/src/components/Tours/TourListRow.tsx b/client/src/components/Tours/TourListRow.tsx index aa4ab40ce..5fbc53b59 100644 --- a/client/src/components/Tours/TourListRow.tsx +++ b/client/src/components/Tours/TourListRow.tsx @@ -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" > +
diff --git a/client/src/components/Tours/activity/TourActivityBadge.test.tsx b/client/src/components/Tours/activity/TourActivityBadge.test.tsx new file mode 100644 index 000000000..0eeae2daf --- /dev/null +++ b/client/src/components/Tours/activity/TourActivityBadge.test.tsx @@ -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( + + ); + expect(screen.getByTestId('tour-activity-badge')).toHaveAttribute('aria-label', 'tours.activity.badgeHint'); + + rerender(); + expect(screen.getByTestId('tour-activity-badge')).toHaveAttribute('aria-label', 'tours.activity.isTrackHint'); + + rerender(); + expect(screen.queryByTestId('tour-activity-badge')).toBeNull(); + rerender(); + expect(screen.queryByTestId('tour-activity-badge')).toBeNull(); + }); +}); diff --git a/client/src/components/Tours/activity/TourActivityDialog.test.tsx b/client/src/components/Tours/activity/TourActivityDialog.test.tsx new file mode 100644 index 000000000..9feebc6a6 --- /dev/null +++ b/client/src/components/Tours/activity/TourActivityDialog.test.tsx @@ -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 { + 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 = {}) => + ({ + busy: false, + canEdit: true, + assigning: {}, + assign: vi.fn(), + closeAssign: vi.fn(), + ...overrides, + }) as unknown as TourActivities; + +const show = (current: TourActivities = state()) => + render(); + +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(); + }); +}); diff --git a/client/src/components/Tours/activity/TourActivityDialog.tsx b/client/src/components/Tours/activity/TourActivityDialog.tsx new file mode 100644 index 000000000..415872db4 --- /dev/null +++ b/client/src/components/Tours/activity/TourActivityDialog.tsx @@ -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 ( + + ); +} + +/** 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 ( +
+ +
+ ); + } + if (candidates.length === 0) { + return ( + }> + {t('tours.activity.noCandidates')} + + ); + } + return ( +
+ {candidates.map((candidate) => ( + assignment.choose(candidate.tour.place_id)} + /> + ))} +
+ ); +} + +/** 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 ( + + + + ); +} + +/** 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 ( + 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; +} + +/** + * 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 ( + <> + + + + } + tint={NEUTRAL_TINT} + labelId={labelId} + onClose={state.closeAssign} + eyebrow={t('tours.activity.dialogEyebrow')} + title={tour.name} + sub={t('tours.activity.dialogHint')} + subWraps + /> + } + footer={ + + + + {t('common.cancel')} + + : + } + onClick={confirm} + > + {t('tours.activity.confirm')} + + + } + > + + + + + ) : ( + + ) + } + onClick={gpxImport.pick} + disabled={importing} + > + {t('tours.activity.importGpx')} + + } + > +
+ + {assignment.replaces && ( + }> + {t('tours.activity.replaces', { name: assignment.replaces })} + + )} +
+
+ {choice && choice.takenBy === null && } +
+ + + ); +} diff --git a/client/src/components/Tours/activity/TourActivitySection.test.tsx b/client/src/components/Tours/activity/TourActivitySection.test.tsx new file mode 100644 index 000000000..9a32f2859 --- /dev/null +++ b/client/src/components/Tours/activity/TourActivitySection.test.tsx @@ -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: () =>
})); + +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 = {}, 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 { + 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(); + +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(); + 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(); + }); +}); diff --git a/client/src/components/Tours/activity/TourActivitySection.tsx b/client/src/components/Tours/activity/TourActivitySection.tsx new file mode 100644 index 000000000..fd818d81c --- /dev/null +++ b/client/src/components/Tours/activity/TourActivitySection.tsx @@ -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; + +/** 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 ( + +