diff --git a/server/src/nest/journey/journey-domain.module.ts b/server/src/nest/journey/journey-domain.module.ts index 681b90ef3..a8d36513d 100644 --- a/server/src/nest/journey/journey-domain.module.ts +++ b/server/src/nest/journey/journey-domain.module.ts @@ -17,6 +17,7 @@ import { SettingsModule } from '../settings/settings.module'; import { JourneyDomainService } from './journey-domain.service'; import { JourneyEntryStaysService } from './journey-entry-stays.service'; import { JourneyMapService } from './journey-map.service'; +import { JourneyPhotoLinksService } from './journey-photo-links.service'; import { JourneyRecordedDaysService } from './journey-recorded-days.service'; import { JourneyRecordingPrepService } from './journey-recording-prep.service'; import { JourneySettingsService } from './journey-settings.service'; @@ -110,6 +111,7 @@ import { Module } from '@nestjs/common'; JourneyRecordingPrepService, JourneyMapService, JourneySettingsService, + JourneyPhotoLinksService, ], exports: [ JourneyDomainService, @@ -119,6 +121,7 @@ import { Module } from '@nestjs/common'; JourneyRecordingPrepService, JourneyMapService, JourneySettingsService, + JourneyPhotoLinksService, ], }) export class JourneyDomainModule {} diff --git a/server/src/nest/journey/journey-photo-links.service.ts b/server/src/nest/journey/journey-photo-links.service.ts new file mode 100644 index 000000000..63d5262ae --- /dev/null +++ b/server/src/nest/journey/journey-photo-links.service.ts @@ -0,0 +1,125 @@ +import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity'; +import type { JourneyPhotosRepository } from '../../db/repositories/JourneyPhotos.repository'; +import type { GalleryPhoto, JourneyPhoto } from '../../types'; +import { badRequest, notFound } from '../common/domain-error'; +import { UnitOfWork } from '../database/unit-of-work'; +import { JourneyDomainService } from './journey-domain.service'; +import { InjectRepository } from '@mikro-orm/nestjs'; +import { Injectable } from '@nestjs/common'; +import type { JourneyPhotosMoveRequest, JourneyPhotosMoveResponse } from '@trek/shared'; + +/** + * Which entries a journey's photos sit on, and what they are called: a + * gallery photo linked to an entry or taken off it, photos moved from one + * entry to another, a caption changed. Every change is told to everyone on + * the journey after it is written (the link and the unlink told nobody, so + * another tab, and the journey page after an assistant change, stayed as it + * was). The REST routes and the MCP tools both go through here. + */ +@Injectable() +export class JourneyPhotoLinksService { + constructor( + private readonly journeys: JourneyDomainService, + private readonly uow: UnitOfWork, + @InjectRepository(JourneyPhotos) private readonly photosRepo: JourneyPhotosRepository, + ) {} + + /** Links a gallery photo of the entry's journey to the entry; null when either is not the user's to change. */ + async link(entryId: number, journeyPhotoId: number, userId: number, sid?: string): Promise { + const photo = await this.journeys.linkPhotoToEntry(entryId, journeyPhotoId, userId); + if (photo) await this.announce([entryId], sid); + return photo; + } + + /** Takes a photo off the entry; it stays in the gallery. False when nothing was taken off. */ + async unlink(entryId: number, journeyPhotoId: number, userId: number, sid?: string): Promise { + const done = await this.journeys.unlinkPhotoFromEntry(entryId, journeyPhotoId, userId); + if (done) await this.announce([entryId], sid); + return done; + } + + /** + * Moves photos of one entry to another of the same journey, in one write: + * each is linked to the target (a suggestion it lands on becomes an entry, + * as on any add) and, unless kept, taken off the source. Every photo must + * be one of the source entry's; an entry outside the journey, or one the + * user may not change, reads as not found. + */ + async move( + fromEntryId: number, + req: JourneyPhotosMoveRequest, + userId: number, + sid?: string, + ): Promise { + const journeyId = await this.journeys.journeyIdOfEntry(fromEntryId); + const target = await this.journeys.journeyIdOfEntry(req.toEntryId); + if (journeyId === null || target !== journeyId || !(await this.journeys.canEdit(journeyId, userId))) { + throw notFound('Entry not found'); + } + if (fromEntryId === req.toEntryId) throw badRequest('Photos cannot move to the entry they are on'); + const entries = (await this.journeys.listEntries(journeyId, userId)) ?? []; + const onSource = new Set( + (entries.find((entry) => entry.id === fromEntryId)?.photos ?? []).map((photo) => photo.id), + ); + const ids = [...new Set(req.photoIds)]; + if (ids.some((id) => !onSource.has(id))) throw badRequest('Every photo must be one of this entry'); + const kept = req.keep_in_source === true; + await this.uow.transactional(async () => { + for (const id of ids) { + if (!(await this.journeys.linkPhotoToEntry(req.toEntryId, id, userId))) throw notFound('Entry not found'); + if (!kept) await this.journeys.unlinkPhotoFromEntry(fromEntryId, id, userId); + } + }); + await this.announce([fromEntryId, req.toEntryId], sid); + return { moved: ids, fromEntryId, toEntryId: req.toEntryId, kept }; + } + + /** + * A gallery photo's caption, with the one it replaces, read in the same + * write; null when the photo is not the user's to change or not in the + * journey the call is about. + */ + async setCaption( + journeyId: number, + journeyPhotoId: number, + caption: string | null, + userId: number, + ): Promise<{ photo: GalleryPhoto; previous: { caption: string | null } } | null> { + const scope = await this.photosRepo.findScopeById(journeyPhotoId); + if (!scope || scope.journey_id !== journeyId || !(await this.journeys.canEdit(journeyId, userId))) return null; + const previous = await this.uow.transactional(async () => { + const before = await this.photosRepo.galleryReadOne(journeyPhotoId); + await this.photosRepo.updateCaption(journeyPhotoId, caption as string); + return { caption: before?.caption ?? null }; + }); + await this.journeys.broadcastJourneyEvent(journeyId, 'journey:updated', {}); + const photo = await this.photosRepo.galleryReadOne(journeyPhotoId); + return photo ? { photo, previous } : null; + } + + /** + * The REST route's change of a photo (its caption, its place among the + * entry's photos), told to everyone on the journey once written, as the + * MCP caption is. Null when the service refused it. + */ + async updatePhoto( + journeyPhotoId: number, + userId: number, + data: { caption?: string; sort_order?: number }, + sid?: string, + ): Promise { + const photo = await this.journeys.updatePhoto(journeyPhotoId, userId, data); + const scope = photo ? await this.photosRepo.findScopeById(journeyPhotoId) : undefined; + if (scope) await this.journeys.broadcastJourneyEvent(scope.journey_id, 'journey:updated', {}, sid); + return photo; + } + + /** Tells everyone on the journey that these entries' photos changed; the asking tab already knows. */ + private async announce(entryIds: number[], sid?: string): Promise { + const journeyId = await this.journeys.journeyIdOfEntry(entryIds[0]); + if (journeyId === null) return; + for (const entryId of new Set(entryIds)) { + await this.journeys.broadcastJourneyEvent(journeyId, 'journey:entry:updated', { entryId }, sid); + } + } +} diff --git a/server/src/nest/journey/journey-photos.mcp.ts b/server/src/nest/journey/journey-photos.mcp.ts new file mode 100644 index 000000000..d0916c1f8 --- /dev/null +++ b/server/src/nest/journey/journey-photos.mcp.ts @@ -0,0 +1,93 @@ +import { ADDON_IDS } from '../../addons'; +import { McpController, TOOL_ANNOTATIONS_WRITE, Tool, errorResult, ok, type McpContext } from '../../nest-mcp'; +import { addonGate } from '../addons/addon-gate'; +import { AddonsService } from '../addons/addons.service'; +import { JourneyPhotoLinksService } from './journey-photo-links.service'; +import { + idSchema, + journeyPhotoCaptionToolSchema, + journeyPhotoLinkToolSchema, + journeyPhotosMoveToolSchema, + type JourneyPhotoCaptionTool, + type JourneyPhotoLinkTool, + type JourneyPhotosMoveTool, +} from '@trek/shared'; + +const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY); + +/** + * Which entries a journey's photos sit on, and their captions, over MCP: the + * service the REST routes use (POST `entries/:entryId/link-photo`, DELETE + * `entries/:entryId/photos/:journeyPhotoId`, POST + * `entries/:entryId/photos/move`), the same edit right on the journey and the + * same event to every open tab. Each answer names what a way back needs. + */ +@McpController() +export class JourneyPhotoLinksMcp { + constructor( + private readonly photoLinks: JourneyPhotoLinksService, + readonly addons: AddonsService, + ) {} + + @Tool({ + name: 'link_journey_photo', + description: + "Put a photo of the journey's gallery on one of its entries as well; it stays in the gallery and on any other entry. The photo ids are the ids of the gallery and entry photos get_journey answers.", + inputSchema: journeyPhotoLinkToolSchema.shape, + annotations: TOOL_ANNOTATIONS_WRITE, + when: journeyAddonOn, + access: { group: 'journey', mode: 'write' }, + }) + async linkJourneyPhoto({ entryId, journey_photo_id }: JourneyPhotoLinkTool, ctx: McpContext) { + const photo = await this.photoLinks.link(entryId, journey_photo_id, ctx.userId); + if (!photo) return errorResult('Entry or photo not found, or access denied.'); + return ok({ photo, entryId }); + } + + @Tool({ + name: 'unlink_journey_photo', + description: + 'Take a photo off one journal entry. It stays in the journey gallery and on any other entry; nothing is deleted.', + inputSchema: journeyPhotoLinkToolSchema.shape, + annotations: TOOL_ANNOTATIONS_WRITE, + when: journeyAddonOn, + access: { group: 'journey', mode: 'write' }, + }) + async unlinkJourneyPhoto({ entryId, journey_photo_id }: JourneyPhotoLinkTool, ctx: McpContext) { + if (!(await this.photoLinks.unlink(entryId, journey_photo_id, ctx.userId))) { + return errorResult('The photo is not on this entry, or access denied.'); + } + return ok({ success: true, entryId, journey_photo_id }); + } + + @Tool({ + name: 'move_journey_photos', + description: + 'Move photos of one journal entry to another entry of the same journey, in one change: each is put on the other entry and taken off the first, unless keep_in_source keeps it there too. A suggestion the photos land on becomes a written entry. The photos stay in the gallery.', + inputSchema: journeyPhotosMoveToolSchema.shape, + annotations: TOOL_ANNOTATIONS_WRITE, + when: journeyAddonOn, + access: { group: 'journey', mode: 'write' }, + }) + async moveJourneyPhotos({ fromEntryId, ...move }: JourneyPhotosMoveTool, ctx: McpContext) { + return ok(await this.photoLinks.move(fromEntryId, move, ctx.userId)); + } + + @Tool({ + name: 'set_journey_photo_caption', + description: + 'Set the caption of one photo of the journey gallery, shown wherever the photo appears; null clears it. Answers with the photo and, under previous, the caption it had.', + inputSchema: { journeyId: idSchema, ...journeyPhotoCaptionToolSchema.shape }, + annotations: TOOL_ANNOTATIONS_WRITE, + when: journeyAddonOn, + access: { group: 'journey', mode: 'write' }, + }) + async setJourneyPhotoCaption( + { journeyId, journey_photo_id, caption }: JourneyPhotoCaptionTool & { journeyId: number }, + ctx: McpContext, + ) { + const updated = await this.photoLinks.setCaption(journeyId, journey_photo_id, caption, ctx.userId); + if (!updated) return errorResult('Photo not found in this journey, or access denied.'); + return ok(updated); + } +} diff --git a/server/src/nest/journey/journey.controller.ts b/server/src/nest/journey/journey.controller.ts index b1a87cd2f..f5695bf01 100644 --- a/server/src/nest/journey/journey.controller.ts +++ b/server/src/nest/journey/journey.controller.ts @@ -27,6 +27,7 @@ import { journeyThumbName } from '../memories/thumbnail.service'; import { JourneyService } from './journey.service'; import { JourneyBookService } from './journey-book.service'; import { JourneyPhotoCaptureService, type ProviderPhotoBatch, type ProviderPhotoTarget } from './journey-photo-capture.service'; +import { JourneyPhotoLinksService } from './journey-photo-links.service'; import { AddonGuard } from '../addons/addon.guard'; import { RequireAddon } from '../addons/require-addon.decorator'; import { ADDON_IDS } from '../../addons'; @@ -35,7 +36,7 @@ import { CurrentUser } from '../auth-core/current-user.decorator'; import { JourneyAddTripDto, JourneyContributorAddDto, JourneyContributorUpdateDto, JourneyCreateDto, JourneyEntryCreateDto, JourneyEntryPhotoUploadDto, JourneyEntryUpdateDto, JourneyGalleryVideoDto, - JourneyLinkPhotoDto, JourneyPhotoUpdateDto, JourneyPreferencesDto, JourneyProviderPhotosDto, + JourneyLinkPhotoDto, JourneyPhotosMoveDto, JourneyPhotoUpdateDto, JourneyPreferencesDto, JourneyProviderPhotosDto, JourneyReorderEntriesDto, JourneyReorderEntryPhotosDto, JourneyShareLinkDto, JourneyUpdateDto, BookSaveDto, @@ -47,6 +48,7 @@ import { ResponseContract } from '../common/response-contract'; import { emptyResponseSchema, journeyListResponseSchema, + journeyPhotosMoveResponseSchema, journeySchema, journeyShareLinkResponseSchema, journeyShareLinkSetResponseSchema, @@ -168,6 +170,8 @@ export class JourneyController { private readonly storage: StorageService, private readonly books: JourneyBookService, private readonly photoCapture: JourneyPhotoCaptureService, + // Which entries the gallery's photos sit on, told to every tab once written. + private readonly photoLinks: JourneyPhotoLinksService, ) {} /** @@ -392,30 +396,38 @@ export class JourneyController { } @Post('entries/:entryId/link-photo') - async linkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: JourneyLinkPhotoDto) { + async linkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: JourneyLinkPhotoDto, @Headers('x-socket-id') socketId?: string) { const journeyPhotoId = body.journey_photo_id ?? body.photo_id; if (!journeyPhotoId) { throw new HttpException({ error: 'journey_photo_id required' }, 400); } - const result = await this.journey.linkPhotoToEntry(Number(entryId), Number(journeyPhotoId), user.id); + const result = await this.photoLinks.link(Number(entryId), Number(journeyPhotoId), user.id, socketId); if (!result) { throw new HttpException({ error: 'Not allowed' }, 403); } return result; } + // Photos of this entry moved to another entry of the journey, in one write (POST, 200: nothing is created). + @Post('entries/:entryId/photos/move') + @HttpCode(200) + @ResponseContract(journeyPhotosMoveResponseSchema) + async movePhotos(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: JourneyPhotosMoveDto, @Headers('x-socket-id') socketId?: string) { + return this.photoLinks.move(Number(entryId), body, user.id, socketId); + } + @Delete('entries/:entryId/photos/:journeyPhotoId') @HttpCode(204) @ResponseContract(emptyResponseSchema) - async unlinkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Param('journeyPhotoId') journeyPhotoId: string): Promise { - if (!(await this.journey.unlinkPhotoFromEntry(Number(entryId), Number(journeyPhotoId), user.id))) { + async unlinkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Param('journeyPhotoId') journeyPhotoId: string, @Headers('x-socket-id') socketId?: string): Promise { + if (!(await this.photoLinks.unlink(Number(entryId), Number(journeyPhotoId), user.id, socketId))) { throw new HttpException({ error: 'Not found or not allowed' }, 404); } } @Patch('photos/:photoId') - async updatePhoto(@CurrentUser() user: User, @Param('photoId') photoId: string, @Body() body: JourneyPhotoUpdateDto) { - const result = await this.journey.updatePhoto(Number(photoId), user.id, body); + async updatePhoto(@CurrentUser() user: User, @Param('photoId') photoId: string, @Body() body: JourneyPhotoUpdateDto, @Headers('x-socket-id') socketId?: string) { + const result = await this.photoLinks.updatePhoto(Number(photoId), user.id, body, socketId); if (!result) { throw new HttpException({ error: 'Photo not found' }, 404); } diff --git a/server/src/nest/journey/journey.dto.ts b/server/src/nest/journey/journey.dto.ts index 6df82a6b8..47bcea8e4 100644 --- a/server/src/nest/journey/journey.dto.ts +++ b/server/src/nest/journey/journey.dto.ts @@ -9,6 +9,7 @@ import { journeyGalleryVideoRequestSchema, journeyLinkPhotoRequestSchema, journeyPhotoUpdateRequestSchema, + journeyPhotosMoveRequestSchema, journeyPreferencesRequestSchema, journeyProviderPhotosRequestSchema, journeyReorderEntriesRequestSchema, @@ -51,6 +52,8 @@ export class JourneyShareLinkDto extends createZodDto(journeyShareLinkRequestSch export class JourneyProviderPhotosDto extends createZodDto(journeyProviderPhotosRequestSchema) {} export class JourneyLinkPhotoDto extends createZodDto(journeyLinkPhotoRequestSchema) {} export class JourneyPhotoUpdateDto extends createZodDto(journeyPhotoUpdateRequestSchema) {} +/** Photos of an entry moved to another entry: strict, a new route with nothing older to keep answering. */ +export class JourneyPhotosMoveDto extends createZodDto(journeyPhotosMoveRequestSchema) {} export class JourneyEntryPhotoUploadDto extends createZodDto(journeyEntryPhotoUploadRequestSchema) {} export class JourneyGalleryVideoDto extends createZodDto(journeyGalleryVideoRequestSchema) {} diff --git a/server/src/nest/journey/journey.module.ts b/server/src/nest/journey/journey.module.ts index 87dc21abe..2ef49913e 100644 --- a/server/src/nest/journey/journey.module.ts +++ b/server/src/nest/journey/journey.module.ts @@ -13,6 +13,7 @@ import { JourneyDomainModule } from './journey-domain.module'; import { JourneyMapController } from './journey-map.controller'; import { JourneyMapMcp } from './journey-map.mcp'; import { JourneyPhotoCaptureModule } from './journey-photo-capture.module'; +import { JourneyPhotoLinksMcp } from './journey-photos.mcp'; import { JourneyPublicController } from './journey-public.controller'; import { JourneyTracksMcp } from './journey-tracks.mcp'; import { JourneyController } from './journey.controller'; @@ -58,6 +59,6 @@ import { MulterModule } from '@nestjs/platform-express'; MikroOrmModule.forFeature([Users]), ], controllers: [JourneyController, JourneyMapController, JourneyPublicController], - providers: [JourneyService, JourneyMcp, JourneyMapMcp, JourneyTracksMcp], + providers: [JourneyService, JourneyMcp, JourneyMapMcp, JourneyTracksMcp, JourneyPhotoLinksMcp], }) export class JourneyModule {} diff --git a/server/src/nest/journey/journey.service.ts b/server/src/nest/journey/journey.service.ts index 592bdf812..75b47f28d 100644 --- a/server/src/nest/journey/journey.service.ts +++ b/server/src/nest/journey/journey.service.ts @@ -118,15 +118,7 @@ export class JourneyService { setPhotoProvider(photoId: number, provider: string, assetId: string, ownerId: number) { return this.journey.setPhotoProvider(photoId, provider, assetId, ownerId); } - linkPhotoToEntry(entryId: number, journeyPhotoId: number, userId: number) { - return this.journey.linkPhotoToEntry(entryId, journeyPhotoId, userId); - } - unlinkPhotoFromEntry(entryId: number, journeyPhotoId: number, userId: number) { - return this.journey.unlinkPhotoFromEntry(entryId, journeyPhotoId, userId); - } - updatePhoto(photoId: number, userId: number, data: Parameters[2]) { - return this.journey.updatePhoto(photoId, userId, data); - } + // Linking, unlinking and captioning a photo go through JourneyPhotoLinksService, which tells every tab. deletePhoto(photoId: number, userId: number) { return this.journey.deletePhoto(photoId, userId); } diff --git a/server/tests/e2e/journey.e2e.test.ts b/server/tests/e2e/journey.e2e.test.ts index 4b0a232ed..9d02158d4 100644 --- a/server/tests/e2e/journey.e2e.test.ts +++ b/server/tests/e2e/journey.e2e.test.ts @@ -105,6 +105,10 @@ const { jsvc } = vi.hoisted(() => ({ broadcastJourneyEvent: vi.fn(), journeyIdOfEntry: vi.fn(), journeyTracks: vi.fn(), + canEdit: vi.fn(), + listEntries: vi.fn(), + linkPhotoToEntry: vi.fn(), + unlinkPhotoFromEntry: vi.fn(), }, })); @@ -676,4 +680,73 @@ describe('Journey e2e (real auth guard + temp SQLite)', () => { const tool = await app.get(JourneyTracksMcp).getJourneyTracks({ journeyId: 9 }, asMcp); expect(tool).toEqual({ content: [{ type: 'text', text: 'Journey not found or access denied.' }], isError: true }); }); + + describe('POST /api/journeys/entries/:entryId/photos/move', () => { + const path = '/api/journeys/entries/3/photos/move'; + + beforeEach(() => { + for (const fn of [jsvc.journeyIdOfEntry, jsvc.canEdit, jsvc.listEntries, jsvc.linkPhotoToEntry]) fn.mockReset(); + jsvc.unlinkPhotoFromEntry.mockReset(); + jsvc.broadcastJourneyEvent.mockReset(); + jsvc.journeyIdOfEntry.mockResolvedValue(9); + jsvc.canEdit.mockResolvedValue(true); + jsvc.listEntries.mockResolvedValue([ + { id: 3, photos: [{ id: 5 }] }, + { id: 4, photos: [] }, + ]); + jsvc.linkPhotoToEntry.mockResolvedValue({ id: 5 }); + jsvc.unlinkPhotoFromEntry.mockResolvedValue(true); + }); + + it('JOURNEY-E2E-010: 401 without a session, and the move runs nothing', async () => { + const res = await request(server) + .post(path) + .send({ toEntryId: 4, photoIds: [5] }); + expect(res.status).toBe(401); + expect(jsvc.linkPhotoToEntry).not.toHaveBeenCalled(); + }); + + it('JOURNEY-E2E-011: 200 with what moved, each photo put on the target and taken off the source, both entries told', async () => { + const res = await request(server) + .post(path) + .set('Cookie', sessionCookie(1)) + .set('X-Socket-Id', 'sock-1') + .send({ toEntryId: 4, photoIds: [5] }); + expect(res.status).toBe(200); + expect(res.body).toEqual({ moved: [5], fromEntryId: 3, toEntryId: 4, kept: false }); + expect(jsvc.linkPhotoToEntry).toHaveBeenCalledWith(4, 5, 1); + expect(jsvc.unlinkPhotoFromEntry).toHaveBeenCalledWith(3, 5, 1); + expect(jsvc.broadcastJourneyEvent.mock.calls).toEqual([ + [9, 'journey:entry:updated', { entryId: 3 }, 'sock-1'], + [9, 'journey:entry:updated', { entryId: 4 }, 'sock-1'], + ]); + }); + + it('JOURNEY-E2E-012: 400 for a body the contract refuses, a photo not on the entry; 404 for an entry out of reach', async () => { + const strict = await request(server) + .post(path) + .set('Cookie', sessionCookie(1)) + .send({ toEntryId: 4, photoIds: [5], extra: true }); + expect(strict.status).toBe(400); + const empty = await request(server) + .post(path) + .set('Cookie', sessionCookie(1)) + .send({ toEntryId: 4, photoIds: [] }); + expect(empty.status).toBe(400); + const foreign = await request(server) + .post(path) + .set('Cookie', sessionCookie(1)) + .send({ toEntryId: 4, photoIds: [6] }); + expect(foreign.status).toBe(400); + expect(foreign.body).toEqual({ error: 'Every photo must be one of this entry' }); + jsvc.canEdit.mockResolvedValue(false); + const denied = await request(server) + .post(path) + .set('Cookie', sessionCookie(1)) + .send({ toEntryId: 4, photoIds: [5] }); + expect(denied.status).toBe(404); + expect(denied.body).toEqual({ error: 'Entry not found' }); + expect(jsvc.linkPhotoToEntry).not.toHaveBeenCalled(); + }); + }); }); diff --git a/server/tests/integration/broadcast-parity/user.cases.ts b/server/tests/integration/broadcast-parity/user.cases.ts index 88ee0a10c..00cc197cd 100644 --- a/server/tests/integration/broadcast-parity/user.cases.ts +++ b/server/tests/integration/broadcast-parity/user.cases.ts @@ -17,7 +17,7 @@ import { PhotoCaptureBackfillService } from '../../../src/nest/memories/photo-ca import { NotificationsService } from '../../../src/nest/notifications/notifications.service'; import { addCollectionMember } from '../../helpers/factories/collections'; import { inContext } from '../../helpers/factories/context'; -import { addJourneyContributor, linkTripToJourney } from '../../helpers/factories/journeys'; +import { addJourneyContributor, linkTripToJourney, makeJourneyEntry } from '../../helpers/factories/journeys'; import { createRow, insertRow, updateRows } from '../../helpers/factories/rows'; import { addVacayPlanMember } from '../../helpers/factories/vacay'; import { holidayCode } from './harness'; @@ -342,6 +342,87 @@ const journeyCases: ParityCase[] = [ }, expect: [{ event: 'journey:entry:updated', user: 'actor' }], }, + { + tool: 'link_journey_photo', + needs: ['journey'], + setup: async (s, app) => { + const photo = await withRequestContext(ormOf(app), () => + app.get(JourneyDomainService).addProviderPhotoToGallery(s.journey.id, s.owner.id, 'immich', `gallery-${s.n}`), + ); + if (!photo) throw new Error('the gallery took no photo'); + keep(s, 'galleryPhoto', photo.id); + }, + args: (s) => ({ entryId: s.journeyEntry.id, journey_photo_id: kept(s, 'galleryPhoto') }), + rest: { + method: 'post', + path: (s) => `/api/journeys/entries/${s.journeyEntry.id}/link-photo`, + body: (s) => ({ journey_photo_id: kept(s, 'galleryPhoto') }), + }, + expect: [{ event: 'journey:entry:updated', user: 'actor' }], + }, + { + tool: 'unlink_journey_photo', + needs: ['journey'], + setup: async (s, app) => { + const photo = await withRequestContext(ormOf(app), () => + app.get(JourneyDomainService).addProviderPhoto(s.journeyEntry.id, s.owner.id, 'immich', `unlink-${s.n}`), + ); + if (!photo) throw new Error('the entry took no photo'); + keep(s, 'entryPhoto', photo.id); + }, + args: (s) => ({ entryId: s.journeyEntry.id, journey_photo_id: kept(s, 'entryPhoto') }), + rest: { + method: 'delete', + path: (s) => `/api/journeys/entries/${s.journeyEntry.id}/photos/${kept(s, 'entryPhoto')}`, + }, + expect: [{ event: 'journey:entry:updated', user: 'actor' }], + }, + { + tool: 'move_journey_photos', + needs: ['journey'], + setup: async (s, app) => { + const target = await makeJourneyEntry(ormOf(app), s.journey.id, s.owner.id, { entry_date: '2027-05-04' }); + const photo = await withRequestContext(ormOf(app), () => + app.get(JourneyDomainService).addProviderPhoto(s.journeyEntry.id, s.owner.id, 'immich', `move-${s.n}`), + ); + if (!target || !photo) throw new Error('the scene took no second entry or no photo'); + keep(s, 'targetEntry', target.id); + keep(s, 'movedPhoto', photo.id); + }, + args: (s) => ({ + fromEntryId: s.journeyEntry.id, + toEntryId: kept(s, 'targetEntry'), + photoIds: [kept(s, 'movedPhoto')], + }), + rest: { + method: 'post', + path: (s) => `/api/journeys/entries/${s.journeyEntry.id}/photos/move`, + body: (s) => ({ toEntryId: kept(s, 'targetEntry'), photoIds: [kept(s, 'movedPhoto')] }), + }, + // One for each entry the photos left and reached. + expect: [ + { event: 'journey:entry:updated', user: 'actor' }, + { event: 'journey:entry:updated', user: 'actor' }, + ], + }, + { + tool: 'set_journey_photo_caption', + needs: ['journey'], + setup: async (s, app) => { + const photo = await withRequestContext(ormOf(app), () => + app.get(JourneyDomainService).addProviderPhoto(s.journeyEntry.id, s.owner.id, 'immich', `caption-${s.n}`), + ); + if (!photo) throw new Error('the entry took no photo'); + keep(s, 'captionPhoto', photo.id); + }, + args: (s) => ({ journeyId: s.journey.id, journey_photo_id: kept(s, 'captionPhoto'), caption: 'Black sand' }), + rest: { + method: 'patch', + path: (s) => `/api/journeys/photos/${kept(s, 'captionPhoto')}`, + body: () => ({ caption: 'Black sand' }), + }, + expect: [{ event: 'journey:updated', user: 'actor' }], + }, { tool: 'add_journey_contributor', needs: ['journey', 'member'], diff --git a/server/tests/unit/mcp/tools-journey.test.ts b/server/tests/unit/mcp/tools-journey.test.ts index 7a3c6145e..5b59469d7 100644 --- a/server/tests/unit/mcp/tools-journey.test.ts +++ b/server/tests/unit/mcp/tools-journey.test.ts @@ -6,10 +6,13 @@ import { ADDON_IDS } from '../../../src/addons'; import { db as testDb } from '../../../src/db/database'; import { JourneyEntries } from '../../../src/db/entities/JourneyEntries.entity'; +import { JourneyEntryPhotos } from '../../../src/db/entities/JourneyEntryPhotos.entity'; +import { JourneyPhotos } from '../../../src/db/entities/JourneyPhotos.entity'; import { Journeys } from '../../../src/db/entities/Journeys.entity'; +import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity'; import { createUser, createTrip } from '../../helpers/factories'; import { addJourneyContributor } from '../../helpers/factories/journeys'; -import { createRow, findRow } from '../../helpers/factories/rows'; +import { createRow, findRow, insertRow } from '../../helpers/factories/rows'; import { FakeRealtimeService } from '../../helpers/fake-realtime'; import { createMcpHarness, parseToolResult, parseResourceResult, type McpHarness } from '../../helpers/mcp-harness'; import { resetTestDb } from '../../helpers/test-db'; @@ -794,6 +797,112 @@ async function seedEntry(h: McpHarness, journeyId: number, args: Record { + assetSeq += 1; + const trek = await createRow(orm, TrekPhotos, { provider: 'immich', asset_id: `asset-${assetSeq}` }); + const gallery = await createRow(orm, JourneyPhotos, { + journey: journeyId, + photo: trek.id, + caption: null, + shared: 0, + sort_order: 0, + created_at: Date.now(), + }); + if (entryId !== undefined) { + await insertRow(orm, JourneyEntryPhotos, { + entry: entryId, + journeyPhoto: gallery.id, + sort_order: 0, + created_at: Date.now(), + }); + } + return gallery.id; +} + +describe('journey photo tools', () => { + it('link_journey_photo and unlink_journey_photo put a gallery photo on an entry and take it off, telling the tabs', async () => { + const { user } = createUser(testDb); + await withHarness(user.id, async (h) => { + const journey = await seedJourney(h); + const entry = await seedEntry(h, journey.id, { title: 'Vik' }); + const photoId = await seedGalleryPhoto(journey.id); + broadcastMock.mockClear(); + const linked = parseToolResult( + await h.client.callTool({ + name: 'link_journey_photo', + arguments: { entryId: entry.id, journey_photo_id: photoId }, + }), + ) as { photo: { id: number }; entryId: number }; + expect(linked).toMatchObject({ photo: { id: photoId }, entryId: entry.id }); + expect(broadcastMock).toHaveBeenCalledWith( + user.id, + expect.objectContaining({ type: 'journey:entry:updated' }), + undefined, + ); + const unlinked = parseToolResult( + await h.client.callTool({ + name: 'unlink_journey_photo', + arguments: { entryId: entry.id, journey_photo_id: photoId }, + }), + ); + expect(unlinked).toEqual({ success: true, entryId: entry.id, journey_photo_id: photoId }); + const again = await h.client.callTool({ + name: 'unlink_journey_photo', + arguments: { entryId: entry.id, journey_photo_id: photoId }, + }); + expect(again.isError).toBe(true); + }); + }); + + it('move_journey_photos moves photos between entries of a journey and refuses one of another journey', async () => { + const { user } = createUser(testDb); + await withHarness(user.id, async (h) => { + const journey = await seedJourney(h); + const from = await seedEntry(h, journey.id, { title: 'Vik' }); + const to = await seedEntry(h, journey.id, { title: 'Reynisfjara', entry_date: '2026-07-02' }); + const photoId = await seedGalleryPhoto(journey.id, from.id); + const moved = parseToolResult( + await h.client.callTool({ + name: 'move_journey_photos', + arguments: { fromEntryId: from.id, toEntryId: to.id, photoIds: [photoId] }, + }), + ); + expect(moved).toEqual({ moved: [photoId], fromEntryId: from.id, toEntryId: to.id, kept: false }); + const other = await seedJourney(h, 'Other'); + const elsewhere = await seedEntry(h, other.id); + const refused = await h.client.callTool({ + name: 'move_journey_photos', + arguments: { fromEntryId: to.id, toEntryId: elsewhere.id, photoIds: [photoId] }, + }); + expect(refused.isError).toBe(true); + }); + }); + + it('set_journey_photo_caption answers the caption it replaced and refuses a photo of another journey', async () => { + const { user } = createUser(testDb); + await withHarness(user.id, async (h) => { + const journey = await seedJourney(h); + const other = await seedJourney(h, 'Other'); + const photoId = await seedGalleryPhoto(journey.id); + const first = parseToolResult( + await h.client.callTool({ + name: 'set_journey_photo_caption', + arguments: { journeyId: journey.id, journey_photo_id: photoId, caption: 'Black sand' }, + }), + ) as { photo: { caption: string }; previous: { caption: string | null } }; + expect(first).toMatchObject({ photo: { caption: 'Black sand' }, previous: { caption: null } }); + const refused = await h.client.callTool({ + name: 'set_journey_photo_caption', + arguments: { journeyId: other.id, journey_photo_id: photoId, caption: 'x' }, + }); + expect(refused.isError).toBe(true); + }); + }); +}); + describe('journey entry fields', () => { it('create_journey_entry persists the place, coordinates, weather, tags, verdict, visibility and type', async () => { const { user } = createUser(testDb); diff --git a/server/tests/unit/nest/journey-photo-links.service.test.ts b/server/tests/unit/nest/journey-photo-links.service.test.ts new file mode 100644 index 000000000..d677fd5fe --- /dev/null +++ b/server/tests/unit/nest/journey-photo-links.service.test.ts @@ -0,0 +1,164 @@ +/** + * JourneyPhotoLinksService: which entries a journey's photos sit on, and + * their captions, with every change told to everyone on the journey once it + * is written (the link and the unlink used to tell nobody). The suite takes + * the service from its module over a snapshot test db, so the journey access, + * the writes and the realtime fake are the ones the app uses. + */ +import { DomainError } from '../../../src/nest/common/domain-error'; +import { JourneyDomainModule } from '../../../src/nest/journey/journey-domain.module'; +import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service'; +import { JourneyPhotoLinksService } from '../../../src/nest/journey/journey-photo-links.service'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { addJourneyContributor, makeJourney, makeJourneyEntry } from '../../helpers/factories/journeys'; +import { makeUser } from '../../helpers/factories/users'; +import { resetTestDb } from '../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../helpers/test-module'; +import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let links: JourneyPhotoLinksService; +let journeys: JourneyDomainService; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [JourneyDomainModule] }); + links = t.get(JourneyPhotoLinksService); + journeys = t.get(JourneyDomainService); + orm = await createTestOrm(db); +}); +beforeEach(() => { + resetTestDb(db); + orm.clear(); + t.realtime.reset(); +}); +afterAll(async () => { + await orm.close(); + await t.close(); + db.close(); +}); + +/** What each user was sent, as [user, event type, payload entry id, left-out socket], in user order. */ +const sent = () => + t.realtime.broadcastToUserMock.mock.calls + .map(([to, msg, sid]) => [to, (msg as { type: string }).type, (msg as { entryId?: number }).entryId, sid] as const) + .sort((a, b) => a[0] - b[0] || (a[2] ?? 0) - (b[2] ?? 0)); + +async function scene() { + const { user: owner } = await makeUser(orm); + const { user: editor } = await makeUser(orm); + const journey = await makeJourney(orm, owner.id); + await addJourneyContributor(orm, journey.id, editor.id, 'editor'); + const first = await makeJourneyEntry(orm, journey.id, owner.id, { title: 'Arrival' }); + const second = await makeJourneyEntry(orm, journey.id, owner.id, { title: 'Next day', entry_date: '2026-01-16' }); + const photo = await journeys.addProviderPhoto(first.id, owner.id, 'immich', `asset-${first.id}`); + const gallery = await journeys.addProviderPhotoToGallery(journey.id, owner.id, 'immich', `gallery-${first.id}`); + if (!photo || !gallery) throw new Error('the scene took no photo'); + const other = await makeJourney(orm, owner.id); + const elsewhere = await makeJourneyEntry(orm, other.id, owner.id); + t.realtime.broadcastToUserMock.mockClear(); + const everyone = [owner.id, editor.id].sort((a, b) => a - b); + return { owner, editor, journey, first, second, photo, gallery, elsewhere, everyone }; +} + +async function photoIdsOf(journeyId: number, entryId: number, userId: number): Promise { + const entries = (await journeys.listEntries(journeyId, userId)) ?? []; + return (entries.find((entry) => entry.id === entryId)?.photos ?? []).map((photo) => photo.id); +} + +describe('JourneyPhotoLinksService', () => { + it('PLINK-001: a link tells everyone on the journey, the asking tab left out; a refused one tells nobody', async () => { + const s = await scene(); + expect(await links.link(s.second.id, s.gallery.id, s.editor.id, 'sock-e')).toMatchObject({ id: s.gallery.id }); + expect(sent()).toEqual(s.everyone.map((id) => [id, 'journey:entry:updated', s.second.id, 'sock-e'])); + t.realtime.broadcastToUserMock.mockClear(); + const { user: stranger } = await makeUser(orm); + expect(await links.link(s.second.id, s.gallery.id, stranger.id)).toBeNull(); + expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled(); + }); + + it('PLINK-002: an unlink takes the photo off the entry, keeps it in the gallery and tells everyone', async () => { + const s = await scene(); + expect(await links.unlink(s.first.id, s.photo.id, s.owner.id)).toBe(true); + expect(await photoIdsOf(s.journey.id, s.first.id, s.owner.id)).toEqual([]); + expect(sent()).toEqual(s.everyone.map((id) => [id, 'journey:entry:updated', s.first.id, undefined])); + t.realtime.broadcastToUserMock.mockClear(); + expect(await links.unlink(s.first.id, s.photo.id, s.owner.id)).toBe(false); + expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled(); + }); + + it('PLINK-003: a move puts the photos on the other entry and takes them off the first, telling both', async () => { + const s = await scene(); + const moved = await links.move(s.first.id, { toEntryId: s.second.id, photoIds: [s.photo.id] }, s.editor.id, 'x'); + expect(moved).toEqual({ moved: [s.photo.id], fromEntryId: s.first.id, toEntryId: s.second.id, kept: false }); + expect(await photoIdsOf(s.journey.id, s.first.id, s.owner.id)).toEqual([]); + expect(await photoIdsOf(s.journey.id, s.second.id, s.owner.id)).toEqual([s.photo.id]); + expect(sent()).toEqual( + s.everyone.flatMap((id) => [ + [id, 'journey:entry:updated', s.first.id, 'x'], + [id, 'journey:entry:updated', s.second.id, 'x'], + ]), + ); + }); + + it('PLINK-004: a move that keeps the source leaves the photos on both entries', async () => { + const s = await scene(); + await links.move(s.first.id, { toEntryId: s.second.id, photoIds: [s.photo.id], keep_in_source: true }, s.owner.id); + expect(await photoIdsOf(s.journey.id, s.first.id, s.owner.id)).toEqual([s.photo.id]); + expect(await photoIdsOf(s.journey.id, s.second.id, s.owner.id)).toEqual([s.photo.id]); + }); + + it('PLINK-005: refuses another journey, the same entry, a photo not on the source and a viewer, and moves nothing', async () => { + const s = await scene(); + const { user: viewer } = await makeUser(orm); + await addJourneyContributor(orm, s.journey.id, viewer.id, 'viewer'); + const refusal = async (run: Promise) => { + try { + await run; + } catch (err) { + if (err instanceof DomainError) return { status: err.getStatus(), message: err.publicMessage }; + throw err; + } + throw new Error('expected a refusal'); + }; + const req = { toEntryId: s.elsewhere.id, photoIds: [s.photo.id] }; + expect(await refusal(links.move(s.first.id, req, s.owner.id))).toEqual({ status: 404, message: 'Entry not found' }); + const same = { toEntryId: s.first.id, photoIds: [s.photo.id] }; + expect((await refusal(links.move(s.first.id, same, s.owner.id))).status).toBe(400); + const notOnSource = { toEntryId: s.second.id, photoIds: [s.gallery.id] }; + expect(await refusal(links.move(s.first.id, notOnSource, s.owner.id))).toEqual({ + status: 400, + message: 'Every photo must be one of this entry', + }); + const asViewer = { toEntryId: s.second.id, photoIds: [s.photo.id] }; + expect((await refusal(links.move(s.first.id, asViewer, viewer.id))).status).toBe(404); + expect(await photoIdsOf(s.journey.id, s.first.id, s.owner.id)).toEqual([s.photo.id]); + expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled(); + }); + + it('PLINK-006: a caption answers the one it replaced and tells everyone; another journey is refused', async () => { + const s = await scene(); + const first = await links.setCaption(s.journey.id, s.photo.id, 'Black sand', s.owner.id); + expect(first).toMatchObject({ photo: { id: s.photo.id, caption: 'Black sand' }, previous: { caption: null } }); + const second = await links.setCaption(s.journey.id, s.photo.id, null, s.owner.id); + expect(second).toMatchObject({ photo: { caption: null }, previous: { caption: 'Black sand' } }); + expect(sent().filter(([, type]) => type === 'journey:updated')).toHaveLength(s.everyone.length * 2); + const other = await makeJourney(orm, s.owner.id); + expect(await links.setCaption(other.id, s.photo.id, 'x', s.owner.id)).toBeNull(); + }); + + it('PLINK-007: the REST photo change tells everyone once it is written, and a refused one nobody', async () => { + const s = await scene(); + expect(await links.updatePhoto(s.photo.id, s.owner.id, { caption: 'Vik' }, 'sock-o')).toMatchObject({ + caption: 'Vik', + }); + expect(sent()).toEqual(s.everyone.map((id) => [id, 'journey:updated', undefined, 'sock-o'])); + t.realtime.broadcastToUserMock.mockClear(); + const { user: stranger } = await makeUser(orm); + expect(await links.updatePhoto(s.photo.id, stranger.id, { caption: 'x' })).toBeNull(); + expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/unit/nest/journey.controller.test.ts b/server/tests/unit/nest/journey.controller.test.ts index 8699681e4..8b5910ff3 100644 --- a/server/tests/unit/nest/journey.controller.test.ts +++ b/server/tests/unit/nest/journey.controller.test.ts @@ -3,6 +3,7 @@ import { AddonGuard } from '../../../src/nest/addons/addon.guard'; import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator'; import type { JourneyBookService } from '../../../src/nest/journey/journey-book.service'; import type { JourneyPhotoCaptureService } from '../../../src/nest/journey/journey-photo-capture.service'; +import type { JourneyPhotoLinksService } from '../../../src/nest/journey/journey-photo-links.service'; import { JourneyPublicController } from '../../../src/nest/journey/journey-public.controller'; import { JourneyController } from '../../../src/nest/journey/journey.controller'; import type { JourneyService } from '../../../src/nest/journey/journey.service'; @@ -49,8 +50,18 @@ const captureBackfillStub = { * the book, and reach for `storageStub`'s own mocks when it is about an object * being stored or served. */ -function ctl(service: JourneyService, books: Partial = {}): JourneyController { - return new JourneyController(service, storageStub, books as JourneyBookService, captureBackfillStub); +function ctl( + service: JourneyService, + books: Partial = {}, + photoLinks: Partial = {}, +): JourneyController { + return new JourneyController( + service, + storageStub, + books as JourneyBookService, + captureBackfillStub, + photoLinks as JourneyPhotoLinksService, + ); } async function thrownAsync(fn: () => Promise): Promise<{ status: number; body: unknown }> { @@ -179,42 +190,38 @@ describe('JourneyController', () => { ]); }); - it('link-photo: 400 without id (accepts legacy photo_id), 403, success', async () => { + it('link-photo: 400 without id (accepts legacy photo_id), 403, success, and the asking tab is skipped', async () => { expect(await thrownAsync(() => ctl(svc()).linkPhoto(user, '3', {}))).toEqual({ status: 400, body: { error: 'journey_photo_id required' }, }); - const linkPhotoToEntry = vi.fn().mockReturnValue({ id: 5 }); - const c = ctl(svc({ linkPhotoToEntry } as Partial)); - expect(await c.linkPhoto(user, '3', { photo_id: 5 })).toEqual({ id: 5 }); - expect(linkPhotoToEntry).toHaveBeenCalledWith(3, 5, 1); + const link = vi.fn().mockResolvedValue({ id: 5 }); + const c = ctl(svc(), {}, { link }); + expect(await c.linkPhoto(user, '3', { photo_id: 5 }, 'sock-1')).toEqual({ id: 5 }); + expect(link).toHaveBeenCalledWith(3, 5, 1, 'sock-1'); // accepts the canonical journey_photo_id, 403 when the service refuses expect( await thrownAsync(() => - ctl(svc({ linkPhotoToEntry: vi.fn().mockReturnValue(null) } as Partial)).linkPhoto(user, '3', { - journey_photo_id: 9, - }), + ctl(svc(), {}, { link: vi.fn().mockResolvedValue(null) }).linkPhoto(user, '3', { journey_photo_id: 9 }), ), ).toEqual({ status: 403, body: { error: 'Not allowed' } }); }); + it('move photos: hands the source entry, the body and the socket to the service, and answers what moved', async () => { + const moved = { moved: [5], fromEntryId: 3, toEntryId: 4, kept: false }; + const move = vi.fn().mockResolvedValue(moved); + const c = ctl(svc(), {}, { move }); + expect(await c.movePhotos(user, '3', { toEntryId: 4, photoIds: [5] }, 'sock-1')).toEqual(moved); + expect(move).toHaveBeenCalledWith(3, { toEntryId: 4, photoIds: [5] }, 1, 'sock-1'); + }); + it('unlink photo (204) maps 404; delete photo 404 then removes the object', async () => { expect( - await thrownAsync(() => - ctl(svc({ unlinkPhotoFromEntry: vi.fn().mockReturnValue(false) } as Partial)).unlinkPhoto( - user, - '3', - '7', - ), - ), + await thrownAsync(() => ctl(svc(), {}, { unlink: vi.fn().mockResolvedValue(false) }).unlinkPhoto(user, '3', '7')), ).toEqual({ status: 404, body: { error: 'Not found or not allowed' } }); - expect( - await ctl(svc({ unlinkPhotoFromEntry: vi.fn().mockReturnValue(true) } as Partial)).unlinkPhoto( - user, - '3', - '7', - ), - ).toBeUndefined(); + const unlink = vi.fn().mockResolvedValue(true); + expect(await ctl(svc(), {}, { unlink }).unlinkPhoto(user, '3', '7', 'sock-1')).toBeUndefined(); + expect(unlink).toHaveBeenCalledWith(3, 7, 1, 'sock-1'); expect( await thrownAsync(() => ctl(svc({ deletePhoto: vi.fn().mockReturnValue(null) } as Partial)).deletePhoto(user, '7'), @@ -685,18 +692,12 @@ describe('JourneyController', () => { it('PATCH photos: 404 then returns the updated photo', async () => { expect( await thrownAsync(() => - ctl(svc({ updatePhoto: vi.fn().mockReturnValue(null) } as Partial)).updatePhoto(user, '7', { - caption: 'x', - }), + ctl(svc(), {}, { updatePhoto: vi.fn().mockResolvedValue(null) }).updatePhoto(user, '7', { caption: 'x' }), ), ).toEqual({ status: 404, body: { error: 'Photo not found' } }); - expect( - await ctl(svc({ updatePhoto: vi.fn().mockReturnValue({ id: 7 }) } as Partial)).updatePhoto( - user, - '7', - { caption: 'x' }, - ), - ).toEqual({ id: 7 }); + const updatePhoto = vi.fn().mockResolvedValue({ id: 7 }); + expect(await ctl(svc(), {}, { updatePhoto }).updatePhoto(user, '7', { caption: 'x' }, 'sock-1')).toEqual({ id: 7 }); + expect(updatePhoto).toHaveBeenCalledWith(7, 1, { caption: 'x' }, 'sock-1'); }); it('DELETE photo removes the storage object when a path exists', async () => { diff --git a/shared/src/journey/journey.schema.ts b/shared/src/journey/journey.schema.ts index 3a5cea801..72a2f0795 100644 --- a/shared/src/journey/journey.schema.ts +++ b/shared/src/journey/journey.schema.ts @@ -159,6 +159,53 @@ export const journeyLinkPhotoRequestSchema = z.looseObject({ }); export type JourneyLinkPhotoRequest = z.infer; +/** + * POST /api/journeys/entries/:entryId/photos/move: photos of the entry in the + * path moved to another entry of the same journey, in one write. Each must be + * one of the entry's own; `keep_in_source` links them to the other entry + * without taking them off this one. They stay in the gallery either way. + */ +export const journeyPhotosMoveRequestSchema = z.strictObject({ + toEntryId: idSchema, + photoIds: z.array(idSchema).min(1).max(100), + keep_in_source: z.boolean().optional(), +}); +export type JourneyPhotosMoveRequest = z.infer; + +export const journeyPhotosMoveResponseSchema = z.object({ + moved: z.array(idSchema), + fromEntryId: idSchema, + toEntryId: idSchema, + kept: z.boolean(), +}); +export type JourneyPhotosMoveResponse = z.infer; + +/** The MCP tool `move_journey_photos`: the same move, the source entry named in the arguments. */ +export const journeyPhotosMoveToolSchema = journeyPhotosMoveRequestSchema.extend({ + fromEntryId: idSchema, + photoIds: journeyPhotosMoveRequestSchema.shape.photoIds.describe( + 'The journey photo ids (the id of each photo in list_journey_entries) to move, each one of the source entry', + ), + keep_in_source: journeyPhotosMoveRequestSchema.shape.keep_in_source.describe( + 'True links the photos to the other entry as well and leaves them on the source entry', + ), +}); +export type JourneyPhotosMoveTool = z.infer; + +/** The MCP tools `link_journey_photo` and `unlink_journey_photo`: one gallery photo of the entry's journey. */ +export const journeyPhotoLinkToolSchema = z.strictObject({ + entryId: idSchema, + journey_photo_id: idSchema.describe('The journey photo id, from the gallery or an entry in get_journey'), +}); +export type JourneyPhotoLinkTool = z.infer; + +/** The MCP tool `set_journey_photo_caption`: one gallery photo's caption, or null to clear it. */ +export const journeyPhotoCaptionToolSchema = z.strictObject({ + journey_photo_id: idSchema, + caption: z.string().max(500).nullable(), +}); +export type JourneyPhotoCaptionTool = z.infer; + /** Free-form: forwarded to the service as-is. */ export const journeyPhotoUpdateRequestSchema = z.looseObject({}); export type JourneyPhotoUpdateRequest = z.infer;