mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-01 00:43:15 +00:00
feat(collections): own order, KML/KMZ import, copy options, position search, place names on the trip map
- A list keeps its own order: drag a place by its grip (desktop and phone) or move it with the arrow keys. Reordering is off while a search or filter hides places and the list says why. New PUT /collections/:id/places/reorder and the MCP tool reorder_collection_places; new places go to the end. Client and server now order ties the same way (sort_order, oldest first, id). - Copying saved places into a trip no longer takes their notes and tags along unasked. The picker offers both; a tag taken along becomes a trip tag (a trip tag of the same name is reused), never someone's personal tag. - The source trip and place a saved place names are only kept when the user can open that trip and the place belongs to it. - A KML or KMZ map can be read into a list: the dialog lists every placemark to keep or leave out and says which entries were skipped and why (POST /collections/map/read writes nothing; the import does). - A saved place without coordinates says so and can be looked up on the map from its edit form, on the phone too, where a missing position could not be added at all. A typed address without a pick says it will not be on the map. - The trip map can show the place names beside the pins (desktop and phone, both renderers). Names that would cover another pin or a control give way, the selected place and the planned stops first.
This commit is contained in:
@@ -81,9 +81,8 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
|
||||
* per the plan's own "do not collapse" instruction for that pair).
|
||||
* `saveFromTripPlaces`'s own call site passes `status: 'idea', links:
|
||||
* null` explicitly, reproducing the literal exactly. `em.insert()`
|
||||
* returns the generated id; `sort_order` is never in the column list
|
||||
* either statement writes, so the table's own `DEFAULT 0` fills it,
|
||||
* matching both legacy statements.
|
||||
* returns the generated id. `sort_order` is the caller's: a new place goes
|
||||
* after the last one of its list (PLC-03), read in the same transaction.
|
||||
*/
|
||||
async insertSavedPlace(row: {
|
||||
collection_id: number;
|
||||
@@ -108,6 +107,7 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
|
||||
source_trip_id: number | null;
|
||||
source_place_id: number | null;
|
||||
links: string | null;
|
||||
sort_order: number;
|
||||
}): Promise<number> {
|
||||
return await this.insert({
|
||||
collection: row.collection_id,
|
||||
@@ -132,9 +132,35 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
|
||||
source_trip_id: row.source_trip_id,
|
||||
source_place_id: row.source_place_id,
|
||||
links: row.links,
|
||||
sort_order: row.sort_order,
|
||||
});
|
||||
}
|
||||
|
||||
/** A list's place ids in the list's order: `sort_order`, then `created_at`, then `id`, as listPlaceRows reads them. */
|
||||
async idsInOrder(collectionId: number): Promise<number[]> {
|
||||
const rows = await this.db_()
|
||||
.selectFrom('collection_places')
|
||||
.select('id')
|
||||
.where('collection_id', '=', collectionId)
|
||||
.orderBy((eb) => eb.fn.coalesce('sort_order', eb.val(0)))
|
||||
.orderBy((eb) => eb.fn.coalesce('created_at', eb.val('')))
|
||||
.orderBy('id')
|
||||
.execute();
|
||||
return rows.map((r) => r.id);
|
||||
}
|
||||
|
||||
/** `UPDATE collection_places SET sort_order=? WHERE id=? AND collection_id=?`, per place, inside the caller's transaction. */
|
||||
async setSortOrders(collectionId: number, orderedIds: number[]): Promise<void> {
|
||||
for (const [position, id] of orderedIds.entries()) {
|
||||
await this.db_()
|
||||
.updateTable('collection_places')
|
||||
.set({ sort_order: position })
|
||||
.where('id', '=', id)
|
||||
.where('collection_id', '=', collectionId)
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// CL47/CL48 — updatePlace
|
||||
// ---------------------------------------------------------------------
|
||||
@@ -180,6 +206,7 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
|
||||
currency: string | null;
|
||||
collection_id: number;
|
||||
owner_id: number;
|
||||
sort_order: number;
|
||||
}>,
|
||||
): Promise<void> {
|
||||
if (Object.keys(write).length === 0) return;
|
||||
@@ -350,20 +377,6 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// CL67 — copyToTrip's per-source tag read (loop, TX)
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
/** CL67 (`copyToTrip`, loop, TX) — `SELECT tag_id FROM collection_place_tags WHERE collection_place_id=?`. Pivot table, Kysely. */
|
||||
async tagIdsFor(collectionPlaceId: number): Promise<number[]> {
|
||||
const rows = await this.db_()
|
||||
.selectFrom('collection_place_tags')
|
||||
.select('tag_id')
|
||||
.where('collection_place_id', '=', collectionPlaceId)
|
||||
.execute();
|
||||
return rows.map((r) => r.tag_id);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
// CL69 — findMembership (library-wide membership lookup)
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
@@ -10,7 +10,7 @@ import { PLACE_IMAGE_FILE_FILTER } from '../common/place-image-upload';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { SpoolCleanupInterceptor } from '../common/spool-cleanup.interceptor';
|
||||
import { CollectionGpxError } from '../place-import/place-import.types';
|
||||
import { CollectionGpxError, CollectionMapError } from '../place-import/place-import.types';
|
||||
import { placeImageUrl } from '../places/place-image';
|
||||
import { PlaceRatingDto } from '../places/places.dto';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
@@ -38,6 +38,7 @@ import {
|
||||
CollectionImportDto,
|
||||
CollectionImportIntoDto,
|
||||
CollectionGpxReadDto,
|
||||
CollectionPlacesReorderDto,
|
||||
} from './collections.dto';
|
||||
import { CollectionsService } from './collections.service';
|
||||
import {
|
||||
@@ -58,12 +59,19 @@ import {
|
||||
UseInterceptors,
|
||||
} from '@nestjs/common';
|
||||
import { FileInterceptor } from '@nestjs/platform-express';
|
||||
import { collectionKmlExportSchema } from '@trek/shared';
|
||||
import {
|
||||
collectionKmlExportSchema,
|
||||
collectionMapReadResultSchema,
|
||||
MAX_COLLECTION_MAP_UPLOAD_BYTES,
|
||||
successResponseSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
import type { Options } from 'multer';
|
||||
import { memoryStorage, type Options } from 'multer';
|
||||
import path from 'path';
|
||||
|
||||
export const MAX_COVER_SIZE = 20 * 1024 * 1024;
|
||||
// A map file is read and dropped, never stored: held in memory under the trip map import's cap.
|
||||
const MAP_UPLOAD = { storage: memoryStorage(), limits: { fileSize: MAX_COLLECTION_MAP_UPLOAD_BYTES } };
|
||||
// Duplicated on purpose from trips.controller.ts (historical parity — no
|
||||
// drive-by consolidation). Quirk preserved: a plain Error without statusCode
|
||||
// maps to 500, not 400. Passed inline on the cover route; the storage engine
|
||||
@@ -295,6 +303,26 @@ export class CollectionsController {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A KML or KMZ map read into the list file it amounts to (PLC-22), like
|
||||
* gpx/read above: nothing is written, so 200, and the browser sends what the
|
||||
* user keeps of it to /import or /:id/import. A multipart upload, checked in
|
||||
* the handler; the list's own rights apply where the places are written.
|
||||
*/
|
||||
@Post('map/read')
|
||||
@HttpCode(200)
|
||||
@UseInterceptors(FileInterceptor('file', MAP_UPLOAD))
|
||||
@ResponseContract(collectionMapReadResultSchema)
|
||||
async readMap(@UploadedFile() file: Express.Multer.File | undefined) {
|
||||
if (!file) throw new HttpException({ error: 'No file uploaded', code: 'no-file' }, 400);
|
||||
try {
|
||||
return await this.collections.readCollectionMap(file.buffer, file.originalname);
|
||||
} catch (err) {
|
||||
if (!(err instanceof CollectionMapError)) throw err;
|
||||
throw new HttpException({ error: err.message, code: err.code }, err.code === 'too-large' ? 413 : 400);
|
||||
}
|
||||
}
|
||||
|
||||
@Post('copy-to-trip')
|
||||
@HttpCode(200)
|
||||
copyToTrip(
|
||||
@@ -540,6 +568,23 @@ export class CollectionsController {
|
||||
return this.collections.importIntoCollection(user.id, id, body, socketId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The list's places in a new order (PLC-03). Anyone who may edit the list,
|
||||
* every id one of its places; the members' open tabs reload it, the asking
|
||||
* one left out.
|
||||
*/
|
||||
@Put(':id/places/reorder')
|
||||
@ResponseContract(successResponseSchema)
|
||||
async reorderPlaces(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id', rowId('Collection not found')) id: number,
|
||||
@Body() body: CollectionPlacesReorderDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
await this.collections.reorderPlaces(user.id, id, body.orderedIds, socketId);
|
||||
return { success: true as const };
|
||||
}
|
||||
|
||||
@Get(':id/importable/:tripId')
|
||||
importable(
|
||||
@CurrentUser() user: User,
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
collectionLabelAssignRequestSchema,
|
||||
collectionImportRequestSchema,
|
||||
collectionGpxReadRequestSchema,
|
||||
collectionPlacesReorderRequestSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
@@ -56,3 +57,4 @@ export class CollectionLabelUpdateDto extends createZodDto(collectionLabelUpdate
|
||||
export class CollectionLabelAssignDto extends createZodDto(collectionLabelAssignRequestSchema) {}
|
||||
export class CollectionImportDto extends createZodDto(collectionImportRequestSchema) {}
|
||||
export class CollectionGpxReadDto extends createZodDto(collectionGpxReadRequestSchema) {}
|
||||
export class CollectionPlacesReorderDto extends createZodDto(collectionPlacesReorderRequestSchema) {}
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
import type { CollectionPlacePosition, CollectionPlaceRow } from '../../db/repositories/Collections.repository';
|
||||
import type { CollectionFilePlace, CollectionLink, CollectionPlaceUpdateRequest, CollectionStatus } from '@trek/shared';
|
||||
import type { PlaceRow } from '../../db/repositories/Places.repository';
|
||||
import type { DedupSet } from '../places/places.helpers';
|
||||
import { externalIdsOf } from '@trek/shared';
|
||||
import type {
|
||||
CollectionFilePlace,
|
||||
CollectionLink,
|
||||
CollectionPlaceUpdateRequest,
|
||||
CollectionStatus,
|
||||
PlaceMatchCandidate,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
@@ -107,3 +116,55 @@ export function decodePlacesCursor(cursor: string): CollectionPlacePosition | nu
|
||||
const [sortOrder, createdAt, id] = parsed.data;
|
||||
return { sortOrder, createdAt, id };
|
||||
}
|
||||
|
||||
/** Rows grouped by their pid, each group in the order the rows came, for the batched hydration reads. */
|
||||
export function groupByPid<R extends { pid: number }, V>(rows: R[], value: (row: R) => V): Record<number, V[]> {
|
||||
const out: Record<number, V[]> = {};
|
||||
for (const row of rows) (out[row.pid] ??= []).push(value(row));
|
||||
return out;
|
||||
}
|
||||
|
||||
/** What saving a trip place into a list takes from it, for the single and the bulk save alike. */
|
||||
export function tripPlaceFields(p: PlaceRow) {
|
||||
return {
|
||||
name: p.name,
|
||||
description: p.description ?? null,
|
||||
lat: p.lat ?? null,
|
||||
lng: p.lng ?? null,
|
||||
address: p.address ?? null,
|
||||
category_id: p.category_id ?? null,
|
||||
price: p.price ?? null,
|
||||
currency: p.currency ?? null,
|
||||
notes: p.notes ?? null,
|
||||
image_url: p.image_url ?? null,
|
||||
google_place_id: p.google_place_id ?? null,
|
||||
google_ftid: p.google_ftid ?? null,
|
||||
osm_id: p.osm_id ?? null,
|
||||
website: p.website ?? null,
|
||||
phone: p.phone ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The importers' dedup set over a trip's places: a place renamed in the trip is still known by its provider id (#1550). */
|
||||
export function tripDedupSet(existing: PlaceMatchCandidate[]): DedupSet {
|
||||
const dedup: DedupSet = { names: new Set(), coords: [], externalIds: new Set() };
|
||||
for (const r of existing) {
|
||||
for (const id of externalIdsOf(r)) dedup.externalIds.add(id);
|
||||
if (r.name) dedup.names.add(r.name.trim().toLowerCase());
|
||||
else if (r.lat != null && r.lng != null) dedup.coords.push({ lat: r.lat, lng: r.lng });
|
||||
}
|
||||
return dedup;
|
||||
}
|
||||
|
||||
/**
|
||||
* A list's ids in the order a reorder asks for (PLC-03): the named ones first,
|
||||
* then the ones it did not name in the order they had, so a place saved by
|
||||
* somebody else since the list was loaded is kept rather than dropped.
|
||||
* Null when the request names an id twice or one the list does not hold.
|
||||
*/
|
||||
export function placeOrderOf(current: number[], requested: number[]): number[] | null {
|
||||
const held = new Set(current);
|
||||
const named = new Set(requested);
|
||||
if (named.size !== requested.length || requested.some((id) => !held.has(id))) return null;
|
||||
return [...requested, ...current.filter((id) => !named.has(id))];
|
||||
}
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
collectionSavePlaceRequestSchema,
|
||||
collectionPlaceUpdateRequestSchema,
|
||||
collectionCopyToTripRequestSchema,
|
||||
collectionPlacesReorderRequestSchema,
|
||||
collectionLabelCreateRequestSchema,
|
||||
collectionLabelUpdateRequestSchema,
|
||||
collectionLabelAssignRequestSchema,
|
||||
@@ -45,6 +46,7 @@ import type {
|
||||
CollectionSavePlaceRequest,
|
||||
CollectionPlaceUpdateRequest,
|
||||
CollectionCopyToTripRequest,
|
||||
CollectionPlacesReorderRequest,
|
||||
CollectionInviteRequest,
|
||||
CollectionLabelCreateRequest,
|
||||
CollectionLabelUpdateRequest,
|
||||
@@ -445,7 +447,7 @@ export class CollectionsMcp {
|
||||
@Tool({
|
||||
name: 'copy_collection_places_to_trip',
|
||||
description:
|
||||
'Copy one or more saved collection places into a trip (dedup precheck on the server). Ratings (#1435) travel into the trip; trip members keep voting there. Requires edit access to the target trip.',
|
||||
"Copy one or more saved collection places into a trip (dedup precheck on the server). Ratings (#1435) travel into the trip; trip members keep voting there. A saved place's notes and tags stay in the list unless asked for: include_notes: true copies the notes, tag_ids names the tags (of those the places carry) to bring, each as a tag of the trip, reusing a trip tag of the same name. Without either field, neither is copied. Requires edit access to the target trip.",
|
||||
inputSchema: collectionCopyToTripRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: collectionsAddonOn,
|
||||
@@ -460,6 +462,27 @@ export class CollectionsMcp {
|
||||
}
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'reorder_collection_places',
|
||||
description:
|
||||
"Put a list's saved places in a new order, the order every member sees and get_collection and list_collection_places read. Pass the list's place ids (collection place ids) first to last; places left out follow in the order they had. Every id must be a place of that list. Needs edit rights on the list (owner, admin or editor).",
|
||||
inputSchema: { collectionId: idSchema, ...collectionPlacesReorderRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: collectionsAddonOn,
|
||||
access: { group: 'collections', mode: 'write' },
|
||||
})
|
||||
async reorderCollectionPlaces(
|
||||
{ collectionId, orderedIds }: { collectionId: number } & CollectionPlacesReorderRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
try {
|
||||
await this.collections.reorderPlaces(ctx.userId, collectionId, orderedIds);
|
||||
return ok({ success: true });
|
||||
} catch (err) {
|
||||
return fail(err);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Labels ────────────────────────────────────────────────────────────
|
||||
|
||||
@Tool({
|
||||
|
||||
@@ -31,13 +31,7 @@ import { Tags } from '../../db/entities/Tags.entity';
|
||||
import type { TagsRepository } from '../../db/repositories/Tags.repository';
|
||||
import { Users } from '../../db/entities/Users.entity';
|
||||
import type { UsersRepository } from '../../db/repositories/Users.repository';
|
||||
import {
|
||||
COORD_DEDUP_TOLERANCE,
|
||||
externalIdsOf,
|
||||
isPlaceDuplicate,
|
||||
trackInsertedInDedupSet,
|
||||
type DedupSet,
|
||||
} from '../places/places.helpers';
|
||||
import { COORD_DEDUP_TOLERANCE, isPlaceDuplicate, trackInsertedInDedupSet } from '../places/places.helpers';
|
||||
import {
|
||||
placeMatchStrategies,
|
||||
collectionFilePlaceSchema,
|
||||
@@ -55,6 +49,7 @@ import {
|
||||
type CollectionKmlExport,
|
||||
type CollectionGpxReadRequest,
|
||||
type CollectionGpxReadResult,
|
||||
type CollectionMapReadResult,
|
||||
} from '@trek/shared';
|
||||
import type {
|
||||
Collection,
|
||||
@@ -76,7 +71,9 @@ import type {
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { PlaceImportService, type ExportedCollectionFile } from '../place-import/place-import.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { filePlaceOf, listingWriteOf, parseLinks, serializeLinks } from './collections.helpers';
|
||||
import {
|
||||
filePlaceOf, groupByPid, listingWriteOf, parseLinks, placeOrderOf, serializeLinks, tripDedupSet, tripPlaceFields,
|
||||
} from './collections.helpers';
|
||||
|
||||
// Errors: a DomainError carrying a status; TrekExceptionFilter maps it to that code with an `{ error }` body.
|
||||
|
||||
@@ -190,13 +187,7 @@ export class CollectionsService {
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private async loadTagsByCollectionPlaceIds(placeIds: number[]): Promise<Record<number, { id: number; name: string; color: string }[]>> {
|
||||
const out: Record<number, { id: number; name: string; color: string }[]> = {};
|
||||
const rows = await this.collectionsRepo.loadTagsByPlaceIds(placeIds);
|
||||
for (const r of rows) {
|
||||
if (!out[r.pid]) out[r.pid] = [];
|
||||
out[r.pid].push({ id: r.id, name: r.name, color: r.color });
|
||||
}
|
||||
return out;
|
||||
return groupByPid(await this.collectionsRepo.loadTagsByPlaceIds(placeIds), r => ({ id: r.id, name: r.name, color: r.color }));
|
||||
}
|
||||
|
||||
/** A list's own label definitions, in display order. */
|
||||
@@ -206,24 +197,12 @@ export class CollectionsService {
|
||||
|
||||
/** Assigned label ids per place, batched (mirrors loadTagsByCollectionPlaceIds). */
|
||||
private async loadLabelIdsByPlaceIds(placeIds: number[]): Promise<Record<number, number[]>> {
|
||||
const out: Record<number, number[]> = {};
|
||||
const rows = await this.collectionsRepo.loadLabelIdsByPlaceIds(placeIds);
|
||||
for (const r of rows) {
|
||||
if (!out[r.pid]) out[r.pid] = [];
|
||||
out[r.pid].push(r.label_id);
|
||||
}
|
||||
return out;
|
||||
return groupByPid(await this.collectionsRepo.loadLabelIdsByPlaceIds(placeIds), r => r.label_id);
|
||||
}
|
||||
|
||||
/** Per-voter rating rows (#1435), batched (mirrors loadTagsByCollectionPlaceIds). */
|
||||
private async loadRatingsByCollectionPlaceIds(placeIds: number[]): Promise<Record<number, { user_id: number; username: string; avatar: string | null; rating: number }[]>> {
|
||||
const out: Record<number, { user_id: number; username: string; avatar: string | null; rating: number }[]> = {};
|
||||
const rows = await this.collectionsRepo.loadRatingsByPlaceIds(placeIds);
|
||||
for (const { pid, ...rest } of rows) {
|
||||
if (!out[pid]) out[pid] = [];
|
||||
out[pid].push(rest);
|
||||
}
|
||||
return out;
|
||||
return groupByPid(await this.collectionsRepo.loadRatingsByPlaceIds(placeIds), ({ pid: _pid, ...vote }) => vote);
|
||||
}
|
||||
|
||||
private async hydratePlaces(rows: PlaceRow[]): Promise<CollectionPlace[]> {
|
||||
@@ -372,6 +351,11 @@ export class CollectionsService {
|
||||
return this.placeImport.readCollectionGpx(body.gpx, body.file_name);
|
||||
}
|
||||
|
||||
/** A KML or KMZ upload read the same way (PLC-22): nothing written, the result goes to an import route. */
|
||||
readCollectionMap(file: Buffer, fileName: string): Promise<CollectionMapReadResult> {
|
||||
return this.placeImport.readCollectionMap(file, fileName);
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a file back as a new list of the caller's own.
|
||||
*
|
||||
@@ -616,6 +600,21 @@ export class CollectionsService {
|
||||
if (moved) this.realtime.broadcastToUser(userId, { type: 'collections:updated', collectionId: moved }, socketId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The list's places in the order its members set by hand (PLC-03), for anyone who may edit it. The whole
|
||||
* list is written 0..n-1 in one transaction, so a first reorder fixes exactly the order asked for, and a
|
||||
* place saved meanwhile by somebody else follows the named ones instead of being dropped.
|
||||
*/
|
||||
async reorderPlaces(userId: number, collectionId: number, orderedIds: number[], socketId?: string): Promise<void> {
|
||||
await this.assertCanEdit(userId, collectionId);
|
||||
await this.uow.transactional(async () => {
|
||||
const order = placeOrderOf(await this.collectionPlaces.idsInOrder(collectionId), orderedIds);
|
||||
if (!order) httpError(400, 'Every place of the order must be in this list, once');
|
||||
await this.collectionPlaces.setSortOrders(collectionId, order);
|
||||
});
|
||||
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Dedup (collection-scoped ports of placeService helpers)
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -709,31 +708,22 @@ export class CollectionsService {
|
||||
// Insert + tags + ratings-copy are one logical write — atomic since the
|
||||
// post-fold quirk pass (the relocation carried them un-transacted).
|
||||
const placeId = await this.uow.transactional(async () => {
|
||||
// source_place_id/source_trip_id are raw client input: kept only when the caller can see that
|
||||
// trip and the place lives in it, else both are stored as null, and only then do the trip's
|
||||
// ratings come along, so nobody harvests votes from a trip they cannot open. R6's two-layer
|
||||
// order: assertCanEdit (the entry guard, above) ran FIRST; the trip-access check (AP1) SECOND.
|
||||
const source = await this.verifiedSource(userId, body.source_trip_id, body.source_place_id);
|
||||
const id = await this.collectionPlaces.insertSavedPlace({
|
||||
collection_id: body.collection_id, owner_id: ownerId, saved_by: userId,
|
||||
name: body.name, description: body.description ?? null, lat: body.lat ?? null, lng: body.lng ?? null, address: body.address ?? null,
|
||||
category_id: body.category_id ?? null, price: body.price ?? null, currency: body.currency ?? null, notes: body.notes ?? null,
|
||||
image_url: body.image_url ?? null, google_place_id: body.google_place_id ?? null, google_ftid: body.google_ftid ?? null,
|
||||
osm_id: body.osm_id ?? null, website: body.website ?? null, phone: body.phone ?? null,
|
||||
status: body.status ?? 'idea', source_trip_id: body.source_trip_id ?? null, source_place_id: body.source_place_id ?? null,
|
||||
links: serializeLinks(body.links),
|
||||
status: body.status ?? 'idea', source_trip_id: source?.tripId ?? null, source_place_id: source?.placeId ?? null,
|
||||
links: serializeLinks(body.links), sort_order: await this.nextPlaceOrder(body.collection_id),
|
||||
});
|
||||
|
||||
await this.attachTags(id, body.tag_ids);
|
||||
// Carry trip ratings ONLY when the caller can actually see the source place.
|
||||
// source_place_id/source_trip_id are raw client input, so verify trip access +
|
||||
// that the place lives in that trip before reading place_ratings — otherwise a
|
||||
// member could harvest co-members' votes on places in trips they cannot access
|
||||
// (mirrors the canAccessTrip gate in saveFromTripPlace). R6's two-layer order:
|
||||
// assertCanEdit (this method's own entry guard, above) ran FIRST; the trip-access
|
||||
// check (AP1) runs SECOND, here, inside the write path — never reversed.
|
||||
if (
|
||||
body.source_place_id && body.source_trip_id &&
|
||||
(await this.trips.findAccessible(body.source_trip_id, userId)) &&
|
||||
(await this.tripPlaces.existsInTrip(body.source_place_id, body.source_trip_id))
|
||||
) {
|
||||
await this.copyTripRatings(body.source_place_id, id, body.collection_id);
|
||||
}
|
||||
if (source) await this.copyTripRatings(source.placeId, id, body.collection_id);
|
||||
return id;
|
||||
});
|
||||
await this.notifyCollectionUsers(body.collection_id, socketId, 'collections:updated');
|
||||
@@ -750,28 +740,21 @@ export class CollectionsService {
|
||||
if (!place) httpError(404, 'Place not found');
|
||||
|
||||
return this.savePlace(userId, {
|
||||
collection_id: collectionId,
|
||||
name: place.name,
|
||||
description: place.description ?? null,
|
||||
lat: place.lat ?? null,
|
||||
lng: place.lng ?? null,
|
||||
address: place.address ?? null,
|
||||
category_id: place.category_id ?? null,
|
||||
price: place.price ?? null,
|
||||
currency: place.currency ?? null,
|
||||
notes: place.notes ?? null,
|
||||
image_url: place.image_url ?? null,
|
||||
google_place_id: place.google_place_id ?? null,
|
||||
google_ftid: place.google_ftid ?? null,
|
||||
osm_id: place.osm_id ?? null,
|
||||
website: place.website ?? null,
|
||||
phone: place.phone ?? null,
|
||||
source_trip_id: tripId,
|
||||
source_place_id: placeId,
|
||||
force,
|
||||
collection_id: collectionId, ...tripPlaceFields(place), source_trip_id: tripId, source_place_id: placeId, force,
|
||||
}, socketId);
|
||||
}
|
||||
|
||||
/** The source a save names, when the caller can open that trip and the place is one of its own; null otherwise. */
|
||||
private async verifiedSource(userId: number, tripId?: number | null, placeId?: number | null) {
|
||||
if (!tripId || !placeId || !(await this.trips.findAccessible(tripId, userId))) return null;
|
||||
return (await this.tripPlaces.existsInTrip(placeId, tripId)) ? { tripId, placeId } : null;
|
||||
}
|
||||
|
||||
/** Where a new place goes in a list: after its last one (PLC-03). Read inside the writing transaction. */
|
||||
private async nextPlaceOrder(collectionId: number): Promise<number> {
|
||||
return (await this.collectionsRepo.maxPlaceSortOrder(collectionId)) + 1;
|
||||
}
|
||||
|
||||
/** The trip's places as offered to the bulk import, each already carrying the verdict
|
||||
* saveFromTripPlaces would reach for it. Reusing findDuplicateCollectionPlace is the
|
||||
* whole point: a row the dialog shows as new can never come back as `skipped`, and a
|
||||
@@ -815,6 +798,7 @@ export class CollectionsService {
|
||||
const skipped: { id: number; name: string }[] = [];
|
||||
// The whole batch is one logical write — atomic since the post-fold quirk pass.
|
||||
await this.uow.transactional(async () => {
|
||||
let sortOrder = await this.nextPlaceOrder(collectionId);
|
||||
for (const placeId of placeIds) {
|
||||
const p = await this.tripPlaces.findInTrip(placeId, tripId);
|
||||
if (!p) continue;
|
||||
@@ -834,17 +818,10 @@ export class CollectionsService {
|
||||
skipped.push({ id: placeId, name });
|
||||
continue;
|
||||
}
|
||||
// Same 22-column insert shape as `savePlace` (CL42), with `status`/`links`
|
||||
// hardcoded ('idea'/null) exactly the way the legacy statement bound them
|
||||
// as literals rather than placeholders — see `insertSavedPlace`'s own
|
||||
// docstring for why this is the SAME method, not a second insert shape.
|
||||
// savePlace's insert (CL42), with `status`/`links` as the legacy literals ('idea'/null).
|
||||
const newId = await this.collectionPlaces.insertSavedPlace({
|
||||
collection_id: collectionId, owner_id: ownerId, saved_by: userId,
|
||||
name, description: p.description ?? null, lat, lng, address: p.address ?? null,
|
||||
category_id: p.category_id ?? null, price: p.price ?? null, currency: p.currency ?? null, notes: p.notes ?? null,
|
||||
image_url: p.image_url ?? null, google_place_id: p.google_place_id ?? null, google_ftid: p.google_ftid ?? null,
|
||||
osm_id: p.osm_id ?? null, website: p.website ?? null, phone: p.phone ?? null,
|
||||
status: 'idea', source_trip_id: tripId, source_place_id: placeId, links: null,
|
||||
collection_id: collectionId, owner_id: ownerId, saved_by: userId, ...tripPlaceFields(p),
|
||||
status: 'idea', source_trip_id: tripId, source_place_id: placeId, links: null, sort_order: sortOrder++,
|
||||
});
|
||||
await this.copyTripRatings(placeId, newId, collectionId);
|
||||
copied++;
|
||||
@@ -882,6 +859,7 @@ export class CollectionsService {
|
||||
|
||||
// Field update + tag rewrite + label rewrite are one logical write, so one transaction.
|
||||
await this.uow.transactional(async () => {
|
||||
if (movedTo) write.sort_order = await this.nextPlaceOrder(movedTo); // a moved place joins the end of its new list
|
||||
await this.collectionPlaces.updateFields(placeId, write);
|
||||
|
||||
if (body.tag_ids !== undefined) {
|
||||
@@ -1084,19 +1062,21 @@ export class CollectionsService {
|
||||
sources.push(row);
|
||||
}
|
||||
|
||||
// The importers' dedup set: a place renamed in the trip is still known by its provider id (#1550).
|
||||
const existing = await this.tripPlaces.dedupCandidatesForTrip(body.trip_id);
|
||||
const dedup: DedupSet = { names: new Set(), coords: [], externalIds: new Set() };
|
||||
for (const r of existing) {
|
||||
for (const id of externalIdsOf(r)) dedup.externalIds.add(id);
|
||||
if (r.name) dedup.names.add(r.name.trim().toLowerCase());
|
||||
else if (r.lat != null && r.lng != null) dedup.coords.push({ lat: r.lat, lng: r.lng });
|
||||
}
|
||||
const dedup = tripDedupSet(await this.tripPlaces.dedupCandidatesForTrip(body.trip_id));
|
||||
// D9: only the tags asked for, where the saved place carries them, and as tags of the trip, never the person's own.
|
||||
const asked = new Set(body.tag_ids ?? []);
|
||||
const carried = asked.size
|
||||
? groupByPid((await this.collectionsRepo.loadTagsByPlaceIds(sources.map(s => s.id))).filter(t => asked.has(t.id)), t => t)
|
||||
: null;
|
||||
const tripTags = new Map<string, number>(); // by name, read in the transaction that adds to them
|
||||
let tagsBefore = 0;
|
||||
|
||||
const created: CollectionCopyToTripResponse['created'] = []; // each new trip place by the saved place it came from
|
||||
const skipped: { id: number; name: string }[] = [];
|
||||
// The whole copy is one logical write — atomic since the post-fold quirk pass.
|
||||
await this.uow.transactional(async () => {
|
||||
if (carried) for (const t of await this.tags.listByTrip(body.trip_id)) tripTags.set(t.name.trim().toLowerCase(), t.id);
|
||||
tagsBefore = tripTags.size;
|
||||
for (const s of sources) {
|
||||
if (!body.force && isPlaceDuplicate({
|
||||
name: s.name, lat: s.lat, lng: s.lng,
|
||||
@@ -1109,11 +1089,11 @@ export class CollectionsService {
|
||||
const newPlaceId = await this.tripPlaces.insertFromCollectionPlace({
|
||||
trip_id: body.trip_id, name: s.name, description: s.description, lat: s.lat, lng: s.lng,
|
||||
address: s.address, category_id: s.category_id, price: s.price, currency: s.currency,
|
||||
notes: s.notes, image_url: s.image_url, google_place_id: s.google_place_id, google_ftid: s.google_ftid,
|
||||
notes: body.include_notes === true ? s.notes : null, // a note stays in the list unless asked for (D9)
|
||||
image_url: s.image_url, google_place_id: s.google_place_id, google_ftid: s.google_ftid,
|
||||
website: s.website, phone: s.phone, osm_id: s.osm_id,
|
||||
});
|
||||
const tagIds = await this.collectionPlaces.tagIdsFor(s.id);
|
||||
await this.tags.insertIgnore(newPlaceId, tagIds);
|
||||
await this.tags.insertIgnore(newPlaceId, await this.tripTagIds(body.trip_id, userId, carried?.[s.id] ?? [], tripTags));
|
||||
// Ratings of trip members travel along (#1435); nothing is mirrored back.
|
||||
const votes = await this.collectionPlaceRatings.listForPlace(s.id);
|
||||
for (const v of votes) if (tripMemberIds.has(v.user_id)) await this.tripPlaceRatings.insertIgnore(newPlaceId, v.user_id, v.rating);
|
||||
@@ -1121,6 +1101,7 @@ export class CollectionsService {
|
||||
created.push({ id: newPlaceId, source_id: s.id });
|
||||
}
|
||||
});
|
||||
if (tripTags.size > tagsBefore) events.emit('tripTags:changed', {});
|
||||
const rows = await Promise.all(created.map(({ id }) => this.tripPlaces.findWithTagsAndRatings(id))); // reads only
|
||||
for (const [i, place] of rows.entries()) {
|
||||
if (place) events.emit('place:created', { place }); // as the place routes send it
|
||||
@@ -1129,6 +1110,17 @@ export class CollectionsService {
|
||||
return { copied: created.length, skipped, created };
|
||||
}
|
||||
|
||||
/** The trip's own tag of each name: the one it has, or one made now; `known` keeps the new ones for the next place. */
|
||||
private async tripTagIds(tripId: number, userId: number, tags: { name: string; color: string }[], known: Map<string, number>): Promise<number[]> {
|
||||
const ids: number[] = [];
|
||||
for (const { name, color } of tags) {
|
||||
const key = name.trim().toLowerCase();
|
||||
if (!known.has(key)) known.set(key, (await this.tags.createTag({ user_id: userId, trip_id: tripId, name: name.trim(), color })).id);
|
||||
ids.push(known.get(key)!);
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
// Library-wide membership lookup (inspector indicator)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { PlaceImportService } from './place-import.service';
|
||||
import { CollectionGpxProvider } from './providers/collection-gpx.provider';
|
||||
import { CollectionKmlProvider } from './providers/collection-kml.provider';
|
||||
import { GoogleDirectionsProvider } from './providers/google-directions.provider';
|
||||
import { GoogleListProvider } from './providers/google-list.provider';
|
||||
import { GoogleMapsShortLinkProvider } from './providers/google-maps-short-link.provider';
|
||||
@@ -24,6 +25,7 @@ import { Module } from '@nestjs/common';
|
||||
GpxProvider,
|
||||
CollectionGpxProvider,
|
||||
KmlProvider,
|
||||
CollectionKmlProvider,
|
||||
GoogleListProvider,
|
||||
GoogleDirectionsProvider,
|
||||
NaverListProvider,
|
||||
|
||||
@@ -12,6 +12,7 @@ import type {
|
||||
ShortLinkOutcome,
|
||||
} from './place-import.types';
|
||||
import { CollectionGpxProvider, type ExportedCollectionFile } from './providers/collection-gpx.provider';
|
||||
import { CollectionKmlProvider } from './providers/collection-kml.provider';
|
||||
import { GoogleDirectionsProvider } from './providers/google-directions.provider';
|
||||
import { GoogleListProvider } from './providers/google-list.provider';
|
||||
import { GoogleMapsShortLinkProvider } from './providers/google-maps-short-link.provider';
|
||||
@@ -25,7 +26,12 @@ import {
|
||||
import { KmlProvider } from './providers/kml.provider';
|
||||
import { NaverListProvider } from './providers/naver-list.provider';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { CollectionGpxExport, CollectionGpxReadResult, CollectionKmlExport } from '@trek/shared';
|
||||
import type {
|
||||
CollectionGpxExport,
|
||||
CollectionGpxReadResult,
|
||||
CollectionKmlExport,
|
||||
CollectionMapReadResult,
|
||||
} from '@trek/shared';
|
||||
|
||||
// The directions-link reading is also what the road trip planner reads a
|
||||
// shared route with, what the import routes dispatch on, and what the city
|
||||
@@ -61,6 +67,7 @@ export class PlaceImportService {
|
||||
private readonly gpx: GpxProvider,
|
||||
private readonly collectionGpx: CollectionGpxProvider,
|
||||
private readonly kml: KmlProvider,
|
||||
private readonly collectionKml: CollectionKmlProvider,
|
||||
private readonly googleList: GoogleListProvider,
|
||||
private readonly googleDirections: GoogleDirectionsProvider,
|
||||
private readonly naverList: NaverListProvider,
|
||||
@@ -131,6 +138,11 @@ export class PlaceImportService {
|
||||
return this.kml.tripFilename(tripTitle);
|
||||
}
|
||||
|
||||
/** A .kml or .kmz upload as the list file it amounts to (PLC-22). Throws CollectionMapError on a refusal. */
|
||||
readCollectionMap(fileBuffer: Buffer, fileName: string): Promise<CollectionMapReadResult> {
|
||||
return this.collectionKml.read(fileBuffer, fileName);
|
||||
}
|
||||
|
||||
/** A list file as KML pins for Google My Maps (#1866). */
|
||||
writeCollectionKml(file: ExportedCollectionFile): CollectionKmlExport {
|
||||
return this.kml.writeCollection(file);
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
* insert, track colours, enrichment) stays with the domain that owns the rows,
|
||||
* PlacesService for a trip and CollectionsService for a list.
|
||||
*/
|
||||
import type { CollectionGpxProblem } from '@trek/shared';
|
||||
import type { CollectionGpxProblem, CollectionMapProblem } from '@trek/shared';
|
||||
|
||||
/** One place parsed out of a GPX file, not yet persisted. */
|
||||
export interface PreparedGpxPlace {
|
||||
@@ -155,6 +155,17 @@ export class CollectionGpxError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
/** Why a KML or KMZ file was refused for a list (PLC-22), carried to the controller as the response's `code`. */
|
||||
export class CollectionMapError extends Error {
|
||||
constructor(
|
||||
readonly code: CollectionMapProblem,
|
||||
message: string,
|
||||
) {
|
||||
super(message);
|
||||
this.name = 'CollectionMapError';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CW-06: where a Google Maps short link led. `refused` when a hop or the
|
||||
* landing link is not one the walk import may follow or read, `unreachable`
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* A KML or KMZ map (Google My Maps, Google Earth) read into the list file it
|
||||
* amounts to (PLC-22), the way a GPX is: nothing is written here, the file
|
||||
* goes back to the browser and comes in again through the list import, so a
|
||||
* map passes the same contract and the same one transaction as any list file.
|
||||
*
|
||||
* A list holds points. A placemark with a line or an area, or with no
|
||||
* geometry at all, is reported with its reason instead of being guessed into
|
||||
* a pin. Each place keeps the folder it sat in beside the file, for a later
|
||||
* mapping onto categories or labels; nothing reads it yet.
|
||||
*/
|
||||
import { CollectionMapError, KmlReadError, type KmlDocumentRead, type ParsedKmlPlacemark } from '../place-import.types';
|
||||
import { KmlProvider } from './kml.provider';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
COLLECTION_FILE_FORMAT,
|
||||
COLLECTION_FILE_VERSION,
|
||||
MAX_COLLECTION_FILE_BYTES,
|
||||
MAX_COLLECTION_FILE_PLACES,
|
||||
collectionFilePlaceSchema,
|
||||
type CollectionFilePlace,
|
||||
type CollectionMapReadResult,
|
||||
type CollectionMapSkipReason,
|
||||
} from '@trek/shared';
|
||||
|
||||
import path from 'path';
|
||||
|
||||
const MAP_EXTENSIONS = new Set(['.kml', '.kmz']);
|
||||
|
||||
/** The list's name: the file's own name without its extension, or a plain one when that is empty. */
|
||||
function listNameOf(fileName: string): string {
|
||||
return (
|
||||
path
|
||||
.basename(fileName)
|
||||
.replace(/\.km[lz]$/i, '')
|
||||
.trim()
|
||||
.slice(0, 120) || 'KML import'
|
||||
);
|
||||
}
|
||||
|
||||
/** Why a placemark cannot be a place of a list, or null for a pin. */
|
||||
function reasonToLeaveOut(placemark: ParsedKmlPlacemark): CollectionMapSkipReason | null {
|
||||
if (placemark.routeGeometry !== null) return 'line';
|
||||
if (placemark.lat === null || placemark.lng === null) return 'no_point';
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The placemarks of a read map as a list file, every one left out named with its reason. */
|
||||
export function kmlToCollectionFile(read: KmlDocumentRead, fileName: string): CollectionMapReadResult {
|
||||
const places: CollectionFilePlace[] = [];
|
||||
const folders: Array<string | null> = [];
|
||||
const skipped: CollectionMapReadResult['skipped'] = [];
|
||||
for (const [index, placemark] of read.placemarks.entries()) {
|
||||
const folder = placemark.folderName ?? null;
|
||||
const place =
|
||||
reasonToLeaveOut(placemark) ??
|
||||
collectionFilePlaceSchema.safeParse({
|
||||
// Unnamed pins are numbered by their place in the document, as the trip import names them.
|
||||
name: (placemark.name || `Placemark ${index + 1}`).slice(0, 500),
|
||||
description: placemark.description ? placemark.description.slice(0, 5000) : null,
|
||||
lat: placemark.lat,
|
||||
lng: placemark.lng,
|
||||
});
|
||||
if (typeof place === 'string' || !place.success) {
|
||||
skipped.push({ name: placemark.name, folder, reason: typeof place === 'string' ? place : 'invalid' });
|
||||
continue;
|
||||
}
|
||||
places.push(place.data);
|
||||
folders.push(folder);
|
||||
}
|
||||
|
||||
if (places.length > MAX_COLLECTION_FILE_PLACES) {
|
||||
throw new CollectionMapError('too-many-places', `That map file has more than ${MAX_COLLECTION_FILE_PLACES} places`);
|
||||
}
|
||||
const file = {
|
||||
format: COLLECTION_FILE_FORMAT,
|
||||
version: COLLECTION_FILE_VERSION,
|
||||
name: listNameOf(fileName),
|
||||
places,
|
||||
} as const;
|
||||
// What comes back has to fit the import's body again, which takes a list file of this size.
|
||||
if (Buffer.byteLength(JSON.stringify(file), 'utf8') > MAX_COLLECTION_FILE_BYTES) {
|
||||
throw new CollectionMapError('too-large', 'That map file holds more text than a list file can take');
|
||||
}
|
||||
return { file, folders, skipped };
|
||||
}
|
||||
|
||||
/** KML and KMZ for lists: the trip import's reader (and its KMZ size cap), its placemarks as a list file. */
|
||||
@Injectable()
|
||||
export class CollectionKmlProvider {
|
||||
constructor(private readonly kml: KmlProvider) {}
|
||||
|
||||
async read(fileBuffer: Buffer, fileName: string): Promise<CollectionMapReadResult> {
|
||||
if (!MAP_EXTENSIONS.has(path.extname(fileName).toLowerCase())) {
|
||||
throw new CollectionMapError('not-map', 'Please upload a .kml or .kmz file');
|
||||
}
|
||||
let read: KmlDocumentRead;
|
||||
try {
|
||||
read = await this.kml.readMapFile(fileBuffer, fileName);
|
||||
} catch (err) {
|
||||
if (!(err instanceof KmlReadError)) throw err;
|
||||
throw new CollectionMapError(err.reason === 'archive_too_large' ? 'too-large' : 'unreadable', err.message);
|
||||
}
|
||||
return kmlToCollectionFile(read, fileName);
|
||||
}
|
||||
}
|
||||
@@ -49,6 +49,9 @@ export { MAX_DASHBOARD_TIMEZONES };
|
||||
* refusal it can act on instead of parking 'kelvin' in a row the client then
|
||||
* silently ignores.
|
||||
*/
|
||||
/** A display switch the client keeps as true or false. */
|
||||
const onOff = z.boolean();
|
||||
|
||||
const DISPLAY_PREFERENCES = {
|
||||
start_page: z.enum(['dashboard', 'active_trip']),
|
||||
// The planner falls back to its plan view for a tab that does not exist, and
|
||||
@@ -79,11 +82,13 @@ const DISPLAY_PREFERENCES = {
|
||||
// path accepts, and refusing them here would make a value TREK itself wrote
|
||||
// unwritable through this tool.
|
||||
dark_mode: z.union([z.enum(['light', 'dark', 'auto']), z.boolean()]),
|
||||
map_booking_labels: z.boolean(),
|
||||
map_always_show_routes: z.boolean(),
|
||||
map_poi_pill_enabled: z.boolean(),
|
||||
blur_booking_codes: z.boolean(),
|
||||
optimize_from_accommodation: z.boolean(),
|
||||
map_booking_labels: onOff,
|
||||
// The names of a trip's places beside their pins on the trip map (PLC-05).
|
||||
map_place_labels: onOff,
|
||||
map_always_show_routes: onOff,
|
||||
map_poi_pill_enabled: onOff,
|
||||
blur_booking_codes: onOff,
|
||||
optimize_from_accommodation: onOff,
|
||||
// The dashboard world clocks (#3044). [] is a valid choice and shows none;
|
||||
// leaving the key unset keeps the widget's own fallback list.
|
||||
dashboard_timezones: dashboardTimezonesSchema,
|
||||
|
||||
Reference in New Issue
Block a user