mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-06-21 14:21:46 +00:00
9bec97fc19
* Start the Journey date picker week on Monday (#1078) The Journey entry date picker started the week on Sunday (firstDow = getDay(), headers Su-first) while every other picker (CustomDateTimePicker, VacayCalendar) starts on Monday. Align it: Monday-first leading offset ((getDay()+6)%7) and Mo-first weekday headers. * Fix Taiwan resolving to CN-TW in the Atlas country search (#1049) natural-earth gives Taiwan ISO_A2='CN-TW' (a subdivision-style value) with ADM0_A3='TWN'. The dynamic A2_TO_A3 augmentation added 'CN-TW'->'TWN', which then overwrote the legitimate TWN->TW entry in the reverse map, so Taiwan's country option resolved to 'CN-TW' — unresolvable by Intl.DisplayNames (no name, broken flag, not searchable). Only augment A2_TO_A3 with real 2-letter codes. * Drop empty leftover dateless days when a trip gets a shorter dated range (#1083) generateDays kept all unused dateless placeholder days after switching to an explicit (shorter) date range, so day_count (COUNT(*) FROM days) stayed inflated. Delete the empty leftovers (no assignments/notes/accommodations) like the dateless path already does, while preserving any that still hold content. Adds TRIP-SVC-017. * Render GPX and route overlays once the Mapbox style has loaded (#1036) The GPX and route geojson effects ran before the map 'load' event had attached their sources, so on the first paint they hit the early return and never re-ran. Add mapReady to their dependencies so they fire again the moment the sources exist. * Convert HEIC trip and journey covers to JPEG before upload (#1085) HEIC/HEIF covers coming straight off an iPhone could not be rendered in the preview or stored as a usable image. Route both cover pickers through normalizeImageFile, the same conversion the journal entry editor already uses, so the file becomes a JPEG before it leaves the browser. * Name GPX routes and tracks after their source file so multiple imports stick (#1054) Unnamed routes and tracks all fell back to the same generic 'GPX Route' / 'GPX Track' label, so the name-based import dedup dropped every one after the first - importing several files (or one file with several tracks) only kept a single place. Derive the default name from the source filename with an index suffix when a file holds more than one geometry, thread the filename down through the controller, and let the import modal take more than one file at a time. Adds PLACE-SVC-037/038. * Namespace the modal backdrop class so content blockers stop hiding it (#1027) Generic class names like .modal-backdrop sit on the cosmetic filter lists that content blockers (1Blocker, EasyList Annoyances) ship, and get hidden with display:none. The shared Modal - used by New Trip and Add Place - carried that class, so Safari users running such a blocker saw the modal silently fail to open with no error and no network request. Rename it to .trek-modal-backdrop. * Highlight GB regions by resolving England/Scotland/Wales/NI to finer admin-1 codes (#1067) A zoom-8 reverse geocode of a UK place only resolves to the constituent country (GB-ENG/SCT/WLS/NIR), but Natural Earth's admin-1 polygons for GB are counties and boroughs (GB-LND, GB-MAN, GB-CON, ...). Those four codes match no polygon, so places in England never highlighted in the Atlas while CH/IT/NL/etc. worked. When a GB lookup lands on a constituent country, re-resolve it at a finer zoom where Nominatim exposes the county/borough code the polygons actually carry. Other countries keep the exact zoom-8 behaviour. Adds ATLAS-UNIT-021. * Surface the real place-search error instead of a generic toast (#1092) When a place search or detail lookup fails, the backend already forwards the upstream reason - including descriptive Google Places API messages such as 'Places API (New) has not been used in project ... or it is disabled'. The planner discarded it and always showed 'Place search failed', so a key that is mis-enabled, unbilled, or pointed at the legacy API instead of Places API (New) looked like an unexplained silent failure. Show the server-provided message when present, and stop the Atlas bucket-list search from swallowing its error without a trace. * Await the async cover normalization in the TripFormModal paste test (#1085) handleCoverSelect now normalizes the pasted file before previewing it, so URL.createObjectURL is called a microtask later. The assertion moves into waitFor; a non-HEIC file still passes through unchanged.
283 lines
10 KiB
TypeScript
283 lines
10 KiB
TypeScript
import {
|
|
Body,
|
|
Controller,
|
|
Delete,
|
|
Get,
|
|
Headers,
|
|
HttpCode,
|
|
HttpException,
|
|
Param,
|
|
Post,
|
|
Put,
|
|
Query,
|
|
UploadedFile,
|
|
UseGuards,
|
|
UseInterceptors,
|
|
} from '@nestjs/common';
|
|
import { FileInterceptor } from '@nestjs/platform-express';
|
|
import { memoryStorage } from 'multer';
|
|
import type { User } from '../../types';
|
|
import { PlacesService } from './places.service';
|
|
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
|
import { CurrentUser } from '../auth/current-user.decorator';
|
|
|
|
const STRING_LIMITS: Record<string, number> = { name: 200, description: 2000, address: 500, notes: 2000 };
|
|
const UPLOAD = { storage: memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } };
|
|
|
|
function validateLengths(body: Record<string, unknown>): void {
|
|
for (const [field, max] of Object.entries(STRING_LIMITS)) {
|
|
const value = body[field];
|
|
if (value && typeof value === 'string' && value.length > max) {
|
|
throw new HttpException({ error: `${field} must be ${max} characters or less` }, 400);
|
|
}
|
|
}
|
|
}
|
|
|
|
function parseBool(v: unknown, defaultVal: boolean): boolean {
|
|
return v === undefined || v === null ? defaultVal : String(v) === 'true';
|
|
}
|
|
|
|
/**
|
|
* /api/trips/:tripId/places — the trip's place pool + importers.
|
|
*
|
|
* Byte-identical to the legacy Express route (server/src/routes/places.ts):
|
|
* trip access (404) runs first, then the string-length guard (400), then the
|
|
* 'place_edit' permission (403); create 201 / rest 200; the bespoke 400/404
|
|
* bodies; the journey create/update/delete hooks; and WebSocket broadcasts with
|
|
* the forwarded X-Socket-Id. The /import/* and /bulk-delete routes are declared
|
|
* before /:id so the static segments win over the param.
|
|
*/
|
|
@Controller('api/trips/:tripId/places')
|
|
@UseGuards(JwtAuthGuard)
|
|
export class PlacesController {
|
|
constructor(private readonly places: PlacesService) {}
|
|
|
|
private requireTrip(tripId: string, user: User) {
|
|
const trip = this.places.verifyTripAccess(tripId, user.id);
|
|
if (!trip) {
|
|
throw new HttpException({ error: 'Trip not found' }, 404);
|
|
}
|
|
return trip;
|
|
}
|
|
|
|
private requireEdit(trip: NonNullable<ReturnType<PlacesService['verifyTripAccess']>>, user: User): void {
|
|
if (!this.places.canEdit(trip, user)) {
|
|
throw new HttpException({ error: 'No permission' }, 403);
|
|
}
|
|
}
|
|
|
|
@Get()
|
|
list(
|
|
@CurrentUser() user: User,
|
|
@Param('tripId') tripId: string,
|
|
@Query('search') search?: string,
|
|
@Query('category') category?: string,
|
|
@Query('tag') tag?: string,
|
|
) {
|
|
this.requireTrip(tripId, user);
|
|
return { places: this.places.list(tripId, { search, category, tag }) };
|
|
}
|
|
|
|
@Post()
|
|
create(
|
|
@CurrentUser() user: User,
|
|
@Param('tripId') tripId: string,
|
|
@Body() body: Record<string, unknown> & { name?: string },
|
|
@Headers('x-socket-id') socketId?: string,
|
|
) {
|
|
const trip = this.requireTrip(tripId, user);
|
|
validateLengths(body);
|
|
this.requireEdit(trip, user);
|
|
if (!body.name) {
|
|
throw new HttpException({ error: 'Place name is required' }, 400);
|
|
}
|
|
const place = this.places.create(tripId, body as never);
|
|
this.places.broadcast(tripId, 'place:created', { place }, socketId);
|
|
this.places.onCreated(tripId, place.id);
|
|
return { place };
|
|
}
|
|
|
|
@Post('import/gpx')
|
|
@UseInterceptors(FileInterceptor('file', UPLOAD))
|
|
importGpx(
|
|
@CurrentUser() user: User,
|
|
@Param('tripId') tripId: string,
|
|
@UploadedFile() file: Express.Multer.File | undefined,
|
|
@Body() body: Record<string, unknown>,
|
|
@Headers('x-socket-id') socketId?: string,
|
|
) {
|
|
const trip = this.requireTrip(tripId, user);
|
|
this.requireEdit(trip, user);
|
|
if (!file) {
|
|
throw new HttpException({ error: 'No file uploaded' }, 400);
|
|
}
|
|
const importWaypoints = parseBool(body.importWaypoints, true);
|
|
const importRoutes = parseBool(body.importRoutes, true);
|
|
const importTracks = parseBool(body.importTracks, true);
|
|
if (!importWaypoints && !importRoutes && !importTracks) {
|
|
throw new HttpException({ error: 'No import types selected' }, 400);
|
|
}
|
|
const result = this.places.importGpx(tripId, file.buffer, { importWaypoints, importRoutes, importTracks, defaultName: file.originalname });
|
|
if (!result) {
|
|
throw new HttpException({ error: 'No matching places found in GPX file' }, 400);
|
|
}
|
|
for (const place of result.places) {
|
|
this.places.broadcast(tripId, 'place:created', { place }, socketId);
|
|
}
|
|
return { places: result.places, count: result.count, skipped: result.skipped };
|
|
}
|
|
|
|
@Post('import/map')
|
|
@UseInterceptors(FileInterceptor('file', UPLOAD))
|
|
async importMap(
|
|
@CurrentUser() user: User,
|
|
@Param('tripId') tripId: string,
|
|
@UploadedFile() file: Express.Multer.File | undefined,
|
|
@Body() body: Record<string, unknown>,
|
|
@Headers('x-socket-id') socketId?: string,
|
|
) {
|
|
const trip = this.requireTrip(tripId, user);
|
|
this.requireEdit(trip, user);
|
|
if (!file) {
|
|
throw new HttpException({ error: 'No file uploaded' }, 400);
|
|
}
|
|
const importPoints = parseBool(body.importPoints, true);
|
|
const importPaths = parseBool(body.importPaths, true);
|
|
if (!importPoints && !importPaths) {
|
|
throw new HttpException({ error: 'No import types selected' }, 400);
|
|
}
|
|
try {
|
|
const result = await this.places.importMapFile(tripId, file.buffer, file.originalname, { importPoints, importPaths });
|
|
if (result.summary?.totalPlacemarks === 0) {
|
|
throw new HttpException({ error: 'No valid Placemarks found in map file', summary: result.summary }, 400);
|
|
}
|
|
for (const place of result.places) {
|
|
this.places.broadcast(tripId, 'place:created', { place }, socketId);
|
|
}
|
|
return result;
|
|
} catch (err: unknown) {
|
|
if (err instanceof HttpException) throw err;
|
|
const message = err instanceof Error ? err.message : 'Failed to import map file';
|
|
throw new HttpException({ error: message }, 400);
|
|
}
|
|
}
|
|
|
|
@Post('import/google-list')
|
|
async importGoogle(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body('url') url: unknown, @Headers('x-socket-id') socketId?: string) {
|
|
return this.importList('google', user, tripId, url, socketId);
|
|
}
|
|
|
|
@Post('import/naver-list')
|
|
async importNaver(@CurrentUser() user: User, @Param('tripId') tripId: string, @Body('url') url: unknown, @Headers('x-socket-id') socketId?: string) {
|
|
return this.importList('naver', user, tripId, url, socketId);
|
|
}
|
|
|
|
/** Shared google/naver list import — identical flow, different provider + error string. */
|
|
private async importList(provider: 'google' | 'naver', user: User, tripId: string, url: unknown, socketId?: string) {
|
|
const trip = this.requireTrip(tripId, user);
|
|
this.requireEdit(trip, user);
|
|
if (!url || typeof url !== 'string') {
|
|
throw new HttpException({ error: 'URL is required' }, 400);
|
|
}
|
|
const label = provider === 'google' ? 'Google' : 'Naver';
|
|
try {
|
|
const result = provider === 'google'
|
|
? await this.places.importGoogleList(tripId, url)
|
|
: await this.places.importNaverList(tripId, url);
|
|
if ('error' in result) {
|
|
throw new HttpException({ error: result.error }, result.status);
|
|
}
|
|
for (const place of result.places) {
|
|
this.places.broadcast(tripId, 'place:created', { place }, socketId);
|
|
}
|
|
return { places: result.places, count: result.places.length, listName: result.listName, skipped: result.skipped };
|
|
} catch (err: unknown) {
|
|
if (err instanceof HttpException) throw err;
|
|
console.error(`[Places] ${label} list import error:`, err instanceof Error ? err.message : err);
|
|
throw new HttpException({ error: `Failed to import ${label} Maps list. Make sure the list is shared publicly.` }, 400);
|
|
}
|
|
}
|
|
|
|
@Post('bulk-delete')
|
|
@HttpCode(200) // Express answers bulk-delete with res.json (200), unlike the 201 imports.
|
|
bulkDelete(
|
|
@CurrentUser() user: User,
|
|
@Param('tripId') tripId: string,
|
|
@Body('ids') ids: unknown,
|
|
@Headers('x-socket-id') socketId?: string,
|
|
) {
|
|
const trip = this.requireTrip(tripId, user);
|
|
this.requireEdit(trip, user);
|
|
if (!Array.isArray(ids) || ids.some((v) => typeof v !== 'number')) {
|
|
throw new HttpException({ error: 'ids must be an array of numbers' }, 400);
|
|
}
|
|
if (ids.length === 0) {
|
|
return { deleted: [], count: 0 };
|
|
}
|
|
for (const id of ids) this.places.onDeleted(id);
|
|
const deleted = this.places.removeMany(tripId, ids);
|
|
for (const id of deleted) {
|
|
this.places.broadcast(tripId, 'place:deleted', { placeId: id }, socketId);
|
|
}
|
|
return { deleted, count: deleted.length };
|
|
}
|
|
|
|
@Get(':id')
|
|
get(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) {
|
|
this.requireTrip(tripId, user);
|
|
const place = this.places.get(tripId, id);
|
|
if (!place) {
|
|
throw new HttpException({ error: 'Place not found' }, 404);
|
|
}
|
|
return { place };
|
|
}
|
|
|
|
@Get(':id/image')
|
|
async image(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) {
|
|
this.requireTrip(tripId, user);
|
|
try {
|
|
const result = await this.places.searchImage(tripId, id, user.id);
|
|
if ('error' in result) {
|
|
throw new HttpException({ error: result.error }, result.status);
|
|
}
|
|
return { photos: result.photos };
|
|
} catch (err: unknown) {
|
|
if (err instanceof HttpException) throw err;
|
|
console.error('Unsplash error:', err);
|
|
throw new HttpException({ error: 'Error searching for image' }, 500);
|
|
}
|
|
}
|
|
|
|
@Put(':id')
|
|
update(
|
|
@CurrentUser() user: User,
|
|
@Param('tripId') tripId: string,
|
|
@Param('id') id: string,
|
|
@Body() body: Record<string, unknown>,
|
|
@Headers('x-socket-id') socketId?: string,
|
|
) {
|
|
const trip = this.requireTrip(tripId, user);
|
|
validateLengths(body);
|
|
this.requireEdit(trip, user);
|
|
const place = this.places.update(tripId, id, body as never);
|
|
if (!place) {
|
|
throw new HttpException({ error: 'Place not found' }, 404);
|
|
}
|
|
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
|
|
this.places.onUpdated(place.id);
|
|
return { place };
|
|
}
|
|
|
|
@Delete(':id')
|
|
remove(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
|
|
const trip = this.requireTrip(tripId, user);
|
|
this.requireEdit(trip, user);
|
|
this.places.onDeleted(Number(id)); // sync before actual delete
|
|
if (!this.places.remove(tripId, id)) {
|
|
throw new HttpException({ error: 'Place not found' }, 404);
|
|
}
|
|
this.places.broadcast(tripId, 'place:deleted', { placeId: Number(id) }, socketId);
|
|
return { success: true };
|
|
}
|
|
}
|