refactor(places): reclaim place images and collection covers through storage

This commit is contained in:
jubnl
2026-08-17 05:31:53 +02:00
parent 4eca78b53e
commit 965566369e
16 changed files with 216 additions and 183 deletions
@@ -121,8 +121,8 @@ export class CollectionsController {
@Post('places/delete-many')
@HttpCode(200)
deleteMany(@CurrentUser() user: User, @Body() body: CollectionDeleteManyDto, @Headers('x-socket-id') socketId?: string) {
return { deleted: this.collections.deletePlacesMany(user.id, body.ids, socketId) };
async deleteMany(@CurrentUser() user: User, @Body() body: CollectionDeleteManyDto, @Headers('x-socket-id') socketId?: string) {
return { deleted: await this.collections.deletePlacesMany(user.id, body.ids, socketId) };
}
@Post('places/status-many')
@@ -193,8 +193,8 @@ export class CollectionsController {
}
@Delete('places/:pid')
deletePlace(@CurrentUser() user: User, @Param('pid') pid: string, @Headers('x-socket-id') socketId?: string) {
this.collections.deletePlace(user.id, Number(pid), socketId);
async deletePlace(@CurrentUser() user: User, @Param('pid') pid: string, @Headers('x-socket-id') socketId?: string) {
await this.collections.deletePlace(user.id, Number(pid), socketId);
return { success: true };
}
@@ -211,7 +211,7 @@ export class CollectionsMcp {
})
async updateCollectionPlace({ placeId, ...body }: { placeId: number } & CollectionPlaceUpdateRequest, ctx: McpContext) {
const demo = this.denyDemo(ctx.userId); if (demo) return demo;
try { return ok({ place: this.collections.updatePlace(ctx.userId, placeId, body) }); } catch (err) { return fail(err); }
try { return ok({ place: await this.collections.updatePlace(ctx.userId, placeId, body) }); } catch (err) { return fail(err); }
}
@Tool({
@@ -253,7 +253,7 @@ export class CollectionsMcp {
})
async deleteCollectionPlace({ placeId }: { placeId: number }, ctx: McpContext) {
const demo = this.denyDemo(ctx.userId); if (demo) return demo;
try { this.collections.deletePlace(ctx.userId, placeId); return ok({ success: true }); } catch (err) { return fail(err); }
try { await this.collections.deletePlace(ctx.userId, placeId); return ok({ success: true }); } catch (err) { return fail(err); }
}
@Tool({
@@ -1,10 +1,10 @@
import fs from 'fs';
import path from 'path';
import { Injectable } from '@nestjs/common';
import { DatabaseService } from '../database/database.service';
import { PermissionsService } from '../permissions/permissions.service';
import { RealtimeService } from '../realtime/realtime.service';
import { reclaimPlaceImage } from '../places/place-image';
import { StorageService } from '../storage/storage.service';
import {
COORD_DEDUP_TOLERANCE,
externalIdsOf,
@@ -47,17 +47,6 @@ function serializeLinks(links: CollectionLink[] | undefined): string | null {
return links && links.length ? JSON.stringify(links) : null;
}
/**
* Reclaim a replaced cover file. Path-confined to uploads/covers (mirrors
* tripService.deleteOldCover — kept local so this service doesn't pull the
* trips import graph). Collection + trip covers share the same directory.
*/
function deleteOldCollectionCover(coverImage: string | null | undefined): void {
if (!coverImage) return;
const coversDir = path.resolve(__dirname, '../../../uploads/covers');
const resolved = path.resolve(path.join(coversDir, path.basename(coverImage)));
if (resolved.startsWith(coversDir + path.sep) && fs.existsSync(resolved)) fs.unlinkSync(resolved);
}
// ---------------------------------------------------------------------------
// Errors — thrown as plain Errors carrying a status; TrekExceptionFilter maps
@@ -96,8 +85,24 @@ export class CollectionsService {
private readonly permissions: PermissionsService,
private readonly realtime: RealtimeService,
private readonly notifications: NotificationsService,
private readonly storage: StorageService,
) {}
/**
* Reclaim a replaced cover object (mirrors tripService.deleteOldCover — kept
* local so this service doesn't pull the trips import graph). Collection +
* trip covers share the 'covers' category; basename() tolerates the stored
* /uploads/covers/<name> URL form and any external URL the client saved
* (central key validation rejects hostile values; the catch swallows them
* like the old containment guard did).
*/
private async deleteOldCollectionCover(coverImage: string | null | undefined): Promise<void> {
if (!coverImage) return;
await this.storage.delete('covers', path.basename(coverImage)).catch(() => {
/* external URL or already gone */
});
}
// -------------------------------------------------------------------------
// Visibility — a user may see/edit a collection if they own it OR are an
// accepted member. Every read/write goes through assertAccess.
@@ -374,11 +379,11 @@ export class CollectionsService {
}
/** Set (or clear) a list's cover image, reclaiming the previous file. */
setCollectionCover(userId: number, id: number, coverUrl: string | null, socketId?: string): Collection {
async setCollectionCover(userId: number, id: number, coverUrl: string | null, socketId?: string): Promise<Collection> {
this.assertCanEdit(userId, id);
const prev = this.db.get<{ cover_image: string | null }>('SELECT cover_image FROM collections WHERE id = ?', id)?.cover_image ?? null;
this.db.run('UPDATE collections SET cover_image = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', coverUrl, id);
if (prev && prev !== coverUrl) deleteOldCollectionCover(prev);
if (prev && prev !== coverUrl) await this.deleteOldCollectionCover(prev);
this.notifyCollectionUsers(id, socketId, 'collections:updated');
const col = this.getCollectionRow(id);
return { ...col, is_owner: col.owner_id === userId };
@@ -636,7 +641,7 @@ export class CollectionsService {
return { copied, skipped };
}
updatePlace(userId: number, placeId: number, body: CollectionPlaceUpdateRequest, socketId?: string): CollectionPlace {
async updatePlace(userId: number, placeId: number, body: CollectionPlaceUpdateRequest, socketId?: string): Promise<CollectionPlace> {
const currentCollection = this.collectionIdOfPlace(placeId);
this.assertCanEdit(userId, currentCollection);
@@ -688,7 +693,7 @@ export class CollectionsService {
});
if (body.image_url !== undefined && prevImage !== (body.image_url ?? null)) {
reclaimPlaceImage(prevImage);
await reclaimPlaceImage(this.storage, prevImage);
}
this.notifyCollectionUsers(currentCollection, socketId, 'collections:updated');
@@ -724,16 +729,16 @@ export class CollectionsService {
return this.getPlaceById(placeId);
}
deletePlace(userId: number, placeId: number, socketId?: string): void {
async deletePlace(userId: number, placeId: number, socketId?: string): Promise<void> {
const collectionId = this.collectionIdOfPlace(placeId);
this.assertCanDelete(userId, collectionId);
const image = this.db.get<{ image_url: string | null }>('SELECT image_url FROM collection_places WHERE id = ?', placeId)?.image_url ?? null;
this.db.run('DELETE FROM collection_places WHERE id = ?', placeId); // CASCADE drops tags. NO photo-cache reclaim.
reclaimPlaceImage(image);
await reclaimPlaceImage(this.storage, image);
this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
}
deletePlacesMany(userId: number, ids: number[], socketId?: string): number[] {
async deletePlacesMany(userId: number, ids: number[], socketId?: string): Promise<number[]> {
// All-or-nothing since the post-fold quirk pass: every id is resolved and
// permission-checked BEFORE any delete (the relocated legacy interleaved
// checks with deletes, so a mid-list 403/404 left earlier deletes committed),
@@ -753,7 +758,7 @@ export class CollectionsService {
deleted.push(id);
}
});
for (const image of images) reclaimPlaceImage(image);
for (const image of images) await reclaimPlaceImage(this.storage, image);
touched.forEach(cid => this.notifyCollectionUsers(cid, socketId, 'collections:updated'));
return deleted;
}
@@ -862,12 +867,12 @@ export class CollectionsService {
}
/** Set (or clear) a saved place's custom thumbnail, reclaiming the previous upload. */
setPlaceImage(userId: number, placeId: number, imageUrl: string | null, socketId?: string): CollectionPlace {
async setPlaceImage(userId: number, placeId: number, imageUrl: string | null, socketId?: string): Promise<CollectionPlace> {
const collectionId = this.collectionIdOfPlace(placeId);
this.assertCanEdit(userId, collectionId);
const prev = this.db.get<{ image_url: string | null }>('SELECT image_url FROM collection_places WHERE id = ?', placeId)?.image_url ?? null;
this.db.run('UPDATE collection_places SET image_url = ?, updated_at = CURRENT_TIMESTAMP WHERE id = ?', imageUrl, placeId);
if (prev !== imageUrl) reclaimPlaceImage(prev);
if (prev !== imageUrl) await reclaimPlaceImage(this.storage, prev);
this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
return this.getPlaceById(placeId);
}
+11 -14
View File
@@ -1,11 +1,7 @@
import fs from 'fs';
import path from 'path';
import path from 'node:path';
import { db } from '../../db/database';
import type { StorageService } from '../storage/storage.service';
// Custom place images (the user-uploaded thumbnails from #1136) live in their own
// uploads subdir, served statically like covers. Storing the full /uploads/places/…
// path in image_url lets every existing thumbnail renderer show it unchanged.
export const PLACE_IMAGES_DIR = path.resolve(__dirname, '../../../uploads/places');
const URL_PREFIX = '/uploads/places/';
export function placeImageUrl(filename: string): string {
@@ -17,20 +13,21 @@ export function isUploadedPlaceImage(url: string | null | undefined): url is str
}
/**
* Delete a custom place-image file once nothing references it any more. A trip
* Delete a custom place-image object once nothing references it any more. A trip
* place and a collection saved-place can share the same uploaded file — save-to-
* collection and copy-to-trip copy image_url by reference — so we ref-count across
* both tables before unlinking. The path is confined to PLACE_IMAGES_DIR via
* basename, mirroring tripService.deleteOldCover. Best-effort: never throws.
* both tables before deleting. basename() keeps the storage name confined to the
* 'places' category, mirroring tripService.deleteOldCover. Best-effort: never
* throws (central key validation rejects a hostile stored value; the catch
* swallows it exactly like the old unlink guard).
*/
export function reclaimPlaceImage(url: string | null | undefined): void {
export async function reclaimPlaceImage(storage: StorageService, url: string | null | undefined): Promise<void> {
if (!isUploadedPlaceImage(url)) return;
const referenced =
db.prepare('SELECT 1 FROM places WHERE image_url = ? LIMIT 1').get(url) ||
db.prepare('SELECT 1 FROM collection_places WHERE image_url = ? LIMIT 1').get(url);
if (referenced) return;
try {
const resolved = path.resolve(path.join(PLACE_IMAGES_DIR, path.basename(url)));
if (resolved.startsWith(PLACE_IMAGES_DIR + path.sep) && fs.existsSync(resolved)) fs.unlinkSync(resolved);
} catch { /* best-effort */ }
await storage.delete('places', path.basename(url)).catch(() => {
/* best-effort */
});
}
+5 -5
View File
@@ -305,7 +305,7 @@ export class PlacesController {
@Post('bulk-update')
@HttpCode(200)
bulkUpdate(
async bulkUpdate(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: PlaceBulkUpdateDto,
@@ -322,7 +322,7 @@ export class PlacesController {
if (!('category_id' in body)) {
throw new HttpException({ error: 'Provide at least one field to update' }, 400);
}
const updated = this.places.updateMany(tripId, ids, { category_id: body.category_id as number | null });
const updated = await this.places.updateMany(tripId, ids, { category_id: body.category_id as number | null });
for (const place of updated) {
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
this.places.onUpdated(place.id);
@@ -365,7 +365,7 @@ export class PlacesController {
await this.storage.put('places', file.filename, { tmpPath: file.path });
// Reuse the existing image_url slot (the top-precedence thumbnail source); the
// update path reclaims any previously uploaded file it replaces.
const result = this.places.update(tripId, id, { image_url: placeImageUrl(file.filename) } as never);
const result = await this.places.update(tripId, id, { image_url: placeImageUrl(file.filename) } as never);
if (!result || isUpdateConflict(result)) {
throw new HttpException({ error: 'Place not found' }, 404);
}
@@ -422,7 +422,7 @@ export class PlacesController {
}
@Put(':id')
update(
async update(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@@ -434,7 +434,7 @@ export class PlacesController {
validateLengths(body);
validateRouteColor(body);
this.requireEdit(trip, user);
const result = this.places.update(tripId, id, body as never, ifMatch);
const result = await this.places.update(tripId, id, body as never, ifMatch);
if (!result) {
throw new HttpException({ error: 'Place not found' }, 404);
}
+2 -2
View File
@@ -181,7 +181,7 @@ export class PlacesMcp {
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
if (!this.guards.hasTripPermission('place_edit', tripId, ctx.userId)) return permissionDenied();
const place = this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, transport_mode, osm_id, google_place_id, google_ftid });
const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, transport_mode, osm_id, google_place_id, google_ftid });
if (!place) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
this.guards.safeBroadcast(tripId, 'place:updated', { place });
return ok({ place });
@@ -391,7 +391,7 @@ export class PlacesMcp {
return { content: [{ type: 'text' as const, text: 'Provide at least one field to update.' }], isError: true };
}
const updated = this.places.updateMany(String(tripId), placeIds, fields);
const updated = await this.places.updateMany(String(tripId), placeIds, fields);
for (const place of updated) this.guards.safeBroadcast(tripId, 'place:updated', { place });
return ok({ count: updated.length, updatedIds: updated.map(p => p.id), skipped: placeIds.length - updated.length });
}
+39 -15
View File
@@ -26,6 +26,7 @@ import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.servic
import { type UpdateConflict, isUpdateConflict } from '../common/conflictResult';
import { reclaimPlaceImage } from './place-image';
import { JourneyDomainService } from '../journey/journey-domain.service';
import { StorageService } from '../storage/storage.service';
import {
COORD_DEDUP_TOLERANCE,
ENRICH_CONCURRENCY,
@@ -112,6 +113,7 @@ export class PlacesService {
private readonly unsplash: UnsplashService,
private readonly photoCache: PlacePhotoCacheService,
private readonly journey: JourneyDomainService,
private readonly storage: StorageService,
) {}
verifyTripAccess(tripId: string, userId: number) {
@@ -245,20 +247,36 @@ export class PlacesService {
// Update place
// -------------------------------------------------------------------------
update(
async update(
tripId: string,
placeId: string,
body: PlaceUpdateInput,
ifMatch?: string,
): PlaceWithTags | UpdateConflict | null {
): Promise<PlaceWithTags | UpdateConflict | null> {
const { result, reclaim } = this.applyUpdate(tripId, placeId, body, ifMatch);
if (reclaim !== undefined) await reclaimPlaceImage(this.storage, reclaim);
return result;
}
/**
* The synchronous DB half of update(). Split out so updateMany() can run it
* inside a better-sqlite3 transaction (which cannot await) and settle the
* storage reclaims after the transaction commits.
*/
private applyUpdate(
tripId: string,
placeId: string,
body: PlaceUpdateInput,
ifMatch?: string,
): { result: PlaceWithTags | UpdateConflict | null; reclaim?: string | null } {
const existingPlace = this.dbs.get<Place>('SELECT * FROM places WHERE id = ? AND trip_id = ?', placeId, tripId);
if (!existingPlace) return null;
if (!existingPlace) return { result: null };
// Optimistic concurrency (#1135): when the caller sent the version it based its
// edit on and the row has moved on since, reject instead of clobbering. Absent
// token => unconditional update (back-compat — old clients keep last-write-wins).
if (ifMatch !== undefined && existingPlace.updated_at != null && String(existingPlace.updated_at) !== ifMatch) {
return { conflict: true, server: this.dbs.getPlaceWithTags(placeId) };
return { result: { conflict: true, server: this.dbs.getPlaceWithTags(placeId) } };
}
const {
@@ -331,12 +349,13 @@ export class PlacesService {
}
// A custom uploaded thumbnail (#1136) that was just replaced or cleared leaves
// an orphan file behind — reclaim it once nothing references it any more.
if (image_url !== undefined && image_url !== existingPlace.image_url) {
reclaimPlaceImage(existingPlace.image_url);
}
// an orphan file behind — reclaim it (in the caller, once any enclosing
// transaction committed) if nothing references it any more.
const reclaim = image_url !== undefined && image_url !== existingPlace.image_url
? existingPlace.image_url
: undefined;
return this.dbs.getPlaceWithTags(placeId);
return { result: this.dbs.getPlaceWithTags(placeId), reclaim };
}
// -------------------------------------------------------------------------
@@ -370,7 +389,7 @@ export class PlacesService {
this.dbs.run('DELETE FROM places WHERE id = ?', placeId);
});
await reclaimPhotoCache(this.photoCache, place.google_place_id, place.image_url);
reclaimPlaceImage(place.image_url);
await reclaimPlaceImage(this.storage, place.image_url);
return true;
}
@@ -394,7 +413,7 @@ export class PlacesService {
// Reclaim after the transaction commits so isReferenced() sees the final place set.
for (const row of reclaimable) {
await reclaimPhotoCache(this.photoCache, row.google_place_id, row.image_url);
reclaimPlaceImage(row.image_url);
await reclaimPlaceImage(this.storage, row.image_url);
}
return deleted;
}
@@ -425,17 +444,22 @@ export class PlacesService {
* fields change and everything else is preserved. IDs that don't belong to the
* trip are skipped. Returns the updated places.
*/
updateMany(tripId: string, ids: number[], body: PlaceUpdateInput): PlaceWithTags[] {
async updateMany(tripId: string, ids: number[], body: PlaceUpdateInput): Promise<PlaceWithTags[]> {
if (ids.length === 0) return [];
const updated: PlaceWithTags[] = [];
const reclaims: (string | null)[] = [];
this.dbs.transaction(() => {
for (const id of ids) {
// Bulk update sends no If-Match, so update() never returns a conflict
// here; the guard keeps the types honest.
const place = this.update(tripId, String(id), body);
// Bulk update sends no If-Match, so applyUpdate() never returns a
// conflict here; the guard keeps the types honest.
const { result: place, reclaim } = this.applyUpdate(tripId, String(id), body);
if (place && !isUpdateConflict(place)) updated.push(place);
if (reclaim !== undefined) reclaims.push(reclaim);
}
});
// Settle reclaims after the transaction commits, so the refcount sees the
// final image_url state.
for (const reclaim of reclaims) await reclaimPlaceImage(this.storage, reclaim);
return updated;
}
+3 -1
View File
@@ -114,6 +114,7 @@ export function createMcpTestRegistry(): McpRegistry {
// Exactly one instance, shared by maps, places and share: its stampede guard
// and its on-disk set only work if all three readers see the same maps.
const placePhotoCache = new PlacePhotoCacheService(dbService, makeStorageFixture('photos/google/').storage);
const generalStorage = makeStorageFixture('').storage;
const mapsService = new MapsService(dbService, placePhotoCache);
const journeyDomain = new JourneyDomainService(dbService, realtimeService, new TrekPhotosRepository(dbService));
// The last three were previously omitted, which left them `undefined` at
@@ -125,6 +126,7 @@ export function createMcpTestRegistry(): McpRegistry {
new UnsplashService(dbService, new RuntimeEnvService()),
placePhotoCache,
journeyDomain,
generalStorage,
);
const reservationsService = new ReservationsService(dbService, permissionsService, budgetService, realtimeService, notificationsStub(), new ReservationsReadRepository(dbService));
const accommodationsService = new AccommodationsService(dbService, permissionsService, realtimeService);
@@ -175,7 +177,7 @@ export function createMcpTestRegistry(): McpRegistry {
new ShareMcp(new ShareService(dbService, new SettingsService(dbService), permissionsService, queryHelpersService, placePhotoCache), authService, guards),
new MapsMcp(mapsService),
new PlacesMcp(placesService, mapsService, dbService, authService, journeyDomain, assignmentsService, guards),
new CollectionsMcp(new CollectionsService(dbService, permissionsService, realtimeService, notificationsStub()), dbService, authService, addonsService),
new CollectionsMcp(new CollectionsService(dbService, permissionsService, realtimeService, notificationsStub(), generalStorage), dbService, authService, addonsService),
new TransitMcp(new TransitService(), daysService, reservationsService, dbService, authService, guards),
new AtlasMcp(new AtlasService(dbService), addonsService, authService),
new JourneyMcp(journeyDomain, new JourneyShareService(dbService, journeyDomain), addonsService, authService),
+3 -2
View File
@@ -97,10 +97,11 @@ export function createPluginRpcHostFactory(dbs: DatabaseService): PluginRpcHostF
const vacay = new VacayService(dbs, realtime, notificationsStub());
const days = new DaysService(dbs, permissions, realtime, queryHelpers);
const photoCache = new PlacePhotoCacheService(dbs, makeStorageFixture('photos/google/').storage);
const generalStorage = makeStorageFixture('').storage;
const unsplash = new UnsplashService(dbs, new RuntimeEnvService());
const journey = new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs));
const places = new PlacesService(dbs, permissions, realtime, new MapsService(dbs, photoCache), queryHelpers, unsplash, photoCache, journey);
const collections = new CollectionsService(dbs, permissions, realtime, notificationsStub());
const places = new PlacesService(dbs, permissions, realtime, new MapsService(dbs, photoCache), queryHelpers, unsplash, photoCache, journey, generalStorage);
const collections = new CollectionsService(dbs, permissions, realtime, notificationsStub(), generalStorage);
const atlas = new AtlasService(dbs);
const dayNotes = new DayNotesService(dbs, permissions, realtime);
const assignments = new AssignmentsService(dbs, permissions, realtime, queryHelpers, journey);
@@ -92,7 +92,7 @@ describe('CollectionsController', () => {
});
describe('places', () => {
it('savePlace / updatePlace / setStatus / deletePlace forward the socket id', () => {
it('savePlace / updatePlace / setStatus / deletePlace forward the socket id', async () => {
const svc = makeService();
const c = new CollectionsController(svc, new RuntimeEnvService(), storageStub);
c.savePlace(user, { collection_id: 3, name: 'A' } as never, 'sid');
@@ -101,7 +101,7 @@ describe('CollectionsController', () => {
expect(svc.updatePlace).toHaveBeenCalledWith(1, 9, { name: 'B' }, 'sid');
c.setStatus(user, '9', { status: 'want' } as never, 'sid');
expect(svc.setStatus).toHaveBeenCalledWith(1, 9, 'want', 'sid');
expect(c.deletePlace(user, '9', 'sid')).toEqual({ success: true });
expect(await c.deletePlace(user, '9', 'sid')).toEqual({ success: true });
expect(svc.deletePlace).toHaveBeenCalledWith(1, 9, 'sid');
c.saveFromTrip(user, { collection_id: 3, source_trip_id: 5, source_place_id: 8 } as never, 'sid');
expect(svc.saveFromTripPlace).toHaveBeenCalledWith(1, 3, 5, 8, undefined, 'sid');
@@ -111,9 +111,9 @@ describe('CollectionsController', () => {
// The legacy 'ids must be an array of numbers' 400 is gone:
// collectionDeleteManyRequestSchema types the array, so the pipe rejects a
// bad payload before the handler runs.
it('deleteMany deletes a valid list', () => {
it('deleteMany deletes a valid list', async () => {
const svc = makeService();
expect(new CollectionsController(svc, new RuntimeEnvService(), storageStub).deleteMany(user, { ids: [1, 2] } as never, 'sid')).toEqual({ deleted: [1, 2] });
expect(await new CollectionsController(svc, new RuntimeEnvService(), storageStub).deleteMany(user, { ids: [1, 2] } as never, 'sid')).toEqual({ deleted: [1, 2] });
expect(svc.deletePlacesMany).toHaveBeenCalledWith(1, [1, 2], 'sid');
});
});
@@ -54,10 +54,10 @@ import { RealtimeService } from '../../../src/nest/realtime/realtime.service';
import { CollectionsService } from '../../../src/nest/collections/collections.service';
import { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service';
import { makeStorageFixture } from '../../helpers/storage-fixture';
import { PLACE_IMAGES_DIR } from '../../../src/nest/places/place-image';
import { notificationsStub } from '../../helpers/notifications';
const svc = new CollectionsService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb)), new RealtimeService(), notificationsStub(notifSend));
const storageFx = makeStorageFixture('');
const svc = new CollectionsService(new DatabaseService(testDb), new PermissionsService(new DatabaseService(testDb)), new RealtimeService(), notificationsStub(notifSend), storageFx.storage);
// The real cache: these cases assert what removeIfUnreferenced actually does
// about collection_places (#1081), so a stub would assert nothing.
const photoCache = new PlacePhotoCacheService(new DatabaseService(testDb), makeStorageFixture('photos/google/').storage);
@@ -222,7 +222,7 @@ describe('status + updatePlace move', () => {
expect(svc.setStatus(u.id, p.id, 'visited').status).toBe('visited');
});
it('COLLECTIONS-SVC-017: updatePlace moves to another list (asserts access on target, resets owner_id)', () => {
it('COLLECTIONS-SVC-017: updatePlace moves to another list (asserts access on target, resets owner_id)', async () => {
const owner = createUser(testDb).user;
const a = svc.createCollection(owner.id, { name: 'A' });
const targetOwner = createUser(testDb).user;
@@ -231,38 +231,38 @@ describe('status + updatePlace move', () => {
testDb.prepare("INSERT INTO collection_members (collection_id, user_id, status) VALUES (?, ?, 'accepted')").run(b.id, owner.id);
const p = svc.savePlace(owner.id, { collection_id: a.id, name: 'Movable' }).place!;
const moved = svc.updatePlace(owner.id, p.id, { collection_id: b.id });
const moved = await svc.updatePlace(owner.id, p.id, { collection_id: b.id });
expect(moved.collection_id).toBe(b.id);
const row = testDb.prepare('SELECT owner_id FROM collection_places WHERE id = ?').get(p.id) as { owner_id: number };
expect(row.owner_id).toBe(targetOwner.id); // reset to the target collection's owner
});
it('COLLECTIONS-SVC-018: updatePlace move to an inaccessible target is rejected', () => {
it('COLLECTIONS-SVC-018: updatePlace move to an inaccessible target is rejected', async () => {
const owner = createUser(testDb).user;
const a = svc.createCollection(owner.id, { name: 'A' });
const stranger = createUser(testDb).user;
const b = svc.createCollection(stranger.id, { name: 'B' });
const p = svc.savePlace(owner.id, { collection_id: a.id, name: 'X' }).place!;
expect(() => svc.updatePlace(owner.id, p.id, { collection_id: b.id })).toThrow();
await expect(svc.updatePlace(owner.id, p.id, { collection_id: b.id })).rejects.toThrow();
});
// #1870: the address column was missing from the UPDATE set, so a typo or a
// moved restaurant could only be fixed by deleting and re-adding the place.
it('COLLECTIONS-SVC-019: updatePlace corrects the address and clears it with null', () => {
it('COLLECTIONS-SVC-019: updatePlace corrects the address and clears it with null', async () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'Rome' });
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'Trattoria', address: 'Via Vechia 1' }).place!;
expect(svc.updatePlace(u.id, p.id, { address: 'Via Nuova 1' }).address).toBe('Via Nuova 1');
expect(svc.updatePlace(u.id, p.id, { address: null }).address).toBeNull();
expect((await svc.updatePlace(u.id, p.id, { address: 'Via Nuova 1' })).address).toBe('Via Nuova 1');
expect((await svc.updatePlace(u.id, p.id, { address: null })).address).toBeNull();
});
it('COLLECTIONS-SVC-019b: an update without an address leaves the stored one alone', () => {
it('COLLECTIONS-SVC-019b: an update without an address leaves the stored one alone', async () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'Rome' });
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'Trattoria', address: 'Via Vechia 1' }).place!;
expect(svc.updatePlace(u.id, p.id, { name: 'Trattoria da Enzo' }).address).toBe('Via Vechia 1');
expect((await svc.updatePlace(u.id, p.id, { name: 'Trattoria da Enzo' })).address).toBe('Via Vechia 1');
});
});
@@ -329,14 +329,14 @@ describe('copyToTrip', () => {
// ── delete + delete-many ─────────────────────────────────────────────────────
describe('delete places', () => {
it('COLLECTIONS-SVC-024: deletePlace + deletePlacesMany assert access', () => {
it('COLLECTIONS-SVC-024: deletePlace + deletePlacesMany assert access', async () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'D' });
const p1 = svc.savePlace(u.id, { collection_id: col.id, name: 'A' }).place!;
const p2 = svc.savePlace(u.id, { collection_id: col.id, name: 'B' }).place!;
svc.deletePlace(u.id, p1.id);
await svc.deletePlace(u.id, p1.id);
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_places WHERE collection_id = ?').get(col.id)).toEqual({ n: 1 });
expect(svc.deletePlacesMany(u.id, [p2.id])).toEqual([p2.id]);
expect(await svc.deletePlacesMany(u.id, [p2.id])).toEqual([p2.id]);
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_places WHERE collection_id = ?').get(col.id)).toEqual({ n: 0 });
});
});
@@ -553,14 +553,14 @@ describe('collection labels', () => {
expect(svc.createLabel(editor.id, col.id, 'Museums').id).toBeGreaterThan(0);
});
it('COLLECTIONS-SVC-052: updatePlace label_ids sets labels; a label from another list is ignored', () => {
it('COLLECTIONS-SVC-052: updatePlace label_ids sets labels; a label from another list is ignored', async () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'DE' });
const other = svc.createCollection(u.id, { name: 'Other' });
const l1 = svc.createLabel(u.id, col.id, 'Berlin');
const foreign = svc.createLabel(u.id, other.id, 'Paris');
const place = svc.savePlace(u.id, { collection_id: col.id, name: 'Gate' }).place!;
svc.updatePlace(u.id, place.id, { label_ids: [l1.id, foreign.id] });
await svc.updatePlace(u.id, place.id, { label_ids: [l1.id, foreign.id] });
const stored = svc.getCollection(u.id, col.id).places.find(p => p.id === place.id)!;
expect(stored.label_ids).toEqual([l1.id]);
});
@@ -581,27 +581,27 @@ describe('collection labels', () => {
expect(after.find(p => p.id === p2.id)!.label_ids).toEqual([l.id]);
});
it('COLLECTIONS-SVC-054: deleteLabel removes it and cascades its place assignments', () => {
it('COLLECTIONS-SVC-054: deleteLabel removes it and cascades its place assignments', async () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'DE' });
const l = svc.createLabel(u.id, col.id, 'Berlin');
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'Gate' }).place!;
svc.updatePlace(u.id, p.id, { label_ids: [l.id] });
await svc.updatePlace(u.id, p.id, { label_ids: [l.id] });
svc.deleteLabel(u.id, l.id);
expect(svc.getCollection(u.id, col.id).collection.labels).toHaveLength(0);
expect(svc.getCollection(u.id, col.id).places.find(x => x.id === p.id)!.label_ids).toEqual([]);
});
it('COLLECTIONS-SVC-055: moving a place to another list drops its labels', () => {
it('COLLECTIONS-SVC-055: moving a place to another list drops its labels', async () => {
const u = createUser(testDb).user;
const a = svc.createCollection(u.id, { name: 'A' });
const b = svc.createCollection(u.id, { name: 'B' });
const l = svc.createLabel(u.id, a.id, 'Berlin');
const p = svc.savePlace(u.id, { collection_id: a.id, name: 'Gate' }).place!;
svc.updatePlace(u.id, p.id, { label_ids: [l.id] });
await svc.updatePlace(u.id, p.id, { label_ids: [l.id] });
svc.updatePlace(u.id, p.id, { collection_id: b.id });
await svc.updatePlace(u.id, p.id, { collection_id: b.id });
expect(svc.getCollection(u.id, b.id).places.find(x => x.id === p.id)!.label_ids).toEqual([]);
});
});
@@ -610,41 +610,40 @@ describe('collection labels', () => {
describe('custom saved-place image', () => {
function writePlaceImage(name: string): string {
fs.mkdirSync(PLACE_IMAGES_DIR, { recursive: true });
const filePath = path.join(PLACE_IMAGES_DIR, name);
const filePath = path.join(storageFx.root, name);
fs.writeFileSync(filePath, 'jpeg-bytes');
return filePath;
}
it('COLLECTIONS-SVC-060: updatePlace sets image_url', () => {
it('COLLECTIONS-SVC-060: updatePlace sets image_url', async () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'Photos' });
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'Pic' }).place!;
const updated = svc.updatePlace(u.id, p.id, { image_url: '/uploads/places/col-set.jpg' });
const updated = await svc.updatePlace(u.id, p.id, { image_url: '/uploads/places/col-set.jpg' });
expect(updated.image_url).toBe('/uploads/places/col-set.jpg');
});
it('COLLECTIONS-SVC-061: setPlaceImage stores the url and reclaims a replaced upload', () => {
it('COLLECTIONS-SVC-061: setPlaceImage stores the url and reclaims a replaced upload', async () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'Photos' });
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'Pic' }).place!;
const fileA = writePlaceImage('col-replace-a.jpg');
svc.setPlaceImage(u.id, p.id, '/uploads/places/col-replace-a.jpg');
await svc.setPlaceImage(u.id, p.id, '/uploads/places/col-replace-a.jpg');
expect(fs.existsSync(fileA)).toBe(true);
const res = svc.setPlaceImage(u.id, p.id, '/uploads/places/col-replace-b.jpg');
const res = await svc.setPlaceImage(u.id, p.id, '/uploads/places/col-replace-b.jpg');
expect(res.image_url).toBe('/uploads/places/col-replace-b.jpg');
expect(fs.existsSync(fileA)).toBe(false);
});
it('COLLECTIONS-SVC-062: deletePlace reclaims the uploaded image when unreferenced', () => {
it('COLLECTIONS-SVC-062: deletePlace reclaims the uploaded image when unreferenced', async () => {
const u = createUser(testDb).user;
const col = svc.createCollection(u.id, { name: 'Photos' });
const p = svc.savePlace(u.id, { collection_id: col.id, name: 'Pic', image_url: '/uploads/places/col-delete.jpg' }).place!;
const fileA = writePlaceImage('col-delete.jpg');
expect(fs.existsSync(fileA)).toBe(true);
svc.deletePlace(u.id, p.id);
await svc.deletePlace(u.id, p.id);
expect(fs.existsSync(fileA)).toBe(false);
});
});
@@ -820,7 +819,7 @@ describe('membership lookups', () => {
// ── Post-fold quirk fixes (the trailing fix(server) commit) ─────────────────
describe('atomic bulk writes (post-fold quirk fixes)', () => {
it('COLLECTIONS-SVC-090: deletePlacesMany is all-or-nothing — a mid-list 403 deletes nothing', () => {
it('COLLECTIONS-SVC-090: deletePlacesMany is all-or-nothing — a mid-list 403 deletes nothing', async () => {
const u = createUser(testDb).user;
const otherOwner = createUser(testDb).user;
const mine = svc.createCollection(u.id, { name: 'Mine' });
@@ -832,7 +831,7 @@ describe('atomic bulk writes (post-fold quirk fixes)', () => {
// The relocated legacy interleaved checks with deletes, so p1 was gone by
// the time p2's 403 fired. Now every id is checked first: nothing deleted.
expect(() => svc.deletePlacesMany(u.id, [p1.id, p2.id])).toThrow('Only an admin can delete places from this list');
await expect(svc.deletePlacesMany(u.id, [p1.id, p2.id])).rejects.toThrow('Only an admin can delete places from this list');
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_places WHERE id = ?').get(p1.id)).toEqual({ n: 1 });
expect(testDb.prepare('SELECT COUNT(*) n FROM collection_places WHERE id = ?').get(p2.id)).toEqual({ n: 1 });
});
@@ -925,7 +924,7 @@ describe('bulk status', () => {
expect(statuses.map(s => s.status)).toEqual(['visited', 'visited', 'idea']);
});
it('COLLECTIONS-SVC-096: a place renamed in the list is still found by its source link', () => {
it('COLLECTIONS-SVC-096: a place renamed in the list is still found by its source link', async () => {
const u = createUser(testDb).user;
createCategory(testDb);
const trip = createTrip(testDb, u.id);
@@ -933,7 +932,7 @@ describe('bulk status', () => {
const col = svc.createCollection(u.id, { name: 'Rome' });
const saved = svc.saveFromTripPlace(u.id, col.id, trip.id, place.id).place!;
// Renamed on both sides, and moved far enough that coordinates cannot match.
svc.updatePlace(u.id, saved.id, { name: 'Dinner spot', lat: 45, lng: 9 });
await svc.updatePlace(u.id, saved.id, { name: 'Dinner spot', lat: 45, lng: 9 });
testDb.prepare('UPDATE places SET name = ? WHERE id = ?').run('Enzo', place.id);
expect(svc.setStatusFromTrip(u.id, trip.id, [place.id], 'visited')).toEqual({ updated: 1, places: 1 });
@@ -185,28 +185,28 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
// The legacy 'ids must be an array of numbers' 400 is gone:
// placeBulkDeleteRequestSchema types the array, so the pipe rejects a bad
// element before the handler runs.
it('returns empty for an empty list without touching the service', () => {
it('returns empty for an empty list without touching the service', async () => {
const removeMany = vi.fn();
expect(new PlacesController(svc({ removeMany } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [] })).toEqual({ deleted: [], count: 0 });
expect(await new PlacesController(svc({ removeMany } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [] })).toEqual({ deleted: [], count: 0 });
expect(removeMany).not.toHaveBeenCalled();
});
it('deletes, fires hooks + broadcasts per deleted id', () => {
it('deletes, fires hooks + broadcasts per deleted id', async () => {
const removeMany = vi.fn().mockReturnValue([1, 2]); const onDeleted = vi.fn(); const broadcast = vi.fn();
const scopedIds = vi.fn().mockReturnValue([1, 2]);
const s = svc({ removeMany, onDeleted, broadcast, scopedIds } as Partial<PlacesService>);
expect(new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1, 2] }, 'sock')).toEqual({ deleted: [1, 2], count: 2 });
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1, 2] }, 'sock')).toEqual({ deleted: [1, 2], count: 2 });
expect(onDeleted).toHaveBeenCalledTimes(2);
expect(broadcast).toHaveBeenCalledTimes(2);
});
// #1745: the hook keys on the place id alone, so an id from another trip
// would detach that trip's journey entries even though removeMany skips it.
it('fires the journey hook only for ids that belong to the trip, ahead of the delete', () => {
it('fires the journey hook only for ids that belong to the trip, ahead of the delete', async () => {
const removeMany = vi.fn().mockReturnValue([1]);
const scopedIds = vi.fn().mockReturnValue([1]);
const onDeleted = vi.fn();
const s = svc({ removeMany, scopedIds, onDeleted, broadcast: vi.fn() } as Partial<PlacesService>);
new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1, 99] });
await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1, 99] });
expect(scopedIds).toHaveBeenCalledWith('5', [1, 99]);
expect(onDeleted).toHaveBeenCalledTimes(1);
expect(onDeleted).toHaveBeenCalledWith(1);
@@ -214,12 +214,12 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
});
// #1298: the link is gone once the place is, so the ids have to be read first.
it('announces the expenses the deleted places took with them', () => {
it('announces the expenses the deleted places took with them', async () => {
const removeMany = vi.fn().mockReturnValue([1, 2]);
const linkedExpenseIds = vi.fn().mockReturnValue([77]);
const broadcast = vi.fn();
const s = svc({ removeMany, linkedExpenseIds, broadcast } as Partial<PlacesService>);
new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1, 2] }, 'sock');
await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkDelete(user, '5', { ids: [1, 2] }, 'sock');
expect(linkedExpenseIds).toHaveBeenCalledWith('5', [1, 2]);
expect(linkedExpenseIds.mock.invocationCallOrder[0]).toBeLessThan(removeMany.mock.invocationCallOrder[0]);
@@ -228,33 +228,33 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
});
describe('POST /bulk-update', () => {
it('404 when trip not accessible, 403 without place_edit (before any write)', () => {
expect(thrown(() => new PlacesController(svc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }), new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1], category_id: 3 }))).toEqual({ status: 404, body: { error: 'Trip not found' } });
expect(thrown(() => new PlacesController(svc({ canEdit: vi.fn().mockReturnValue(false) }), new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1], category_id: 3 }))).toEqual({ status: 403, body: { error: 'No permission' } });
it('404 when trip not accessible, 403 without place_edit (before any write)', async () => {
expect(await thrownAsync(() => new PlacesController(svc({ verifyTripAccess: vi.fn().mockReturnValue(undefined) }), new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1], category_id: 3 }))).toEqual({ status: 404, body: { error: 'Trip not found' } });
expect(await thrownAsync(() => new PlacesController(svc({ canEdit: vi.fn().mockReturnValue(false) }), new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1], category_id: 3 }))).toEqual({ status: 403, body: { error: 'No permission' } });
});
// Same as bulk-delete: placeBulkUpdateRequestSchema types `ids`, so the
// pipe owns that 400 now. `.min(1)` was deliberately left off the schema so
// the empty-list short-circuit below stays reachable.
it('400 when no patch field is present', () => {
expect(thrown(() => new PlacesController(svc(), new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1] }))).toEqual({ status: 400, body: { error: 'Provide at least one field to update' } });
it('400 when no patch field is present', async () => {
expect(await thrownAsync(() => new PlacesController(svc(), new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1] }))).toEqual({ status: 400, body: { error: 'Provide at least one field to update' } });
});
it('returns empty for an empty list without touching the service', () => {
it('returns empty for an empty list without touching the service', async () => {
const updateMany = vi.fn();
expect(new PlacesController(svc({ updateMany } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [] })).toEqual({ updated: [], count: 0 });
expect(await new PlacesController(svc({ updateMany } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [] })).toEqual({ updated: [], count: 0 });
expect(updateMany).not.toHaveBeenCalled();
});
it('updates, fires hooks + broadcasts per updated place', () => {
it('updates, fires hooks + broadcasts per updated place', async () => {
const updateMany = vi.fn().mockReturnValue([{ id: 1 }, { id: 2 }]); const onUpdated = vi.fn(); const broadcast = vi.fn();
const s = svc({ updateMany, onUpdated, broadcast } as Partial<PlacesService>);
expect(new PlacesController(s, new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1, 2], category_id: 3 }, 'sock')).toEqual({ updated: [1, 2], count: 2 });
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1, 2], category_id: 3 }, 'sock')).toEqual({ updated: [1, 2], count: 2 });
expect(updateMany).toHaveBeenCalledWith('5', [1, 2], { category_id: 3 });
expect(onUpdated).toHaveBeenCalledTimes(2);
expect(broadcast).toHaveBeenCalledWith('5', 'place:updated', { place: { id: 1 } }, 'sock');
});
it('passes category_id: null through to clear the category', () => {
it('passes category_id: null through to clear the category', async () => {
const updateMany = vi.fn().mockReturnValue([{ id: 1 }]);
const s = svc({ updateMany } as Partial<PlacesService>);
expect(new PlacesController(s, new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1], category_id: null })).toEqual({ updated: [1], count: 1 });
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).bulkUpdate(user, '5', { ids: [1], category_id: null })).toEqual({ updated: [1], count: 1 });
expect(updateMany).toHaveBeenCalledWith('5', [1], { category_id: null });
});
});
@@ -265,50 +265,50 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
expect(new PlacesController(s, new RuntimeEnvService(), storageStub).get(user, '5', '9')).toEqual({ place: { id: 9 } });
});
it('PUT /:id 404 when missing, else updates + hooks', () => {
expect(thrown(() => new PlacesController(svc({ update: vi.fn().mockReturnValue(null) } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).update(user, '5', '9', { name: 'X' }))).toEqual({ status: 404, body: { error: 'Place not found' } });
it('PUT /:id 404 when missing, else updates + hooks', async () => {
expect(await thrownAsync(() => new PlacesController(svc({ update: vi.fn().mockReturnValue(null) } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).update(user, '5', '9', { name: 'X' }))).toEqual({ status: 404, body: { error: 'Place not found' } });
const update = vi.fn().mockReturnValue({ id: 9 }); const onUpdated = vi.fn(); const broadcast = vi.fn();
const s = svc({ update, onUpdated, broadcast } as Partial<PlacesService>);
expect(new PlacesController(s, new RuntimeEnvService(), storageStub).update(user, '5', '9', { name: 'X' }, 'sock')).toEqual({ place: { id: 9 } });
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).update(user, '5', '9', { name: 'X' }, 'sock')).toEqual({ place: { id: 9 } });
expect(onUpdated).toHaveBeenCalledWith(9);
});
describe('route_color (#776)', () => {
it('400s on anything that is not a hex colour, before the permission check', () => {
it('400s on anything that is not a hex colour, before the permission check', async () => {
const canEdit = vi.fn().mockReturnValue(false); // would 403 if it got that far
const err = { status: 400, body: { error: 'route_color must be a hex colour like #4f46e5' } };
expect(thrown(() => new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: 'red' }))).toEqual(err);
expect(thrown(() => new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: '#12345' }))).toEqual(err);
expect(thrown(() => new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: 123 }))).toEqual(err);
expect(await thrownAsync(() => new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: 'red' }))).toEqual(err);
expect(await thrownAsync(() => new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: '#12345' }))).toEqual(err);
expect(await thrownAsync(() => new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: 123 }))).toEqual(err);
expect(thrown(() => new PlacesController(svc({ canEdit }), new RuntimeEnvService(), storageStub).create(user, '5', { name: 'T', route_color: 'red' }))).toEqual(err);
expect(canEdit).not.toHaveBeenCalled();
});
it('passes a valid hex through, and null through as the reset to auto', () => {
it('passes a valid hex through, and null through as the reset to auto', async () => {
const update = vi.fn().mockReturnValue({ id: 9, route_color: '#e11d48' });
const broadcast = vi.fn();
const s = svc({ update, broadcast } as Partial<PlacesService>);
expect(new PlacesController(s, new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: '#e11d48' }, 'sock'))
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: '#e11d48' }, 'sock'))
.toEqual({ place: { id: 9, route_color: '#e11d48' } });
expect(update).toHaveBeenCalledWith('5', '9', expect.objectContaining({ route_color: '#e11d48' }), undefined);
// The colour has to reach the other members too, not just the DB.
expect(broadcast).toHaveBeenCalledWith('5', 'place:updated', { place: { id: 9, route_color: '#e11d48' } }, 'sock');
new PlacesController(svc({ update } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: null });
await new PlacesController(svc({ update } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: null });
expect(update).toHaveBeenLastCalledWith('5', '9', expect.objectContaining({ route_color: null }), undefined);
});
it('accepts the short #abc form', () => {
it('accepts the short #abc form', async () => {
const update = vi.fn().mockReturnValue({ id: 9 });
expect(new PlacesController(svc({ update } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: '#abc' })).toEqual({ place: { id: 9 } });
expect(await new PlacesController(svc({ update } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).update(user, '5', '9', { route_color: '#abc' })).toEqual({ place: { id: 9 } });
});
});
it('PUT /:id forwards the base-version token and 409s on a conflict (#1135)', () => {
it('PUT /:id forwards the base-version token and 409s on a conflict (#1135)', async () => {
const update = vi.fn().mockReturnValue({ conflict: true, server: { id: 9, name: 'Theirs' } });
const onUpdated = vi.fn(); const broadcast = vi.fn();
const s = svc({ update, onUpdated, broadcast } as Partial<PlacesService>);
expect(thrown(() => new PlacesController(s, new RuntimeEnvService(), storageStub).update(user, '5', '9', { name: 'Mine' }, 'sock', '2026-01-01 00:00:00'))).toEqual({
expect(await thrownAsync(() => new PlacesController(s, new RuntimeEnvService(), storageStub).update(user, '5', '9', { name: 'Mine' }, 'sock', '2026-01-01 00:00:00'))).toEqual({
status: 409, body: { error: 'conflict', server: { id: 9, name: 'Theirs' } },
});
expect(update).toHaveBeenCalledWith('5', '9', expect.objectContaining({ name: 'Mine' }), '2026-01-01 00:00:00');
@@ -316,23 +316,23 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou
expect(onUpdated).not.toHaveBeenCalled();
});
it('DELETE /:id fires the hook then 404 / success', () => {
it('DELETE /:id fires the hook then 404 / success', async () => {
const onDeleted = vi.fn();
const remove = vi.fn().mockReturnValue(false);
expect(thrown(() => new PlacesController(svc({ remove, onDeleted } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).remove(user, '5', '9'))).toEqual({ status: 404, body: { error: 'Place not found' } });
expect(await thrownAsync(() => new PlacesController(svc({ remove, onDeleted } as Partial<PlacesService>), new RuntimeEnvService(), storageStub).remove(user, '5', '9'))).toEqual({ status: 404, body: { error: 'Place not found' } });
expect(onDeleted).toHaveBeenCalledWith(9);
expect(onDeleted.mock.invocationCallOrder[0]).toBeLessThan(remove.mock.invocationCallOrder[0]);
const s = svc({ remove: vi.fn().mockReturnValue(true), broadcast: vi.fn() } as Partial<PlacesService>);
expect(new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '9')).toEqual({ success: true });
expect(await new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '9')).toEqual({ success: true });
});
// #1745: a place on another trip must 404 without the hook ever running —
// onPlaceDeleted keys on the place id alone, so it would detach that trip's
// journey entries.
it('DELETE /:id 404s a foreign place before the journey hook runs', () => {
it('DELETE /:id 404s a foreign place before the journey hook runs', async () => {
const onDeleted = vi.fn(); const remove = vi.fn();
const s = svc({ get: vi.fn().mockReturnValue(null), onDeleted, remove } as Partial<PlacesService>);
expect(thrown(() => new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '99'))).toEqual({ status: 404, body: { error: 'Place not found' } });
expect(await thrownAsync(() => new PlacesController(s, new RuntimeEnvService(), storageStub).remove(user, '5', '99'))).toEqual({ status: 404, body: { error: 'Place not found' } });
expect(onDeleted).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
});
+34 -32
View File
@@ -75,7 +75,7 @@ import { MapsService } from '../../../src/nest/maps/maps.service';
import { QueryHelpersService } from '../../../src/nest/query-helpers/query-helpers.service';
import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
import { TrekPhotosRepository } from '../../../src/nest/photos/trek-photos.repository';
import { PLACE_IMAGES_DIR } from '../../../src/nest/places/place-image';
import { makeStorageFixture } from '../../helpers/storage-fixture';
const GPX_FIXTURE = path.join(__dirname, '../../fixtures/test.gpx');
const KML_FIXTURE = path.join(__dirname, '../../fixtures/test.kml');
@@ -91,6 +91,8 @@ const dbs = new DatabaseService(testDb);
* creates a journey, so every hook returns on its first lookup.
* `maps` is a parameter because the enrichment cases hand in their own provider.
*/
const placesStorageFx = makeStorageFixture('');
function makePlacesService(maps: MapsService = new MapsService(dbs, photoCacheStub)): PlacesService {
return new PlacesService(
dbs,
@@ -101,6 +103,7 @@ function makePlacesService(maps: MapsService = new MapsService(dbs, photoCacheSt
new UnsplashService(dbs, new RuntimeEnvService()),
photoCacheStub,
new JourneyDomainService(dbs, new RealtimeService(), new TrekPhotosRepository(dbs)),
placesStorageFx.storage,
);
}
@@ -240,71 +243,71 @@ describe('get', () => {
// ── update ────────────────────────────────────────────────────────────────────
describe('update', () => {
it('PLACE-SVC-013 — updates place name and lat/lng', () => {
it('PLACE-SVC-013 — updates place name and lat/lng', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Old', lat: 0, lng: 0 }) as any;
const updated = svc.update(String(trip.id), String(place.id), { name: 'New', lat: 48.8, lng: 2.3 }) as any;
const updated = await svc.update(String(trip.id), String(place.id), { name: 'New', lat: 48.8, lng: 2.3 }) as any;
expect(updated.name).toBe('New');
expect(updated.lat).toBe(48.8);
expect(updated.lng).toBe(2.3);
});
it('PLACE-SVC-014 — returns null for non-existent place', () => {
it('PLACE-SVC-014 — returns null for non-existent place', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(svc.update(String(trip.id), '99999', { name: 'Ghost' })).toBeNull();
expect(await svc.update(String(trip.id), '99999', { name: 'Ghost' })).toBeNull();
});
it('PLACE-SVC-015 — updates tags (replaces old set)', () => {
it('PLACE-SVC-015 — updates tags (replaces old set)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const tag1 = createTag(testDb, user.id, { name: 'Old Tag' }) as any;
const tag2 = createTag(testDb, user.id, { name: 'New Tag' }) as any;
const place = svc.create(String(trip.id), { name: 'Taggable', tags: [tag1.id] }) as any;
const updated = svc.update(String(trip.id), String(place.id), { tags: [tag2.id] }) as any;
const updated = await svc.update(String(trip.id), String(place.id), { tags: [tag2.id] }) as any;
expect(updated.tags).toHaveLength(1);
expect(updated.tags[0].id).toBe(tag2.id);
});
it('PLACE-SVC-016 — clears tags when tags: [] is passed', () => {
it('PLACE-SVC-016 — clears tags when tags: [] is passed', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const tag = createTag(testDb, user.id, { name: 'Temp' }) as any;
const place = svc.create(String(trip.id), { name: 'Untaggable', tags: [tag.id] }) as any;
const updated = svc.update(String(trip.id), String(place.id), { tags: [] }) as any;
const updated = await svc.update(String(trip.id), String(place.id), { tags: [] }) as any;
expect(updated.tags).toHaveLength(0);
});
// ── Track colour (#776) ─────────────────────────────────────────────────────
it('PLACE-SVC-052 — stores a picked route_color', () => {
it('PLACE-SVC-052 — stores a picked route_color', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Walk' }) as any;
const updated = svc.update(String(trip.id), String(place.id), { route_color: '#e11d48' }) as any;
const updated = await svc.update(String(trip.id), String(place.id), { route_color: '#e11d48' }) as any;
expect(updated.route_color).toBe('#e11d48');
});
it('PLACE-SVC-053 — an explicit null clears it again (the reset to auto)', () => {
it('PLACE-SVC-053 — an explicit null clears it again (the reset to auto)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Walk' }) as any;
svc.update(String(trip.id), String(place.id), { route_color: '#e11d48' });
await svc.update(String(trip.id), String(place.id), { route_color: '#e11d48' });
// Guards the COALESCE trap: name/currency/transport_mode can never be
// emptied, and route_color built that way would be a one-way door.
const cleared = svc.update(String(trip.id), String(place.id), { route_color: null }) as any;
const cleared = await svc.update(String(trip.id), String(place.id), { route_color: null }) as any;
expect(cleared.route_color).toBeNull();
});
it('PLACE-SVC-054 — an unrelated update leaves the colour alone', () => {
it('PLACE-SVC-054 — an unrelated update leaves the colour alone', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Walk' }) as any;
svc.update(String(trip.id), String(place.id), { route_color: '#059669' });
const renamed = svc.update(String(trip.id), String(place.id), { name: 'Hike' }) as any;
await svc.update(String(trip.id), String(place.id), { route_color: '#059669' });
const renamed = await svc.update(String(trip.id), String(place.id), { name: 'Hike' }) as any;
expect(renamed.name).toBe('Hike');
expect(renamed.route_color).toBe('#059669');
});
@@ -325,14 +328,14 @@ describe('update', () => {
// ── updateMany ────────────────────────────────────────────────────────────────
describe('updateMany', () => {
it('PLACE-SVC-039 — applies the same fields to many places, preserving the rest', () => {
it('PLACE-SVC-039 — applies the same fields to many places, preserving the rest', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const a = createPlace(testDb, trip.id, { name: 'A' }) as any;
const b = createPlace(testDb, trip.id, { name: 'B' }) as any;
const c = createPlace(testDb, trip.id, { name: 'C' }) as any;
const updated = svc.updateMany(String(trip.id), [a.id, b.id, c.id], { notes: 'visited', transport_mode: 'walking' });
const updated = await svc.updateMany(String(trip.id), [a.id, b.id, c.id], { notes: 'visited', transport_mode: 'walking' });
expect(updated).toHaveLength(3);
for (const p of updated) {
@@ -343,14 +346,14 @@ describe('updateMany', () => {
expect(updated.map(p => (p as any).name).sort()).toEqual(['A', 'B', 'C']);
});
it('PLACE-SVC-040 — skips ids that are not in the trip and reports the rest', () => {
it('PLACE-SVC-040 — skips ids that are not in the trip and reports the rest', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const other = createTrip(testDb, user.id);
const mine = createPlace(testDb, trip.id, { name: 'Mine' }) as any;
const foreign = createPlace(testDb, other.id, { name: 'Foreign' }) as any;
const updated = svc.updateMany(String(trip.id), [mine.id, foreign.id, 99999], { notes: 'tagged' });
const updated = await svc.updateMany(String(trip.id), [mine.id, foreign.id, 99999], { notes: 'tagged' });
expect(updated).toHaveLength(1);
expect((updated[0] as any).id).toBe(mine.id);
@@ -358,10 +361,10 @@ describe('updateMany', () => {
expect((svc.get(String(other.id), String(foreign.id)) as any).notes).toBeNull();
});
it('PLACE-SVC-041 — returns [] for an empty id list', () => {
it('PLACE-SVC-041 — returns [] for an empty id list', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(svc.updateMany(String(trip.id), [], { notes: 'x' })).toEqual([]);
expect(await svc.updateMany(String(trip.id), [], { notes: 'x' })).toEqual([]);
});
});
@@ -912,13 +915,12 @@ describe('importKmlPlaces deduplication', () => {
describe('custom place image reclaim', () => {
function writePlaceImage(name: string): string {
fs.mkdirSync(PLACE_IMAGES_DIR, { recursive: true });
const filePath = path.join(PLACE_IMAGES_DIR, name);
const filePath = path.join(placesStorageFx.root, name);
fs.writeFileSync(filePath, 'jpeg-bytes');
return filePath;
}
it('PLACE-SVC-046 — replacing image_url unlinks the previous upload once unreferenced', () => {
it('PLACE-SVC-046 — replacing image_url unlinks the previous upload once unreferenced', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Photo' }) as any;
@@ -926,11 +928,11 @@ describe('custom place image reclaim', () => {
testDb.prepare('UPDATE places SET image_url = ? WHERE id = ?').run('/uploads/places/svc-replace-a.jpg', place.id);
expect(fs.existsSync(fileA)).toBe(true);
svc.update(String(trip.id), String(place.id), { image_url: '/uploads/places/svc-replace-b.jpg' });
await svc.update(String(trip.id), String(place.id), { image_url: '/uploads/places/svc-replace-b.jpg' });
expect(fs.existsSync(fileA)).toBe(false);
});
it('PLACE-SVC-047 — clearing image_url to null unlinks the previous upload', () => {
it('PLACE-SVC-047 — clearing image_url to null unlinks the previous upload', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Photo' }) as any;
@@ -938,7 +940,7 @@ describe('custom place image reclaim', () => {
testDb.prepare('UPDATE places SET image_url = ? WHERE id = ?').run('/uploads/places/svc-clear.jpg', place.id);
expect(fs.existsSync(fileA)).toBe(true);
svc.update(String(trip.id), String(place.id), { image_url: null } as any);
await svc.update(String(trip.id), String(place.id), { image_url: null } as any);
expect(fs.existsSync(fileA)).toBe(false);
});
@@ -1275,17 +1277,17 @@ describe('zero-valued numeric fields', () => {
expect((svc.create(String(trip.id), { name: 'Default' }) as any).duration_minutes).toBe(60);
});
it('PLACE-SVC-067 — update can set duration_minutes to 0', () => {
it('PLACE-SVC-067 — update can set duration_minutes to 0', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = createPlace(testDb, trip.id, { name: 'Stop' }) as any;
testDb.prepare('UPDATE places SET duration_minutes = 90 WHERE id = ?').run(place.id);
const zeroed = svc.update(String(trip.id), String(place.id), { duration_minutes: 0 }) as any;
const zeroed = await svc.update(String(trip.id), String(place.id), { duration_minutes: 0 }) as any;
expect(zeroed.duration_minutes).toBe(0);
// An omitted duration still leaves the stored value alone (COALESCE).
const untouched = svc.update(String(trip.id), String(place.id), { name: 'Stop 2' }) as any;
const untouched = await svc.update(String(trip.id), String(place.id), { name: 'Stop 2' }) as any;
expect(untouched.duration_minutes).toBe(0);
});
});
@@ -90,6 +90,7 @@ const placesSvc = new PlacesService(
new MapsService(dbs(), photoCache), new QueryHelpersService(dbs()),
new UnsplashService(dbs(), new RuntimeEnvService()), photoCache,
new JourneyDomainService(dbs(), new RealtimeService(), new TrekPhotosRepository(dbs())),
makeStorageFixture('').storage,
);
const accommodationsSvc = new AccommodationsService(dbs(), new PermissionsService(dbs()), new RealtimeService());
const membersSvc = new TripMembersService(dbs(), budgetSvc, new UserCleanupService(dbs(), budgetSvc), new PermissionsService(dbs()), new RealtimeService(), notificationsStub());
@@ -107,6 +107,7 @@ const placesSvc = new PlacesService(
new UnsplashService(dbs(), new RuntimeEnvService()),
photoCache,
new JourneyDomainService(dbs(), new RealtimeService(), new TrekPhotosRepository(dbs())),
makeStorageFixture('').storage,
);
const accommodationsSvc = new AccommodationsService(dbs(), new PermissionsService(dbs()), new RealtimeService());
const createAccommodation = accommodationsSvc.createAccommodation.bind(accommodationsSvc);
@@ -71,6 +71,7 @@ const places = new PlacesService(
new UnsplashService(dbs, runtimeEnv),
photoCache,
new JourneyDomainService(dbs, realtime, new TrekPhotosRepository(dbs)),
makeStorageFixture('').storage,
);
beforeAll(() => {
@@ -92,32 +93,32 @@ function freshPlace(tripId: number) {
}
describe('PlacesService.update — optimistic concurrency', () => {
it('updates normally when no If-Match token is sent (back-compat)', () => {
it('updates normally when no If-Match token is sent (back-compat)', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = places.update(String(trip.id), String(place.id), { name: 'Edited' });
const result = await places.update(String(trip.id), String(place.id), { name: 'Edited' });
expect(isUpdateConflict(result)).toBe(false);
expect((result as { name: string }).name).toBe('Edited');
});
it('updates when the If-Match token matches the current updated_at', () => {
it('updates when the If-Match token matches the current updated_at', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = places.update(String(trip.id), String(place.id), { name: 'Edited' }, place.updated_at);
const result = await places.update(String(trip.id), String(place.id), { name: 'Edited' }, place.updated_at);
expect(isUpdateConflict(result)).toBe(false);
expect((result as { name: string }).name).toBe('Edited');
});
it('returns a conflict (with the server row) when the token is stale', () => {
it('returns a conflict (with the server row) when the token is stale', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
const place = freshPlace(trip.id);
const result = places.update(String(trip.id), String(place.id), { name: 'Mine' }, '1999-01-01 00:00:00');
const result = await places.update(String(trip.id), String(place.id), { name: 'Mine' }, '1999-01-01 00:00:00');
expect(isUpdateConflict(result)).toBe(true);
if (isUpdateConflict(result)) {
expect((result.server as { name: string }).name).toBe('Original');
@@ -127,10 +128,10 @@ describe('PlacesService.update — optimistic concurrency', () => {
expect(row.name).toBe('Original');
});
it('returns null for a place that does not exist', () => {
it('returns null for a place that does not exist', async () => {
const { user } = createUser(testDb);
const trip = createTrip(testDb, user.id);
expect(places.update(String(trip.id), '999999', { name: 'x' }, 'whatever')).toBeNull();
expect(await places.update(String(trip.id), '999999', { name: 'x' }, 'whatever')).toBeNull();
});
});