diff --git a/client/src/api/journeyEntriesFromPhotos.test.ts b/client/src/api/journeyEntriesFromPhotos.test.ts new file mode 100644 index 000000000..a734ba4f6 --- /dev/null +++ b/client/src/api/journeyEntriesFromPhotos.test.ts @@ -0,0 +1,31 @@ +// FE-API-JOURNEY-FROM-PHOTOS-001 +// +// #1920: the preview and the create pin their path and body and hand back what the server answered. +import { http, HttpResponse } from 'msw'; +import { describe, expect, it } from 'vitest'; +import { server } from '../../tests/helpers/msw/server'; +import { journeyEntriesFromPhotosApi } from './journeyEntriesFromPhotos'; + +describe('journeyEntriesFromPhotosApi', () => { + it('FE-API-JOURNEY-FROM-PHOTOS-001: posts the preview and the create of a journey', async () => { + const sent: Array<{ path: string; body: unknown }> = []; + const preview = { clusters: [], withoutCaptureTime: 0, maxGapMinutes: 180, maxDistanceKm: 20 }; + const created = { entries: [], skippedPhotoIds: [4] }; + server.use( + http.post('/api/journeys/7/entries/from-photos/preview', async ({ request }) => { + sent.push({ path: new URL(request.url).pathname, body: await request.json() }); + return HttpResponse.json(preview); + }), + http.post('/api/journeys/7/entries/from-photos', async ({ request }) => { + sent.push({ path: new URL(request.url).pathname, body: await request.json() }); + return HttpResponse.json(created); + }) + ); + expect(await journeyEntriesFromPhotosApi.preview(7, { lang: 'de' })).toEqual(preview); + expect(await journeyEntriesFromPhotosApi.create(7, { groups: [{ photoIds: [4] }] })).toEqual(created); + expect(sent).toEqual([ + { path: '/api/journeys/7/entries/from-photos/preview', body: { lang: 'de' } }, + { path: '/api/journeys/7/entries/from-photos', body: { groups: [{ photoIds: [4] }] } }, + ]); + }); +}); diff --git a/client/src/api/journeyEntriesFromPhotos.ts b/client/src/api/journeyEntriesFromPhotos.ts new file mode 100644 index 000000000..480f8c220 --- /dev/null +++ b/client/src/api/journeyEntriesFromPhotos.ts @@ -0,0 +1,23 @@ +import type { + JourneyEntriesFromPhotosCreateRequest, + JourneyEntriesFromPhotosCreateResponse, + JourneyEntriesFromPhotosPreviewRequest, + JourneyEntriesFromPhotosPreviewResponse, +} from '@trek/shared'; +import apiClient from './client'; + +const base = (journeyId: number) => `/journeys/${journeyId}/entries/from-photos`; + +/** #1920: the gallery photos on no entry as proposed entries, and the drafts made of the groups kept. */ +export const journeyEntriesFromPhotosApi = { + preview: ( + journeyId: number, + body: JourneyEntriesFromPhotosPreviewRequest, + signal?: AbortSignal + ): Promise => + apiClient.post(`${base(journeyId)}/preview`, body, { signal }).then((r) => r.data), + create: ( + journeyId: number, + body: JourneyEntriesFromPhotosCreateRequest + ): Promise => apiClient.post(base(journeyId), body).then((r) => r.data), +}; diff --git a/client/src/components/Journey/journeyEntriesFromPhotosModel.test.ts b/client/src/components/Journey/journeyEntriesFromPhotosModel.test.ts new file mode 100644 index 000000000..3f3c9ea77 --- /dev/null +++ b/client/src/components/Journey/journeyEntriesFromPhotosModel.test.ts @@ -0,0 +1,87 @@ +// FE-JRN-FROMPHOTOS-MODEL-001 to FE-JRN-FROMPHOTOS-MODEL-004 +// +// #1920: what the traveller chose of a preview, and the create request it becomes. +import type { JourneyEntriesFromPhotosCluster } from '@trek/shared'; +import { describe, expect, it } from 'vitest'; +import { + carryChoice, + chooseAll, + clusterKey, + initialChoice, + renameCluster, + requestOf, + titleOf, + toggleCluster, +} from './journeyEntriesFromPhotosModel'; + +function cluster( + photoIds: number[], + over: Partial = {} +): JourneyEntriesFromPhotosCluster { + return { + date: '2026-05-14', + startTime: '09:00', + endTime: '10:00', + timezone: 'Europe/Rome', + lat: null, + lng: null, + countryCode: null, + locationName: null, + suggestedTitle: '14 May 2026', + titleSource: 'date', + photoIds, + photoCount: photoIds.length, + coverPhotoId: photoIds[0] ?? 1, + ...over, + }; +} + +const VENICE = cluster([4, 5], { locationName: 'Venezia', suggestedTitle: 'Venezia', titleSource: 'place' }); +const DAY = cluster([6]); + +describe('journeyEntriesFromPhotosModel', () => { + it('FE-JRN-FROMPHOTOS-MODEL-001: a fresh preview chooses every group, and a group is known by its first photo', () => { + expect(clusterKey(VENICE)).toBe(4); + const choice = initialChoice([VENICE, DAY]); + expect([...choice.selected]).toEqual([4, 6]); + expect(choice.titles).toEqual({}); + }); + + it('FE-JRN-FROMPHOTOS-MODEL-002: toggling, choosing all or none and renaming change only what they name', () => { + let choice = initialChoice([VENICE, DAY]); + choice = toggleCluster(choice, 6); + expect([...choice.selected]).toEqual([4]); + choice = toggleCluster(choice, 6); + expect(choice.selected.has(6)).toBe(true); + expect(chooseAll(choice, [VENICE, DAY], false).selected.size).toBe(0); + expect(chooseAll(chooseAll(choice, [VENICE, DAY], false), [VENICE, DAY], true).selected.size).toBe(2); + choice = renameCluster(choice, 4, ' San Marco '); + expect(titleOf(choice, VENICE)).toBe('San Marco'); + expect(titleOf(renameCluster(choice, 4, ' '), VENICE)).toBe('Venezia'); + expect(titleOf(choice, DAY)).toBe('14 May 2026'); + }); + + it('FE-JRN-FROMPHOTOS-MODEL-003: a new preview keeps the choice of the groups still there and chooses new ones', () => { + let choice = toggleCluster(initialChoice([VENICE, DAY]), 6); + choice = renameCluster(choice, 4, 'San Marco'); + const later = cluster([7]); + const carried = carryChoice(choice, [4, 6], [VENICE, DAY, later]); + expect([...carried.selected].sort()).toEqual([4, 7]); + expect(carried.titles).toEqual({ 4: 'San Marco' }); + expect(carryChoice(null, [], [DAY]).selected.has(6)).toBe(true); + }); + + it('FE-JRN-FROMPHOTOS-MODEL-004: the request holds the chosen groups with their titles and place names, or nothing', () => { + const choice = renameCluster(initialChoice([VENICE, DAY]), 6, 'Rainy day'); + expect(requestOf([VENICE, DAY], choice, { timezone: 'Europe/Rome', lang: 'de-DE' })).toEqual({ + groups: [ + { photoIds: [4, 5], title: 'Venezia', locationName: 'Venezia' }, + { photoIds: [6], title: 'Rainy day' }, + ], + timezone: 'Europe/Rome', + lang: 'de-DE', + }); + expect(requestOf([VENICE], toggleCluster(choice, 4), {})).toBeNull(); + expect(requestOf([DAY], choice, {})).toEqual({ groups: [{ photoIds: [6], title: 'Rainy day' }] }); + }); +}); diff --git a/client/src/components/Journey/journeyEntriesFromPhotosModel.ts b/client/src/components/Journey/journeyEntriesFromPhotosModel.ts new file mode 100644 index 000000000..fa15d3e20 --- /dev/null +++ b/client/src/components/Journey/journeyEntriesFromPhotosModel.ts @@ -0,0 +1,91 @@ +import type { JourneyEntriesFromPhotosCluster, JourneyEntriesFromPhotosCreateRequest } from '@trek/shared'; + +/** + * What the traveller chose of a preview (#1920): which groups become drafts + * and the titles they edited. A group is known by its first photo, so a + * fresh preview keeps the choice for the groups that are still there. + */ +export interface FromPhotosChoice { + selected: ReadonlySet; + /** Edited titles by group key; a group not listed keeps its suggestion. */ + titles: Readonly>; +} + +/** The key of a group: its first photo, which belongs to no other group. */ +export function clusterKey(cluster: JourneyEntriesFromPhotosCluster): number { + return cluster.photoIds[0] ?? cluster.coverPhotoId; +} + +/** Every group chosen, no title edited: what a fresh preview starts with. */ +export function initialChoice(clusters: readonly JourneyEntriesFromPhotosCluster[]): FromPhotosChoice { + return { selected: new Set(clusters.map(clusterKey)), titles: {} }; +} + +/** A choice carried over to a new preview: groups still there keep their state, new ones are chosen. */ +export function carryChoice( + previous: FromPhotosChoice | null, + previousKeys: readonly number[], + clusters: readonly JourneyEntriesFromPhotosCluster[] +): FromPhotosChoice { + if (!previous) return initialChoice(clusters); + const known = new Set(previousKeys); + const selected = new Set(); + const titles: Record = {}; + for (const cluster of clusters) { + const key = clusterKey(cluster); + if (!known.has(key) || previous.selected.has(key)) selected.add(key); + const title = previous.titles[key]; + if (title !== undefined) titles[key] = title; + } + return { selected, titles }; +} + +export function toggleCluster(choice: FromPhotosChoice, key: number): FromPhotosChoice { + const selected = new Set(choice.selected); + if (selected.has(key)) selected.delete(key); + else selected.add(key); + return { ...choice, selected }; +} + +export function chooseAll( + choice: FromPhotosChoice, + clusters: readonly JourneyEntriesFromPhotosCluster[], + on: boolean +): FromPhotosChoice { + return { ...choice, selected: new Set(on ? clusters.map(clusterKey) : []) }; +} + +export function renameCluster(choice: FromPhotosChoice, key: number, title: string): FromPhotosChoice { + return { ...choice, titles: { ...choice.titles, [key]: title } }; +} + +/** The title a group goes in under: the edited one when it holds more than blanks, else the suggestion. */ +export function titleOf(choice: FromPhotosChoice, cluster: JourneyEntriesFromPhotosCluster): string { + const edited = choice.titles[clusterKey(cluster)]?.trim(); + return edited ? edited.slice(0, 255) : cluster.suggestedTitle; +} + +/** + * The create request for the chosen groups, in the order they were lived: + * each with its photos, its title and the place name the preview found. + * Null while nothing is chosen. + */ +export function requestOf( + clusters: readonly JourneyEntriesFromPhotosCluster[], + choice: FromPhotosChoice, + options: { timezone?: string; lang?: string } +): JourneyEntriesFromPhotosCreateRequest | null { + const groups = clusters + .filter((cluster) => choice.selected.has(clusterKey(cluster))) + .map((cluster) => ({ + photoIds: cluster.photoIds, + title: titleOf(choice, cluster), + ...(cluster.locationName ? { locationName: cluster.locationName } : {}), + })); + if (!groups.length) return null; + return { + groups, + ...(options.timezone ? { timezone: options.timezone } : {}), + ...(options.lang ? { lang: options.lang } : {}), + }; +} diff --git a/client/src/components/Journey/useJourneyEntriesFromPhotos.test.ts b/client/src/components/Journey/useJourneyEntriesFromPhotos.test.ts new file mode 100644 index 000000000..5a76707ee --- /dev/null +++ b/client/src/components/Journey/useJourneyEntriesFromPhotos.test.ts @@ -0,0 +1,169 @@ +// FE-JRN-FROMPHOTOS-001 to FE-JRN-FROMPHOTOS-005 +// +// #1920: journal entries made from gallery photos, for the desktop dialog and +// the phone sheet alike. Nothing is written before submit; a failed create +// reads the gallery again and keeps what was chosen. +import type { JourneyEntriesFromPhotosCluster } from '@trek/shared'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { act, renderHook, waitFor } from '../../../tests/helpers/render'; +import { TranslationProvider } from '../../i18n/TranslationContext'; +import { useJourneyEntriesFromPhotos } from './useJourneyEntriesFromPhotos'; + +const repo = vi.hoisted(() => ({ preview: vi.fn(), create: vi.fn() })); +vi.mock('../../repo/journeyEntriesFromPhotosRepo', () => ({ journeyEntriesFromPhotosRepo: repo })); + +const toast = { success: vi.fn(), error: vi.fn(), warning: vi.fn(), info: vi.fn() }; +vi.mock('../shared/Toast', () => ({ useToast: () => toast })); + +function cluster( + photoIds: number[], + over: Partial = {} +): JourneyEntriesFromPhotosCluster { + return { + date: '2026-05-14', + startTime: '09:00', + endTime: '10:00', + timezone: 'Europe/Rome', + lat: 45.43, + lng: 12.33, + countryCode: 'IT', + locationName: 'Venezia', + suggestedTitle: 'Venezia', + titleSource: 'place', + photoIds, + photoCount: photoIds.length, + coverPhotoId: photoIds[0] ?? 1, + ...over, + }; +} + +const VENICE = cluster([4, 5]); +const VERONA = cluster([6], { suggestedTitle: 'Italy', titleSource: 'country', locationName: null }); +const PREVIEW = { clusters: [VENICE, VERONA], withoutCaptureTime: 2, maxGapMinutes: 180, maxDistanceKm: 20 }; + +function setup() { + const onCreated = vi.fn(); + const onClose = vi.fn(); + const view = renderHook(() => useJourneyEntriesFromPhotos({ journeyId: 7, onCreated, onClose }), { + wrapper: TranslationProvider, + }); + return { ...view, onCreated, onClose }; +} + +beforeEach(() => { + for (const fn of [...Object.values(repo), ...Object.values(toast)]) fn.mockReset(); + repo.preview.mockResolvedValue(PREVIEW); + repo.create.mockResolvedValue({ + entries: [ + { id: 11, title: 'San Marco', entry_date: '2026-05-14', entry_time: '09:00', photoCount: 2 }, + { id: 12, title: 'Italy', entry_date: '2026-05-14', entry_time: '12:00', photoCount: 1 }, + ], + skippedPhotoIds: [], + }); +}); + +describe('useJourneyEntriesFromPhotos', () => { + it('FE-JRN-FROMPHOTOS-001: reads the groups in the app language and chooses all of them, writing nothing', async () => { + const { result } = setup(); + await waitFor(() => expect(result.current.loading).toBe(false)); + + expect(repo.preview).toHaveBeenCalledWith(7, expect.objectContaining({ lang: 'en-US' }), expect.any(AbortSignal)); + expect(result.current.clusters).toEqual([VENICE, VERONA]); + expect(result.current.withoutCaptureTime).toBe(2); + expect(result.current.maxGapMinutes).toBe(180); + expect(result.current.selectedCount).toBe(2); + expect(result.current.isSelected(VERONA)).toBe(true); + expect(result.current.canSubmit).toBe(true); + expect(result.current.error).toBeNull(); + expect(repo.create).not.toHaveBeenCalled(); + }); + + it('FE-JRN-FROMPHOTOS-002: writes the chosen groups under their titles, then reloads the journey and closes', async () => { + const { result, onCreated, onClose } = setup(); + await waitFor(() => expect(result.current.selectedCount).toBe(2)); + + act(() => result.current.rename(VENICE, 'San Marco')); + expect(result.current.titleOf(VENICE)).toBe('San Marco'); + await act(async () => result.current.submit()); + + expect(repo.create).toHaveBeenCalledWith( + 7, + expect.objectContaining({ + groups: [ + { photoIds: [4, 5], title: 'San Marco', locationName: 'Venezia' }, + { photoIds: [6], title: 'Italy' }, + ], + lang: 'en-US', + }) + ); + await waitFor(() => expect(onClose).toHaveBeenCalled()); + expect(onCreated).toHaveBeenCalledOnce(); + expect(toast.success).toHaveBeenCalledWith('2 draft entries created from your photos'); + expect(toast.info).not.toHaveBeenCalled(); + }); + + it('FE-JRN-FROMPHOTOS-003: says which photos were left out, and that nothing was written when every photo was taken meanwhile', async () => { + repo.create.mockResolvedValue({ entries: [], skippedPhotoIds: [6] }); + const { result, onCreated, onClose } = setup(); + await waitFor(() => expect(result.current.selectedCount).toBe(2)); + + act(() => result.current.toggle(VENICE)); + expect(result.current.selectedCount).toBe(1); + await act(async () => result.current.submit()); + + expect(repo.create).toHaveBeenCalledWith( + 7, + expect.objectContaining({ groups: [{ photoIds: [6], title: 'Italy' }] }) + ); + expect(toast.info).toHaveBeenCalledWith('None of these photos could become an entry. Nothing was created.'); + expect(toast.info).toHaveBeenCalledWith( + '1 photo was left out: it is on an entry already or no longer in the gallery.' + ); + expect(onCreated).not.toHaveBeenCalled(); + expect(onClose).toHaveBeenCalledOnce(); + }); + + it('FE-JRN-FROMPHOTOS-004: a failed create keeps the dialog and the choice, says so and reads the gallery again', async () => { + repo.create.mockRejectedValue(new Error('500')); + const { result, onClose } = setup(); + await waitFor(() => expect(result.current.selectedCount).toBe(2)); + act(() => result.current.toggle(VERONA)); + + await act(async () => result.current.submit()); + + expect(toast.error).toHaveBeenCalledWith('No entries were created. Nothing was written, try again.'); + expect(onClose).not.toHaveBeenCalled(); + await waitFor(() => expect(repo.preview).toHaveBeenCalledTimes(2)); + await waitFor(() => expect(result.current.loading).toBe(false)); + expect(result.current.isSelected(VERONA)).toBe(false); + expect(result.current.isSelected(VENICE)).toBe(true); + expect(result.current.busy).toBe(false); + }); + + it('FE-JRN-FROMPHOTOS-005: a failed preview says so and retries; nothing chosen means nothing to send; a new gap reads again', async () => { + repo.preview.mockRejectedValueOnce(new Error('offline')); + const { result } = setup(); + await waitFor(() => expect(result.current.error).toBe('The photos could not be grouped. Try again.')); + expect(result.current.canSubmit).toBe(false); + + act(() => result.current.retry()); + await waitFor(() => expect(result.current.clusters).toHaveLength(2)); + expect(result.current.error).toBeNull(); + + act(() => result.current.selectAll(false)); + expect(result.current.canSubmit).toBe(false); + await act(async () => result.current.submit()); + expect(repo.create).not.toHaveBeenCalled(); + act(() => result.current.selectAll(true)); + expect(result.current.selectedCount).toBe(2); + + act(() => result.current.setMaxGapMinutes(60)); + await waitFor(() => + expect(repo.preview).toHaveBeenLastCalledWith( + 7, + expect.objectContaining({ maxGapMinutes: 60 }), + expect.any(AbortSignal) + ) + ); + }); +}); diff --git a/client/src/components/Journey/useJourneyEntriesFromPhotos.ts b/client/src/components/Journey/useJourneyEntriesFromPhotos.ts new file mode 100644 index 000000000..b88aae68c --- /dev/null +++ b/client/src/components/Journey/useJourneyEntriesFromPhotos.ts @@ -0,0 +1,153 @@ +import type { JourneyEntriesFromPhotosCluster, JourneyEntriesFromPhotosPreviewResponse } from '@trek/shared'; +import { useCallback, useEffect, useMemo, useState } from 'react'; +import { useTranslation } from '../../i18n'; +import { journeyEntriesFromPhotosRepo } from '../../repo/journeyEntriesFromPhotosRepo'; +import { browserTimeZone } from '../../utils/localDate'; +import { useToast } from '../shared/Toast'; +import { + carryChoice, + chooseAll, + clusterKey, + renameCluster, + requestOf, + titleOf, + toggleCluster, + type FromPhotosChoice, +} from './journeyEntriesFromPhotosModel'; + +/** What the desktop dialog and the phone sheet are opened with. */ +interface JourneyEntriesFromPhotosOptions { + journeyId: number; + /** Drafts were written: the journey is read again. */ + onCreated: () => void; + onClose: () => void; +} + +interface Answer { + key: string; + preview: JourneyEntriesFromPhotosPreviewResponse | null; + failed: boolean; +} + +const NO_ANSWER: Answer = { key: '', preview: null, failed: false }; + +/** + * The preview of the gallery's photos as proposed entries, read again when + * the gap changes or on retry; the choice carries over to the groups that are + * still there. The last answer stays shown while the next one is read. + */ +function usePreview(journeyId: number, maxGapMinutes: number | undefined, timezone: string | undefined, lang: string) { + const [reloadToken, setReloadToken] = useState(0); + const requestKey = `${journeyId}|${maxGapMinutes ?? ''}|${timezone ?? ''}|${lang}|${reloadToken}`; + const [answer, setAnswer] = useState(NO_ANSWER); + const [chosen, setChosen] = useState<{ keys: number[]; choice: FromPhotosChoice } | null>(null); + + useEffect(() => { + const controller = new AbortController(); + let cancelled = false; + journeyEntriesFromPhotosRepo + .preview( + journeyId, + { ...(maxGapMinutes ? { maxGapMinutes } : {}), ...(timezone ? { timezone } : {}), lang }, + controller.signal + ) + .then((preview) => { + if (cancelled) return; + setAnswer({ key: requestKey, preview, failed: false }); + setChosen((prev) => ({ + keys: preview.clusters.map(clusterKey), + choice: carryChoice(prev?.choice ?? null, prev?.keys ?? [], preview.clusters), + })); + }) + .catch(() => { + if (!cancelled) setAnswer((prev) => ({ key: requestKey, preview: prev.preview, failed: true })); + }); + return () => { + cancelled = true; + controller.abort(); + }; + }, [journeyId, maxGapMinutes, timezone, lang, requestKey]); + + const update = useCallback( + (change: (choice: FromPhotosChoice) => FromPhotosChoice) => + setChosen((prev) => (prev ? { ...prev, choice: change(prev.choice) } : prev)), + [] + ); + + return { + preview: answer.preview, + loading: answer.key !== requestKey, + failed: answer.key === requestKey && answer.failed, + choice: chosen?.choice ?? null, + update, + reload: useCallback(() => setReloadToken((n) => n + 1), []), + }; +} + +/** + * Journal entries made from the photos of the journey's gallery (#1920), for + * the desktop dialog and the phone sheet alike: the gallery photos on no + * entry grouped by local day, time and place, the choice of groups and their + * titles, and the create. Nothing is written before `submit`; the entries + * are drafts, and a photo put on an entry meanwhile is left out by the server + * and reported. Markup-free: the views only render what it answers. + */ +export function useJourneyEntriesFromPhotos({ journeyId, onCreated, onClose }: JourneyEntriesFromPhotosOptions) { + const { t, locale } = useTranslation(); + const toast = useToast(); + const timezone = useMemo(() => browserTimeZone(), []); + const [maxGapMinutes, setMaxGapMinutes] = useState(undefined); + const [busy, setBusy] = useState(false); + const state = usePreview(journeyId, maxGapMinutes, timezone, locale); + const { preview, choice, update, reload } = state; + const clusters = useMemo(() => preview?.clusters ?? [], [preview]); + const request = useMemo( + () => (choice ? requestOf(clusters, choice, { timezone, lang: locale }) : null), + [clusters, choice, timezone, locale] + ); + + const submit = useCallback(async () => { + if (!request || busy) return; + setBusy(true); + try { + const result = await journeyEntriesFromPhotosRepo.create(journeyId, request); + const created = result.entries.length; + if (created > 0) toast.success(t('journey.fromPhotos.created', { count: created })); + else toast.info(t('journey.fromPhotos.nothingCreated')); + if (result.skippedPhotoIds.length > 0) { + toast.info(t('journey.fromPhotos.skipped', { count: result.skippedPhotoIds.length })); + } + if (created > 0) onCreated(); + onClose(); + } catch { + // Nothing was written: the create is one transaction. Read the gallery again, it may have changed. + toast.error(t('journey.fromPhotos.createFailed')); + reload(); + } finally { + setBusy(false); + } + }, [request, busy, journeyId, toast, t, onCreated, onClose, reload]); + + return { + clusters, + /** Gallery photos on no entry that do not know when they were taken and so are in no group. */ + withoutCaptureTime: preview?.withoutCaptureTime ?? 0, + /** The gap the groups were cut with, in minutes. */ + maxGapMinutes: preview?.maxGapMinutes ?? maxGapMinutes ?? null, + setMaxGapMinutes, + loading: state.loading, + /** Translated; null while the last preview did not fail. */ + error: state.failed ? t('journey.fromPhotos.previewFailed') : null, + retry: reload, + isSelected: (cluster: JourneyEntriesFromPhotosCluster) => !!choice?.selected.has(clusterKey(cluster)), + titleOf: (cluster: JourneyEntriesFromPhotosCluster) => (choice ? titleOf(choice, cluster) : cluster.suggestedTitle), + selectedCount: request?.groups.length ?? 0, + toggle: (cluster: JourneyEntriesFromPhotosCluster) => update((c) => toggleCluster(c, clusterKey(cluster))), + selectAll: (on: boolean) => update((c) => chooseAll(c, clusters, on)), + rename: (cluster: JourneyEntriesFromPhotosCluster, title: string) => + update((c) => renameCluster(c, clusterKey(cluster), title)), + busy, + canSubmit: !!request && !busy, + submit: () => void submit(), + }; +} diff --git a/client/src/repo/journeyEntriesFromPhotosRepo.test.ts b/client/src/repo/journeyEntriesFromPhotosRepo.test.ts new file mode 100644 index 000000000..a9738dd37 --- /dev/null +++ b/client/src/repo/journeyEntriesFromPhotosRepo.test.ts @@ -0,0 +1,64 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { journeyEntriesFromPhotosApi } from '../api/journeyEntriesFromPhotos'; +import { journeyEntriesFromPhotosRepo } from './journeyEntriesFromPhotosRepo'; +import { OnlineOnlyError } from './onlineOnly'; + +// FE-REPO-JOURNEY-FROM-PHOTOS-001 to FE-REPO-JOURNEY-FROM-PHOTOS-003 + +const network = vi.hoisted(() => ({ offline: false })); +vi.mock('../sync/networkMode', () => ({ isEffectivelyOffline: () => network.offline })); + +const CLUSTER = { + date: '2026-05-14', + startTime: '09:00', + endTime: '10:00', + timezone: 'Europe/Rome', + lat: 45.43, + lng: 12.33, + countryCode: 'IT', + locationName: 'Venezia', + suggestedTitle: 'Venezia', + titleSource: 'place' as const, + photoIds: [4, 5], + photoCount: 2, + coverPhotoId: 4, +}; + +beforeEach(() => { + network.offline = false; + vi.restoreAllMocks(); +}); + +describe('journeyEntriesFromPhotosRepo', () => { + it('FE-REPO-JOURNEY-FROM-PHOTOS-001: asks nothing offline', async () => { + network.offline = true; + const preview = vi.spyOn(journeyEntriesFromPhotosApi, 'preview'); + const create = vi.spyOn(journeyEntriesFromPhotosApi, 'create'); + await expect(journeyEntriesFromPhotosRepo.preview(7, {})).rejects.toBeInstanceOf(OnlineOnlyError); + await expect(journeyEntriesFromPhotosRepo.create(7, { groups: [{ photoIds: [4] }] })).rejects.toBeInstanceOf( + OnlineOnlyError + ); + expect(preview).not.toHaveBeenCalled(); + expect(create).not.toHaveBeenCalled(); + }); + + it('FE-REPO-JOURNEY-FROM-PHOTOS-002: answers what the contract describes', async () => { + const preview = { clusters: [CLUSTER], withoutCaptureTime: 1, maxGapMinutes: 180, maxDistanceKm: 20 }; + vi.spyOn(journeyEntriesFromPhotosApi, 'preview').mockResolvedValue(preview); + vi.spyOn(journeyEntriesFromPhotosApi, 'create').mockResolvedValue({ + entries: [{ id: 9, title: 'Venezia', entry_date: '2026-05-14', entry_time: '09:00', photoCount: 2 }], + skippedPhotoIds: [], + }); + const controller = new AbortController(); + expect(await journeyEntriesFromPhotosRepo.preview(7, { lang: 'it' }, controller.signal)).toEqual(preview); + expect(journeyEntriesFromPhotosApi.preview).toHaveBeenCalledWith(7, { lang: 'it' }, controller.signal); + expect((await journeyEntriesFromPhotosRepo.create(7, { groups: [{ photoIds: [4, 5] }] })).entries[0]?.id).toBe(9); + }); + + it('FE-REPO-JOURNEY-FROM-PHOTOS-003: refuses an answer the contract does not describe', async () => { + vi.spyOn(journeyEntriesFromPhotosApi, 'preview').mockResolvedValue({ clusters: 'none' } as never); + vi.spyOn(journeyEntriesFromPhotosApi, 'create').mockResolvedValue({ entries: [{ id: 'x' }] } as never); + await expect(journeyEntriesFromPhotosRepo.preview(7, {})).rejects.toThrow(); + await expect(journeyEntriesFromPhotosRepo.create(7, { groups: [{ photoIds: [4] }] })).rejects.toThrow(); + }); +}); diff --git a/client/src/repo/journeyEntriesFromPhotosRepo.ts b/client/src/repo/journeyEntriesFromPhotosRepo.ts new file mode 100644 index 000000000..9318abc7e --- /dev/null +++ b/client/src/repo/journeyEntriesFromPhotosRepo.ts @@ -0,0 +1,40 @@ +import { + journeyEntriesFromPhotosCreateResponseSchema, + journeyEntriesFromPhotosPreviewResponseSchema, + type JourneyEntriesFromPhotosCreateRequest, + type JourneyEntriesFromPhotosCreateResponse, + type JourneyEntriesFromPhotosPreviewRequest, + type JourneyEntriesFromPhotosPreviewResponse, +} from '@trek/shared'; +import { journeyEntriesFromPhotosApi } from '../api/journeyEntriesFromPhotos'; +import { requireOnline } from './onlineOnly'; + +/** + * #1920, online only like the journey itself: the grouping reads the gallery + * as the server holds it and names the groups through the geocoder, and the + * create links photos the server checks again inside its transaction, which + * an offline replay could not do. Answers are parsed against the shared + * contract, so a server that answered something else fails here. + */ +export const journeyEntriesFromPhotosRepo = { + async preview( + journeyId: number, + body: JourneyEntriesFromPhotosPreviewRequest, + signal?: AbortSignal + ): Promise { + requireOnline(); + return journeyEntriesFromPhotosPreviewResponseSchema.parse( + await journeyEntriesFromPhotosApi.preview(journeyId, body, signal) + ); + }, + + async create( + journeyId: number, + body: JourneyEntriesFromPhotosCreateRequest + ): Promise { + requireOnline(); + return journeyEntriesFromPhotosCreateResponseSchema.parse( + await journeyEntriesFromPhotosApi.create(journeyId, body) + ); + }, +};