diff --git a/server/tests/unit/nest/addons.service.test.ts b/server/tests/unit/nest/addons.service.test.ts index a12a8eeec..4b69e2dba 100644 --- a/server/tests/unit/nest/addons.service.test.ts +++ b/server/tests/unit/nest/addons.service.test.ts @@ -14,6 +14,7 @@ const { getPhotoProviderConfig } = vi.hoisted(() => ({ getPhotoProviderConfig: v vi.mock('../../../src/nest/memories/memories.helpers', () => ({ getPhotoProviderConfig })); import { AddonsService } from '../../../src/nest/addons/addons.service'; +import { PlaceShadowService } from '../../../src/nest/place-shadow/place-shadow.service'; function svc() { return new AddonsService(new DatabaseService(dbConn)); @@ -482,3 +483,86 @@ describe('AddonsService transit provider', () => { expect(svc().getTransitProvider(7).googleKeySource).toBeNull(); }); }); + +/** + * The shadow log reads fail-CLOSED like the three flags above, for the opposite + * reason: they need `=== 'true'` because a migration backfilled a row for + * installs that were already using the feature. Nothing writes this key on + * upgrade, so an absent row genuinely means off. It has to keep agreeing with + * PlaceShadowService.enabled(), which reads the same key itself — if the two + * diverge the admin panel shows "off" while the log keeps collecting picks. + */ +describe('AddonsService place shadow flag', () => { + beforeEach(() => { + vi.clearAllMocks(); + }); + + it('ADDONS-SVC-090 an unset flag reads as OFF, and so does every value but the literal "true"', () => { + dbMock._stmt.get.mockReturnValueOnce(undefined); + expect(svc().getPlaceShadow()).toEqual({ enabled: false }); + expect(dbMock.prepare).toHaveBeenLastCalledWith('SELECT value FROM app_settings WHERE key = ?'); + expect(dbMock._stmt.get).toHaveBeenLastCalledWith('place_shadow_enabled'); + + for (const value of ['false', 'TRUE', '1', '']) { + dbMock._stmt.get.mockReturnValueOnce({ value }); + expect(svc().getPlaceShadow()).toEqual({ enabled: false }); + } + }); + + it('ADDONS-SVC-091 a stored "true" reads as ON', () => { + dbMock._stmt.get.mockReturnValueOnce({ value: 'true' }); + expect(svc().getPlaceShadow()).toEqual({ enabled: true }); + }); + + it('ADDONS-SVC-092 the setter round-trips through the getter under its own key', () => { + // Keyed store instead of an echo assertion: the write has to produce the + // exact string the read compares against, so a setter persisting '1' fails + // here rather than silently reading back OFF in production. + const stored = new Map(); + dbMock._stmt.run.mockImplementation((key: string, value: string) => { + stored.set(key, value); + }); + dbMock._stmt.get.mockImplementation((key: string) => { + const value = stored.get(key); + return value === undefined ? undefined : { value }; + }); + + expect(svc().updatePlaceShadow(true)).toEqual({ enabled: true }); + expect(dbMock._stmt.run).toHaveBeenLastCalledWith('place_shadow_enabled', 'true'); + expect(svc().getPlaceShadow()).toEqual({ enabled: true }); + // a sibling switch must not ride along on the shared statement + expect(svc().getPlacesDetails()).toEqual({ enabled: false }); + + expect(svc().updatePlaceShadow(false)).toEqual({ enabled: false }); + expect(dbMock._stmt.run).toHaveBeenLastCalledWith('place_shadow_enabled', 'false'); + expect(svc().getPlaceShadow()).toEqual({ enabled: false }); + expect([...stored.keys()]).toEqual(['place_shadow_enabled']); + }); + + it('ADDONS-SVC-093 answers the same as PlaceShadowService.enabled() for every stored value', () => { + const shadow = new PlaceShadowService(new DatabaseService(dbConn)); + const rows: Array<[{ value: string } | undefined, boolean]> = [ + [undefined, false], + [{ value: 'true' }, true], + [{ value: 'false' }, false], + [{ value: 'garbage' }, false], + ]; + + for (const [row, expected] of rows) { + // one read for the admin getter, one for the service that gates the log + dbMock._stmt.get.mockReturnValueOnce(row).mockReturnValueOnce(row); + + // The shared statement hands both readers this row whatever they ask for, + // so the key each one names has to be asserted too: the getter binds it, + // the gate inlines it, and a divergence there would still look like + // agreement on the value alone. + expect(svc().getPlaceShadow()).toEqual({ enabled: expected }); + expect(dbMock._stmt.get).toHaveBeenLastCalledWith('place_shadow_enabled'); + + expect(shadow.enabled()).toBe(expected); + expect(dbMock.prepare).toHaveBeenLastCalledWith( + "SELECT value FROM app_settings WHERE key = 'place_shadow_enabled'", + ); + } + }); +}); diff --git a/server/tests/unit/nest/admin.controller.test.ts b/server/tests/unit/nest/admin.controller.test.ts index c39fbddd7..fb420fa73 100644 --- a/server/tests/unit/nest/admin.controller.test.ts +++ b/server/tests/unit/nest/admin.controller.test.ts @@ -42,6 +42,9 @@ const addonsStub = () => ({ updatePlacesAutocomplete: vi.fn((enabled: boolean) => ({ enabled })), getPlacesDetails: vi.fn(() => ({ enabled: false })), updatePlacesDetails: vi.fn((enabled: boolean) => ({ enabled })), + // Fail-closed with nothing to backfill — see AddonsService.getPlaceShadow. + getPlaceShadow: vi.fn(() => ({ enabled: false })), + updatePlaceShadow: vi.fn((enabled: boolean) => ({ enabled })), // Fail-open, unlike its three neighbours — see AddonsService.getPlacesEnrich. getPlacesEnrich: vi.fn(() => ({ enabled: true })), updatePlacesEnrich: vi.fn((enabled: boolean) => ({ enabled })), @@ -255,6 +258,7 @@ describe('AdminController feature toggles', () => { [() => c.updatePlacesPhotos(user, { enabled: true }, req), 'admin.places_photos', 'updatePlacesPhotos'], [() => c.updatePlacesAutocomplete(user, { enabled: true }, req), 'admin.places_autocomplete', 'updatePlacesAutocomplete'], [() => c.updatePlacesDetails(user, { enabled: true }, req), 'admin.places_details', 'updatePlacesDetails'], + [() => c.updatePlaceShadow(user, { enabled: true }, req), 'admin.place_shadow', 'updatePlaceShadow'], ]; for (const [run, action, method] of cases) { writeAudit.mockClear(); @@ -270,6 +274,7 @@ describe('AdminController feature toggles', () => { expect(c.getPlacesPhotos()).toEqual({ enabled: false }); expect(c.getPlacesAutocomplete()).toEqual({ enabled: false }); expect(c.getPlacesDetails()).toEqual({ enabled: false }); + expect(c.getPlaceShadow()).toEqual({ enabled: false }); expect(c.getPlacesEnrich()).toEqual({ enabled: true }); expect(c.getCollabFeatures()).toEqual({ chat: false }); }); @@ -294,6 +299,28 @@ describe('AdminController feature toggles', () => { ); }); + it('ADMIN-TOGGLE-004 place-shadow forwards the body value and audits the stored one', () => { + // The handler audits result.enabled. A service that declines the flip must + // not leave behind an audit row claiming the shadow log was switched on. + const updatePlaceShadow = vi.fn(() => ({ enabled: false })); + const c = adminCtl(svc(), undefined, { ...addonsStub(), updatePlaceShadow } as unknown as AddonsService); + expect(c.updatePlaceShadow(user, { enabled: true }, req)).toEqual({ enabled: false }); + expect(updatePlaceShadow).toHaveBeenCalledWith(true); + expect(writeAudit).toHaveBeenCalledWith({ userId: user.id, action: 'admin.place_shadow', ip: '1.2.3.4', details: { enabled: false } }); + // Off is carried too: the table above only ever asks for true, so a handler + // that hardcoded the argument would pass it. + c.updatePlaceShadow(user, { enabled: false }, req); + expect(updatePlaceShadow).toHaveBeenLastCalledWith(false); + }); + + it('ADMIN-TOGGLE-004b place-shadow reads through to AddonsService instead of a controller-side default', () => { + const getPlaceShadow = vi.fn(() => ({ enabled: true })); + const c = adminCtl(svc(), undefined, { ...addonsStub(), getPlaceShadow } as unknown as AddonsService); + expect(c.getPlaceShadow()).toEqual({ enabled: true }); + expect(getPlaceShadow).toHaveBeenCalledTimes(1); + expect(writeAudit).not.toHaveBeenCalled(); + }); + it('ADMIN-TOGGLE-003 collab-features invalidates MCP sessions only when a flag flipped (#1414)', () => { const invalidateMcpSessions = vi.fn(); const c = adminCtl(svc({ invalidateMcpSessions } as Partial)); diff --git a/server/tests/unit/nest/auth.service.test.ts b/server/tests/unit/nest/auth.service.test.ts index 5e570429f..d568c9922 100644 --- a/server/tests/unit/nest/auth.service.test.ts +++ b/server/tests/unit/nest/auth.service.test.ts @@ -646,6 +646,22 @@ describe('getAppConfig', () => { expect(svc.getAppConfig(null).passkey_configured).toBe(false); vi.unstubAllEnvs(); }); + + it('AUTH-DB-052g: place_shadow_enabled fails closed, on the unauthenticated payload', () => { + createUser(testDb); + const set = testDb.prepare("INSERT OR REPLACE INTO app_settings (key, value) VALUES ('place_shadow_enabled', ?)"); + // No row is the state of every install that never touched the switch. + expect(svc.getAppConfig(null).place_shadow_enabled).toBe(false); + set.run('false'); + expect(svc.getAppConfig(null).place_shadow_enabled).toBe(false); + // Only the literal 'true' opens it, the mirror image of the fail-open + // places_* flags beside it, which close only on the literal 'false'. + set.run('1'); + expect(svc.getAppConfig(null).place_shadow_enabled).toBe(false); + expect(svc.getAppConfig(null).places_enrich_enabled).toBe(true); + set.run('true'); + expect(svc.getAppConfig(null).place_shadow_enabled).toBe(true); + }); }); describe('demoLogin', () => { diff --git a/server/tests/unit/nest/maps.geocode.test.ts b/server/tests/unit/nest/maps.geocode.test.ts new file mode 100644 index 000000000..2ec2c24da --- /dev/null +++ b/server/tests/unit/nest/maps.geocode.test.ts @@ -0,0 +1,140 @@ +/** + * MAPS-GEOCODE-001..009 — turning one string into one coordinate. + * + * The lookup behind booking-import: a confirmation mail names a hotel, a + * station, an airport, and this is what puts it on the map. It runs up to + * thirty times in a single import, so both halves matter — whether the query + * leaves the instance at all (the index is asked first, and only while the + * admin leaves it on), and that a failure on either side ends as a coordinate + * or a null rather than a half-answer the importer would store. + */ +import { describe, it, expect, vi, beforeEach } from 'vitest'; + +const { mockSearch, mockNominatim } = vi.hoisted(() => ({ + mockSearch: vi.fn(async (_query: string, _opts?: { limit?: number }): Promise => []), + mockNominatim: vi.fn( + async (_endpoint: string, _params: URLSearchParams, _opts?: { lane?: string }): Promise => ({ + ok: true, + json: async () => [], + }), + ), +})); +vi.mock('../../../src/nest/maps/trek-places.client', async (importOriginal) => ({ + ...(await importOriginal()), + trekPlacesSearch: mockSearch, +})); +vi.mock('../../../src/nest/geo/nominatim.client', async (importOriginal) => ({ + ...(await importOriginal()), + nominatimFetch: mockNominatim, +})); + +vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret', ENCRYPTION_KEY: '0'.repeat(64) })); + +import { MapsService } from '../../../src/nest/maps/maps.service'; +import type { DatabaseService } from '../../../src/nest/database/database.service'; +import type { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service'; + +const QUERY = 'Hotel Adlon Kempinski, Unter den Linden 77, Berlin'; + +const indexHit = (lat: unknown, lng: unknown) => [ + { gers: 'abc-123', name: 'Hotel Adlon Kempinski', lat, lng, source: 'overture' }, +]; + +const OSM_ROW = { + osm_type: 'way', + osm_id: 24838110, + lat: '52.5162746', + lon: '13.3796780', + name: 'Hotel Adlon Kempinski', + display_name: 'Hotel Adlon Kempinski, Unter den Linden, Mitte, Berlin, Deutschland', +}; + +const osmAnswer = (rows: unknown[]) => ({ ok: true, json: async () => rows }); + +function make(enabled = true) { + const database = { + get: vi.fn(() => (enabled ? undefined : { value: 'false' })), + } as unknown as DatabaseService; + return new MapsService(database, {} as PlacePhotoCacheService); +} + +beforeEach(() => { + mockSearch.mockReset(); + mockSearch.mockResolvedValue([]); + mockNominatim.mockReset(); + mockNominatim.mockResolvedValue(osmAnswer([OSM_ROW])); + vi.spyOn(console, 'warn').mockImplementation(() => {}); +}); + +describe('MapsService.geocodeQuery', () => { + it('MAPS-GEOCODE-001: an index hit answers on its own, without a second lookup', async () => { + mockSearch.mockResolvedValue(indexHit(52.5162746, 13.379678)); + expect(await make().geocodeQuery(QUERY)).toEqual({ lat: 52.5162746, lng: 13.379678 }); + // One result is all the caller can use; asking for ten would only cost the + // index work. + expect(mockSearch).toHaveBeenCalledWith(QUERY, { limit: 1 }); + expect(mockNominatim).not.toHaveBeenCalled(); + }); + + it('MAPS-GEOCODE-002: a zero coordinate is a place, not a missing value', async () => { + // Pontianak sits on the equator. A truthiness check would drop it and send + // the query on to Nominatim for no reason. + mockSearch.mockResolvedValue(indexHit(0, 109.3333)); + expect(await make().geocodeQuery('Tugu Khatulistiwa, Pontianak')).toEqual({ lat: 0, lng: 109.3333 }); + expect(mockNominatim).not.toHaveBeenCalled(); + }); + + it('MAPS-GEOCODE-003: a hit with one unusable coordinate falls through instead of being returned', async () => { + // Half a coordinate lands the booking in the Gulf of Guinea. Both halves + // are driven, so neither finiteness check can be dropped unnoticed. + mockSearch.mockResolvedValue(indexHit(48.8583701, Number.NaN)); + expect(await make().geocodeQuery(QUERY)).toEqual({ lat: 52.5162746, lng: 13.379678 }); + mockSearch.mockResolvedValue(indexHit(undefined, 2.2944813)); + expect(await make().geocodeQuery(QUERY)).toEqual({ lat: 52.5162746, lng: 13.379678 }); + expect(mockNominatim).toHaveBeenCalledTimes(2); + }); + + it('MAPS-GEOCODE-004: an index that found nothing falls through to OpenStreetMap', async () => { + mockSearch.mockResolvedValue([]); + expect(await make().geocodeQuery(QUERY)).toEqual({ lat: 52.5162746, lng: 13.379678 }); + expect(mockNominatim).toHaveBeenCalledTimes(1); + }); + + it('MAPS-GEOCODE-005: an index failure is a warning and a fallback, not a lost booking', async () => { + mockSearch.mockRejectedValue(new Error('places api down')); + expect(await make().geocodeQuery(QUERY)).toEqual({ lat: 52.5162746, lng: 13.379678 }); + expect(console.warn).toHaveBeenCalledWith('TREK Places geocode failed, falling back:', 'places api down'); + }); + + it('MAPS-GEOCODE-006: the query never leaves for the index while the admin has it off', async () => { + // The index has an answer, and a different one: the OSM coordinate coming + // back is what proves the gate held rather than the call merely being made. + mockSearch.mockResolvedValue(indexHit(1.2345, 2.3456)); + expect(await make(false).geocodeQuery(QUERY)).toEqual({ lat: 52.5162746, lng: 13.379678 }); + expect(mockSearch).not.toHaveBeenCalled(); + }); + + it('MAPS-GEOCODE-007: the fallback goes out on the background lane', async () => { + // Thirty of these run inside one import. On the interactive lane they take + // every slot and somebody typing in the place search waits behind them. + await make().geocodeQuery(QUERY); + const [endpoint, params, opts] = mockNominatim.mock.calls[0]; + expect(endpoint).toBe('search'); + expect(params.get('q')).toBe(QUERY); + expect(opts?.lane).toBe('background'); + }); + + it('MAPS-GEOCODE-008: a Nominatim row with an unparseable coordinate is null, not NaN', async () => { + // searchNominatim turns the failed parse into null, and half a coordinate + // is no coordinate — asserted per side, so neither null check is free. + mockNominatim.mockResolvedValue(osmAnswer([{ ...OSM_ROW, lon: 'unknown' }])); + expect(await make().geocodeQuery(QUERY)).toBeNull(); + mockNominatim.mockResolvedValue(osmAnswer([{ ...OSM_ROW, lat: 'unknown' }])); + expect(await make().geocodeQuery(QUERY)).toBeNull(); + }); + + it('MAPS-GEOCODE-009: neither source knowing the place is a null, not a guess', async () => { + mockNominatim.mockResolvedValue(osmAnswer([])); + expect(await make().geocodeQuery('Zzz Hotel, Nowhere')).toBeNull(); + }); +}); diff --git a/server/tests/unit/nest/place-enrichment.description.test.ts b/server/tests/unit/nest/place-enrichment.description.test.ts index 6fee19b47..6f373b619 100644 --- a/server/tests/unit/nest/place-enrichment.description.test.ts +++ b/server/tests/unit/nest/place-enrichment.description.test.ts @@ -414,4 +414,55 @@ describe("the description on the place's own website", () => { const out = await make(mapsStub()).enrich(1, GERS_REQ); expect(out.description).toBeNull(); }); + + it('ENRICH-101: a place the index knows, whose site publishes no summary', async () => { + // The common answer, not an error: the GERS id resolves, and the place has + // no description field at all because its page carried nothing readable. + mockTrekPlacesById.mockResolvedValue({ gers: 'abc-123', name: "L'Osteria" }); + + const out = await make(mapsStub()).enrich(1, GERS_REQ); + + expect(mockTrekPlacesById).toHaveBeenCalledWith('abc-123'); + expect(out.description).toBeNull(); + }); + + it('ENRICH-102: still quotes a summary the API could not name a page for', async () => { + // The link is the credit, not the content. Dropping the text for want of a + // footnote would lose the only description the place has. The field is + // absent rather than null, so `sourceUrl` below is the normalisation and + // not the fixture read back. + mockTrekPlacesById.mockResolvedValue({ description: { text: 'Pizza in Rostock.' } }); + + const out = await make(mapsStub()).enrich(1, GERS_REQ); + + expect(out.description).toEqual({ + text: 'Pizza in Rostock.', + source: 'website', + sourceUrl: null, + license: null, + }); + }); + + it("ENRICH-103: the branch's own words come before the chain's article", async () => { + // L'Osteria Rostock carries brand:wikidata and has no article of its own. + // The chain article is about the company; the site is about this branch, + // and the branch is what was asked about. + mockTrekPlacesById.mockResolvedValue({ + description: { text: 'Unsere Filiale in der Steinstraße.', sourceUrl: 'https://losteria.net/rostock' }, + }); + const maps = mapsStub({ + resolveOsmIdentity: vi.fn(async () => ({ + tags: { 'brand:wikidata': 'Q17323478', 'brand:wikipedia': 'de:L’Osteria' }, + osmUrl: null, + matchedName: "L'Osteria", + })), + fetchWikiExtractFor: vi.fn(async () => EXTRACT), + }); + + const out = await make(maps).enrich(1, GERS_REQ); + + expect(out.description).toMatchObject({ source: 'website', text: 'Unsere Filiale in der Steinstraße.' }); + // The chain lookup starts at the brand's Wikidata item — it never ran. + expect(maps.fetchWikidataSitelinks).not.toHaveBeenCalled(); + }); }); diff --git a/server/tests/unit/nest/place-enrichment.service.test.ts b/server/tests/unit/nest/place-enrichment.service.test.ts index dca411403..de1d25949 100644 --- a/server/tests/unit/nest/place-enrichment.service.test.ts +++ b/server/tests/unit/nest/place-enrichment.service.test.ts @@ -40,6 +40,17 @@ vi.mock('../../../src/utils/ssrfGuard', () => ({ vi.mock('../../../src/config', () => ({ JWT_SECRET: 'test-secret', ENCRYPTION_KEY: '0'.repeat(64) })); +// Reached for any `gers:` place id, where the real one is an outbound request +// to the TREK Places API. Only this export is replaced; the record shaping the +// rest of the module provides stays as it is. +const { mockTrekPlacesById } = vi.hoisted(() => ({ + mockTrekPlacesById: vi.fn(async (_gers: string): Promise => null), +})); +vi.mock('../../../src/nest/maps/trek-places.client', async (importOriginal) => ({ + ...(await importOriginal()), + trekPlacesById: mockTrekPlacesById, +})); + import { db } from '../../../src/db/database'; import { DatabaseService } from '../../../src/nest/database/database.service'; import { @@ -49,6 +60,7 @@ import { collectFacts, collectHours, collectRating, + nearbyWouldMislead, } from '../../../src/nest/place-enrichment/place-enrichment.service'; import type { MapsService } from '../../../src/nest/maps/maps.service'; import type { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service'; @@ -125,6 +137,8 @@ beforeEach(() => { mockDbRun.mockReset(); mockSafeFetchFollow.mockReset(); mockSafeFetchFollow.mockResolvedValue({ ok: true, arrayBuffer: async () => new Uint8Array([1, 2, 3]).buffer }); + mockTrekPlacesById.mockReset(); + mockTrekPlacesById.mockResolvedValue(null); }); // ── Kill switch ────────────────────────────────────────────────────────────── @@ -996,3 +1010,118 @@ describe('picture source ladder', () => { expect(shifted?.key).toBe(first); }); }); + +/** + * ENRICH-110..116 — the categories cut off from the nearby fallback. + * + * The bottom rung is "anything photographed within 300m", and for an ordinary + * business that is the building opposite. Two percent of them have a picture on + * Commons against seventy percent of churches, so for a cafe the curated rungs + * practically never fire and the fallback practically always does — which is + * how a doner shop ended up illustrated with the town hall across the square. + */ +describe('nearby pictures that would mislead', () => { + const GERS_REQ = { ...REQ, placeId: 'gers:abc-123' }; + + // What the TREK index reports for a place: one `category` string. + const indexPlace = (category: string) => + mapsStub({ + details: vi.fn(async () => ({ place: { source: 'trek-places', category } })), + fetchCommonsCandidates: vi.fn(async () => [commonsCandidate()]), + }); + + it('ENRICH-110: a business is cut off, whichever field names its trade', () => { + // Overture reports `category`; the OSM tags the identity lookup brings back + // report `amenity`, `shop` or `cuisine`. `category_path` is the name the + // API gives the field — the guard reads it, though toPlaceRecord drops it + // before a details record is ever shaped. + expect(nearbyWouldMislead({ category: 'pizza_restaurant' })).toBe(true); + expect(nearbyWouldMislead({ category_path: 'eat_and_drink>cafe' })).toBe(true); + expect(nearbyWouldMislead({ amenity: 'fast_food' })).toBe(true); + expect(nearbyWouldMislead({ shop: 'bakery' })).toBe(true); + expect(nearbyWouldMislead({ cuisine: 'coffee_shop' })).toBe(true); + }); + + it('ENRICH-111: a monument is not, which is the case the fallback exists for', () => { + // At 300m from a castle or a church, what was photographed is the castle. + expect(nearbyWouldMislead({ category: 'landmark_and_historical_building' })).toBe(false); + expect(nearbyWouldMislead({ category: 'castle' })).toBe(false); + expect(nearbyWouldMislead({ category: 'museum' })).toBe(false); + expect(nearbyWouldMislead({ amenity: 'place_of_worship' })).toBe(false); + }); + + it('ENRICH-112: fails open when nothing says what the place is', () => { + // Unlabelled is not the same as harmless, but there is no telling a + // cathedral from a kebab shop without a category, and cutting off + // everything unlabelled would take the fallback from the places it works + // for. The name is not a category either: "Cafe Central" may well be a + // listed building. + expect(nearbyWouldMislead(null)).toBe(false); + expect(nearbyWouldMislead({})).toBe(false); + expect(nearbyWouldMislead({ name: 'Cafe Central', category: null })).toBe(false); + }); + + it('ENRICH-113: never asks the coordinate search about a cafe', async () => { + const maps = indexPlace('coffee_shop'); + + const out = await make(maps, cacheStub()).enrich(1, GERS_REQ); + + // Skipped outright rather than fetched and then filtered: the request is + // the whole cost, and there is nothing in the answer worth looking at. + expect(maps.fetchCommonsCandidates).not.toHaveBeenCalled(); + expect(out.photos).toEqual([]); + }); + + it('ENRICH-114: still asks it for a place the fallback was built for', async () => { + const maps = indexPlace('landmark_and_historical_building'); + + const out = await make(maps, cacheStub()).enrich(1, GERS_REQ); + + expect(maps.fetchCommonsCandidates).toHaveBeenCalledWith(REQ.lat, REQ.lng, 5); + expect(out.photos).toHaveLength(1); + }); + + it('ENRICH-115: reads the OSM tags too, which is where a takeaway says so', async () => { + // buildOsmDetails carries cuisine but neither amenity nor shop, so for an + // OSM place — cuisine=kebab, amenity=fast_food — only the tags the identity + // lookup brought back name the trade. + const maps = mapsStub({ + details: vi.fn(async () => ({ place: { source: 'openstreetmap', cuisine: 'kebab' } })), + resolveOsmIdentity: vi.fn(async () => ({ + tags: { amenity: 'fast_food', cuisine: 'kebab' }, + osmUrl: null, + matchedName: 'Döner Rostock', + })), + fetchCommonsCandidates: vi.fn(async () => [commonsCandidate()]), + }); + + const out = await make(maps, cacheStub()).enrich(1, OSM_REQ); + + expect(maps.fetchCommonsCandidates).not.toHaveBeenCalled(); + expect(out.photos).toEqual([]); + }); + + it('ENRICH-116: cuts only the bottom rung, not the curated ones above it', async () => { + // A cafe somebody tagged in OpenStreetMap still has pictures attached to + // that exact object. One of them is below the bar of two that normally lets + // the coordinate search top the strip up — being a cafe is what stops it. + // The item comes from the OSM tag and not from the index record, whose + // `wikidata` holds the chain's item rather than this branch's. + const maps = mapsStub({ + details: vi.fn(async () => ({ place: { source: 'trek-places', category: 'cafe' } })), + resolveOsmIdentity: vi.fn(async () => ({ + tags: { wikidata: 'Q1' }, + osmUrl: null, + matchedName: 'Café Central', + })), + fetchWikidataCandidates: vi.fn(async () => ({ candidates: [commonsCandidate()], commonsCategory: null })), + fetchCommonsCandidates: vi.fn(async () => [commonsCandidate({ attribution: 'Bob' })]), + }); + + const out = await make(maps, cacheStub()).enrich(1, GERS_REQ); + + expect(maps.fetchWikidataCandidates).toHaveBeenCalledWith('Q1', 5); + expect(maps.fetchCommonsCandidates).not.toHaveBeenCalled(); + expect(out.photos).toHaveLength(1); + }); +});