Files
TREK/server/tests/unit/nest/place-import/collection-kml.provider.test.ts
Maurice 82165855c7 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.
2026-11-29 14:57:00 +01:00

127 lines
6.6 KiB
TypeScript

/**
* PLC-22: a KML or KMZ map read into a list file. Pins become places, a line,
* an area or a placemark without geometry is named with its reason, each
* place keeps its folder beside the file, and a refusal carries the code the
* client translates. Nothing here touches a table.
*/
import { CollectionMapError } from '../../../../src/nest/place-import/place-import.types';
import {
CollectionKmlProvider,
kmlToCollectionFile,
} from '../../../../src/nest/place-import/providers/collection-kml.provider';
import { KmlProvider } from '../../../../src/nest/place-import/providers/kml.provider';
import { buildPlaceImportService } from '../../../helpers/place-import';
import { COLLECTION_FILE_FORMAT, collectionFilePlaceSchema, MAX_COLLECTION_FILE_PLACES } from '@trek/shared';
import archiver from 'archiver';
import { PassThrough } from 'stream';
import { describe, expect, it } from 'vitest';
const KML = `<?xml version="1.0"?><kml xmlns="http://www.opengis.net/kml/2.2"><Document><name>Lisbon</name>
<Placemark><name>Rossio</name><description>The square</description><Point><coordinates>-9.14,38.71</coordinates></Point></Placemark>
<Folder><name>Views</name>
<Placemark><name>Miradouro</name><Point><coordinates>-9.13,38.72,0</coordinates></Point></Placemark>
<Placemark><Point><coordinates>-9.15,38.70</coordinates></Point></Placemark>
<Placemark><name>Tram 28</name><LineString><coordinates>-9.14,38.71 -9.13,38.72</coordinates></LineString></Placemark>
<Placemark><name>Park</name><Polygon><outerBoundaryIs><LinearRing><coordinates>-9.1,38.7 -9.2,38.7 -9.2,38.8 -9.1,38.7</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>
</Folder>
<Placemark><name>Nowhere</name></Placemark>
<Placemark><name>Off the map</name><Point><coordinates>-9.1,95</coordinates></Point></Placemark>
</Document></kml>`;
/** A KMZ archive holding these entries. */
async function kmz(entries: Record<string, string>): Promise<Buffer> {
const chunks: Buffer[] = [];
const output = new PassThrough();
output.on('data', (chunk: Buffer) => chunks.push(chunk));
const archive = archiver('zip', { zlib: { level: 1 } });
archive.pipe(output);
for (const [name, content] of Object.entries(entries)) archive.append(Buffer.from(content), { name });
await archive.finalize();
return Buffer.concat(chunks);
}
/** The code of the refusal a read ends in. */
async function refusal(read: Promise<unknown>): Promise<string> {
try {
await read;
} catch (err) {
if (err instanceof CollectionMapError) return err.code;
throw err;
}
throw new Error('expected a refusal');
}
describe('CollectionKmlProvider.read', () => {
const provider = new CollectionKmlProvider(new KmlProvider());
it('COLLECTION-KML-001: pins become places with their folder, everything else is named with its reason', async () => {
const read = await provider.read(Buffer.from(KML), 'Lisbon trip.kml');
expect(read.file).toMatchObject({ format: COLLECTION_FILE_FORMAT, version: 1, name: 'Lisbon trip' });
// A level's own placemarks come before its folders', as the trip import reads them.
expect(read.file.places).toEqual([
{ name: 'Rossio', description: 'The square', lat: 38.71, lng: -9.14, status: 'idea' },
{ name: 'Miradouro', description: null, lat: 38.72, lng: -9.13, status: 'idea' },
// An unnamed pin is numbered by where it stands among the placemarks, as the trip import names it.
{ name: 'Placemark 5', description: null, lat: 38.7, lng: -9.15, status: 'idea' },
]);
expect(read.folders).toEqual([null, 'Views', 'Views']);
expect(read.skipped).toEqual([
{ name: 'Nowhere', folder: null, reason: 'no_point' },
{ name: 'Off the map', folder: null, reason: 'invalid' },
{ name: 'Tram 28', folder: 'Views', reason: 'line' },
{ name: 'Park', folder: 'Views', reason: 'no_point' },
]);
// Each place passes the contract the import applies to it again.
for (const place of read.file.places) expect(collectionFilePlaceSchema.safeParse(place).success).toBe(true);
});
it('COLLECTION-KML-002: a KMZ is unpacked by its extension and read the same way', async () => {
const archive = await kmz({ 'doc.kml': KML, 'images/pin.png': 'png' });
const read = await provider.read(archive, 'Lisbon.KMZ');
expect(read.file.name).toBe('Lisbon');
expect(read.file.places.map((p) => (p as { name: string }).name)).toEqual(['Rossio', 'Miradouro', 'Placemark 5']);
});
it('COLLECTION-KML-003: another file type, a broken document and an archive without KML are refused with their code', async () => {
expect(await refusal(provider.read(Buffer.from(KML), 'lisbon.gpx'))).toBe('not-map');
expect(await refusal(provider.read(Buffer.from('<kml><Document>'), 'broken.kml'))).toBe('unreadable');
expect(await refusal(provider.read(await kmz({ 'photo.jpg': 'jpeg' }), 'photos.kmz'))).toBe('unreadable');
expect(await refusal(provider.read(Buffer.from('not a zip'), 'broken.kmz'))).toBe('unreadable');
});
it('COLLECTION-KML-004: reaches the place import service as readCollectionMap', async () => {
const read = await buildPlaceImportService().readCollectionMap(Buffer.from(KML), 'map.kml');
expect(read.file.places).toHaveLength(3);
});
});
describe('kmlToCollectionFile', () => {
const summary = { totalPlacemarks: 0, createdCount: 0, skippedCount: 0, warnings: [], errors: [] };
const pin = (name: string) => ({ name, description: null, lat: 1, lng: 2, folderName: null, routeGeometry: null });
it(`COLLECTION-KML-005: more than ${MAX_COLLECTION_FILE_PLACES} pins are refused rather than cut`, () => {
const placemarks = Array.from({ length: MAX_COLLECTION_FILE_PLACES + 1 }, (_, i) => pin(`Pin ${i}`));
expect(() => kmlToCollectionFile({ placemarks, summary }, 'big.kml')).toThrow(CollectionMapError);
});
it('COLLECTION-KML-006: a file whose places would not fit the import body again is refused as too large', () => {
const long = 'x'.repeat(5000);
const placemarks = Array.from({ length: 300 }, (_, i) => ({ ...pin(`Pin ${i}`), description: long }));
try {
kmlToCollectionFile({ placemarks, summary }, 'long.kml');
expect.unreachable('expected a refusal');
} catch (err) {
expect((err as CollectionMapError).code).toBe('too-large');
}
});
it('COLLECTION-KML-007: a file name without a usable name gives the list a plain one, a long one is cut', () => {
expect(kmlToCollectionFile({ placemarks: [], summary }, '.kml').file.name).toBe('KML import');
expect(kmlToCollectionFile({ placemarks: [], summary }, `${'a'.repeat(200)}.kml`).file.name).toHaveLength(120);
});
});