mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 05:21:15 +00:00
places: let an admin share the details users typed with the TREK Places API
Every shareable field of a place now records where its value came from: typed by a user, filled by a provider, written by the assistant, a plugin or an import. Only values a user typed are ever sent, and only after an admin agreed to the current terms for the whole installation, field by field. The new place-contrib domain keeps the decision in app settings, queues values in an outbox a cron job sends from, logs what the service made of each one and can withdraw everything this installation sent. Development, test and demo instances, an own TREK_PLACES_URL, TREK_SERVICES=off and TREK_PLACES_CONTRIBUTE=off never send anything. Index results carry the community version, so the details caches refresh when it changes.
This commit is contained in:
@@ -70,6 +70,7 @@ DEMO_MODE=false # Demo mode: resets data hourly
|
||||
|
||||
# TREK_PLACES_ENABLED=false # Whether place search asks the TREK Places API at https://places.liketrek.com: suggestions, the full search, the category buttons on the map, the Road trip search along the route, import geocoding, offline downloads, and the OpenStreetMap ways and horse routes Tours reads. It is on by default and has no switch in the admin panel, because whether searches leave the instance is a deployment decision. Set false to search the way it did before 4.3.0 (OpenStreetMap, or your Google/Amap key) and send nothing to that host. (default: true)
|
||||
# TREK_PLACES_URL=https://places.liketrek.com # Base URL of a copy of the Places API you run yourself; it has to answer the same /v1 API. Read from configuration rather than typed by a user, so an address on your LAN or Docker network works without ALLOW_INTERNAL_NETWORK. (default: https://places.liketrek.com)
|
||||
# TREK_PLACES_CONTRIBUTE=admin # Whether an admin may let this installation send place details its users typed in (website, phone, e-mail, opening hours, description, picture) to the TREK Places API, so every installation gets better details. admin shows the choice in the admin panel, where it stays off until an admin agrees; off takes the choice away and nothing is ever sent. Nothing is sent outside NODE_ENV=production, in demo mode, with a custom TREK_PLACES_URL or with TREK_SERVICES=off. (default: admin)
|
||||
# TREK_SERVICES=auto # How this installation identifies itself to the TREK services. On first use it registers itself in the background and keeps a key in the database; nothing to click, no account. off sends no key, and searches use the shared pool. (default: auto)
|
||||
# TREK_SERVICES_KEY= # A key issued to you for this installation. Wins over the stored one and turns self-registration off; meant for hosted and pre-provisioned instances. (default: none)
|
||||
# TREK_SERVICES_HOSTS=places.liketrek.com,photon.liketrek.com,valhalla.liketrek.com # Comma-separated hosts that receive the installation key over https. No other host ever sees it. (default: places.liketrek.com,photon.liketrek.com,valhalla.liketrek.com)
|
||||
|
||||
@@ -79,7 +79,10 @@
|
||||
"PhotoProviderFields": "addons",
|
||||
"PhotoProviders": "addons",
|
||||
"Photos": "photos",
|
||||
"PlaceContribLog": "place-contrib",
|
||||
"PlaceContribOutbox": "place-contrib",
|
||||
"PlaceDetailsCache": "maps",
|
||||
"PlaceFieldOrigin": "places",
|
||||
"PlaceRatings": "places",
|
||||
"PlaceRegions": "atlas",
|
||||
"PlaceShadowPicks": "place-shadow",
|
||||
|
||||
@@ -165,6 +165,13 @@ export function deriveMaps(raw: RawEnv) {
|
||||
* the install back to Nominatim.
|
||||
*/
|
||||
trekPlacesEnabled: parseBool(raw.TREK_PLACES_ENABLED) !== false,
|
||||
/**
|
||||
* The ceiling over sending place details back to the TREK Places API.
|
||||
* `admin` (the default) lets an admin decide in the admin panel; `off` takes
|
||||
* the choice away. Anything but `admin` reads as off, so a typo fails closed.
|
||||
*/
|
||||
trekPlacesContribute:
|
||||
(raw.TREK_PLACES_CONTRIBUTE?.trim().toLowerCase() || 'admin') === 'admin' ? ('admin' as const) : ('off' as const),
|
||||
placesApiKey: raw.PLACES_API_KEY || undefined,
|
||||
/** The same two knobs for Amap (高德), which an install in China uses instead. */
|
||||
amapApiBase: raw.AMAP_API_BASE || undefined,
|
||||
|
||||
@@ -185,6 +185,7 @@ export const envSchema = z.object({
|
||||
GOOGLE_LIST_DATA_BASE: url,
|
||||
TREK_PLACES_URL: url,
|
||||
TREK_PLACES_ENABLED: boolStr,
|
||||
TREK_PLACES_CONTRIBUTE: oneOf(['off', 'admin']),
|
||||
TREK_SERVICES: oneOf(['auto', 'off']),
|
||||
TREK_SERVICES_KEY: optionalWith(isServiceKeyShape, 'must be a TREK services key (tk1.<kid>.<payload>.<signature>)'),
|
||||
TREK_SERVICES_HOSTS: anyString,
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
import { EntityRepositoryType, type Opt, defineEntity, p } from '@mikro-orm/core';
|
||||
import { PlaceContribLogRepository } from '../repositories/PlaceContribLog.repository';
|
||||
|
||||
export class PlaceContribLog {
|
||||
[EntityRepositoryType]?: PlaceContribLogRepository;
|
||||
id!: number & Opt;
|
||||
day!: string;
|
||||
contrib_key!: string;
|
||||
place_name!: string;
|
||||
field!: string;
|
||||
value_summary?: string | null;
|
||||
result!: string;
|
||||
reason?: string | null;
|
||||
}
|
||||
|
||||
export const PlaceContribLogSchema = defineEntity({
|
||||
class: PlaceContribLog,
|
||||
repository: () => PlaceContribLogRepository,
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
day: p.text().index('idx_place_contrib_log_day'),
|
||||
contrib_key: p.text(),
|
||||
place_name: p.text(),
|
||||
field: p.text(),
|
||||
value_summary: p.text().nullable(),
|
||||
result: p.text(),
|
||||
reason: p.text().nullable(),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { PlaceContribOutboxRepository } from '../repositories/PlaceContribOutbox.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { Places } from './Places.entity';
|
||||
|
||||
export class PlaceContribOutbox {
|
||||
[EntityRepositoryType]?: PlaceContribOutboxRepository;
|
||||
id!: number & Opt;
|
||||
contrib_key!: string;
|
||||
field!: string;
|
||||
value!: string;
|
||||
place!: Ref<Places>;
|
||||
place_id!: number;
|
||||
place_name!: string;
|
||||
lat?: number | null;
|
||||
lng?: number | null;
|
||||
country?: string | null;
|
||||
cid!: string;
|
||||
attempts: number & Opt = 0;
|
||||
eligible_at!: string;
|
||||
next_attempt_at!: string;
|
||||
created_at!: string & Opt;
|
||||
}
|
||||
|
||||
export const PlaceContribOutboxSchema = defineEntity({
|
||||
class: PlaceContribOutbox,
|
||||
repository: () => PlaceContribOutboxRepository,
|
||||
uniques: [{ properties: ['contrib_key', 'field'] }],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
contrib_key: p.text(),
|
||||
field: p.text(),
|
||||
value: p.text(),
|
||||
place: () => p.manyToOne(Places).ref().deleteRule('cascade').hidden().index('idx_place_contrib_outbox_place'),
|
||||
place_id: p.integer().persist(false).index('idx_place_contrib_outbox_place'),
|
||||
place_name: p.text(),
|
||||
lat: p.double().nullable(),
|
||||
lng: p.double().nullable(),
|
||||
country: p.text().nullable(),
|
||||
cid: p.text(),
|
||||
attempts: p.integer().default(0),
|
||||
eligible_at: p.type(DbTimestampType),
|
||||
next_attempt_at: p.type(DbTimestampType).index('idx_place_contrib_outbox_due'),
|
||||
created_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,29 @@
|
||||
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { PlaceFieldOriginRepository } from '../repositories/PlaceFieldOrigin.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { Places } from './Places.entity';
|
||||
|
||||
export class PlaceFieldOrigin {
|
||||
[EntityRepositoryType]?: PlaceFieldOriginRepository;
|
||||
[PrimaryKeyProp]?: ['place', 'field'];
|
||||
place!: Ref<Places>;
|
||||
place_id!: number;
|
||||
field!: string;
|
||||
origin!: string;
|
||||
value_hash!: string;
|
||||
updated_at!: string & Opt;
|
||||
}
|
||||
|
||||
export const PlaceFieldOriginSchema = defineEntity({
|
||||
class: PlaceFieldOrigin,
|
||||
repository: () => PlaceFieldOriginRepository,
|
||||
uniques: [{ properties: ['place', 'field'] }],
|
||||
properties: {
|
||||
place: () => p.manyToOne(Places).primary().ref().deleteRule('cascade').hidden(),
|
||||
place_id: p.integer().persist(false),
|
||||
field: p.text().primary(),
|
||||
origin: p.text(),
|
||||
value_hash: p.text(),
|
||||
updated_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
});
|
||||
@@ -9,6 +9,8 @@ import { DayAssignments } from './DayAssignments.entity';
|
||||
import { FileLinks } from './FileLinks.entity';
|
||||
import { JourneyEntries } from './JourneyEntries.entity';
|
||||
import { Photos } from './Photos.entity';
|
||||
import { PlaceContribOutbox } from './PlaceContribOutbox.entity';
|
||||
import { PlaceFieldOrigin } from './PlaceFieldOrigin.entity';
|
||||
import { PlaceRatings } from './PlaceRatings.entity';
|
||||
import { PlaceRegions } from './PlaceRegions.entity';
|
||||
import { Reservations } from './Reservations.entity';
|
||||
@@ -65,6 +67,8 @@ export class Places {
|
||||
file_links_collection = new Collection<FileLinks>(this);
|
||||
journey_entries_collection = new Collection<JourneyEntries>(this);
|
||||
photos_collection = new Collection<Photos>(this);
|
||||
place_contrib_outbox_collection = new Collection<PlaceContribOutbox>(this);
|
||||
place_field_origin_collection = new Collection<PlaceFieldOrigin>(this);
|
||||
place_ratings_collection = new Collection<PlaceRatings>(this);
|
||||
place_regions: Ref<PlaceRegions> | null = null;
|
||||
reservations_collection = new Collection<Reservations>(this);
|
||||
@@ -123,6 +127,8 @@ export const PlacesSchema = defineEntity({
|
||||
file_links_collection: () => p.oneToMany(FileLinks).mappedBy('place').hidden(),
|
||||
journey_entries_collection: () => p.oneToMany(JourneyEntries).mappedBy('sourcePlace').hidden(),
|
||||
photos_collection: () => p.oneToMany(Photos).mappedBy('place').hidden(),
|
||||
place_contrib_outbox_collection: () => p.oneToMany(PlaceContribOutbox).mappedBy('place').hidden(),
|
||||
place_field_origin_collection: () => p.oneToMany(PlaceFieldOrigin).mappedBy('place').hidden(),
|
||||
place_ratings_collection: () => p.oneToMany(PlaceRatings).mappedBy('place').hidden(),
|
||||
place_regions: () => p.oneToOne(PlaceRegions).ref().mappedBy('place').hidden(),
|
||||
reservations_collection: () => p.oneToMany(Reservations).mappedBy('place').hidden(),
|
||||
|
||||
@@ -80,7 +80,10 @@ import { PasswordResetTokensSchema } from './PasswordResetTokens.entity';
|
||||
import { PhotoProviderFieldsSchema } from './PhotoProviderFields.entity';
|
||||
import { PhotoProvidersSchema } from './PhotoProviders.entity';
|
||||
import { PhotosSchema } from './Photos.entity';
|
||||
import { PlaceContribLogSchema } from './PlaceContribLog.entity';
|
||||
import { PlaceContribOutboxSchema } from './PlaceContribOutbox.entity';
|
||||
import { PlaceDetailsCacheSchema } from './PlaceDetailsCache.entity';
|
||||
import { PlaceFieldOriginSchema } from './PlaceFieldOrigin.entity';
|
||||
import { PlaceRatingsSchema } from './PlaceRatings.entity';
|
||||
import { PlaceRegionsSchema } from './PlaceRegions.entity';
|
||||
import { PlaceShadowPicksSchema } from './PlaceShadowPicks.entity';
|
||||
@@ -244,7 +247,10 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
|
||||
PhotoProviderFieldsSchema,
|
||||
PhotoProvidersSchema,
|
||||
PhotosSchema,
|
||||
PlaceContribLogSchema,
|
||||
PlaceContribOutboxSchema,
|
||||
PlaceDetailsCacheSchema,
|
||||
PlaceFieldOriginSchema,
|
||||
PlaceRatingsSchema,
|
||||
PlaceRegionsSchema,
|
||||
PlaceShadowPicksSchema,
|
||||
|
||||
@@ -13,6 +13,8 @@ import {
|
||||
paddleLockSchema,
|
||||
paddleRegionBoundarySchema,
|
||||
paddleRegionGraphStatsSchema,
|
||||
placeContribConsentSchema,
|
||||
placeContribPauseReasonSchema,
|
||||
skiPlannedLegsSchema,
|
||||
skiRouteOptionsSchema,
|
||||
tourChangeSchema,
|
||||
@@ -31,6 +33,8 @@ import {
|
||||
type PaddleLock,
|
||||
type PaddleRegionBoundary,
|
||||
type PaddleRegionGraphStats,
|
||||
type PlaceContribConsent,
|
||||
type PlaceContribPauseReason,
|
||||
type TourChange,
|
||||
type TourFixedLeg,
|
||||
type TourSourceHintChange,
|
||||
@@ -454,3 +458,59 @@ export const TREK_PHOTO_SIGNAL_PALETTE: JsonColumn<string[]> = {
|
||||
schema: z.array(z.string().regex(/^#[0-9a-f]{6}(?::(?:0|1)(?:\.\d{1,2})?)?$/)).max(5),
|
||||
fallback: () => [],
|
||||
};
|
||||
|
||||
/**
|
||||
* The installation's decision on the community enrichment, in the
|
||||
* `places_contribute` app setting. Undecided reads as off, with every field
|
||||
* switch on: that is what the prompt proposes. A broken row reads the same, so
|
||||
* nothing is sent on a value nobody can read.
|
||||
*/
|
||||
export const PLACES_CONTRIBUTE_CONSENT: JsonColumn<PlaceContribConsent> = {
|
||||
column: 'app_settings.places_contribute',
|
||||
schema: placeContribConsentSchema,
|
||||
fallback: () => ({
|
||||
enabled: false,
|
||||
fields: { website: true, phone: true, email: true, opening_hours: true, description: true, image: true },
|
||||
termsVersion: null,
|
||||
decision: null,
|
||||
decidedBy: null,
|
||||
decidedAt: null,
|
||||
}),
|
||||
};
|
||||
|
||||
/** Per admin (by user id), the ISO moment their "not now" ends, in `places_contribute_snooze`. */
|
||||
export const PLACES_CONTRIBUTE_SNOOZE: JsonColumn<Record<string, string>> = {
|
||||
column: 'app_settings.places_contribute_snooze',
|
||||
schema: z.record(z.string().regex(/^\d+$/), z.string()),
|
||||
fallback: () => ({}),
|
||||
};
|
||||
|
||||
/**
|
||||
* Why sending waits although an admin agreed, in `places_contribute_pause`: a
|
||||
* refused key (with the fingerprint of the key that was refused, so a new key
|
||||
* resumes by itself) or the service asking to wait (until when).
|
||||
*/
|
||||
export interface PlacesContributePause {
|
||||
reason: PlaceContribPauseReason;
|
||||
key: string | null;
|
||||
until: string | null;
|
||||
}
|
||||
|
||||
export const PLACES_CONTRIBUTE_PAUSE: JsonColumn<PlacesContributePause | null> = {
|
||||
column: 'app_settings.places_contribute_pause',
|
||||
schema: z
|
||||
.object({ reason: placeContribPauseReasonSchema, key: z.string().nullable(), until: z.string().nullable() })
|
||||
.nullable(),
|
||||
fallback: () => null,
|
||||
};
|
||||
|
||||
/**
|
||||
* A cached details or enrichment record in `place_details_cache.payload_json`,
|
||||
* read by the origin tracking to see what a provider handed out for a place.
|
||||
* Only its object shape is checked here; the reader picks the fields it knows.
|
||||
*/
|
||||
export const PLACE_DETAILS_CACHE_PAYLOAD: JsonColumn<Record<string, unknown> | null> = {
|
||||
column: 'place_details_cache.payload_json',
|
||||
schema: z.record(z.string(), z.unknown()).nullable(),
|
||||
fallback: () => null,
|
||||
};
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface PlaceContribLogTable {
|
||||
id: InsertOptional<number>;
|
||||
day: string;
|
||||
contrib_key: string;
|
||||
place_name: string;
|
||||
field: string;
|
||||
value_summary: InsertOptional<string | null>;
|
||||
result: string;
|
||||
reason: InsertOptional<string | null>;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface PlaceContribOutboxTable {
|
||||
id: InsertOptional<number>;
|
||||
contrib_key: string;
|
||||
field: string;
|
||||
value: string;
|
||||
place_id: number;
|
||||
place_name: string;
|
||||
lat: InsertOptional<number | null>;
|
||||
lng: InsertOptional<number | null>;
|
||||
country: InsertOptional<string | null>;
|
||||
cid: string;
|
||||
attempts: InsertOptional<number>;
|
||||
eligible_at: string;
|
||||
next_attempt_at: string;
|
||||
created_at: InsertOptional<string>;
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface PlaceFieldOriginTable {
|
||||
place_id: number;
|
||||
field: string;
|
||||
origin: string;
|
||||
value_hash: string;
|
||||
updated_at: InsertOptional<string>;
|
||||
}
|
||||
@@ -85,7 +85,10 @@ import type { PasswordResetTokensTable } from './PasswordResetTokens.table';
|
||||
import type { PhotoProviderFieldsTable } from './PhotoProviderFields.table';
|
||||
import type { PhotoProvidersTable } from './PhotoProviders.table';
|
||||
import type { PhotosTable } from './Photos.table';
|
||||
import type { PlaceContribLogTable } from './PlaceContribLog.table';
|
||||
import type { PlaceContribOutboxTable } from './PlaceContribOutbox.table';
|
||||
import type { PlaceDetailsCacheTable } from './PlaceDetailsCache.table';
|
||||
import type { PlaceFieldOriginTable } from './PlaceFieldOrigin.table';
|
||||
import type { PlaceRatingsTable } from './PlaceRatings.table';
|
||||
import type { PlaceRegionsTable } from './PlaceRegions.table';
|
||||
import type { PlaceShadowPicksTable } from './PlaceShadowPicks.table';
|
||||
@@ -255,7 +258,10 @@ export interface DB {
|
||||
photo_provider_fields: PhotoProviderFieldsTable;
|
||||
photo_providers: PhotoProvidersTable;
|
||||
photos: PhotosTable;
|
||||
place_contrib_log: PlaceContribLogTable;
|
||||
place_contrib_outbox: PlaceContribOutboxTable;
|
||||
place_details_cache: PlaceDetailsCacheTable;
|
||||
place_field_origin: PlaceFieldOriginTable;
|
||||
place_ratings: PlaceRatingsTable;
|
||||
place_regions: PlaceRegionsTable;
|
||||
place_shadow_picks: PlaceShadowPicksTable;
|
||||
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* A place remembers where each of its shareable details came from, and an
|
||||
* installation whose admin agreed can send the ones its users typed in to the
|
||||
* TREK Places API (community enrichment).
|
||||
*
|
||||
* `place_field_origin` holds one row per place and field (website, phone,
|
||||
* email, opening_hours, description, image): who set the value (`user`, a
|
||||
* provider, the assistant, a plugin, an import, an attachment, or `unknown`)
|
||||
* and the hash of the value the row describes. Only `user` rows whose hash
|
||||
* still matches the column are ever sent, so every value that existed before
|
||||
* this migration stays home: it has no row. The rows go with their place.
|
||||
*
|
||||
* `place_contrib_outbox` queues what waits to be sent, one row per place key
|
||||
* and field (the newest value replaces a queued one); its place going takes
|
||||
* the row with it. `place_contrib_log` is what the admin sees of what was
|
||||
* sent and what became of it, by day, without user, trip or row ids; a job
|
||||
* keeps 90 days of it.
|
||||
*/
|
||||
export class Migration20200101046320_a_place_knows_where_its_details_came_from extends Migration {
|
||||
override name = 'Migration20200101046320_a_place_knows_where_its_details_came_from';
|
||||
|
||||
override up(): void {
|
||||
this.addSql(`
|
||||
CREATE TABLE IF NOT EXISTS place_field_origin (
|
||||
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
|
||||
field TEXT NOT NULL CHECK(field IN ('website', 'phone', 'email', 'opening_hours', 'description', 'image')),
|
||||
origin TEXT NOT NULL CHECK(origin IN ('user', 'attachment', 'agent', 'plugin', 'import', 'google', 'amap',
|
||||
'osm', 'trek', 'wikimedia', 'website', 'unsplash', 'enrichment', 'unknown')),
|
||||
value_hash TEXT NOT NULL,
|
||||
updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (place_id, field)
|
||||
)
|
||||
`);
|
||||
this.addSql(`
|
||||
CREATE TABLE IF NOT EXISTS place_contrib_outbox (
|
||||
id INTEGER PRIMARY KEY,
|
||||
contrib_key TEXT NOT NULL,
|
||||
field TEXT NOT NULL CHECK(field IN ('website', 'phone', 'email', 'opening_hours', 'description', 'image')),
|
||||
value TEXT NOT NULL,
|
||||
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
|
||||
place_name TEXT NOT NULL,
|
||||
lat REAL,
|
||||
lng REAL,
|
||||
country TEXT,
|
||||
cid TEXT NOT NULL,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
eligible_at DATETIME NOT NULL,
|
||||
next_attempt_at DATETIME NOT NULL,
|
||||
created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(contrib_key, field)
|
||||
)
|
||||
`);
|
||||
this.addSql('CREATE INDEX IF NOT EXISTS idx_place_contrib_outbox_place ON place_contrib_outbox(place_id)');
|
||||
this.addSql('CREATE INDEX IF NOT EXISTS idx_place_contrib_outbox_due ON place_contrib_outbox(next_attempt_at)');
|
||||
this.addSql(`
|
||||
CREATE TABLE IF NOT EXISTS place_contrib_log (
|
||||
id INTEGER PRIMARY KEY,
|
||||
day TEXT NOT NULL,
|
||||
contrib_key TEXT NOT NULL,
|
||||
place_name TEXT NOT NULL,
|
||||
field TEXT NOT NULL CHECK(field IN ('website', 'phone', 'email', 'opening_hours', 'description', 'image')),
|
||||
value_summary TEXT,
|
||||
result TEXT NOT NULL CHECK(result IN ('accepted', 'duplicate', 'rejected', 'withheld', 'retracted')),
|
||||
reason TEXT
|
||||
)
|
||||
`);
|
||||
this.addSql('CREATE INDEX IF NOT EXISTS idx_place_contrib_log_day ON place_contrib_log(day)');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import type { PlaceContribLog } from '../entities/PlaceContribLog.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type LogKyselyDB = Pick<DB, 'place_contrib_log'>;
|
||||
|
||||
/** One line of the transmission log. */
|
||||
interface PlaceContribLogRow {
|
||||
id: number;
|
||||
day: string;
|
||||
contrib_key: string;
|
||||
place_name: string;
|
||||
field: string;
|
||||
value_summary: string | null;
|
||||
result: string;
|
||||
reason: string | null;
|
||||
}
|
||||
|
||||
export type PlaceContribLogWrite = Omit<PlaceContribLogRow, 'id'>;
|
||||
|
||||
/** Which lines a page of the log shows. */
|
||||
interface PlaceContribLogFilter {
|
||||
result?: string;
|
||||
field?: string;
|
||||
}
|
||||
|
||||
const LOG_COLUMNS = ['id', 'day', 'contrib_key', 'place_name', 'field', 'value_summary', 'result', 'reason'] as const;
|
||||
|
||||
/**
|
||||
* `place_contrib_log`: what this installation sent to the TREK Places API and
|
||||
* what became of it, or why it kept a value home. By day, with the place's key
|
||||
* and name, never a user, trip or row id.
|
||||
*/
|
||||
export class PlaceContribLogRepository extends TrekRepository<PlaceContribLog> {
|
||||
private db() {
|
||||
return this.kysely<LogKyselyDB>();
|
||||
}
|
||||
|
||||
async insertLines(rows: PlaceContribLogWrite[]): Promise<void> {
|
||||
if (rows.length === 0) return;
|
||||
await this.db().insertInto('place_contrib_log').values(rows).execute();
|
||||
}
|
||||
|
||||
/** One page, newest first. */
|
||||
async page(filter: PlaceContribLogFilter, limit: number, offset: number): Promise<PlaceContribLogRow[]> {
|
||||
let query = this.db()
|
||||
.selectFrom('place_contrib_log')
|
||||
.select([...LOG_COLUMNS]);
|
||||
if (filter.result) query = query.where('result', '=', filter.result);
|
||||
if (filter.field) query = query.where('field', '=', filter.field);
|
||||
return query.orderBy('id', 'desc').limit(limit).offset(offset).execute();
|
||||
}
|
||||
|
||||
async total(filter: PlaceContribLogFilter): Promise<number> {
|
||||
let query = this.db()
|
||||
.selectFrom('place_contrib_log')
|
||||
.select((eb) => eb.fn.countAll<number>().as('count'));
|
||||
if (filter.result) query = query.where('result', '=', filter.result);
|
||||
if (filter.field) query = query.where('field', '=', filter.field);
|
||||
const row = await query.executeTakeFirst();
|
||||
return Number(row?.count ?? 0);
|
||||
}
|
||||
|
||||
/** Lines per result from `sinceDay` (YYYY-MM-DD) on. */
|
||||
async countsSince(sinceDay: string): Promise<Array<{ result: string; count: number }>> {
|
||||
const rows = await this.db()
|
||||
.selectFrom('place_contrib_log')
|
||||
.select(['result', (eb) => eb.fn.countAll<number>().as('count')])
|
||||
.where('day', '>=', sinceDay)
|
||||
.groupBy('result')
|
||||
.execute();
|
||||
return rows.map((row) => ({ result: row.result, count: Number(row.count) }));
|
||||
}
|
||||
|
||||
/** The newest day a field was accepted, or null. */
|
||||
async lastAcceptedDay(): Promise<string | null> {
|
||||
const row = await this.db()
|
||||
.selectFrom('place_contrib_log')
|
||||
.select((eb) => eb.fn.max('day').as('day'))
|
||||
.where('result', '=', 'accepted')
|
||||
.executeTakeFirst();
|
||||
return row?.day ?? null;
|
||||
}
|
||||
|
||||
/** The retention sweep: drops the lines older than `beforeDay`. */
|
||||
async purgeBefore(beforeDay: string): Promise<number> {
|
||||
const result = await this.db().deleteFrom('place_contrib_log').where('day', '<', beforeDay).executeTakeFirst();
|
||||
return Number(result.numDeletedRows);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import type { PlaceContribOutbox } from '../entities/PlaceContribOutbox.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type OutboxKyselyDB = Pick<DB, 'place_contrib_outbox' | 'place_field_origin' | 'places'>;
|
||||
|
||||
/** One queued value as the sender reads it. */
|
||||
export interface OutboxRow {
|
||||
id: number;
|
||||
contrib_key: string;
|
||||
field: string;
|
||||
value: string;
|
||||
place_id: number;
|
||||
place_name: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
country: string | null;
|
||||
cid: string;
|
||||
attempts: number;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
/** A value to queue: the newest one for its key and field replaces what waits there. */
|
||||
interface OutboxWrite {
|
||||
contrib_key: string;
|
||||
field: string;
|
||||
value: string;
|
||||
place_id: number;
|
||||
place_name: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
country: string | null;
|
||||
cid: string;
|
||||
eligible_at: string;
|
||||
next_attempt_at: string;
|
||||
}
|
||||
|
||||
/** What the place and its origin row say about a queued value right now. */
|
||||
export interface OutboxCurrentRow {
|
||||
id: number;
|
||||
origin: string | null;
|
||||
value_hash: string | null;
|
||||
website: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
opening_hours: string | null;
|
||||
description: string | null;
|
||||
image_url: string | null;
|
||||
}
|
||||
|
||||
const OUTBOX_COLUMNS = [
|
||||
'id',
|
||||
'contrib_key',
|
||||
'field',
|
||||
'value',
|
||||
'place_id',
|
||||
'place_name',
|
||||
'lat',
|
||||
'lng',
|
||||
'country',
|
||||
'cid',
|
||||
'attempts',
|
||||
'created_at',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* `place_contrib_outbox`: the values waiting to be sent to the TREK Places
|
||||
* API, one per contribution key and field. A new value replaces the queued one
|
||||
* (and its attempts); the sender takes what is due, oldest first.
|
||||
*/
|
||||
export class PlaceContribOutboxRepository extends TrekRepository<PlaceContribOutbox> {
|
||||
private db() {
|
||||
return this.kysely<OutboxKyselyDB>();
|
||||
}
|
||||
|
||||
/** Queues a value, replacing whatever waited for the same key and field, attempts included. */
|
||||
async upsertEntry(row: OutboxWrite): Promise<void> {
|
||||
await this.db()
|
||||
.insertInto('place_contrib_outbox')
|
||||
.values({ ...row, attempts: 0 })
|
||||
.onConflict((oc) =>
|
||||
oc.columns(['contrib_key', 'field']).doUpdateSet({
|
||||
value: (eb) => eb.ref('excluded.value'),
|
||||
place_id: (eb) => eb.ref('excluded.place_id'),
|
||||
place_name: (eb) => eb.ref('excluded.place_name'),
|
||||
lat: (eb) => eb.ref('excluded.lat'),
|
||||
lng: (eb) => eb.ref('excluded.lng'),
|
||||
country: (eb) => eb.ref('excluded.country'),
|
||||
cid: (eb) => eb.ref('excluded.cid'),
|
||||
attempts: 0,
|
||||
eligible_at: (eb) => eb.ref('excluded.eligible_at'),
|
||||
next_attempt_at: (eb) => eb.ref('excluded.next_attempt_at'),
|
||||
}),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Whether a value waits for this key and field. */
|
||||
async hasEntry(contribKey: string, field: string): Promise<boolean> {
|
||||
const row = await this.db()
|
||||
.selectFrom('place_contrib_outbox')
|
||||
.select('id')
|
||||
.where('contrib_key', '=', contribKey)
|
||||
.where('field', '=', field)
|
||||
.executeTakeFirst();
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
/** Drops the queued values of these fields of one place. */
|
||||
async deleteForPlace(placeId: number, fields: string[]): Promise<number> {
|
||||
if (fields.length === 0) return 0;
|
||||
const result = await this.db()
|
||||
.deleteFrom('place_contrib_outbox')
|
||||
.where('place_id', '=', placeId)
|
||||
.where('field', 'in', fields)
|
||||
.executeTakeFirst();
|
||||
return Number(result.numDeletedRows);
|
||||
}
|
||||
|
||||
/** Drops every queued value of these fields, for a field an admin switched off. */
|
||||
async deleteFields(fields: string[]): Promise<number> {
|
||||
if (fields.length === 0) return 0;
|
||||
const result = await this.db().deleteFrom('place_contrib_outbox').where('field', 'in', fields).executeTakeFirst();
|
||||
return Number(result.numDeletedRows);
|
||||
}
|
||||
|
||||
async deleteIds(ids: number[]): Promise<number> {
|
||||
if (ids.length === 0) return 0;
|
||||
const result = await this.db().deleteFrom('place_contrib_outbox').where('id', 'in', ids).executeTakeFirst();
|
||||
return Number(result.numDeletedRows);
|
||||
}
|
||||
|
||||
/** Empties the queue; answers how many values went. */
|
||||
async deleteAll(): Promise<number> {
|
||||
const result = await this.db().deleteFrom('place_contrib_outbox').executeTakeFirst();
|
||||
return Number(result.numDeletedRows);
|
||||
}
|
||||
|
||||
async size(): Promise<number> {
|
||||
const row = await this.db()
|
||||
.selectFrom('place_contrib_outbox')
|
||||
.select((eb) => eb.fn.countAll<number>().as('count'))
|
||||
.executeTakeFirst();
|
||||
return Number(row?.count ?? 0);
|
||||
}
|
||||
|
||||
/** The keys whose first value is due at `now`, oldest first, at most `limit` of them. */
|
||||
async dueKeys(now: string, limit: number): Promise<string[]> {
|
||||
const rows = await this.db()
|
||||
.selectFrom('place_contrib_outbox')
|
||||
.select('contrib_key')
|
||||
.where('next_attempt_at', '<=', now)
|
||||
.groupBy('contrib_key')
|
||||
.orderBy((eb) => eb.fn.min('next_attempt_at'))
|
||||
.limit(limit)
|
||||
.execute();
|
||||
return rows.map((row) => row.contrib_key);
|
||||
}
|
||||
|
||||
/** The due values of one key. */
|
||||
async dueFor(contribKey: string, now: string): Promise<OutboxRow[]> {
|
||||
return this.db()
|
||||
.selectFrom('place_contrib_outbox')
|
||||
.select([...OUTBOX_COLUMNS])
|
||||
.where('contrib_key', '=', contribKey)
|
||||
.where('next_attempt_at', '<=', now)
|
||||
.orderBy('id')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* The queued values first queued before `before`, which the sender gives up
|
||||
* on; at most `limit` per call, so a long sweep goes in passes.
|
||||
*/
|
||||
async queuedBefore(before: string, limit: number): Promise<OutboxRow[]> {
|
||||
return this.db()
|
||||
.selectFrom('place_contrib_outbox')
|
||||
.select([...OUTBOX_COLUMNS])
|
||||
.where('created_at', '<', before)
|
||||
.orderBy('id')
|
||||
.limit(limit)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Counts the attempt and moves the values to their next try. */
|
||||
async scheduleRetry(ids: number[], nextAttemptAt: string): Promise<void> {
|
||||
if (ids.length === 0) return;
|
||||
await this.db()
|
||||
.updateTable('place_contrib_outbox')
|
||||
.set((eb) => ({ attempts: eb('attempts', '+', 1), next_attempt_at: nextAttemptAt }))
|
||||
.where('id', 'in', ids)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Moves the values to a later try without counting one (the service is pausing, not failing). */
|
||||
async postpone(ids: number[], nextAttemptAt: string): Promise<void> {
|
||||
if (ids.length === 0) return;
|
||||
await this.db()
|
||||
.updateTable('place_contrib_outbox')
|
||||
.set({ next_attempt_at: nextAttemptAt })
|
||||
.where('id', 'in', ids)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* The value each queued row's place holds now, with the origin row of that
|
||||
* field: the sender sends only what is still the user's.
|
||||
*/
|
||||
async currentOf(ids: number[]): Promise<Array<OutboxCurrentRow & { field: string }>> {
|
||||
if (ids.length === 0) return [];
|
||||
return this.db()
|
||||
.selectFrom('place_contrib_outbox as o')
|
||||
.innerJoin('places as p', 'p.id', 'o.place_id')
|
||||
.leftJoin('place_field_origin as f', (join) =>
|
||||
join.onRef('f.place_id', '=', 'o.place_id').onRef('f.field', '=', 'o.field'),
|
||||
)
|
||||
.select([
|
||||
'o.id as id',
|
||||
'o.field as field',
|
||||
'f.origin as origin',
|
||||
'f.value_hash as value_hash',
|
||||
'p.website as website',
|
||||
'p.phone as phone',
|
||||
'p.email as email',
|
||||
'p.opening_hours as opening_hours',
|
||||
'p.description as description',
|
||||
'p.image_url as image_url',
|
||||
])
|
||||
.where('o.id', 'in', ids)
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
import type { PlaceFieldOrigin } from '../entities/PlaceFieldOrigin.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type OriginKyselyDB = Pick<DB, 'place_field_origin' | 'places' | 'place_details_cache'>;
|
||||
|
||||
/** Where one field of a place got its current value, and the hash of that value. */
|
||||
interface PlaceOriginRow {
|
||||
field: string;
|
||||
origin: string;
|
||||
value_hash: string;
|
||||
}
|
||||
|
||||
/** One origin as it is written. */
|
||||
export interface PlaceOriginWrite {
|
||||
place_id: number;
|
||||
field: string;
|
||||
origin: string;
|
||||
value_hash: string;
|
||||
updated_at: string;
|
||||
}
|
||||
|
||||
/** The columns of a place the origin tracking and the contribution read: its shareable details and what names it. */
|
||||
export interface PlaceShareableRow {
|
||||
id: number;
|
||||
name: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
address: string | null;
|
||||
osm_id: string | null;
|
||||
google_place_id: string | null;
|
||||
amap_poi_id: string | null;
|
||||
website: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
opening_hours: string | null;
|
||||
description: string | null;
|
||||
image_url: string | null;
|
||||
}
|
||||
|
||||
/** One cached details record: the provider id it is keyed by, its kind (0 lean, 1 expanded, 2 enrichment), the JSON. */
|
||||
export interface CachedProviderPayload {
|
||||
place_id: string;
|
||||
expanded: number;
|
||||
payload_json: string;
|
||||
}
|
||||
|
||||
const SHAREABLE_COLUMNS = [
|
||||
'id',
|
||||
'name',
|
||||
'lat',
|
||||
'lng',
|
||||
'address',
|
||||
'osm_id',
|
||||
'google_place_id',
|
||||
'amap_poi_id',
|
||||
'website',
|
||||
'phone',
|
||||
'email',
|
||||
'opening_hours',
|
||||
'description',
|
||||
'image_url',
|
||||
] as const;
|
||||
|
||||
/**
|
||||
* `place_field_origin`: per place and shareable field, who set the value it
|
||||
* holds (the user, a provider, the assistant, a plugin, an import, an
|
||||
* attachment) and the hash of that value. A row whose hash no longer matches
|
||||
* the column describes a value that is gone and counts as unknown.
|
||||
*
|
||||
* The two reads on other tables are the ones the origin rules need next to it:
|
||||
* the place's own shareable columns, and the provider records this instance
|
||||
* cached for the place's ids, so a value claimed as typed can be checked
|
||||
* against what a provider handed out.
|
||||
*/
|
||||
export class PlaceFieldOriginRepository extends TrekRepository<PlaceFieldOrigin> {
|
||||
private db() {
|
||||
return this.kysely<OriginKyselyDB>();
|
||||
}
|
||||
|
||||
/** The place's shareable columns, or null when there is no such place. */
|
||||
async placeValues(placeId: number): Promise<PlaceShareableRow | null> {
|
||||
const row = await this.db()
|
||||
.selectFrom('places')
|
||||
.select([...SHAREABLE_COLUMNS])
|
||||
.where('id', '=', placeId)
|
||||
.executeTakeFirst();
|
||||
return row ?? null;
|
||||
}
|
||||
|
||||
/** The shareable columns of several places, for an import that recorded them all at once. */
|
||||
async placeValuesMany(placeIds: number[]): Promise<PlaceShareableRow[]> {
|
||||
if (placeIds.length === 0) return [];
|
||||
return this.db()
|
||||
.selectFrom('places')
|
||||
.select([...SHAREABLE_COLUMNS])
|
||||
.where('id', 'in', placeIds)
|
||||
.execute();
|
||||
}
|
||||
|
||||
async originsOf(placeId: number): Promise<PlaceOriginRow[]> {
|
||||
return this.db()
|
||||
.selectFrom('place_field_origin')
|
||||
.select(['field', 'origin', 'value_hash'])
|
||||
.where('place_id', '=', placeId)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Writes the origins in one statement; a field that has one already gets the new one. */
|
||||
async upsertOrigins(rows: PlaceOriginWrite[]): Promise<void> {
|
||||
if (rows.length === 0) return;
|
||||
await this.db()
|
||||
.insertInto('place_field_origin')
|
||||
.values(rows)
|
||||
.onConflict((oc) =>
|
||||
oc.columns(['place_id', 'field']).doUpdateSet({
|
||||
origin: (eb) => eb.ref('excluded.origin'),
|
||||
value_hash: (eb) => eb.ref('excluded.value_hash'),
|
||||
updated_at: (eb) => eb.ref('excluded.updated_at'),
|
||||
}),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Forgets the origins of these fields of a place, for a value that was cleared. */
|
||||
async deleteOrigins(placeId: number, fields: string[]): Promise<number> {
|
||||
if (fields.length === 0) return 0;
|
||||
const result = await this.db()
|
||||
.deleteFrom('place_field_origin')
|
||||
.where('place_id', '=', placeId)
|
||||
.where('field', 'in', fields)
|
||||
.executeTakeFirst();
|
||||
return Number(result.numDeletedRows);
|
||||
}
|
||||
|
||||
/**
|
||||
* The details records this instance cached for these provider ids (Google,
|
||||
* Amap, OpenStreetMap, the TREK index), every language and kind, as stored.
|
||||
*/
|
||||
async cachedProviderPayloads(providerIds: string[]): Promise<CachedProviderPayload[]> {
|
||||
if (providerIds.length === 0) return [];
|
||||
return this.db()
|
||||
.selectFrom('place_details_cache')
|
||||
.select(['place_id', 'expanded', 'payload_json'])
|
||||
.where('place_id', 'in', providerIds)
|
||||
.execute();
|
||||
}
|
||||
}
|
||||
@@ -69,6 +69,7 @@ import { PaddleObstaclesModule } from './paddle-obstacles/paddle-obstacles.modul
|
||||
import { PaddleRoutingModule } from './paddle-routing/paddle-routing.module';
|
||||
import { PermissionsModule } from './permissions/permissions.module';
|
||||
import { PhotosModule } from './photos/photos.module';
|
||||
import { PlaceContribModule } from './place-contrib/place-contrib.module';
|
||||
import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
|
||||
import { PlaceImportModule } from './place-import/place-import.module';
|
||||
import { PlaceShadowModule } from './place-shadow/place-shadow.module';
|
||||
@@ -142,6 +143,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
|
||||
MapsModule,
|
||||
PlaceImportModule,
|
||||
GoogleQuotaModule,
|
||||
PlaceContribModule,
|
||||
PlaceEnrichmentModule,
|
||||
PlaceShadowModule,
|
||||
RouteUsageModule,
|
||||
|
||||
@@ -31,6 +31,8 @@ const ACTION_LABELS: Record<string, string> = {
|
||||
'admin.storage_backfill': 'started a storage sync',
|
||||
'admin.storage_backfill_cancel': 'cancelled a storage sync',
|
||||
'admin.storage_stats_refresh': 'refreshed storage usage stats',
|
||||
'admin.places_contribute_decision': 'decided on sharing place details with TREK Places',
|
||||
'admin.places_contribute_withdraw': 'withdrew the place details this installation shared',
|
||||
'immich.private_ip_configured': 'configured Immich with private IP',
|
||||
'oidc.role_change': 'role changed by OIDC claim mapping',
|
||||
};
|
||||
|
||||
@@ -139,6 +139,13 @@ export const APP_SETTINGS = {
|
||||
ai_assistant_web_search: { schema: flag, default: 'true' },
|
||||
/** `urn:uuid:<uuid>`: this install as one host to Sign in with ChatGPT, created on the first sign-in. */
|
||||
ai_siwc_host_id: { schema: text, default: null },
|
||||
// Community enrichment of place details (place-contrib). The installation's decision as the
|
||||
// JSON of placeContribConsentSchema, off until an admin agrees; per admin, when their
|
||||
// "not now" ends; and why sending waits although an admin agreed (a refused key, a pause
|
||||
// the service asked for). None is the operator's to set on a managed install.
|
||||
places_contribute: { schema: text, default: null },
|
||||
places_contribute_snooze: { schema: text, default: null },
|
||||
places_contribute_pause: { schema: text, default: null },
|
||||
/** This installation's key towards the liketrek services, issued on first use (service-identity). */
|
||||
service_key: { schema: text, default: null, encrypted: 'always', managedLocked: true },
|
||||
/** The key's bookkeeping as JSON: when to renew, when to ask again after a refusal, a revocation. */
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
/**
|
||||
* The SHA-256 of a stored value, hex. The origin of a place's field is kept
|
||||
* with the hash of the value it describes, so a value changed by any path that
|
||||
* did not record an origin (a migration, a direct SQL fix, an older plugin SDK,
|
||||
* a restore) no longer matches and counts as unknown.
|
||||
*/
|
||||
export function valueHash(value: string): string {
|
||||
return createHash('sha256').update(value, 'utf8').digest('hex');
|
||||
}
|
||||
@@ -98,6 +98,8 @@ export interface TrekPlace {
|
||||
hours: { osm: string; source: string | null; sourceUrl: string | null } | null;
|
||||
/** Quoted from the place's own site, when it publishes one for machines. */
|
||||
description?: { text: string; source: string | null; sourceUrl: string | null } | null;
|
||||
/** Bumped by the service whenever the community values it overlays for this place change. */
|
||||
community?: { version?: number } | null;
|
||||
score?: number;
|
||||
}
|
||||
|
||||
@@ -673,6 +675,8 @@ export function toPlaceRecord(p: TrekPlace): Record<string, unknown> {
|
||||
// place cost two full round trips to the index. Left as the service shaped
|
||||
// it — the reader validates the URL before it becomes a link.
|
||||
description: p.description ?? null,
|
||||
// Where the cached enrichment of this place has to be read again (place-enrichment).
|
||||
community_version: typeof p.community?.version === 'number' ? p.community.version : null,
|
||||
source: 'trek-places',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import { readImageHeader } from '../common/image-header';
|
||||
import { IMAGE_JPEG_QUALITY, IMAGE_MAX_BYTES, IMAGE_MAX_EDGE, IMAGE_MAX_PIXELS } from './place-contrib.constants';
|
||||
|
||||
import { Jimp } from 'jimp';
|
||||
|
||||
/** The long edges tried, largest first, until the picture fits the byte cap. */
|
||||
const EDGES = [IMAGE_MAX_EDGE, 1600, 1280, 1024] as const;
|
||||
|
||||
/**
|
||||
* A place picture as it is sent: decoded, its long edge at most 2048 px,
|
||||
* re-encoded as a JPEG at quality 85 and at most a megabyte. The re-encode is
|
||||
* what strips the metadata: the encoder writes pixels only, so a camera's EXIF
|
||||
* (the position it was taken at, the device, the owner) never leaves.
|
||||
*
|
||||
* Null for a picture that cannot be sent: one TREK cannot decode (WebP, a
|
||||
* header that says nothing), one over the pixel cap, or one that stays over
|
||||
* the byte cap at the smallest edge tried.
|
||||
*/
|
||||
export async function contribJpeg(data: Buffer): Promise<Buffer | null> {
|
||||
const header = readImageHeader(data);
|
||||
if (!header || header.mimeType === 'image/webp') return null;
|
||||
if (header.width * header.height > IMAGE_MAX_PIXELS) return null;
|
||||
try {
|
||||
const image = await Jimp.read(data, { 'image/jpeg': { maxResolutionInMP: IMAGE_MAX_PIXELS / 1_000_000 } });
|
||||
for (const edge of EDGES) {
|
||||
const copy = image.clone();
|
||||
if (Math.max(copy.width, copy.height) > edge) {
|
||||
if (copy.width >= copy.height) copy.resize({ w: edge });
|
||||
else copy.resize({ h: edge });
|
||||
}
|
||||
const encoded = Buffer.from(await copy.getBuffer('image/jpeg', { quality: IMAGE_JPEG_QUALITY }));
|
||||
if (encoded.length <= IMAGE_MAX_BYTES) return encoded;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,397 @@
|
||||
import { PlaceContribLog } from '../../db/entities/PlaceContribLog.entity';
|
||||
import { PlaceContribOutbox } from '../../db/entities/PlaceContribOutbox.entity';
|
||||
import type { PlaceContribLogRepository, PlaceContribLogWrite } from '../../db/repositories/PlaceContribLog.repository';
|
||||
import type {
|
||||
OutboxCurrentRow,
|
||||
OutboxRow,
|
||||
PlaceContribOutboxRepository,
|
||||
} from '../../db/repositories/PlaceContribOutbox.repository';
|
||||
import { dbNow } from '../../db/types';
|
||||
import { logInfo } from '../audit/audit-log.logger';
|
||||
import { valueHash } from '../common/value-hash';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { contribJpeg } from './place-contrib-image';
|
||||
import { PlaceContribSettings } from './place-contrib-settings';
|
||||
import { PlaceContribClient, type ContribAnswer, type ServedPlace } from './place-contrib.client';
|
||||
import {
|
||||
MAX_ATTEMPTS,
|
||||
NOT_ACCEPTING_WAIT_MS,
|
||||
OUTBOX_MAX_AGE_DAYS,
|
||||
PLACE_BODY_MAX_BYTES,
|
||||
PLACES_PER_RUN,
|
||||
} from './place-contrib.constants';
|
||||
import {
|
||||
UPLOADED_IMAGE_PREFIX,
|
||||
baseHashOf,
|
||||
dayOf,
|
||||
gersOf,
|
||||
logResultOf,
|
||||
payloadOf,
|
||||
requestCid,
|
||||
retryDelayMs,
|
||||
summaryOf,
|
||||
} from './place-contrib.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
PLACE_CONTRIB_TERMS_VERSION,
|
||||
type PlaceContribField,
|
||||
type PlaceContribImageAnswer,
|
||||
type PlaceContribLogResult,
|
||||
type PlaceContribPlaceAnswer,
|
||||
type PlaceContribPlaceBody,
|
||||
} from '@trek/shared';
|
||||
|
||||
const DAY_MS = 24 * 3_600_000;
|
||||
/** The most a stored picture may weigh before it is read for sending: the upload cap. */
|
||||
const STORED_IMAGE_MAX_BYTES = 20 * 1024 * 1024;
|
||||
/** Old values are given up on in passes of this many. */
|
||||
const EXPIRE_BATCH = 500;
|
||||
|
||||
/** Whether the run goes on with the next place or stops here (the service asked to wait, the key was refused). */
|
||||
type Next = 'next' | 'stop';
|
||||
|
||||
/** What became of one queued value for good: the log line it gets, and it leaves the queue. */
|
||||
interface Final {
|
||||
entry: OutboxRow;
|
||||
result: PlaceContribLogResult;
|
||||
reason: string | null;
|
||||
}
|
||||
|
||||
/** What one run did, for the job's log line and the tests. */
|
||||
interface SendRun {
|
||||
skipped: 'inactive' | 'paused' | null;
|
||||
places: number;
|
||||
expired: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends what the queue holds to the TREK Places API, one place after the
|
||||
* other, at most PLACES_PER_RUN per run.
|
||||
*
|
||||
* Before a value goes, it is checked against the place once more: it must
|
||||
* still be what the place holds, and its origin row must still say the user
|
||||
* typed exactly that (C5). Anything else stays home and is logged as withheld.
|
||||
* A value the index already serves is not sent either.
|
||||
*
|
||||
* Every outcome is one of three: final (logged and gone from the queue),
|
||||
* another try later (10 min, 30 min, 2 h, 6 h, the service's Retry-After when
|
||||
* it names one, at most MAX_ATTEMPTS), or a pause for the whole run (a refused
|
||||
* key, the service not taking contributions). A refusal with a reason is
|
||||
* final; only an answer that never came, or a server error, is tried again.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceContribSender {
|
||||
constructor(
|
||||
@InjectRepository(PlaceContribOutbox) private readonly outbox: PlaceContribOutboxRepository,
|
||||
@InjectRepository(PlaceContribLog) private readonly log: PlaceContribLogRepository,
|
||||
private readonly store: PlaceContribSettings,
|
||||
private readonly client: PlaceContribClient,
|
||||
private readonly storage: StorageService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
/** @txIndependent one place after the other, with a request between each place's writes. */
|
||||
async run(now: Date = new Date()): Promise<SendRun> {
|
||||
const fields = await this.store.activeFields();
|
||||
if (fields.length === 0) return { skipped: 'inactive', places: 0, expired: 0 };
|
||||
if (await this.store.pauseReason(now)) return { skipped: 'paused', places: 0, expired: 0 };
|
||||
const expired = await this.expire(now);
|
||||
const keys = await this.outbox.dueKeys(dbNow(now), PLACES_PER_RUN);
|
||||
let places = 0;
|
||||
for (const key of keys) {
|
||||
places += 1;
|
||||
if ((await this.sendKey(key, fields, now)) === 'stop') break;
|
||||
}
|
||||
if (places > 0 || expired > 0) logInfo(`Places contribution: ${places} place(s) sent, ${expired} expired`);
|
||||
return { skipped: null, places, expired };
|
||||
}
|
||||
|
||||
/** Values queued for longer than OUTBOX_MAX_AGE_DAYS are dropped as withheld:expired. */
|
||||
private async expire(now: Date): Promise<number> {
|
||||
const before = dbNow(new Date(now.getTime() - OUTBOX_MAX_AGE_DAYS * DAY_MS));
|
||||
const old = await this.outbox.queuedBefore(before, EXPIRE_BATCH);
|
||||
await this.finish(
|
||||
old.map((entry): Final => ({ entry, result: 'withheld', reason: 'expired' })),
|
||||
now,
|
||||
);
|
||||
return old.length;
|
||||
}
|
||||
|
||||
/** @txIndependent the stale values settle before the place's request, its answer after it. */
|
||||
private async sendKey(key: string, fields: PlaceContribField[], now: Date): Promise<Next> {
|
||||
const entries = await this.outbox.dueFor(key, dbNow(now));
|
||||
const current = new Map((await this.outbox.currentOf(entries.map((e) => e.id))).map((row) => [row.id, row]));
|
||||
const stale: Final[] = [];
|
||||
const valid: OutboxRow[] = [];
|
||||
for (const entry of entries) {
|
||||
const reason = staleReason(entry, current.get(entry.id), fields);
|
||||
if (reason) stale.push({ entry, result: 'withheld', reason });
|
||||
else valid.push(entry);
|
||||
}
|
||||
await this.finish(stale, now);
|
||||
const text = valid.filter((entry) => entry.field !== 'image');
|
||||
if (text.length > 0 && (await this.sendText(key, text, now)) === 'stop') return 'stop';
|
||||
for (const image of valid.filter((entry) => entry.field === 'image')) {
|
||||
if ((await this.sendImage(image, now)) === 'stop') return 'stop';
|
||||
}
|
||||
return 'next';
|
||||
}
|
||||
|
||||
/** @txIndependent the values the index already serves settle before the request, the rest after it. */
|
||||
private async sendText(key: string, entries: OutboxRow[], now: Date): Promise<Next> {
|
||||
const gers = gersOf(key);
|
||||
const served = gers ? await this.client.servedPlace(gers) : null;
|
||||
const unchanged = entries.filter((entry) => servedValue(served, entry.field) === entry.value);
|
||||
await this.finish(
|
||||
unchanged.map((entry): Final => ({ entry, result: 'withheld', reason: 'unchanged' })),
|
||||
now,
|
||||
);
|
||||
const rest = entries.filter((entry) => !unchanged.includes(entry));
|
||||
if (rest.length === 0) return 'next';
|
||||
const body = placeBody(key, rest, served);
|
||||
if (Buffer.byteLength(JSON.stringify(body), 'utf8') > PLACE_BODY_MAX_BYTES) {
|
||||
await this.finish(
|
||||
rest.map((entry): Final => ({ entry, result: 'withheld', reason: 'too_large' })),
|
||||
now,
|
||||
);
|
||||
return 'next';
|
||||
}
|
||||
return this.settlePlace(rest, await this.client.postPlace(body), now);
|
||||
}
|
||||
|
||||
/** @txIndependent a picture that cannot go settles at once, one that goes after its request. */
|
||||
private async sendImage(entry: OutboxRow, now: Date): Promise<Next> {
|
||||
const bytes = await this.storedImage(entry.value.slice(UPLOADED_IMAGE_PREFIX.length));
|
||||
const jpeg = bytes ? await contribJpeg(bytes) : null;
|
||||
if (!jpeg) {
|
||||
await this.finish([{ entry, result: 'withheld', reason: bytes ? 'image_unreadable' : 'image_missing' }], now);
|
||||
return 'next';
|
||||
}
|
||||
const answer = await this.client.postImage(entry.contrib_key, requestCid([entry.cid]), jpeg);
|
||||
// Images are off on the service until it screens them. That is no failure
|
||||
// to try again: the picture stays home and the log says so.
|
||||
if (answer.kind === 'refused' && answer.error === 'images_disabled') {
|
||||
await this.finish([{ entry, result: 'withheld', reason: 'images_disabled' }], now);
|
||||
return 'next';
|
||||
}
|
||||
return this.settleImage(entry, answer, now);
|
||||
}
|
||||
|
||||
private async settlePlace(
|
||||
entries: OutboxRow[],
|
||||
answer: ContribAnswer<PlaceContribPlaceAnswer>,
|
||||
now: Date,
|
||||
): Promise<Next> {
|
||||
if (answer.kind === 'failed') return this.retry(entries, { now, retryAfterMs: answer.retryAfterMs });
|
||||
if (answer.kind === 'refused') return this.refused(entries, answer, now);
|
||||
const finals: Final[] = [];
|
||||
const quota: OutboxRow[] = [];
|
||||
for (const entry of entries) {
|
||||
const outcome = answer.body.results[entry.field as PlaceContribField];
|
||||
if (!outcome) {
|
||||
finals.push({ entry, result: answer.body.duplicate ? 'duplicate' : 'rejected', reason: 'no_result' });
|
||||
} else if (outcome.result === 'quota') {
|
||||
quota.push(entry);
|
||||
} else {
|
||||
finals.push({ entry, result: logResultOf(outcome.result), reason: outcome.reason ?? outcome.result });
|
||||
}
|
||||
}
|
||||
await this.uow.transactional(async () => {
|
||||
await this.finish(finals, now);
|
||||
if (quota.length > 0) await this.retry(quota, { now, retryAfterMs: null });
|
||||
});
|
||||
return 'next';
|
||||
}
|
||||
|
||||
private async settleImage(
|
||||
entry: OutboxRow,
|
||||
answer: ContribAnswer<PlaceContribImageAnswer>,
|
||||
now: Date,
|
||||
): Promise<Next> {
|
||||
if (answer.kind === 'failed') return this.retry([entry], { now, retryAfterMs: answer.retryAfterMs });
|
||||
if (answer.kind === 'refused') return this.refused([entry], answer, now);
|
||||
const outcome = answer.body.result;
|
||||
if (outcome.result === 'quota') return this.retry([entry], { now, retryAfterMs: null });
|
||||
await this.finish([{ entry, result: logResultOf(outcome.result), reason: outcome.reason ?? outcome.result }], now);
|
||||
return 'next';
|
||||
}
|
||||
|
||||
/** A status with the service's reason: its writes land together. */
|
||||
private async refused(
|
||||
entries: OutboxRow[],
|
||||
refusal: { status: number; error: string; retryAfterMs: number | null },
|
||||
now: Date,
|
||||
): Promise<Next> {
|
||||
return this.uow.transactional(() => this.settleRefusal(entries, refusal, now));
|
||||
}
|
||||
|
||||
private async settleRefusal(
|
||||
entries: OutboxRow[],
|
||||
refusal: { status: number; error: string; retryAfterMs: number | null },
|
||||
now: Date,
|
||||
): Promise<Next> {
|
||||
if (refusal.status === 401 || refusal.status === 403) {
|
||||
// The key is not taken: wait for another one, never fall back to sending without.
|
||||
await this.store.pauseFor(refusal.status === 401 ? 'key_invalid' : 'key_refused', null);
|
||||
await this.outbox.postpone(ids(entries), dbNow(new Date(now.getTime() + NOT_ACCEPTING_WAIT_MS)));
|
||||
return 'stop';
|
||||
}
|
||||
if (refusal.status === 429) {
|
||||
await this.retry(entries, { now, retryAfterMs: refusal.retryAfterMs });
|
||||
return 'stop';
|
||||
}
|
||||
if (refusal.status === 503) {
|
||||
const until = new Date(now.getTime() + (refusal.retryAfterMs ?? NOT_ACCEPTING_WAIT_MS));
|
||||
await this.store.pauseFor('not_accepting', until);
|
||||
await this.outbox.postpone(ids(entries), dbNow(until));
|
||||
return 'stop';
|
||||
}
|
||||
const refusedField = /^field_not_accepted:([a-z_]+)$/.exec(refusal.error)?.[1];
|
||||
if (refusedField) {
|
||||
// The service names the one field it does not take; the others go again
|
||||
// on the next run, without it, and without counting an attempt.
|
||||
const [taken, others] = partition(entries, (entry) => entry.field === refusedField);
|
||||
await this.finish(
|
||||
taken.map((entry): Final => ({ entry, result: 'rejected', reason: refusal.error })),
|
||||
now,
|
||||
);
|
||||
await this.outbox.postpone(ids(others), dbNow(now));
|
||||
return 'next';
|
||||
}
|
||||
await this.finish(
|
||||
entries.map((entry): Final => ({ entry, result: 'rejected', reason: refusal.error })),
|
||||
now,
|
||||
);
|
||||
return 'next';
|
||||
}
|
||||
|
||||
/** Another try later, or given up after MAX_ATTEMPTS. */
|
||||
private async retry(entries: OutboxRow[], opts: { now: Date; retryAfterMs: number | null }): Promise<Next> {
|
||||
const [givenUp, again] = partition(entries, (entry) => entry.attempts + 1 >= MAX_ATTEMPTS);
|
||||
const attempts = Math.max(1, ...again.map((entry) => entry.attempts + 1));
|
||||
const next = dbNow(new Date(opts.now.getTime() + (opts.retryAfterMs ?? retryDelayMs(attempts))));
|
||||
await this.uow.transactional(async () => {
|
||||
await this.outbox.scheduleRetry(ids(again), next);
|
||||
await this.finishInTx(
|
||||
givenUp.map((entry): Final => ({ entry, result: 'withheld', reason: 'gave_up' })),
|
||||
opts.now,
|
||||
);
|
||||
});
|
||||
return 'next';
|
||||
}
|
||||
|
||||
/** Logs the outcomes and takes the values out of the queue, together. */
|
||||
private async finish(finals: Final[], now: Date): Promise<void> {
|
||||
if (finals.length === 0) return;
|
||||
await this.uow.transactional(() => this.finishInTx(finals, now));
|
||||
}
|
||||
|
||||
private async finishInTx(finals: Final[], now: Date): Promise<void> {
|
||||
if (finals.length === 0) return;
|
||||
await this.log.insertLines(finals.map((final) => logLine(final, now)));
|
||||
await this.outbox.deleteIds(finals.map((final) => final.entry.id));
|
||||
}
|
||||
|
||||
/** The bytes of an uploaded place picture, null when it is gone or heavier than any upload could be. */
|
||||
private async storedImage(name: string): Promise<Buffer | null> {
|
||||
if (!name || name.includes('/')) return null;
|
||||
try {
|
||||
const stat = await this.storage.stat('places', name);
|
||||
if (!stat || stat.size > STORED_IMAGE_MAX_BYTES) return null;
|
||||
const { stream } = await this.storage.getStream('places', name);
|
||||
const chunks: Buffer[] = [];
|
||||
let total = 0;
|
||||
for await (const chunk of stream) {
|
||||
const part = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk as Uint8Array);
|
||||
total += part.length;
|
||||
if (total > STORED_IMAGE_MAX_BYTES) {
|
||||
stream.destroy();
|
||||
return null;
|
||||
}
|
||||
chunks.push(part);
|
||||
}
|
||||
return Buffer.concat(chunks);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Why a queued value may not go any more, or null when it still may. */
|
||||
function staleReason(
|
||||
entry: OutboxRow,
|
||||
current: OutboxCurrentRow | undefined,
|
||||
fields: readonly PlaceContribField[],
|
||||
): string | null {
|
||||
const field = entry.field as PlaceContribField;
|
||||
if (!fields.includes(field)) return 'field_off';
|
||||
if (!current || current.origin !== 'user' || !current.value_hash) return 'origin_changed';
|
||||
const column = columnOf(current, field);
|
||||
if (column === null || valueHash(column) !== current.value_hash) return 'origin_stale';
|
||||
const payload = payloadOf(field, column);
|
||||
return 'value' in payload && payload.value === entry.value ? null : 'value_changed';
|
||||
}
|
||||
|
||||
/** The column a field is stored in. */
|
||||
function columnOf(row: OutboxCurrentRow, field: PlaceContribField): string | null {
|
||||
return field === 'image' ? row.image_url : row[field];
|
||||
}
|
||||
|
||||
/** What the index serves for a field, in the form a queued value has; null when it serves nothing. */
|
||||
function servedValue(served: ServedPlace | null, field: string): string | null {
|
||||
if (!served || field === 'image') return null;
|
||||
const raw = served[field as Exclude<PlaceContribField, 'image'>];
|
||||
if (!raw) return null;
|
||||
// Served hours are OSM syntax already, which is the form a queued value has.
|
||||
if (field === 'opening_hours') return raw.trim() || null;
|
||||
const payload = payloadOf(field as PlaceContribField, raw);
|
||||
return 'value' in payload ? payload.value : null;
|
||||
}
|
||||
|
||||
function placeBody(key: string, entries: OutboxRow[], served: ServedPlace | null): PlaceContribPlaceBody {
|
||||
const first = entries[0];
|
||||
const fields: PlaceContribPlaceBody['fields'] = {};
|
||||
for (const entry of entries) {
|
||||
const field = entry.field as Exclude<PlaceContribField, 'image'>;
|
||||
fields[field] = { value: entry.value, baseHash: baseHashOf(served?.[field]) };
|
||||
}
|
||||
return {
|
||||
v: 1,
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
cid: requestCid(entries.map((entry) => entry.cid)),
|
||||
key,
|
||||
fields,
|
||||
place: {
|
||||
name: first.place_name.slice(0, 200),
|
||||
lat: first.lat,
|
||||
lng: first.lng,
|
||||
country: first.country && /^[A-Z]{2}$/.test(first.country) ? first.country : null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function logLine(final: Final, now: Date): PlaceContribLogWrite {
|
||||
const field = final.entry.field as PlaceContribField;
|
||||
return {
|
||||
day: dayOf(now),
|
||||
contrib_key: final.entry.contrib_key,
|
||||
place_name: final.entry.place_name,
|
||||
field,
|
||||
value_summary: summaryOf(field, final.entry.value),
|
||||
result: final.result,
|
||||
reason: final.reason?.slice(0, 200) ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
function ids(entries: OutboxRow[]): number[] {
|
||||
return entries.map((entry) => entry.id);
|
||||
}
|
||||
|
||||
function partition<T>(items: T[], test: (item: T) => boolean): [T[], T[]] {
|
||||
const yes: T[] = [];
|
||||
const no: T[] = [];
|
||||
for (const item of items) (test(item) ? yes : no).push(item);
|
||||
return [yes, no];
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
import {
|
||||
PLACES_CONTRIBUTE_CONSENT,
|
||||
PLACES_CONTRIBUTE_PAUSE,
|
||||
PLACES_CONTRIBUTE_SNOOZE,
|
||||
type PlacesContributePause,
|
||||
} from '../../db/json-columns';
|
||||
import { decodeJson, encodeJson } from '../../utils/json-column';
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import { servicesConfig } from '../app-config/tokens';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { PlaceContribClient } from './place-contrib.client';
|
||||
import { CONTRIB_ORIGIN } from './place-contrib.constants';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
import type { ConfigType } from '@nestjs/config';
|
||||
import {
|
||||
PLACE_CONTRIB_FIELDS,
|
||||
PLACE_CONTRIB_TERMS_VERSION,
|
||||
type PlaceContribConsent,
|
||||
type PlaceContribField,
|
||||
type PlaceContribIneligibleReason,
|
||||
type PlaceContribPauseReason,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Where an installation stands before any admin decision: whether it may send at all, and if not, why. */
|
||||
type Eligibility = { eligible: true; reason: null } | { eligible: false; reason: PlaceContribIneligibleReason };
|
||||
|
||||
/**
|
||||
* The stored side of the community enrichment: the admin's decision, the
|
||||
* per-admin snooze and the pause, all in app_settings, and whether this
|
||||
* installation may send at all.
|
||||
*
|
||||
* Eligibility is not stored. It follows the deployment, read live: the
|
||||
* TREK_PLACES_CONTRIBUTE ceiling, a production instance that is no demo, the
|
||||
* index on and at the public address, TREK_SERVICES on and a key in hand.
|
||||
* Development, test and demo instances never send, whatever an admin chose.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceContribSettings {
|
||||
constructor(
|
||||
private readonly settings: SettingsService,
|
||||
private readonly env: RuntimeEnvService,
|
||||
@Inject(servicesConfig.KEY) private readonly services: ConfigType<typeof servicesConfig>,
|
||||
private readonly client: PlaceContribClient,
|
||||
) {}
|
||||
|
||||
ceiling(): 'off' | 'admin' {
|
||||
return this.env.env().maps.trekPlacesContribute;
|
||||
}
|
||||
|
||||
eligibility(): Eligibility {
|
||||
const maps = this.env.env().maps;
|
||||
const reason = ((): PlaceContribIneligibleReason | null => {
|
||||
if (maps.trekPlacesContribute !== 'admin') return 'env_off';
|
||||
if (!this.env.isProduction()) return 'not_production';
|
||||
if (this.env.isDemoMode()) return 'demo';
|
||||
if (!maps.trekPlacesEnabled) return 'index_off';
|
||||
if (customPlacesUrl(maps.trekPlacesUrl)) return 'custom_places_url';
|
||||
if (this.services.mode === 'off') return 'services_off';
|
||||
if (!this.client.hasKey()) return 'no_key';
|
||||
return null;
|
||||
})();
|
||||
return reason === null ? { eligible: true, reason: null } : { eligible: false, reason };
|
||||
}
|
||||
|
||||
async consent(): Promise<PlaceContribConsent> {
|
||||
return decodeJson(PLACES_CONTRIBUTE_CONSENT, await this.settings.getAppSetting('places_contribute'), 'consent');
|
||||
}
|
||||
|
||||
async writeConsent(consent: PlaceContribConsent): Promise<void> {
|
||||
await this.settings.setAppSettings({ places_contribute: encodeJson(PLACES_CONTRIBUTE_CONSENT, consent) });
|
||||
}
|
||||
|
||||
/** The fields an agreement to the current terms switches on; none without one. */
|
||||
async activeFields(): Promise<PlaceContribField[]> {
|
||||
if (!this.eligibility().eligible) return [];
|
||||
const consent = await this.consent();
|
||||
if (!agreedToCurrentTerms(consent)) return [];
|
||||
return PLACE_CONTRIB_FIELDS.filter((field) => consent.fields[field]);
|
||||
}
|
||||
|
||||
async snoozedUntil(adminId: number, now: Date): Promise<string | null> {
|
||||
const until = (await this.snoozes())[String(adminId)] ?? null;
|
||||
return until && Date.parse(until) > now.getTime() ? until : null;
|
||||
}
|
||||
|
||||
async snooze(adminId: number, until: Date): Promise<void> {
|
||||
const snoozes = { ...(await this.snoozes()), [String(adminId)]: until.toISOString() };
|
||||
await this.settings.setAppSettings({ places_contribute_snooze: encodeJson(PLACES_CONTRIBUTE_SNOOZE, snoozes) });
|
||||
}
|
||||
|
||||
/** The pause in force now: a refused key until there is another one, the service's wait until it ends. */
|
||||
async pauseReason(now: Date): Promise<PlaceContribPauseReason | null> {
|
||||
const pause = await this.pause();
|
||||
if (!pause) return null;
|
||||
if (pause.reason === 'not_accepting')
|
||||
return pause.until && Date.parse(pause.until) > now.getTime() ? pause.reason : null;
|
||||
return pause.key === this.client.keyFingerprint() ? pause.reason : null;
|
||||
}
|
||||
|
||||
async pauseFor(reason: PlaceContribPauseReason, until: Date | null): Promise<void> {
|
||||
const pause: PlacesContributePause = {
|
||||
reason,
|
||||
key: reason === 'not_accepting' ? null : this.client.keyFingerprint(),
|
||||
until: until?.toISOString() ?? null,
|
||||
};
|
||||
await this.settings.setAppSettings({ places_contribute_pause: encodeJson(PLACES_CONTRIBUTE_PAUSE, pause) });
|
||||
}
|
||||
|
||||
async clearPause(): Promise<void> {
|
||||
await this.settings.deleteAppSettings(['places_contribute_pause']);
|
||||
}
|
||||
|
||||
private async snoozes(): Promise<Record<string, string>> {
|
||||
return decodeJson(
|
||||
PLACES_CONTRIBUTE_SNOOZE,
|
||||
await this.settings.getAppSetting('places_contribute_snooze'),
|
||||
'snooze',
|
||||
);
|
||||
}
|
||||
|
||||
private async pause(): Promise<PlacesContributePause | null> {
|
||||
return decodeJson(PLACES_CONTRIBUTE_PAUSE, await this.settings.getAppSetting('places_contribute_pause'), 'pause');
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether a decision is a standing agreement to the terms in force. */
|
||||
export function agreedToCurrentTerms(consent: PlaceContribConsent): boolean {
|
||||
return consent.enabled && consent.decision === 'agreed' && consent.termsVersion === PLACE_CONTRIB_TERMS_VERSION;
|
||||
}
|
||||
|
||||
/** An own TREK_PLACES_URL: anything but unset or the public instance itself. */
|
||||
function customPlacesUrl(configured: string | undefined): boolean {
|
||||
const url = configured?.trim().replace(/\/+$/, '');
|
||||
return !!url && url !== CONTRIB_ORIGIN;
|
||||
}
|
||||
@@ -0,0 +1,185 @@
|
||||
import { discardBody, exceedsDeclaredLength, readCappedJson } from '../../utils/cappedFetch';
|
||||
import { ServiceIdentityPort } from '../service-identity/service-identity.interface';
|
||||
import { ANSWER_MAX_BYTES, CONTRIB_ORIGIN, REQUEST_TIMEOUT_MS } from './place-contrib.constants';
|
||||
import { retryAfterMs } from './place-contrib.helpers';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
placeContribErrorSchema,
|
||||
placeContribImageAnswerSchema,
|
||||
placeContribPlaceAnswerSchema,
|
||||
placeContribWithdrawAnswerSchema,
|
||||
type PlaceContribImageAnswer,
|
||||
type PlaceContribPlaceAnswer,
|
||||
type PlaceContribPlaceBody,
|
||||
type PlaceContribWithdrawAnswer,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import { z, type ZodType } from 'zod';
|
||||
|
||||
/**
|
||||
* What one request came back with:
|
||||
* - `ok`: a 200 the schema describes;
|
||||
* - `refused`: a status with the service's `{ error }` code;
|
||||
* - `failed`: no answer, a server error, or an answer that is not what the
|
||||
* service sends (worth another try later).
|
||||
*/
|
||||
export type ContribAnswer<T> =
|
||||
| { kind: 'ok'; body: T }
|
||||
| { kind: 'refused'; status: number; error: string; retryAfterMs: number | null }
|
||||
| { kind: 'failed'; reason: string; retryAfterMs: number | null };
|
||||
|
||||
/** What the index serves for a place right now, community values included: the base of a contribution. */
|
||||
export interface ServedPlace {
|
||||
website: string | null;
|
||||
phone: string | null;
|
||||
email: string | null;
|
||||
opening_hours: string | null;
|
||||
description: string | null;
|
||||
}
|
||||
|
||||
/** A place lookup is a few kB; it carries more than the contribution answers do. */
|
||||
const PLACE_LOOKUP_MAX_BYTES = 512 * 1024;
|
||||
|
||||
const optionalText = z.string().max(4000).nullable().optional();
|
||||
const servedPlaceSchema = z.object({
|
||||
place: z.object({
|
||||
contact: z.object({ website: optionalText, phone: optionalText, email: optionalText }).nullable().optional(),
|
||||
hours: z.object({ osm: optionalText }).nullable().optional(),
|
||||
description: z.object({ text: optionalText }).nullable().optional(),
|
||||
}),
|
||||
});
|
||||
|
||||
/**
|
||||
* The client of the contribution routes on the TREK Places API.
|
||||
*
|
||||
* Every request carries the installation key and goes only out with one: there
|
||||
* is no pool to fall back on for these routes, so a missing key sends nothing.
|
||||
* The key goes to the allowlisted host only (ServiceIdentityPort decides, as for
|
||||
* the search), and each answer is shown to the identity like every other, so a
|
||||
* refused key is noticed there too.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceContribClient {
|
||||
constructor(private readonly identity: ServiceIdentityPort) {}
|
||||
|
||||
/** Whether a request would carry the installation key right now. */
|
||||
hasKey(): boolean {
|
||||
return this.authorization() !== null;
|
||||
}
|
||||
|
||||
/** A short fingerprint of the key in use, so a pause over a refused key ends once there is a new one. */
|
||||
keyFingerprint(): string | null {
|
||||
const auth = this.authorization();
|
||||
return auth ? createHash('sha256').update(auth).digest('hex').slice(0, 16) : null;
|
||||
}
|
||||
|
||||
async postPlace(body: PlaceContribPlaceBody): Promise<ContribAnswer<PlaceContribPlaceAnswer>> {
|
||||
return this.send(
|
||||
'/v1/contrib/place',
|
||||
{ method: 'POST', body: JSON.stringify(body), headers: { 'Content-Type': 'application/json' } },
|
||||
placeContribPlaceAnswerSchema,
|
||||
);
|
||||
}
|
||||
|
||||
async postImage(key: string, cid: string, jpeg: Buffer): Promise<ContribAnswer<PlaceContribImageAnswer>> {
|
||||
return this.send(
|
||||
'/v1/contrib/image',
|
||||
{
|
||||
method: 'POST',
|
||||
body: new Uint8Array(jpeg),
|
||||
headers: { 'Content-Type': 'image/jpeg', 'X-TREK-Contrib-Key': key, 'X-TREK-Contrib-Cid': cid },
|
||||
},
|
||||
placeContribImageAnswerSchema,
|
||||
);
|
||||
}
|
||||
|
||||
/** Withdraws what this installation sent: everything, or one field, key or image. */
|
||||
async withdraw(
|
||||
scope: { field?: string; key?: string; image?: string } = {},
|
||||
): Promise<ContribAnswer<PlaceContribWithdrawAnswer>> {
|
||||
const params = new URLSearchParams();
|
||||
for (const [name, value] of Object.entries(scope)) if (value) params.set(name, value);
|
||||
const query = params.toString();
|
||||
return this.send(
|
||||
`/v1/contrib/install${query ? `?${query}` : ''}`,
|
||||
{ method: 'DELETE' },
|
||||
placeContribWithdrawAnswerSchema,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the index serves for a gers place now, null when it cannot say. Asked
|
||||
* with the key like the search, so it is counted like one.
|
||||
*/
|
||||
async servedPlace(gers: string): Promise<ServedPlace | null> {
|
||||
const answer = await this.send(
|
||||
`/v1/place/${encodeURIComponent(gers)}`,
|
||||
{ method: 'GET' },
|
||||
servedPlaceSchema,
|
||||
PLACE_LOOKUP_MAX_BYTES,
|
||||
);
|
||||
if (answer.kind !== 'ok') return null;
|
||||
const { contact, hours, description } = answer.body.place;
|
||||
return {
|
||||
website: contact?.website ?? null,
|
||||
phone: contact?.phone ?? null,
|
||||
email: contact?.email ?? null,
|
||||
opening_hours: hours?.osm ?? null,
|
||||
description: description?.text ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
private authorization(): string | null {
|
||||
return this.identity.headersFor(new URL(CONTRIB_ORIGIN)).Authorization ?? null;
|
||||
}
|
||||
|
||||
private async send<T>(
|
||||
path: string,
|
||||
init: { method: string; body?: string | Uint8Array; headers?: Record<string, string> },
|
||||
schema: ZodType<T>,
|
||||
maxBytes: number = ANSWER_MAX_BYTES,
|
||||
): Promise<ContribAnswer<T>> {
|
||||
const url = new URL(CONTRIB_ORIGIN + path);
|
||||
const own = this.identity.headersFor(url);
|
||||
if (!own.Authorization) return { kind: 'refused', status: 401, error: 'no_key', retryAfterMs: null };
|
||||
let res: Response;
|
||||
try {
|
||||
res = await fetch(url, {
|
||||
method: init.method,
|
||||
body: init.body,
|
||||
headers: { Accept: 'application/json', ...init.headers, ...own },
|
||||
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
});
|
||||
} catch (err) {
|
||||
return { kind: 'failed', reason: err instanceof Error ? err.name : 'network', retryAfterMs: null };
|
||||
}
|
||||
this.identity.observe(url, res);
|
||||
return readAnswer(res, schema, maxBytes);
|
||||
}
|
||||
}
|
||||
|
||||
async function readAnswer<T>(res: Response, schema: ZodType<T>, maxBytes: number): Promise<ContribAnswer<T>> {
|
||||
const retryAfter = retryAfterMs(res.headers.get('retry-after'));
|
||||
if (exceedsDeclaredLength(res, maxBytes)) {
|
||||
discardBody(res);
|
||||
return { kind: 'failed', reason: 'answer_too_large', retryAfterMs: retryAfter };
|
||||
}
|
||||
const body = await readCappedJson<unknown>(res, maxBytes).catch(() => undefined);
|
||||
if (res.ok) {
|
||||
const parsed = schema.safeParse(body);
|
||||
return parsed.success
|
||||
? { kind: 'ok', body: parsed.data }
|
||||
: { kind: 'failed', reason: 'answer_unreadable', retryAfterMs: retryAfter };
|
||||
}
|
||||
if (res.status >= 500 && res.status !== 503) {
|
||||
return { kind: 'failed', reason: `status_${res.status}`, retryAfterMs: retryAfter };
|
||||
}
|
||||
const refusal = placeContribErrorSchema.safeParse(body);
|
||||
return {
|
||||
kind: 'refused',
|
||||
status: res.status,
|
||||
error: refusal.success ? refusal.data.error : `status_${res.status}`,
|
||||
retryAfterMs: retryAfter,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
/**
|
||||
* The numbers the community enrichment works with, in one place.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Where contributions go. Only the public instance takes them: an install with
|
||||
* its own TREK_PLACES_URL is not eligible, so this is never another host.
|
||||
*/
|
||||
export const CONTRIB_ORIGIN = 'https://places.liketrek.com';
|
||||
|
||||
/** One place per request, and the service refuses a body over this. */
|
||||
export const PLACE_BODY_MAX_BYTES = 8 * 1024;
|
||||
/** Every answer is a short JSON object; anything longer is not read. */
|
||||
export const ANSWER_MAX_BYTES = 64 * 1024;
|
||||
export const REQUEST_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** A value waits a few minutes before it goes, a random share of this window per place. */
|
||||
export const ELIGIBLE_DELAY_MIN_MS = 2 * 60_000;
|
||||
export const ELIGIBLE_DELAY_MAX_MS = 10 * 60_000;
|
||||
|
||||
/** The waits after the first, second, ... failed attempt; the last one repeats. */
|
||||
export const RETRY_DELAYS_MS = [10 * 60_000, 30 * 60_000, 2 * 3_600_000, 6 * 3_600_000] as const;
|
||||
/** After this many failed attempts a value is given up on. */
|
||||
export const MAX_ATTEMPTS = 8;
|
||||
/** The longest Retry-After the sender honours; a larger one is capped to it. */
|
||||
export const MAX_RETRY_AFTER_MS = 24 * 3_600_000;
|
||||
/** How long the sender waits when the service is not taking contributions and says nothing about when. */
|
||||
export const NOT_ACCEPTING_WAIT_MS = 30 * 60_000;
|
||||
|
||||
/** The queue never holds more than this; at the cap nothing more is queued. */
|
||||
export const OUTBOX_CAP = 5_000;
|
||||
/** A value still queued after this long is dropped and logged as withheld. */
|
||||
export const OUTBOX_MAX_AGE_DAYS = 30;
|
||||
|
||||
/** At most this many places per run of the sender, one after the other. */
|
||||
export const PLACES_PER_RUN = 20;
|
||||
/** Every two minutes. */
|
||||
export const SEND_SCHEDULE = '*/2 * * * *';
|
||||
/** The log retention, nightly at 3:50, clear of the 3:00 idempotency purge and 3:40 shadow retention. */
|
||||
export const LOG_RETENTION_SCHEDULE = '50 3 * * *';
|
||||
export const LOG_RETENTION_DAYS = 90;
|
||||
/** The admin state counts the log of this many days. */
|
||||
export const COUNT_WINDOW_DAYS = 30;
|
||||
|
||||
/** "Not now" keeps the prompt away from this admin for two weeks. */
|
||||
export const SNOOZE_DAYS = 14;
|
||||
|
||||
/** A picture is sent at most this large: long edge, JPEG quality, bytes. */
|
||||
export const IMAGE_MAX_EDGE = 2048;
|
||||
export const IMAGE_JPEG_QUALITY = 85;
|
||||
export const IMAGE_MAX_BYTES = 1024 * 1024;
|
||||
/** A picture is decoded only up to this many pixels; a larger one is not sent. */
|
||||
export const IMAGE_MAX_PIXELS = 40_000_000;
|
||||
|
||||
/** The longest value a field sends, and the longest summary of it the log keeps. */
|
||||
export const VALUE_MAX_CHARS = 4_000;
|
||||
export const SUMMARY_MAX_CHARS = 80;
|
||||
@@ -0,0 +1,95 @@
|
||||
import type { User } from '../../types';
|
||||
import { AuditService } from '../audit/audit.service';
|
||||
import { getClientIp } from '../audit/client-ip';
|
||||
import { AdminGuard } from '../auth-core/admin.guard';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { PlaceContribDecisionDto, PlaceContribLogQueryDto, PlaceContribWithdrawDto } from './place-contrib.dto';
|
||||
import { PlaceContribService } from './place-contrib.service';
|
||||
import { Body, Controller, Get, HttpCode, Post, Put, Query, Req, UseGuards } from '@nestjs/common';
|
||||
import {
|
||||
placeContribLogResponseSchema,
|
||||
placeContribStateSchema,
|
||||
placeContribWithdrawResponseSchema,
|
||||
type PlaceContribDecisionRequest,
|
||||
type PlaceContribLogResponse,
|
||||
type PlaceContribState,
|
||||
type PlaceContribWithdrawResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
import type { Request } from 'express';
|
||||
|
||||
/**
|
||||
* /api/admin/places-contribute: the admin's side of sharing place details with
|
||||
* the TREK Places API. The state the panel and the first-visit prompt read, the
|
||||
* decision, the transmission log, and withdrawing everything that was sent.
|
||||
*
|
||||
* Admin only, like every instance setting. On a managed install the tenant's
|
||||
* own admin decides too: the operator never answers for them.
|
||||
*/
|
||||
@Controller('api/admin/places-contribute')
|
||||
@UseGuards(JwtAuthGuard, AdminGuard)
|
||||
export class PlaceContribController {
|
||||
constructor(
|
||||
private readonly contrib: PlaceContribService,
|
||||
private readonly audit: AuditService,
|
||||
) {}
|
||||
|
||||
@Get()
|
||||
@ResponseContract(placeContribStateSchema)
|
||||
async state(@CurrentUser() user: User): Promise<PlaceContribState> {
|
||||
return this.contrib.state(user.id);
|
||||
}
|
||||
|
||||
@Put('decision')
|
||||
@ResponseContract(placeContribStateSchema)
|
||||
async decide(
|
||||
@CurrentUser() user: User,
|
||||
@Body() body: PlaceContribDecisionDto,
|
||||
@Req() req: Request,
|
||||
): Promise<PlaceContribState> {
|
||||
// The pipe validated the body against the full union; the DTO only types its shared fields.
|
||||
const state = await this.contrib.decide(user.id, body as PlaceContribDecisionRequest);
|
||||
await this.audit.writeAudit({
|
||||
userId: user.id,
|
||||
action: 'admin.places_contribute_decision',
|
||||
details: decisionDetails(body),
|
||||
ip: getClientIp(req),
|
||||
});
|
||||
return state;
|
||||
}
|
||||
|
||||
@Get('log')
|
||||
@ResponseContract(placeContribLogResponseSchema)
|
||||
async log(@Query() query: PlaceContribLogQueryDto): Promise<PlaceContribLogResponse> {
|
||||
return this.contrib.logPage(query);
|
||||
}
|
||||
|
||||
@Post('withdraw')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(placeContribWithdrawResponseSchema)
|
||||
async withdraw(
|
||||
@CurrentUser() user: User,
|
||||
@Body() _body: PlaceContribWithdrawDto,
|
||||
@Req() req: Request,
|
||||
): Promise<PlaceContribWithdrawResponse> {
|
||||
const result = await this.contrib.withdrawAll();
|
||||
await this.audit.writeAudit({
|
||||
userId: user.id,
|
||||
action: 'admin.places_contribute_withdraw',
|
||||
details: { cleared: result.cleared },
|
||||
ip: getClientIp(req),
|
||||
});
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
/** What the audit row keeps of a decision: the action, and the switches or terms it named. */
|
||||
function decisionDetails(body: PlaceContribDecisionDto): Record<string, unknown> {
|
||||
const details: Record<string, unknown> = { action: body.action };
|
||||
if (body.termsVersion !== undefined) details.termsVersion = body.termsVersion;
|
||||
if (body.fields !== undefined) details.fields = body.fields;
|
||||
if (body.withdraw !== undefined) details.withdraw = body.withdraw;
|
||||
return details;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import {
|
||||
placeContribDecisionRequestSchema,
|
||||
placeContribLogQuerySchema,
|
||||
placeContribWithdrawRequestSchema,
|
||||
type PlaceContribDecisionRequest,
|
||||
type PlaceContribFieldSwitches,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
import type { z } from 'zod';
|
||||
|
||||
/**
|
||||
* The fields the decision's variants share. Its contract is a union over
|
||||
* `action`, and a class cannot extend a union: the DTO is typed as this common
|
||||
* shape while the pipe validates against the full union.
|
||||
*/
|
||||
interface PlaceContribDecisionFields {
|
||||
action: PlaceContribDecisionRequest['action'];
|
||||
termsVersion?: number;
|
||||
fields?: PlaceContribFieldSwitches;
|
||||
withdraw?: boolean;
|
||||
}
|
||||
|
||||
/** Zod-pipe wrappers over the @trek/shared contracts of /api/admin/places-contribute. */
|
||||
export class PlaceContribDecisionDto extends createZodDto(
|
||||
placeContribDecisionRequestSchema as z.ZodType<PlaceContribDecisionFields>,
|
||||
) {}
|
||||
export class PlaceContribLogQueryDto extends createZodDto(placeContribLogQuerySchema) {}
|
||||
export class PlaceContribWithdrawDto extends createZodDto(placeContribWithdrawRequestSchema) {}
|
||||
@@ -0,0 +1,181 @@
|
||||
import {
|
||||
ELIGIBLE_DELAY_MAX_MS,
|
||||
ELIGIBLE_DELAY_MIN_MS,
|
||||
MAX_RETRY_AFTER_MS,
|
||||
RETRY_DELAYS_MS,
|
||||
SUMMARY_MAX_CHARS,
|
||||
VALUE_MAX_CHARS,
|
||||
} from './place-contrib.constants';
|
||||
import {
|
||||
parsePlaceHours,
|
||||
placeWebsiteSchema,
|
||||
type PlaceContribField,
|
||||
type PlaceContribFieldResult,
|
||||
type PlaceContribLogResult,
|
||||
type PlaceHoursDay,
|
||||
type PlaceOpeningHours,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { createHash, randomInt } from 'node:crypto';
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
||||
const HEX32 = /^[0-9a-f]{32}$/i;
|
||||
const OSM_ID = /^(node|way|relation):(\d{1,15})$/;
|
||||
/** Where the place pictures users upload live (the places domain's `placeImageUrl`). */
|
||||
export const UPLOADED_IMAGE_PREFIX = '/uploads/places/';
|
||||
|
||||
/**
|
||||
* The key the service files a place under: `gers:<id>` for a place from the
|
||||
* TREK index, `osm:<type>/<id>` for an OpenStreetMap element. A place without
|
||||
* one (a free pin, a Google or Amap place) is not sent in this version.
|
||||
*/
|
||||
export function contribKeyOf(osmId: string | null | undefined): string | null {
|
||||
const id = osmId?.trim() ?? '';
|
||||
if (id.startsWith('gers:')) {
|
||||
const gers = id.slice('gers:'.length).toLowerCase();
|
||||
return UUID.test(gers) || HEX32.test(gers) ? `gers:${gers}` : null;
|
||||
}
|
||||
const osm = OSM_ID.exec(id);
|
||||
return osm ? `osm:${osm[1]}/${osm[2]}` : null;
|
||||
}
|
||||
|
||||
/** The gers id inside a key, for the lookup of what the service serves for it. */
|
||||
export function gersOf(key: string): string | null {
|
||||
return key.startsWith('gers:') ? key.slice('gers:'.length) : null;
|
||||
}
|
||||
|
||||
/** What a field sends, or why it stays home. */
|
||||
type ContribPayload = { value: string } | { withheld: string };
|
||||
|
||||
const DAY_NAMES = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'] as const;
|
||||
|
||||
/** One day in OSM syntax: `off`, `HH:MM-HH:MM`, or null for a day nobody set. */
|
||||
function daySpec(day: PlaceHoursDay): string | null {
|
||||
if (day.closed) return 'off';
|
||||
if (!day.open || !day.close) return null;
|
||||
// An interval that ends before it starts runs past midnight, which OSM
|
||||
// spells the same way: 22:00-02:00.
|
||||
return `${day.open}-${day.close}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* The week as an OSM opening_hours rule, consecutive days with the same hours
|
||||
* folded into a range: `Mo-Fr 09:00-18:00; Sa 10:00-14:00; Su off`. Only the
|
||||
* days the user set are named; a day without times stays out instead of being
|
||||
* claimed as closed. Null for a week that says nothing.
|
||||
*/
|
||||
export function osmHoursOf(week: PlaceOpeningHours): string | null {
|
||||
const specs = week.map(daySpec);
|
||||
const parts: string[] = [];
|
||||
let start = 0;
|
||||
while (start < specs.length) {
|
||||
let end = start;
|
||||
while (end + 1 < specs.length && specs[end + 1] === specs[start]) end += 1;
|
||||
const spec = specs[start];
|
||||
if (spec !== null) {
|
||||
const days = start === end ? DAY_NAMES[start] : `${DAY_NAMES[start]}-${DAY_NAMES[end]}`;
|
||||
parts.push(`${days} ${spec}`);
|
||||
}
|
||||
start = end + 1;
|
||||
}
|
||||
return parts.length ? parts.join('; ') : null;
|
||||
}
|
||||
|
||||
function hoursPayload(raw: string): ContribPayload {
|
||||
const week = parsePlaceHours(raw);
|
||||
if (!week) return { withheld: 'hours_unreadable' };
|
||||
if (week.every((day) => day.closed)) return { withheld: 'hours_all_closed' };
|
||||
const value = osmHoursOf(week);
|
||||
return value ? { value } : { withheld: 'hours_empty' };
|
||||
}
|
||||
|
||||
/**
|
||||
* The value a field sends, normalized the way the service reads it, or the
|
||||
* reason it is kept home. The service normalizes again and its reading wins;
|
||||
* this only keeps out what it would refuse anyway.
|
||||
*/
|
||||
export function payloadOf(field: PlaceContribField, raw: string): ContribPayload {
|
||||
const text = raw.trim();
|
||||
if (!text) return { withheld: 'empty' };
|
||||
switch (field) {
|
||||
case 'website': {
|
||||
const parsed = placeWebsiteSchema.safeParse(text);
|
||||
return parsed.success && parsed.data ? { value: parsed.data } : { withheld: 'website_invalid' };
|
||||
}
|
||||
case 'email':
|
||||
return { value: text.toLowerCase() };
|
||||
case 'opening_hours':
|
||||
return hoursPayload(text);
|
||||
case 'image':
|
||||
// Only a picture uploaded to the place itself; a link, a provider's photo
|
||||
// or an inline image is not the user's to give away.
|
||||
return text.startsWith(UPLOADED_IMAGE_PREFIX) ? { value: text } : { withheld: 'image_not_uploaded' };
|
||||
default:
|
||||
return text.length > VALUE_MAX_CHARS ? { withheld: 'too_long' } : { value: text };
|
||||
}
|
||||
}
|
||||
|
||||
/** A short line for the log: enough to recognise the value, never the whole description. */
|
||||
export function summaryOf(field: PlaceContribField, value: string): string {
|
||||
if (field === 'image') return 'image';
|
||||
const line = value.replace(/\s+/g, ' ').trim();
|
||||
return line.length > SUMMARY_MAX_CHARS ? `${line.slice(0, SUMMARY_MAX_CHARS - 1)}…` : line;
|
||||
}
|
||||
|
||||
/** The `baseHash` the service compares with: a prefix of the SHA-256 of the value it served. */
|
||||
export function baseHashOf(value: string | null | undefined): string | null {
|
||||
const text = value?.trim();
|
||||
return text ? createHash('sha256').update(text, 'utf8').digest('hex').slice(0, 16) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The idempotency id of one request: stable for the same queued values, so a
|
||||
* retry after a lost answer is recognised as the same contribution, and new
|
||||
* as soon as one of them was replaced.
|
||||
*/
|
||||
export function requestCid(entryCids: readonly string[]): string {
|
||||
const digest = createHash('sha256')
|
||||
.update([...entryCids].sort().join(','))
|
||||
.digest('base64url');
|
||||
return digest.slice(0, 32);
|
||||
}
|
||||
|
||||
/** A fresh id for a queued value. */
|
||||
export function newEntryCid(): string {
|
||||
return createHash('sha256')
|
||||
.update(`${Date.now()}:${randomInt(2 ** 47)}`)
|
||||
.digest('base64url')
|
||||
.slice(0, 24);
|
||||
}
|
||||
|
||||
/** A few minutes, a different share for every place, so a trip's places do not all go together. */
|
||||
export function eligibleDelayMs(): number {
|
||||
return randomInt(ELIGIBLE_DELAY_MIN_MS, ELIGIBLE_DELAY_MAX_MS + 1);
|
||||
}
|
||||
|
||||
/** The wait after `attempts` failed attempts (1 for the first). */
|
||||
export function retryDelayMs(attempts: number): number {
|
||||
const index = Math.min(Math.max(attempts, 1), RETRY_DELAYS_MS.length) - 1;
|
||||
return RETRY_DELAYS_MS[index];
|
||||
}
|
||||
|
||||
/** A Retry-After header in milliseconds (seconds or an HTTP date), capped; null when there is none or it is unreadable. */
|
||||
export function retryAfterMs(header: string | null, now: number = Date.now()): number | null {
|
||||
const text = header?.trim();
|
||||
if (!text) return null;
|
||||
const seconds = /^\d+$/.test(text) ? Number(text) * 1000 : Date.parse(text) - now;
|
||||
if (!Number.isFinite(seconds) || seconds < 0) return null;
|
||||
return Math.min(seconds, MAX_RETRY_AFTER_MS);
|
||||
}
|
||||
|
||||
/** How the log records what the service made of a field. */
|
||||
export function logResultOf(result: Exclude<PlaceContribFieldResult, 'quota'>): PlaceContribLogResult {
|
||||
if (result === 'unchanged') return 'duplicate';
|
||||
if (result === 'rejected') return 'rejected';
|
||||
return 'accepted';
|
||||
}
|
||||
|
||||
/** The day of a moment as the log keeps it, UTC. */
|
||||
export function dayOf(at: Date): string {
|
||||
return at.toISOString().slice(0, 10);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { PlaceContribLog } from '../../db/entities/PlaceContribLog.entity';
|
||||
import type { PlaceContribLogRepository } from '../../db/repositories/PlaceContribLog.repository';
|
||||
import { logError, logInfo } from '../audit/audit-log.logger';
|
||||
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
|
||||
import { PlaceContribSender } from './place-contrib-sender.service';
|
||||
import { LOG_RETENTION_DAYS, LOG_RETENTION_SCHEDULE, SEND_SCHEDULE } from './place-contrib.constants';
|
||||
import { dayOf } from './place-contrib.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
|
||||
|
||||
const DAY_MS = 24 * 3_600_000;
|
||||
|
||||
/**
|
||||
* The two crons of the community enrichment: the sender every two minutes,
|
||||
* which does nothing unless the installation is eligible and an admin agreed,
|
||||
* and the nightly retention of the transmission log (90 days), which runs
|
||||
* whatever the decision so a log switched off still ages out.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceContribJob implements OnApplicationBootstrap {
|
||||
constructor(
|
||||
private readonly sender: PlaceContribSender,
|
||||
@InjectRepository(PlaceContribLog) private readonly log: PlaceContribLogRepository,
|
||||
private readonly registrar: CronRegistrarService,
|
||||
) {}
|
||||
|
||||
onApplicationBootstrap(): void {
|
||||
if (!this.registrar.isEnabled()) return;
|
||||
this.registrar.register('place-contrib-send', SEND_SCHEDULE, () => this.send());
|
||||
this.registrar.register('place-contrib-log-retention', LOG_RETENTION_SCHEDULE, () => this.retain());
|
||||
}
|
||||
|
||||
async send(): Promise<void> {
|
||||
try {
|
||||
await this.sender.run();
|
||||
} catch (err: unknown) {
|
||||
logError(`Places contribution: the run failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
async retain(now: Date = new Date()): Promise<void> {
|
||||
try {
|
||||
const removed = await this.log.purgeBefore(dayOf(new Date(now.getTime() - LOG_RETENTION_DAYS * DAY_MS)));
|
||||
if (removed > 0) logInfo(`Places contribution: removed ${removed} log line(s) past ${LOG_RETENTION_DAYS} days`);
|
||||
} catch (err: unknown) {
|
||||
logError(`Places contribution: log retention failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { PlaceContribLog } from '../../db/entities/PlaceContribLog.entity';
|
||||
import { PlaceContribOutbox } from '../../db/entities/PlaceContribOutbox.entity';
|
||||
import { AppConfigModule } from '../app-config/app-config.module';
|
||||
import { AuditModule } from '../audit/audit.module';
|
||||
import { SchedulingModule } from '../scheduling/scheduling.module';
|
||||
import { ServiceIdentityModule } from '../service-identity/service-identity.module';
|
||||
import { SettingsModule } from '../settings/settings.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { PlaceContribSender } from './place-contrib-sender.service';
|
||||
import { PlaceContribSettings } from './place-contrib-settings';
|
||||
import { PlaceContribClient } from './place-contrib.client';
|
||||
import { PlaceContribController } from './place-contrib.controller';
|
||||
import { PlaceContribJob } from './place-contrib.job';
|
||||
import { PlaceContribService } from './place-contrib.service';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Community enrichment of place details: the admin's decision, the queue of
|
||||
* values users typed in, the cron that sends them to the TREK Places API and
|
||||
* the transmission log. Exports PlaceContribService for the places domain,
|
||||
* whose origin tracking feeds the queue after every place write.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
AppConfigModule,
|
||||
AuditModule,
|
||||
SchedulingModule,
|
||||
ServiceIdentityModule,
|
||||
SettingsModule,
|
||||
StorageModule,
|
||||
MikroOrmModule.forFeature([PlaceContribOutbox, PlaceContribLog]),
|
||||
],
|
||||
controllers: [PlaceContribController],
|
||||
providers: [PlaceContribService, PlaceContribSettings, PlaceContribClient, PlaceContribSender, PlaceContribJob],
|
||||
exports: [PlaceContribService],
|
||||
})
|
||||
export class PlaceContribModule {}
|
||||
@@ -0,0 +1,309 @@
|
||||
import { PlaceContribLog } from '../../db/entities/PlaceContribLog.entity';
|
||||
import { PlaceContribOutbox } from '../../db/entities/PlaceContribOutbox.entity';
|
||||
import type { PlaceContribLogRepository, PlaceContribLogWrite } from '../../db/repositories/PlaceContribLog.repository';
|
||||
import type { PlaceContribOutboxRepository } from '../../db/repositories/PlaceContribOutbox.repository';
|
||||
import { dbNow } from '../../db/types';
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { DomainError, badRequest, conflict } from '../common/domain-error';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { agreedToCurrentTerms, PlaceContribSettings } from './place-contrib-settings';
|
||||
import { PlaceContribClient } from './place-contrib.client';
|
||||
import { COUNT_WINDOW_DAYS, OUTBOX_CAP, SNOOZE_DAYS } from './place-contrib.constants';
|
||||
import { contribKeyOf, dayOf, eligibleDelayMs, newEntryCid, payloadOf, summaryOf } from './place-contrib.helpers';
|
||||
import type { ContribValue, ContribWrite } from './place-contrib.types';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
PLACE_CONTRIB_FIELDS,
|
||||
PLACE_CONTRIB_TERMS_VERSION,
|
||||
type PlaceContribConsent,
|
||||
type PlaceContribDecisionRequest,
|
||||
type PlaceContribField,
|
||||
type PlaceContribFieldSwitches,
|
||||
type PlaceContribLogQuery,
|
||||
type PlaceContribLogResponse,
|
||||
type PlaceContribLogResult,
|
||||
type PlaceContribState,
|
||||
type PlaceContribWithdrawResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
const DAY_MS = 24 * 3_600_000;
|
||||
const LOG_RESULTS: readonly PlaceContribLogResult[] = ['accepted', 'duplicate', 'rejected', 'withheld', 'retracted'];
|
||||
|
||||
/**
|
||||
* The community enrichment of place details, as the admin and the places
|
||||
* domain see it: the admin's decision and the state the admin panel shows, the
|
||||
* transmission log, withdrawing everything, and the queue a place write feeds.
|
||||
*
|
||||
* Nothing leaves here. The queue is drained by PlaceContribSender on its cron,
|
||||
* and only while the installation is eligible and an admin agreed to the
|
||||
* terms in force; every value it holds is one the origin tracking recorded as
|
||||
* typed by a user.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceContribService {
|
||||
constructor(
|
||||
@InjectRepository(PlaceContribOutbox) private readonly outbox: PlaceContribOutboxRepository,
|
||||
@InjectRepository(PlaceContribLog) private readonly log: PlaceContribLogRepository,
|
||||
private readonly store: PlaceContribSettings,
|
||||
private readonly settings: SettingsService,
|
||||
private readonly client: PlaceContribClient,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
async state(adminId: number, now: Date = new Date()): Promise<PlaceContribState> {
|
||||
const eligibility = this.store.eligibility();
|
||||
const consent = await this.store.consent();
|
||||
const snoozedUntil = await this.store.snoozedUntil(adminId, now);
|
||||
const decidedForTerms = consent.decision !== null && consent.termsVersion === PLACE_CONTRIB_TERMS_VERSION;
|
||||
const size = await this.outbox.size();
|
||||
const active = eligibility.eligible && agreedToCurrentTerms(consent) && anyField(consent.fields);
|
||||
return {
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
ceiling: this.store.ceiling(),
|
||||
eligible: eligibility.eligible,
|
||||
ineligibleReason: eligibility.reason,
|
||||
consent,
|
||||
showPrompt: eligibility.eligible && !decidedForTerms && snoozedUntil === null,
|
||||
snoozedUntil,
|
||||
active,
|
||||
counts: await this.counts(now),
|
||||
lastSuccessDay: await this.log.lastAcceptedDay(),
|
||||
queue: { size, cap: OUTBOX_CAP, full: size >= OUTBOX_CAP },
|
||||
pauseReason: active ? await this.store.pauseReason(now) : null,
|
||||
registrationOpen: (await this.settings.getAppSetting('allow_registration')) !== 'false',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* One decision of an admin. An agreement or a refusal names the terms it
|
||||
* was shown; a dialog built for older terms is refused with 409 and reloads.
|
||||
* Answers the state that follows.
|
||||
*
|
||||
* @txIndependent switching off commits before the withdrawal asks the service, which is network I/O.
|
||||
*/
|
||||
async decide(
|
||||
adminId: number,
|
||||
request: PlaceContribDecisionRequest,
|
||||
now: Date = new Date(),
|
||||
): Promise<PlaceContribState> {
|
||||
const consent = await this.store.consent();
|
||||
const decided = { decidedBy: adminId, decidedAt: now.toISOString() };
|
||||
switch (request.action) {
|
||||
case 'agree':
|
||||
assertCurrentTerms(request.termsVersion);
|
||||
if (!anyField(request.fields)) throw badRequest('Pick at least one field to share', { reason: 'no_field' });
|
||||
// A new agreement is a fresh start: a pause over a key or a wait the
|
||||
// service asked for is tried again on the next run.
|
||||
await this.uow.transactional(async () => {
|
||||
await this.store.writeConsent({
|
||||
enabled: true,
|
||||
fields: request.fields,
|
||||
termsVersion: request.termsVersion,
|
||||
decision: 'agreed',
|
||||
...decided,
|
||||
});
|
||||
await this.store.clearPause();
|
||||
});
|
||||
break;
|
||||
case 'snooze':
|
||||
await this.store.snooze(adminId, new Date(now.getTime() + SNOOZE_DAYS * DAY_MS));
|
||||
break;
|
||||
case 'decline':
|
||||
assertCurrentTerms(request.termsVersion);
|
||||
await this.switchOff(consent, { decision: 'declined', termsVersion: request.termsVersion, ...decided });
|
||||
break;
|
||||
case 'fields':
|
||||
await this.changeFields(consent, request.fields, { withdraw: request.withdraw === true, decided });
|
||||
break;
|
||||
case 'off':
|
||||
await this.switchOff(consent, { decision: 'off', termsVersion: consent.termsVersion, ...decided });
|
||||
if (request.withdraw) await this.withdrawAll(now);
|
||||
break;
|
||||
}
|
||||
return this.state(adminId, now);
|
||||
}
|
||||
|
||||
async logPage(query: PlaceContribLogQuery): Promise<PlaceContribLogResponse> {
|
||||
const filter = { result: query.result, field: query.field };
|
||||
const rows = await this.log.page(filter, query.perPage, (query.page - 1) * query.perPage);
|
||||
return {
|
||||
entries: rows.map((row) => ({
|
||||
id: row.id,
|
||||
day: row.day,
|
||||
key: row.contrib_key,
|
||||
placeName: row.place_name,
|
||||
field: row.field as PlaceContribField,
|
||||
valueSummary: row.value_summary,
|
||||
result: row.result as PlaceContribLogResult,
|
||||
reason: row.reason,
|
||||
})),
|
||||
total: await this.log.total(filter),
|
||||
page: query.page,
|
||||
perPage: query.perPage,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Asks the service to withdraw everything this installation sent, then
|
||||
* empties the queue here. When the service does not confirm, nothing is
|
||||
* dropped and the admin sees why.
|
||||
*/
|
||||
async withdrawAll(now: Date = new Date()): Promise<PlaceContribWithdrawResponse> {
|
||||
const answer = await this.client.withdraw();
|
||||
if (answer.kind !== 'ok') {
|
||||
const reason = answer.kind === 'refused' ? answer.error : answer.reason;
|
||||
logWarn(`Places contribution: the withdrawal was not confirmed (${reason})`);
|
||||
throw new DomainError(502, 'The TREK Places API did not confirm the withdrawal', { details: { reason } });
|
||||
}
|
||||
const withdrawn = countsOf(answer.body.withdrawn);
|
||||
const day = dayOf(now);
|
||||
const lines: PlaceContribLogWrite[] = PLACE_CONTRIB_FIELDS.filter((field) => (withdrawn[field] ?? 0) > 0).map(
|
||||
(field) => ({
|
||||
day,
|
||||
contrib_key: '*',
|
||||
place_name: '',
|
||||
field,
|
||||
value_summary: String(withdrawn[field]),
|
||||
result: 'retracted',
|
||||
reason: 'withdraw_all',
|
||||
}),
|
||||
);
|
||||
const cleared = await this.uow.transactional(async () => {
|
||||
await this.log.insertLines(lines);
|
||||
return this.outbox.deleteAll();
|
||||
});
|
||||
return { withdrawn, cleared };
|
||||
}
|
||||
|
||||
/**
|
||||
* A place write the origin tracking saw. Values that are no longer the
|
||||
* user's leave the queue whatever the decision; the user's values are
|
||||
* queued only while the installation is eligible and an admin agreed, each
|
||||
* for a field that is switched on, and only for a place the service can key.
|
||||
* The newest value replaces a queued one; it goes a few minutes later.
|
||||
*
|
||||
* @txStandalone a derived write after the place write committed: it never fails that write.
|
||||
*/
|
||||
async enqueue(write: ContribWrite, now: Date = new Date()): Promise<void> {
|
||||
const active = await this.store.activeFields();
|
||||
await this.uow.transactional(async () => {
|
||||
await this.outbox.deleteForPlace(write.placeId, write.dropped);
|
||||
const shared = write.values.filter((value) => active.includes(value.field));
|
||||
if (shared.length === 0) return;
|
||||
const key = contribKeyOf(write.osmId);
|
||||
if (!key) {
|
||||
await this.log.insertLines(shared.map((value) => this.withheldLine(write, value, now, 'no_contrib_key')));
|
||||
return;
|
||||
}
|
||||
const due = dbNow(new Date(now.getTime() + eligibleDelayMs()));
|
||||
for (const value of shared) await this.queueOne(write, { key, value, due, now });
|
||||
});
|
||||
}
|
||||
|
||||
private async queueOne(
|
||||
write: ContribWrite,
|
||||
entry: { key: string; value: ContribValue; due: string; now: Date },
|
||||
): Promise<void> {
|
||||
const payload = payloadOf(entry.value.field, entry.value.value);
|
||||
if ('withheld' in payload) {
|
||||
await this.outbox.deleteForPlace(write.placeId, [entry.value.field]);
|
||||
await this.log.insertLines([this.withheldLine(write, entry.value, entry.now, payload.withheld)]);
|
||||
return;
|
||||
}
|
||||
// At the cap nothing new is queued; a value that replaces a queued one still does.
|
||||
if ((await this.outbox.size()) >= OUTBOX_CAP && !(await this.outbox.hasEntry(entry.key, entry.value.field))) {
|
||||
await this.log.insertLines([this.withheldLine(write, entry.value, entry.now, 'queue_full')]);
|
||||
return;
|
||||
}
|
||||
await this.outbox.upsertEntry({
|
||||
contrib_key: entry.key,
|
||||
field: entry.value.field,
|
||||
value: payload.value,
|
||||
place_id: write.placeId,
|
||||
place_name: write.name,
|
||||
lat: write.lat,
|
||||
lng: write.lng,
|
||||
country: write.country,
|
||||
cid: newEntryCid(),
|
||||
eligible_at: entry.due,
|
||||
next_attempt_at: entry.due,
|
||||
});
|
||||
}
|
||||
|
||||
private withheldLine(write: ContribWrite, value: ContribValue, now: Date, reason: string): PlaceContribLogWrite {
|
||||
return {
|
||||
day: dayOf(now),
|
||||
contrib_key: contribKeyOf(write.osmId) ?? '-',
|
||||
place_name: write.name,
|
||||
field: value.field,
|
||||
value_summary: summaryOf(value.field, value.value),
|
||||
result: 'withheld',
|
||||
reason,
|
||||
};
|
||||
}
|
||||
|
||||
private async counts(now: Date): Promise<PlaceContribState['counts']> {
|
||||
const rows = await this.log.countsSince(dayOf(new Date(now.getTime() - COUNT_WINDOW_DAYS * DAY_MS)));
|
||||
const counts = { accepted: 0, duplicate: 0, rejected: 0, withheld: 0, retracted: 0 };
|
||||
for (const row of rows)
|
||||
if (LOG_RESULTS.includes(row.result as PlaceContribLogResult))
|
||||
counts[row.result as PlaceContribLogResult] = row.count;
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** Off or declined: nothing more is sent, and what waits in the queue goes. */
|
||||
private async switchOff(
|
||||
consent: PlaceContribConsent,
|
||||
change: Pick<PlaceContribConsent, 'decision' | 'termsVersion' | 'decidedBy' | 'decidedAt'>,
|
||||
): Promise<void> {
|
||||
await this.uow.transactional(async () => {
|
||||
await this.store.writeConsent({ ...consent, ...change, enabled: false });
|
||||
await this.outbox.deleteAll();
|
||||
});
|
||||
}
|
||||
|
||||
private async changeFields(
|
||||
consent: PlaceContribConsent,
|
||||
fields: PlaceContribFieldSwitches,
|
||||
opts: { withdraw: boolean; decided: Pick<PlaceContribConsent, 'decidedBy' | 'decidedAt'> },
|
||||
): Promise<void> {
|
||||
if (!agreedToCurrentTerms(consent)) {
|
||||
throw conflict('Sharing is not switched on', { reason: 'not_agreed' });
|
||||
}
|
||||
if (!anyField(fields)) throw badRequest('Pick at least one field to share', { reason: 'no_field' });
|
||||
const removed = PLACE_CONTRIB_FIELDS.filter((field) => consent.fields[field] && !fields[field]);
|
||||
await this.uow.transactional(async () => {
|
||||
await this.store.writeConsent({ ...consent, fields, ...opts.decided });
|
||||
await this.outbox.deleteFields(removed);
|
||||
});
|
||||
if (!opts.withdraw) return;
|
||||
for (const field of removed) {
|
||||
const answer = await this.client.withdraw({ field });
|
||||
if (answer.kind !== 'ok') logWarn(`Places contribution: withdrawing ${field} was not confirmed`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function anyField(fields: PlaceContribFieldSwitches): boolean {
|
||||
return PLACE_CONTRIB_FIELDS.some((field) => fields[field]);
|
||||
}
|
||||
|
||||
function assertCurrentTerms(termsVersion: number): void {
|
||||
if (termsVersion !== PLACE_CONTRIB_TERMS_VERSION) {
|
||||
throw conflict('The contribution terms changed', {
|
||||
reason: 'terms_outdated',
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** The service's per-kind counts, the numbers only. */
|
||||
function countsOf(withdrawn: Record<string, unknown> | undefined): Record<string, number> {
|
||||
const counts: Record<string, number> = {};
|
||||
for (const [kind, value] of Object.entries(withdrawn ?? {})) {
|
||||
if (typeof value === 'number' && Number.isInteger(value) && value >= 0) counts[kind] = value;
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import type { PlaceContribField } from '@trek/shared';
|
||||
|
||||
/** One field of a place whose current value the user typed, as the origin tracking hands it over. */
|
||||
export interface ContribValue {
|
||||
field: PlaceContribField;
|
||||
/** The column's value: the place's own text, the hours' JSON, the uploaded picture's URL. */
|
||||
value: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* A place write the origin tracking saw, for the contribution queue: what names
|
||||
* the place, the user-typed values it now holds, and the fields that are no
|
||||
* longer the user's (cleared, or set by someone else), whose queued values go.
|
||||
*/
|
||||
export interface ContribWrite {
|
||||
placeId: number;
|
||||
/** `osm_id` of the place; only a `gers:` or OpenStreetMap id makes it contributable. */
|
||||
osmId: string | null;
|
||||
name: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
country: string | null;
|
||||
values: ContribValue[];
|
||||
dropped: PlaceContribField[];
|
||||
}
|
||||
@@ -160,6 +160,22 @@ interface CachedEnrichment {
|
||||
|
||||
interface CachePayload extends CachedEnrichment {
|
||||
v?: number;
|
||||
/** The community version the index served for a gers place when the row was written. */
|
||||
cv?: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The community version the index serves for a gers place, from the details
|
||||
* record the request carries; null for any other place, or when it says none.
|
||||
* A cached answer written under another version is read again, so a value
|
||||
* another installation contributed shows up on the next open, not a week later.
|
||||
* A sender who puts another number here only makes their own request compute
|
||||
* afresh: nothing of the record is what gets cached.
|
||||
*/
|
||||
function communityVersion(placeId: string, details: Record<string, unknown> | null | undefined): number | null {
|
||||
if (!placeId.startsWith('gers:')) return null;
|
||||
const version = details?.community_version;
|
||||
return typeof version === 'number' && Number.isInteger(version) && version >= 0 ? version : null;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -385,7 +401,8 @@ export class PlaceEnrichmentService {
|
||||
const placeId = req.placeId?.trim() || `coords:${req.lat}:${req.lng}`;
|
||||
const lang = req.lang;
|
||||
|
||||
const cached = await this.readCache(placeId, lang);
|
||||
const served = communityVersion(placeId, req.details);
|
||||
const cached = await this.readCache(placeId, lang, served);
|
||||
if (cached) return cached;
|
||||
|
||||
// One details lookup feeds all three halves: the pictures need its Commons
|
||||
@@ -434,7 +451,7 @@ export class PlaceEnrichmentService {
|
||||
// A summary or a link the lookup here fetched itself is the map's and keeps.
|
||||
const fromCaller =
|
||||
req.details != null && (description?.source === 'osm' || ownFacts.some((fact) => fact.url != null));
|
||||
if (!fromCaller) await this.writeCache(placeId, lang, result);
|
||||
if (!fromCaller) await this.writeCache(placeId, lang, { ...result, cv: communityVersion(placeId, details) });
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -866,12 +883,17 @@ export class PlaceEnrichmentService {
|
||||
|
||||
// ── Result cache ───────────────────────────────────────────────────────────
|
||||
|
||||
private async readCache(placeId: string, lang: string | undefined): Promise<CachedEnrichment | null> {
|
||||
private async readCache(
|
||||
placeId: string,
|
||||
lang: string | undefined,
|
||||
servedVersion: number | null,
|
||||
): Promise<CachedEnrichment | null> {
|
||||
try {
|
||||
const row = await this.cache.findEntry(placeId, lang ?? '', CACHE_KIND);
|
||||
if (!row) return null;
|
||||
const parsed = JSON.parse(row.payload_json) as CachePayload;
|
||||
if (parsed.v !== CACHE_VERSION) return null;
|
||||
if (servedVersion !== null && (parsed.cv ?? null) !== servedVersion) return null;
|
||||
|
||||
// A cached candidate is only usable while its bytes are still on disk, and
|
||||
// the nightly sweep deletes every picture nobody picked — which is most of
|
||||
@@ -898,7 +920,11 @@ export class PlaceEnrichmentService {
|
||||
}
|
||||
}
|
||||
|
||||
private async writeCache(placeId: string, lang: string | undefined, value: CachedEnrichment): Promise<void> {
|
||||
private async writeCache(
|
||||
placeId: string,
|
||||
lang: string | undefined,
|
||||
value: CachedEnrichment & { cv: number | null },
|
||||
): Promise<void> {
|
||||
try {
|
||||
await this.cache.upsertEntry({
|
||||
place_id: placeId,
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
import { PLACE_DETAILS_CACHE_PAYLOAD } from '../../db/json-columns';
|
||||
import type { CachedProviderPayload, PlaceShareableRow } from '../../db/repositories/PlaceFieldOrigin.repository';
|
||||
import { decodeJson } from '../../utils/json-column';
|
||||
import {
|
||||
PLACE_CONTRIB_FIELDS,
|
||||
normalizePlaceWebsite,
|
||||
type PlaceContribField,
|
||||
type PlaceFieldOrigin,
|
||||
type PlaceFieldOrigins,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Who wrote a place: a client reporting per field, or a path that decides the origin of all it changed. */
|
||||
export type OriginWriter =
|
||||
{ kind: 'client'; claims: PlaceFieldOrigins | undefined } | { kind: 'fixed'; origin: PlaceFieldOrigin };
|
||||
|
||||
/** The shareable values of a place, one per field, null where it holds none. */
|
||||
export type OriginSnapshot = Record<PlaceContribField, string | null>;
|
||||
|
||||
/** A value a provider handed out for the place, and which provider that was. */
|
||||
export interface ProviderValue {
|
||||
field: PlaceContribField;
|
||||
value: string;
|
||||
origin: PlaceFieldOrigin;
|
||||
}
|
||||
|
||||
const COLUMN: Record<PlaceContribField, keyof PlaceShareableRow> = {
|
||||
website: 'website',
|
||||
phone: 'phone',
|
||||
email: 'email',
|
||||
opening_hours: 'opening_hours',
|
||||
description: 'description',
|
||||
image: 'image_url',
|
||||
};
|
||||
|
||||
/** The place's shareable values as stored, an empty text read as none. */
|
||||
export function snapshotOf(row: PlaceShareableRow): OriginSnapshot {
|
||||
const snapshot = {} as OriginSnapshot;
|
||||
for (const field of PLACE_CONTRIB_FIELDS) {
|
||||
const value = row[COLUMN[field]];
|
||||
snapshot[field] = typeof value === 'string' && value.trim() !== '' ? value : null;
|
||||
}
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
/** The fields whose value this write changed. */
|
||||
export function changedFields(before: OriginSnapshot | null, after: OriginSnapshot): PlaceContribField[] {
|
||||
return PLACE_CONTRIB_FIELDS.filter((field) => (before?.[field] ?? null) !== after[field]);
|
||||
}
|
||||
|
||||
/** The provider ids a place carries, which its cached details records are keyed by. */
|
||||
export function providerIdsOf(row: PlaceShareableRow): string[] {
|
||||
return [row.google_place_id, row.amap_poi_id, row.osm_id].filter(
|
||||
(id): id is string => typeof id === 'string' && id.trim() !== '',
|
||||
);
|
||||
}
|
||||
|
||||
/** Which provider a cached record belongs to, by the id it is keyed under. */
|
||||
function originOfId(placeId: string): PlaceFieldOrigin {
|
||||
if (placeId.startsWith('gers:')) return 'trek';
|
||||
if (placeId.startsWith('amap:')) return 'amap';
|
||||
if (/^(node|way|relation):/.test(placeId)) return 'osm';
|
||||
return 'google';
|
||||
}
|
||||
|
||||
/** The source an enrichment description names, as an origin. */
|
||||
function originOfSource(source: unknown): PlaceFieldOrigin {
|
||||
if (source === 'website') return 'website';
|
||||
if (source === 'osm') return 'osm';
|
||||
if (source === 'google') return 'google';
|
||||
if (typeof source === 'string' && /^wiki/.test(source)) return 'wikimedia';
|
||||
return 'enrichment';
|
||||
}
|
||||
|
||||
function text(value: unknown): string | null {
|
||||
return typeof value === 'string' && value.trim() !== '' ? value : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The values the cached records hand out for a place: a details record's
|
||||
* website, phone, e-mail and description, an enrichment record's description.
|
||||
* A record that does not read as an object adds nothing.
|
||||
*/
|
||||
export function providerValuesOf(payloads: CachedProviderPayload[]): ProviderValue[] {
|
||||
const values: ProviderValue[] = [];
|
||||
for (const payload of payloads) {
|
||||
const record = decodeJson(PLACE_DETAILS_CACHE_PAYLOAD, payload.payload_json, payload.place_id);
|
||||
if (!record) continue;
|
||||
const origin = originOfId(payload.place_id);
|
||||
for (const field of ['website', 'phone', 'email'] as const) {
|
||||
const value = text(record[field]);
|
||||
if (value) values.push({ field, value, origin });
|
||||
}
|
||||
const description = record.description;
|
||||
const described =
|
||||
typeof description === 'object' && description !== null ? (description as Record<string, unknown>) : null;
|
||||
const descriptionText = described ? text(described.text) : text(description);
|
||||
if (descriptionText) {
|
||||
values.push({
|
||||
field: 'description',
|
||||
value: descriptionText,
|
||||
origin: payload.expanded === 2 && described ? originOfSource(described.source) : origin,
|
||||
});
|
||||
}
|
||||
}
|
||||
return values;
|
||||
}
|
||||
|
||||
/** Two values of one field compared the way they are read: case, spacing and a website's scheme aside. */
|
||||
export function sameValue(field: PlaceContribField, a: string, b: string): boolean {
|
||||
if (field === 'website') return (normalizePlaceWebsite(a) ?? a.trim()) === (normalizePlaceWebsite(b) ?? b.trim());
|
||||
if (field === 'phone') return a.replace(/[^\d+]/g, '') === b.replace(/[^\d+]/g, '');
|
||||
if (field === 'email') return a.trim().toLowerCase() === b.trim().toLowerCase();
|
||||
return a.replace(/\s+/g, ' ').trim() === b.replace(/\s+/g, ' ').trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* The origin a changed field is stored with.
|
||||
*
|
||||
* A path that decides (MCP, a plugin, an import, an attachment, an upload)
|
||||
* gives its own. A client is believed for a provider, since claiming one only
|
||||
* keeps a value home; a value it claims as typed is the user's only when no
|
||||
* provider handed out the same, and otherwise the provider's. A changed field
|
||||
* the client reported nothing for is unknown, and so is a picture a client
|
||||
* claims: the user's own picture arrives through the upload route only.
|
||||
*/
|
||||
export function originFor(
|
||||
field: PlaceContribField,
|
||||
value: string,
|
||||
writer: OriginWriter,
|
||||
providers: readonly ProviderValue[],
|
||||
): PlaceFieldOrigin {
|
||||
if (writer.kind === 'fixed') return writer.origin;
|
||||
const claim = writer.claims?.[field];
|
||||
if (!claim) return 'unknown';
|
||||
if (claim !== 'user') return claim;
|
||||
if (field === 'image') return 'unknown';
|
||||
return providers.find((p) => p.field === field && sameValue(field, p.value, value))?.origin ?? 'user';
|
||||
}
|
||||
|
||||
/** Whether origins of this writer could need the cached provider records at all. */
|
||||
export function needsProviders(writer: OriginWriter, fields: readonly PlaceContribField[]): boolean {
|
||||
return writer.kind === 'client' && fields.some((field) => writer.claims?.[field] === 'user');
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { toRowId } from '../common/row-id';
|
||||
import type { OriginSnapshot, OriginWriter } from './place-origins.helpers';
|
||||
import { PlaceOriginsService } from './place-origins.service';
|
||||
import {
|
||||
applyDecorators,
|
||||
Injectable,
|
||||
SetMetadata,
|
||||
UseInterceptors,
|
||||
type CallHandler,
|
||||
type ExecutionContext,
|
||||
type NestInterceptor,
|
||||
} from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
import { placeFieldOriginsSchema } from '@trek/shared';
|
||||
|
||||
import type { Request } from 'express';
|
||||
import { mergeMap, type Observable } from 'rxjs';
|
||||
|
||||
/**
|
||||
* What a place route writes, for its origin tracking:
|
||||
* - `client`: a create or update from the app, which reports `fieldOrigins`;
|
||||
* - `upload`: the user's own picture for the place;
|
||||
* - `attachment`: a trip file made the picture;
|
||||
* - `import`: new places from a file or a shared list.
|
||||
*/
|
||||
type PlaceOriginRoute = 'client' | 'upload' | 'attachment' | 'import';
|
||||
|
||||
const ROUTE_KEY = 'trekPlaceOriginRoute';
|
||||
|
||||
/** Records where the shareable details a place route wrote came from, once the route answered. */
|
||||
export function TrackPlaceOrigins(route: PlaceOriginRoute): MethodDecorator {
|
||||
return applyDecorators(SetMetadata(ROUTE_KEY, route), UseInterceptors(PlaceOriginsInterceptor));
|
||||
}
|
||||
|
||||
/**
|
||||
* The REST side of the origin tracking. It reads the place's values before
|
||||
* the handler runs and records what changed after it answered, so the
|
||||
* controller's routes stay as they are, and an offline replay, which goes
|
||||
* through the same routes, is recorded the same way. A handler that throws
|
||||
* records nothing.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceOriginsInterceptor implements NestInterceptor {
|
||||
constructor(
|
||||
private readonly origins: PlaceOriginsService,
|
||||
private readonly reflector: Reflector,
|
||||
) {}
|
||||
|
||||
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
|
||||
const route = this.reflector.get<PlaceOriginRoute | undefined>(ROUTE_KEY, context.getHandler()) ?? 'client';
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const placeId = route === 'import' ? null : toRowId(req.params?.id);
|
||||
const before = placeId === null ? null : await this.origins.valuesBefore(placeId);
|
||||
return next.handle().pipe(
|
||||
mergeMap(async (body: unknown) => {
|
||||
await this.recordAnswer(route, { body, before, claims: req.body as unknown });
|
||||
return body;
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
private async recordAnswer(
|
||||
route: PlaceOriginRoute,
|
||||
answer: { body: unknown; before: OriginSnapshot | null; claims: unknown },
|
||||
): Promise<void> {
|
||||
if (route === 'import') {
|
||||
await this.origins.recordImported(idsOf((answer.body as { places?: unknown } | null)?.places));
|
||||
return;
|
||||
}
|
||||
const id = idsOf([(answer.body as { place?: unknown } | null)?.place])[0];
|
||||
if (id === undefined) return;
|
||||
await this.origins.record(id, answer.before, writerFor(route, answer.claims));
|
||||
}
|
||||
}
|
||||
|
||||
function writerFor(route: Exclude<PlaceOriginRoute, 'import'>, body: unknown): OriginWriter {
|
||||
if (route === 'upload') return { kind: 'fixed', origin: 'user' };
|
||||
if (route === 'attachment') return { kind: 'fixed', origin: 'attachment' };
|
||||
// The pipe has refused a malformed body before the handler ran; this reads the same field again.
|
||||
const parsed = placeFieldOriginsSchema.safeParse((body as { fieldOrigins?: unknown } | null)?.fieldOrigins);
|
||||
return { kind: 'client', claims: parsed.success ? parsed.data : undefined };
|
||||
}
|
||||
|
||||
/** The ids of the places in an answer. */
|
||||
function idsOf(places: unknown): number[] {
|
||||
if (!Array.isArray(places)) return [];
|
||||
return places
|
||||
.map((place: unknown) => (place as { id?: unknown } | null)?.id)
|
||||
.filter((id): id is number => typeof id === 'number' && Number.isInteger(id) && id > 0);
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
import { PlaceFieldOrigin } from '../../db/entities/PlaceFieldOrigin.entity';
|
||||
import type {
|
||||
PlaceFieldOriginRepository,
|
||||
PlaceOriginWrite,
|
||||
PlaceShareableRow,
|
||||
} from '../../db/repositories/PlaceFieldOrigin.repository';
|
||||
import { dbNow } from '../../db/types';
|
||||
import { resolveCountryCodeSync } from '../atlas/atlas-geo';
|
||||
import { logWarn } from '../audit/audit-log.logger';
|
||||
import { toRowId } from '../common/row-id';
|
||||
import { valueHash } from '../common/value-hash';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { PlaceContribService } from '../place-contrib/place-contrib.service';
|
||||
import {
|
||||
changedFields,
|
||||
needsProviders,
|
||||
originFor,
|
||||
providerIdsOf,
|
||||
providerValuesOf,
|
||||
snapshotOf,
|
||||
type OriginSnapshot,
|
||||
type OriginWriter,
|
||||
type ProviderValue,
|
||||
} from './place-origins.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { PlaceContribField } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Where the shareable details of a place came from (website, phone, e-mail,
|
||||
* opening hours, description, picture), recorded after every place write.
|
||||
*
|
||||
* A write records an origin for each field whose value it changed, with the
|
||||
* hash of the new value: `user` for what a person typed, the provider for what
|
||||
* a search pick or a details lookup filled, `agent`, `plugin`, `import` or
|
||||
* `attachment` for the paths that decide themselves, `unknown` for a change
|
||||
* nobody vouched for. A cleared value loses its row. An unchanged value keeps
|
||||
* the row it had, so a value that existed before this tracking has none and is
|
||||
* never shared.
|
||||
*
|
||||
* The user's values then go to the contribution queue, which decides whether
|
||||
* anything is sent at all. Recording never fails the write it follows.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceOriginsService {
|
||||
constructor(
|
||||
@InjectRepository(PlaceFieldOrigin) private readonly origins: PlaceFieldOriginRepository,
|
||||
private readonly contrib: PlaceContribService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
/** The shareable values of a place before a write, for {@link record} to see what changed; null without one. */
|
||||
async valuesBefore(placeId: number | string): Promise<OriginSnapshot | null> {
|
||||
const id = toRowId(placeId);
|
||||
if (id === null) return null;
|
||||
try {
|
||||
const row = await this.origins.placeValues(id);
|
||||
return row ? snapshotOf(row) : null;
|
||||
} catch (err) {
|
||||
logWarn(`Place origins: reading place ${id} failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the origins of what this write changed, then hands the user's
|
||||
* values to the contribution queue. `before` is null for a new place.
|
||||
*
|
||||
* @txStandalone a derived write after the place write committed; a failure is logged, never raised.
|
||||
*/
|
||||
async record(placeId: number, before: OriginSnapshot | null, writer: OriginWriter): Promise<void> {
|
||||
try {
|
||||
await this.recordChanges(placeId, before, writer);
|
||||
} catch (err) {
|
||||
logWarn(`Place origins: recording place ${placeId} failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* New places from a file or a list import: every value they hold is the
|
||||
* import's. One read and one write for the whole batch.
|
||||
*
|
||||
* @txStandalone a derived write after the import committed; a failure is logged, never raised.
|
||||
*/
|
||||
async recordImported(placeIds: number[]): Promise<void> {
|
||||
try {
|
||||
const rows = await this.origins.placeValuesMany(placeIds);
|
||||
const updatedAt = dbNow();
|
||||
const writes = rows.flatMap((row) => {
|
||||
const after = snapshotOf(row);
|
||||
return changedFields(null, after).map((field) => originWrite(row.id, field, after, 'import', updatedAt));
|
||||
});
|
||||
await this.origins.upsertOrigins(writes);
|
||||
} catch (err) {
|
||||
logWarn(`Place origins: recording an import failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async recordChanges(placeId: number, before: OriginSnapshot | null, writer: OriginWriter): Promise<void> {
|
||||
const row = await this.origins.placeValues(placeId);
|
||||
if (!row) return;
|
||||
const after = snapshotOf(row);
|
||||
const changed = changedFields(before, after);
|
||||
if (changed.length === 0) return;
|
||||
const providers = needsProviders(writer, changed) ? await this.providerValues(row) : [];
|
||||
const updatedAt = dbNow();
|
||||
const writes: PlaceOriginWrite[] = [];
|
||||
const cleared: PlaceContribField[] = [];
|
||||
const typed: PlaceContribField[] = [];
|
||||
for (const field of changed) {
|
||||
const value = after[field];
|
||||
if (value === null) {
|
||||
cleared.push(field);
|
||||
continue;
|
||||
}
|
||||
const origin = originFor(field, value, writer, providers);
|
||||
writes.push(originWrite(placeId, field, after, origin, updatedAt));
|
||||
if (origin === 'user') typed.push(field);
|
||||
}
|
||||
await this.uow.transactional(async () => {
|
||||
await this.origins.deleteOrigins(placeId, cleared);
|
||||
await this.origins.upsertOrigins(writes);
|
||||
});
|
||||
await this.contrib.enqueue({
|
||||
placeId,
|
||||
osmId: row.osm_id,
|
||||
name: row.name,
|
||||
lat: row.lat,
|
||||
lng: row.lng,
|
||||
country: resolveCountryCodeSync(row),
|
||||
values: typed.map((field) => ({ field, value: after[field] ?? '' })),
|
||||
dropped: changed.filter((field) => !typed.includes(field)),
|
||||
});
|
||||
}
|
||||
|
||||
/** What the providers this instance asked handed out for the place, read from their cached records. */
|
||||
private async providerValues(row: PlaceShareableRow): Promise<ProviderValue[]> {
|
||||
return providerValuesOf(await this.origins.cachedProviderPayloads(providerIdsOf(row)));
|
||||
}
|
||||
}
|
||||
|
||||
function originWrite(
|
||||
placeId: number,
|
||||
field: PlaceContribField,
|
||||
after: OriginSnapshot,
|
||||
origin: PlaceOriginWrite['origin'],
|
||||
updatedAt: string,
|
||||
): PlaceOriginWrite {
|
||||
return { place_id: placeId, field, origin, value_hash: valueHash(after[field] ?? ''), updated_at: updatedAt };
|
||||
}
|
||||
@@ -10,6 +10,7 @@ import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.g
|
||||
import { isDirectionsUrl, isGoogleListDataUrl } from '../place-import/place-import.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { placeImageUrl } from './place-image';
|
||||
import { TrackPlaceOrigins } from './place-origins.interceptor';
|
||||
import {
|
||||
PlaceBulkDeleteDto,
|
||||
PlaceBulkUpdateDto,
|
||||
@@ -157,6 +158,7 @@ export class PlacesController {
|
||||
}
|
||||
|
||||
@Post()
|
||||
@TrackPlaceOrigins('client')
|
||||
async create(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@@ -176,6 +178,7 @@ export class PlacesController {
|
||||
|
||||
@Post('import/gpx')
|
||||
@UseInterceptors(FileInterceptor('file', UPLOAD))
|
||||
@TrackPlaceOrigins('import')
|
||||
async importGpx(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@@ -240,6 +243,7 @@ export class PlacesController {
|
||||
|
||||
@Post('import/map')
|
||||
@UseInterceptors(FileInterceptor('file', UPLOAD))
|
||||
@TrackPlaceOrigins('import')
|
||||
async importMap(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@@ -278,6 +282,7 @@ export class PlacesController {
|
||||
}
|
||||
|
||||
@Post('import/google-list')
|
||||
@TrackPlaceOrigins('import')
|
||||
async importGoogle(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@@ -288,6 +293,7 @@ export class PlacesController {
|
||||
}
|
||||
|
||||
@Post('import/naver-list')
|
||||
@TrackPlaceOrigins('import')
|
||||
async importNaver(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@@ -421,6 +427,7 @@ export class PlacesController {
|
||||
@Post(':id/image')
|
||||
@HttpCode(200)
|
||||
@UseInterceptors(FileInterceptor('image', { fileFilter: PLACE_IMAGE_FILE_FILTER }))
|
||||
@TrackPlaceOrigins('upload')
|
||||
async uploadImage(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@@ -454,6 +461,7 @@ export class PlacesController {
|
||||
}
|
||||
|
||||
@Put(':id/image/from-file')
|
||||
@TrackPlaceOrigins('attachment')
|
||||
async imageFromFile(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@@ -525,6 +533,7 @@ export class PlacesController {
|
||||
}
|
||||
|
||||
@Put(':id')
|
||||
@TrackPlaceOrigins('client')
|
||||
async update(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
|
||||
@@ -26,6 +26,8 @@ import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { MapsService } from '../maps/maps.service';
|
||||
import { PlacesService } from './places.service';
|
||||
import { PlaceOriginsService } from './place-origins.service';
|
||||
import type { OriginWriter } from './place-origins.helpers';
|
||||
import { isUpdateConflict } from '../common/conflictResult';
|
||||
import { isDirectionsUrl } from '../place-import/place-import.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
@@ -38,6 +40,9 @@ function parseId(value: string | string[]): number | null {
|
||||
/** Hours as the column keeps them: JSON text, or null to clear (#2472). */
|
||||
const hoursText = (hours: PlaceOpeningHours | null | undefined): string | null => (hours ? JSON.stringify(hours) : null);
|
||||
|
||||
/** What the assistant writes is the agent's, never shared as a user's correction. */
|
||||
const AGENT: OriginWriter = { kind: 'fixed', origin: 'agent' };
|
||||
|
||||
/**
|
||||
* Places MCP surface — ported 1:1 from the legacy registrar
|
||||
* src/mcp/tools/places.ts (ten tools) plus the trek://trips/{tripId}/places
|
||||
@@ -65,6 +70,7 @@ export class PlacesMcp {
|
||||
private readonly assignments: AssignmentsService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
private readonly uow: UnitOfWork,
|
||||
private readonly origins: PlaceOriginsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
@@ -109,6 +115,7 @@ export class PlacesMcp {
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type });
|
||||
this.guards.safeBroadcast(tripId, 'place:created', { place });
|
||||
await this.origins.record(place.id, null, AGENT);
|
||||
// The journey hook the REST route and the plugin RPC run after the same write.
|
||||
await this.places.onCreated(String(tripId), place.id);
|
||||
return ok({ place });
|
||||
@@ -165,6 +172,7 @@ export class PlacesMcp {
|
||||
});
|
||||
this.guards.safeBroadcast(tripId, 'place:created', { place: result.place });
|
||||
this.guards.safeBroadcast(tripId, 'assignment:created', { assignment: result.assignment });
|
||||
await this.origins.record(result.place.id, null, AGENT);
|
||||
try { await this.journey.reconcileTripSkeletons(tripId); } catch { /* non-fatal */ }
|
||||
return ok(result);
|
||||
} catch {
|
||||
@@ -221,10 +229,12 @@ export class PlacesMcp {
|
||||
) {
|
||||
if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const before = await this.origins.valuesBefore(placeId);
|
||||
const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours: opening_hours === undefined ? undefined : hoursText(opening_hours), image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent });
|
||||
// No base version is sent, so the update never answers a conflict; the guard only narrows the type.
|
||||
if (!place || isUpdateConflict(place)) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
|
||||
this.guards.safeBroadcast(tripId, 'place:updated', { place });
|
||||
await this.origins.record(place.id, before, AGENT);
|
||||
// As on REST: the journey entries made from this place follow its new name, address and time.
|
||||
await this.places.onUpdated(place.id);
|
||||
return ok({ place });
|
||||
@@ -247,12 +257,14 @@ export class PlacesMcp {
|
||||
) {
|
||||
if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const before = await this.origins.valuesBefore(placeId);
|
||||
const result = await this.places.setImageFromFile(String(tripId), String(placeId), fileId);
|
||||
if (result === 'not_found') return errorResult('File not found.');
|
||||
if (result === 'not_image') return errorResult('That file is not a jpg, png, gif or webp image.');
|
||||
if (result === 'too_large') return errorResult('That image is too large.');
|
||||
if (!result || isUpdateConflict(result)) return errorResult('Place not found.');
|
||||
this.guards.safeBroadcast(tripId, 'place:updated', { place: result });
|
||||
await this.origins.record(result.id, before, { kind: 'fixed', origin: 'attachment' });
|
||||
await this.places.onUpdated(result.id);
|
||||
return ok({ place: result });
|
||||
}
|
||||
@@ -400,6 +412,7 @@ export class PlacesMcp {
|
||||
for (const place of result.places) {
|
||||
this.guards.safeBroadcast(tripId, 'place:created', { place });
|
||||
}
|
||||
await this.origins.recordImported(result.places.map((place) => place.id));
|
||||
return ok({ places: result.places, count: result.places.length, listName: result.listName, skipped: result.skipped });
|
||||
}
|
||||
|
||||
@@ -418,6 +431,7 @@ export class PlacesMcp {
|
||||
const imported = await this.places.importGpx(String(input.tripId), Buffer.from(input.gpx, 'utf8'), { importWaypoints: input.importWaypoints, importRoutes: input.importRoutes, importTracks: input.importTracks, defaultName: input.name });
|
||||
if (!imported) return errorResult('No matching places found in GPX.');
|
||||
for (const place of imported.places) this.guards.safeBroadcast(input.tripId, 'place:created', { place });
|
||||
await this.origins.recordImported(imported.places.map((place) => place.id));
|
||||
if (input.enrich) this.places.enrichImportedFilePlaces(String(input.tripId), ctx.userId, imported.places);
|
||||
return ok(imported);
|
||||
} catch {
|
||||
@@ -526,10 +540,13 @@ export class PlacesMcp {
|
||||
return { content: [{ type: 'text' as const, text: 'Provide at least one field to update.' }], isError: true };
|
||||
}
|
||||
|
||||
const before = new Map<number, Awaited<ReturnType<PlaceOriginsService['valuesBefore']>>>();
|
||||
for (const id of placeIds) before.set(id, await this.origins.valuesBefore(id));
|
||||
const updated = await this.places.updateMany(String(tripId), placeIds, fields);
|
||||
// Per place, the event and then the journey hook, in the order POST /places/bulk-update keeps.
|
||||
for (const place of updated) {
|
||||
this.guards.safeBroadcast(tripId, 'place:updated', { place });
|
||||
await this.origins.record(place.id, before.get(place.id) ?? null, AGENT);
|
||||
await this.places.onUpdated(place.id);
|
||||
}
|
||||
return ok({ count: updated.length, updatedIds: updated.map(p => p.id), skipped: placeIds.length - updated.length });
|
||||
|
||||
@@ -2,6 +2,7 @@ import { BudgetItems } from '../../db/entities/BudgetItems.entity';
|
||||
import { Categories } from '../../db/entities/Categories.entity';
|
||||
import { CollectionPlaces } from '../../db/entities/CollectionPlaces.entity';
|
||||
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
|
||||
import { PlaceFieldOrigin } from '../../db/entities/PlaceFieldOrigin.entity';
|
||||
import { PlaceRatings } from '../../db/entities/PlaceRatings.entity';
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { Tags } from '../../db/entities/Tags.entity';
|
||||
@@ -16,6 +17,7 @@ import { JourneyDomainModule } from '../journey/journey-domain.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { PlaceContribModule } from '../place-contrib/place-contrib.module';
|
||||
import { PlaceImportModule } from '../place-import/place-import.module';
|
||||
import { PlacePhotosModule } from '../place-photos/place-photos.module';
|
||||
import { QueryHelpersModule } from '../query-helpers/query-helpers.module';
|
||||
@@ -25,6 +27,7 @@ import { StorageModule } from '../storage/storage.module';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { UnsplashModule } from '../unsplash/unsplash.module';
|
||||
import { PlaceOriginsService } from './place-origins.service';
|
||||
import { PlacesController } from './places.controller';
|
||||
import { PlacesMcp } from './places.mcp';
|
||||
import { PlacesRpc } from './places.rpc';
|
||||
@@ -71,6 +74,9 @@ import { MulterModule } from '@nestjs/platform-express';
|
||||
PluginGuardsModule,
|
||||
AssignmentsDomainModule,
|
||||
AccommodationsDomainModule,
|
||||
// Every place write records where its shareable details came from, and the
|
||||
// user's values go to the community enrichment's queue there.
|
||||
PlaceContribModule,
|
||||
// Plan 3c Task 4: `PlacesService`'s and `PlacesMcp`'s own `@InjectRepository`
|
||||
// constructor params (`PlacesRepository`, `TagsRepository`,
|
||||
// `PlaceRatingsRepository`, `TripMembersRepository`,
|
||||
@@ -95,10 +101,11 @@ import { MulterModule } from '@nestjs/platform-express';
|
||||
Categories,
|
||||
BudgetItems,
|
||||
CollectionPlaces,
|
||||
PlaceFieldOrigin,
|
||||
]),
|
||||
],
|
||||
controllers: [PlacesController],
|
||||
providers: [PlacesService, PlacesMcp, PlacesRpc],
|
||||
providers: [PlacesService, PlacesMcp, PlacesRpc, PlaceOriginsService],
|
||||
exports: [PlacesService],
|
||||
})
|
||||
export class PlacesModule {}
|
||||
|
||||
@@ -5,6 +5,8 @@ import type { PluginRpcContext } from '../../nest-rpc/rpc-kit/types';
|
||||
import { num, schemaMessage } from '../../nest-rpc/rpc-params';
|
||||
import { JourneyDomainService } from '../journey/journey-domain.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import type { OriginWriter } from './place-origins.helpers';
|
||||
import { PlaceOriginsService } from './place-origins.service';
|
||||
import { PlacesService } from './places.service';
|
||||
import type { PlaceCreateInput, PlaceUpdateInput } from './places.service';
|
||||
import {
|
||||
@@ -16,6 +18,9 @@ import {
|
||||
|
||||
const PLACE_EDIT_ACTION = 'place_edit';
|
||||
|
||||
/** What a plugin writes is the plugin's, never shared as a user's correction. */
|
||||
const PLUGIN: OriginWriter = { kind: 'fixed', origin: 'plugin' };
|
||||
|
||||
/**
|
||||
* The @trek/shared write schemas carry no string-length caps, so the plugin path
|
||||
* mirrors the ones the REST controller adds. Without them a plugin could store a
|
||||
@@ -59,6 +64,7 @@ export class PlacesRpc {
|
||||
private readonly journey: JourneyDomainService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly guards: PluginGuards,
|
||||
private readonly origins: PlaceOriginsService,
|
||||
) {}
|
||||
|
||||
@PluginMethod('places.create', { permission: 'db:write:places' })
|
||||
@@ -72,6 +78,7 @@ export class PlacesRpc {
|
||||
await this.guards.requireTripEdit(tripId, actor, PLACE_EDIT_ACTION);
|
||||
const place = await this.places.create(String(tripId), parsed.data as unknown as PlaceCreateInput);
|
||||
this.realtime.broadcast(tripId, 'place:created', { place });
|
||||
await this.origins.record(place.id, null, PLUGIN);
|
||||
await this.mirrorJourneys(() => this.journey.onPlaceCreated(tripId, place.id));
|
||||
return place;
|
||||
}
|
||||
@@ -89,9 +96,11 @@ export class PlacesRpc {
|
||||
// update is async (it may delete a superseded storage object): await it so the
|
||||
// null-refusal check compares against the resolved place, not an always-truthy
|
||||
// Promise, and the broadcast below carries the actual place.
|
||||
const before = await this.origins.valuesBefore(placeId);
|
||||
const place = await this.places.update(String(tripId), String(placeId), parsed.data as PlaceUpdateInput);
|
||||
if (place === null) throw new ForbiddenResource(`no place ${placeId} on trip ${tripId}`);
|
||||
this.realtime.broadcast(tripId, 'place:updated', { place });
|
||||
if ('id' in place) await this.origins.record(place.id, before, PLUGIN);
|
||||
await this.mirrorJourneys(() => this.journey.onPlaceUpdated(placeId));
|
||||
return place;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,245 @@
|
||||
/**
|
||||
* /api/admin/places-contribute e2e: the real JwtAuthGuard, AdminGuard, Zod pipe
|
||||
* and response contracts over PlaceContribModule on a migrated temp database,
|
||||
* with the installation key from TREK_SERVICES_KEY and fetch standing in for
|
||||
* the TREK Places API.
|
||||
*
|
||||
* NODE_ENV=test makes the instance ineligible, which is what the state says;
|
||||
* the decisions, the log and the withdrawal work regardless.
|
||||
*/
|
||||
import { AuditLog } from '../../src/db/entities/AuditLog.entity';
|
||||
import { PlaceContribLog } from '../../src/db/entities/PlaceContribLog.entity';
|
||||
import { servicesConfig } from '../../src/nest/app-config/tokens';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { PlaceContribModule } from '../../src/nest/place-contrib/place-contrib.module';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { countRows, deleteRows, insertRows } from '../helpers/factories/rows';
|
||||
import { makeAdmin, makeUser } from '../helpers/factories/users';
|
||||
import { serviceKeyTokenFor } from '../helpers/service-keys';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
import { PLACE_CONTRIB_TERMS_VERSION } from '@trek/shared';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const USER = 1;
|
||||
const ADMIN = 2;
|
||||
const KEY = serviceKeyTokenFor({ i: 'contrib-e2e', iat: 1_793_000_000, exp: 4_102_444_800 });
|
||||
const FIELDS = { website: true, phone: true, email: false, opening_hours: true, description: true, image: false };
|
||||
const BASE = '/api/admin/places-contribute';
|
||||
|
||||
const fetchMock = vi.fn();
|
||||
let orm: TestOrm;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let server: Server;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), PlaceContribModule],
|
||||
})
|
||||
.overrideProvider(servicesConfig.KEY)
|
||||
.useValue({
|
||||
mode: 'auto',
|
||||
key: KEY,
|
||||
hosts: ['places.liketrek.com'],
|
||||
photonUrl: 'https://photon.liketrek.com',
|
||||
valhallaUrl: 'https://valhalla.liketrek.com',
|
||||
})
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
|
||||
beforeAll(async () => {
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
orm = await createTestOrm(db);
|
||||
await makeUser(orm, { id: USER, username: 'traveler', email: 'traveler@example.test' });
|
||||
await makeAdmin(orm, { id: ADMIN, username: 'admin', email: 'admin@example.test' });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
fetchMock.mockReset();
|
||||
await deleteRows(orm, PlaceContribLog);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('the guards', () => {
|
||||
it('PCE2E-001: 401 without a session and 403 for a user who is no admin, on every route', async () => {
|
||||
const routes = [
|
||||
() => request(server).get(BASE),
|
||||
() => request(server).put(`${BASE}/decision`).send({ action: 'snooze' }),
|
||||
() => request(server).get(`${BASE}/log`),
|
||||
() => request(server).post(`${BASE}/withdraw`).send({ confirm: true }),
|
||||
];
|
||||
for (const route of routes) {
|
||||
expect((await route()).status).toBe(401);
|
||||
expect((await route().set(as(USER))).status).toBe(403);
|
||||
}
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the state and the decisions', () => {
|
||||
it('PCE2E-010: a test instance is not eligible, says why, and shows no prompt', async () => {
|
||||
const res = await request(server).get(BASE).set(as(ADMIN));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toMatchObject({
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
ceiling: 'admin',
|
||||
eligible: false,
|
||||
ineligibleReason: 'not_production',
|
||||
showPrompt: false,
|
||||
active: false,
|
||||
queue: { size: 0, cap: 5000, full: false },
|
||||
counts: { accepted: 0, duplicate: 0, rejected: 0, withheld: 0, retracted: 0 },
|
||||
});
|
||||
});
|
||||
|
||||
it('PCE2E-011: an agreement is stored, answered with the new state and audited', async () => {
|
||||
const res = await request(server)
|
||||
.put(`${BASE}/decision`)
|
||||
.set(as(ADMIN))
|
||||
.send({ action: 'agree', termsVersion: PLACE_CONTRIB_TERMS_VERSION, fields: FIELDS });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.consent).toMatchObject({
|
||||
enabled: true,
|
||||
fields: FIELDS,
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
decision: 'agreed',
|
||||
decidedBy: ADMIN,
|
||||
});
|
||||
expect(await countRows(orm, AuditLog, { action: 'admin.places_contribute_decision' })).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('PCE2E-012: a dialog built for other terms gets 409 with the terms in force', async () => {
|
||||
const res = await request(server)
|
||||
.put(`${BASE}/decision`)
|
||||
.set(as(ADMIN))
|
||||
.send({ action: 'agree', termsVersion: PLACE_CONTRIB_TERMS_VERSION + 1, fields: FIELDS });
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body).toEqual({
|
||||
error: 'The contribution terms changed',
|
||||
reason: 'terms_outdated',
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
});
|
||||
});
|
||||
|
||||
it('PCE2E-013: the pipe refuses a body outside the contract', async () => {
|
||||
for (const body of [
|
||||
{ action: 'maybe' },
|
||||
{ action: 'agree', fields: FIELDS },
|
||||
{ action: 'agree', termsVersion: 1, fields: { website: true } },
|
||||
{ action: 'fields', fields: FIELDS, withdraw: 'yes' },
|
||||
]) {
|
||||
const res = await request(server).put(`${BASE}/decision`).set(as(ADMIN)).send(body);
|
||||
expect(res.status, JSON.stringify(body)).toBe(400);
|
||||
}
|
||||
});
|
||||
|
||||
it('PCE2E-014: "Not now" answers when the prompt comes back for this admin', async () => {
|
||||
const res = await request(server).put(`${BASE}/decision`).set(as(ADMIN)).send({ action: 'snooze' });
|
||||
expect(res.status).toBe(200);
|
||||
expect(Date.parse(res.body.snoozedUntil) - Date.now()).toBeGreaterThan(13 * 24 * 3_600_000);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the log', () => {
|
||||
it('PCE2E-020: pages newest first and filters by result and field', async () => {
|
||||
await insertRows(orm, PlaceContribLog, [
|
||||
{
|
||||
day: '2026-10-29',
|
||||
contrib_key: 'osm:node/1',
|
||||
place_name: 'A',
|
||||
field: 'website',
|
||||
result: 'accepted',
|
||||
reason: 'published',
|
||||
},
|
||||
{
|
||||
day: '2026-10-30',
|
||||
contrib_key: 'osm:node/2',
|
||||
place_name: 'B',
|
||||
field: 'phone',
|
||||
result: 'withheld',
|
||||
reason: 'unchanged',
|
||||
},
|
||||
{
|
||||
day: '2026-10-30',
|
||||
contrib_key: 'osm:node/3',
|
||||
place_name: 'C',
|
||||
field: 'website',
|
||||
result: 'rejected',
|
||||
reason: 'key',
|
||||
},
|
||||
]);
|
||||
const page = await request(server).get(`${BASE}/log?page=1&perPage=2`).set(as(ADMIN));
|
||||
expect(page.status).toBe(200);
|
||||
expect(page.body).toMatchObject({ total: 3, page: 1, perPage: 2 });
|
||||
expect(page.body.entries.map((entry: { placeName: string }) => entry.placeName)).toEqual(['C', 'B']);
|
||||
const filtered = await request(server).get(`${BASE}/log?field=website&result=accepted`).set(as(ADMIN));
|
||||
expect(filtered.body.entries).toEqual([
|
||||
{
|
||||
id: expect.any(Number),
|
||||
day: '2026-10-29',
|
||||
key: 'osm:node/1',
|
||||
placeName: 'A',
|
||||
field: 'website',
|
||||
valueSummary: null,
|
||||
result: 'accepted',
|
||||
reason: 'published',
|
||||
},
|
||||
]);
|
||||
expect((await request(server).get(`${BASE}/log?result=sent`).set(as(ADMIN))).status).toBe(400);
|
||||
});
|
||||
});
|
||||
|
||||
describe('withdrawing everything', () => {
|
||||
it('PCE2E-030: needs the confirmation', async () => {
|
||||
expect((await request(server).post(`${BASE}/withdraw`).set(as(ADMIN)).send({})).status).toBe(400);
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('PCE2E-031: asks the service with the installation key and answers what it took back', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response(JSON.stringify({ ok: true, withdrawn: { website: 2, image: 0 } }), {
|
||||
status: 200,
|
||||
headers: { 'content-type': 'application/json' },
|
||||
}),
|
||||
);
|
||||
const res = await request(server).post(`${BASE}/withdraw`).set(as(ADMIN)).send({ confirm: true });
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body).toEqual({ withdrawn: { website: 2, image: 0 }, cleared: 0 });
|
||||
const [url, init] = fetchMock.mock.calls[0] as [URL, RequestInit & { headers: Record<string, string> }];
|
||||
expect(String(url)).toBe('https://places.liketrek.com/v1/contrib/install');
|
||||
expect(init.method).toBe('DELETE');
|
||||
expect(init.headers.Authorization).toBe(`Bearer ${KEY}`);
|
||||
expect(await countRows(orm, PlaceContribLog, { result: 'retracted' })).toBe(1);
|
||||
expect(await countRows(orm, AuditLog, { action: 'admin.places_contribute_withdraw' })).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('PCE2E-032: a withdrawal the service does not confirm is a 502', async () => {
|
||||
fetchMock.mockResolvedValue(new Response(JSON.stringify({ error: 'unavailable' }), { status: 500 }));
|
||||
const res = await request(server).post(`${BASE}/withdraw`).set(as(ADMIN)).send({ confirm: true });
|
||||
expect(res.status).toBe(502);
|
||||
expect(res.body).toEqual({ error: 'The TREK Places API did not confirm the withdrawal', reason: 'status_500' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Origin tracking through the real place routes: PlacesModule behind the real
|
||||
* JwtAuthGuard and Zod pipe on a migrated temp database. A create or update
|
||||
* records where each shareable field it changed came from, the way the
|
||||
* offline replay of the same request does, and a test instance queues nothing
|
||||
* for the TREK Places API.
|
||||
*
|
||||
* Replaced: the journey hooks and the realtime transport.
|
||||
*/
|
||||
import { PlaceContribOutbox } from '../../src/db/entities/PlaceContribOutbox.entity';
|
||||
import { PlaceDetailsCache } from '../../src/db/entities/PlaceDetailsCache.entity';
|
||||
import { PlaceFieldOrigin } from '../../src/db/entities/PlaceFieldOrigin.entity';
|
||||
import { Trips } from '../../src/db/entities/Trips.entity';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { valueHash } from '../../src/nest/common/value-hash';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
|
||||
import { PlacesModule } from '../../src/nest/places/places.module';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { countRows, deleteRows, findRows, insertRow } from '../helpers/factories/rows';
|
||||
import { makeUser } from '../helpers/factories/users';
|
||||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const GERS = 'gers:ceba0e62-172b-4343-bb3b-78b915a18383';
|
||||
const journey = { onPlaceCreated: async () => undefined, onPlaceUpdated: async () => undefined };
|
||||
|
||||
let orm: TestOrm;
|
||||
let app: Awaited<ReturnType<typeof build>>;
|
||||
let server: Server;
|
||||
|
||||
async function build() {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), RealtimeModule, PlacesModule],
|
||||
})
|
||||
.overrideProvider(RealtimeService)
|
||||
.useValue(new FakeRealtimeService())
|
||||
.overrideProvider(JourneyDomainService)
|
||||
.useValue(journey)
|
||||
.compile();
|
||||
const nest = moduleRef.createNestApplication();
|
||||
nest.use(cookieParser());
|
||||
nest.useGlobalFilters(new TrekExceptionFilter());
|
||||
nest.useGlobalPipes(new ZodValidationPipe());
|
||||
await nest.init();
|
||||
return nest;
|
||||
}
|
||||
|
||||
const as = () => ({ Cookie: sessionCookie(1) });
|
||||
|
||||
async function origins(placeId: number): Promise<Record<string, string>> {
|
||||
const rows = await findRows(orm, PlaceFieldOrigin, { place: placeId });
|
||||
return Object.fromEntries(rows.map((row) => [row.field, row.origin]));
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
orm = await createTestOrm(db);
|
||||
await makeUser(orm, { id: 1, username: 'e2e-user', email: 'e2e@example.test' });
|
||||
app = await build();
|
||||
server = app.getHttpServer();
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
await deleteRows(orm, Trips, { id: 5 });
|
||||
await insertRow(orm, Trips, { id: 5, title: 'Trip', user: 1 });
|
||||
await deleteRows(orm, PlaceDetailsCache);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
});
|
||||
|
||||
describe('origin tracking on the place routes', () => {
|
||||
it('POE2E-001: a create records the origins the client reported, and unknown where it reported none', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/trips/5/places')
|
||||
.set(as())
|
||||
.send({
|
||||
name: 'Café Luna',
|
||||
osm_id: GERS,
|
||||
website: 'https://cafe-luna.de',
|
||||
phone: '+49 381 1',
|
||||
description: 'Coffee by the sea.',
|
||||
fieldOrigins: { website: 'user', phone: 'trek' },
|
||||
});
|
||||
expect(res.status).toBe(201);
|
||||
expect(res.body.place).not.toHaveProperty('fieldOrigins');
|
||||
expect(await origins(res.body.place.id)).toEqual({ website: 'user', phone: 'trek', description: 'unknown' });
|
||||
const [website] = await findRows(orm, PlaceFieldOrigin, { place: res.body.place.id, field: 'website' });
|
||||
expect(website?.value_hash).toBe(valueHash('https://cafe-luna.de'));
|
||||
// Not eligible under NODE_ENV=test: nothing waits to be sent.
|
||||
expect(await countRows(orm, PlaceContribOutbox)).toBe(0);
|
||||
});
|
||||
|
||||
it('POE2E-002: an update records only the field it changed', async () => {
|
||||
const created = await request(server)
|
||||
.post('/api/trips/5/places')
|
||||
.set(as())
|
||||
.send({ name: 'Café Luna', website: 'https://cafe-luna.de', fieldOrigins: { website: 'user' } });
|
||||
const id = created.body.place.id as number;
|
||||
const res = await request(server)
|
||||
.put(`/api/trips/5/places/${id}`)
|
||||
.set(as())
|
||||
.send({
|
||||
name: 'Café Luna',
|
||||
website: 'https://cafe-luna.de',
|
||||
email: 'info@cafe-luna.de',
|
||||
fieldOrigins: { email: 'user' },
|
||||
});
|
||||
expect(res.status).toBe(200);
|
||||
expect(await origins(id)).toEqual({ website: 'user', email: 'user' });
|
||||
const cleared = await request(server).put(`/api/trips/5/places/${id}`).set(as()).send({ email: '' });
|
||||
expect(cleared.status).toBe(200);
|
||||
expect(await origins(id)).toEqual({ website: 'user' });
|
||||
});
|
||||
|
||||
it('POE2E-003: a value claimed as typed that a provider handed out for the place is the provider', async () => {
|
||||
await insertRow(orm, PlaceDetailsCache, {
|
||||
place_id: GERS,
|
||||
lang: 'en',
|
||||
expanded: 0,
|
||||
payload_json: JSON.stringify({ website: 'https://cafe-luna.de', phone: '+49 381 1' }),
|
||||
fetched_at: Date.now(),
|
||||
});
|
||||
const res = await request(server)
|
||||
.post('/api/trips/5/places')
|
||||
.set(as())
|
||||
.send({ name: 'Café Luna', osm_id: GERS, phone: '+49 381 1', fieldOrigins: { phone: 'user' } });
|
||||
expect(await origins(res.body.place.id)).toEqual({ phone: 'trek' });
|
||||
});
|
||||
|
||||
it('POE2E-004: the pipe refuses an origin only the server may decide', async () => {
|
||||
const res = await request(server)
|
||||
.post('/api/trips/5/places')
|
||||
.set(as())
|
||||
.send({ name: 'Café Luna', website: 'https://cafe-luna.de', fieldOrigins: { website: 'agent' } });
|
||||
expect(res.status).toBe(400);
|
||||
});
|
||||
});
|
||||
@@ -60,6 +60,7 @@ import { PackingService } from '../../src/nest/packing/packing.service';
|
||||
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
|
||||
import { TrekPhotoRegistrationService } from '../../src/nest/photos/trek-photo-registration.service';
|
||||
import { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-cache.service';
|
||||
import type { PlaceOriginsService } from '../../src/nest/places/place-origins.service';
|
||||
import { PlacesRpc } from '../../src/nest/places/places.rpc';
|
||||
import { PlacesService } from '../../src/nest/places/places.service';
|
||||
import { PluginRpcHostFactory } from '../../src/nest/plugins/host/plugin-rpc-host.factory';
|
||||
@@ -185,6 +186,19 @@ import type { ModuleRef } from '@nestjs/core';
|
||||
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
/**
|
||||
* The places surface records the origin of what a plugin writes; these
|
||||
* runtime tests are about the RPC wiring, so the recording is a no-op here
|
||||
* (its own suite is place-origins.service.test.ts).
|
||||
*/
|
||||
function placeOriginsStub(): PlaceOriginsService {
|
||||
return {
|
||||
valuesBefore: async () => null,
|
||||
record: async () => undefined,
|
||||
recordImported: async () => undefined,
|
||||
} as unknown as PlaceOriginsService;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand-wired counterpart of the PluginsModule DI graph for no-Nest tests
|
||||
* (same pattern as mcp-test-controllers.ts): real domain services over the
|
||||
@@ -562,7 +576,7 @@ export async function createPluginRpcHostParts(
|
||||
new DayNotesRpc(dayNotes, realtime, guards),
|
||||
new PackingRpc(packing, realtime, guards),
|
||||
new FilesRpc(files, realtime, usersRepo, guards, generalStorage),
|
||||
new PlacesRpc(places, journey, realtime, guards),
|
||||
new PlacesRpc(places, journey, realtime, guards, placeOriginsStub()),
|
||||
new DaysRpc(
|
||||
days,
|
||||
realtime,
|
||||
|
||||
@@ -68,7 +68,7 @@ export function allRpcControllers(): object[] {
|
||||
new DayNotesRpc(anyService(), anyService(), anyService()),
|
||||
new PackingRpc(anyService(), anyService(), anyService()),
|
||||
new FilesRpc(anyService(), anyService(), anyService(), anyService(), anyService()),
|
||||
new PlacesRpc(anyService(), anyService(), anyService(), anyService()),
|
||||
new PlacesRpc(anyService(), anyService(), anyService(), anyService(), anyService()),
|
||||
new DaysRpc(anyService(), anyService(), anyService(), anyService()),
|
||||
new ItineraryRpc(anyService(), anyService(), anyService()),
|
||||
new TripsRpc(
|
||||
|
||||
@@ -438,6 +438,14 @@ describe('deriveMaps', () => {
|
||||
}
|
||||
});
|
||||
|
||||
it('TREK_PLACES_CONTRIBUTE leaves the choice to an admin unless it says off, and fails closed on anything else', () => {
|
||||
expect(deriveMaps({} as never).trekPlacesContribute).toBe('admin');
|
||||
expect(deriveMaps({ TREK_PLACES_CONTRIBUTE: ' Admin ' } as never).trekPlacesContribute).toBe('admin');
|
||||
for (const value of ['off', 'OFF', 'false', 'yes']) {
|
||||
expect(deriveMaps({ TREK_PLACES_CONTRIBUTE: value } as never).trekPlacesContribute, value).toBe('off');
|
||||
}
|
||||
});
|
||||
|
||||
it('TREK_PLACES_ENABLED fails open when unset, blank or outside the family', () => {
|
||||
// A typo must not silently drop a whole install back to Nominatim, whose
|
||||
// usage policy forbids what TREK was doing with it. Outside the family the
|
||||
|
||||
@@ -99,6 +99,7 @@ const UNNUMBERED = [
|
||||
'Migration20200101046290_a_removed_member_cannot_rejoin_by_invite_link',
|
||||
'Migration20200101046300_an_attached_file_stays_with_its_conversation',
|
||||
'Migration20200101046310_an_admin_can_run_a_plugin_outside_its_trek_range',
|
||||
'Migration20200101046320_a_place_knows_where_its_details_came_from',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* A place picture as it is sent: at most 2048 px on its long edge, a JPEG
|
||||
* without the camera's metadata, at most a megabyte, or nothing.
|
||||
*/
|
||||
import { contribJpeg } from '../../../../src/nest/place-contrib/place-contrib-image';
|
||||
import { IMAGE_MAX_BYTES, IMAGE_MAX_EDGE } from '../../../../src/nest/place-contrib/place-contrib.constants';
|
||||
import { jpegWithExif } from '../../../helpers/exif-jpeg';
|
||||
|
||||
import { Jimp } from 'jimp';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
async function picture(
|
||||
width: number,
|
||||
height: number,
|
||||
mime: 'image/jpeg' | 'image/png' = 'image/jpeg',
|
||||
): Promise<Buffer> {
|
||||
return Buffer.from(await new Jimp({ width, height, color: 0x336699ff }).getBuffer(mime));
|
||||
}
|
||||
|
||||
describe('contribJpeg', () => {
|
||||
it('PCI-001: shrinks a large picture to the long edge and keeps its proportions', async () => {
|
||||
const out = await contribJpeg(await picture(4000, 1000));
|
||||
expect(out).not.toBeNull();
|
||||
const decoded = await Jimp.read(out ?? Buffer.alloc(0));
|
||||
expect(decoded.width).toBe(IMAGE_MAX_EDGE);
|
||||
expect(decoded.height).toBe(512);
|
||||
expect(out?.length).toBeLessThanOrEqual(IMAGE_MAX_BYTES);
|
||||
});
|
||||
|
||||
it('PCI-002: a portrait is held by its height, a small picture keeps its size, a PNG becomes a JPEG', async () => {
|
||||
const tall = await Jimp.read((await contribJpeg(await picture(500, 3000))) ?? Buffer.alloc(0));
|
||||
expect(tall.height).toBe(IMAGE_MAX_EDGE);
|
||||
const small = await contribJpeg(await picture(64, 48, 'image/png'));
|
||||
expect(small?.subarray(0, 2)).toEqual(Buffer.from([0xff, 0xd8]));
|
||||
const decoded = await Jimp.read(small ?? Buffer.alloc(0));
|
||||
expect([decoded.width, decoded.height]).toEqual([64, 48]);
|
||||
});
|
||||
|
||||
it('PCI-003: the camera metadata does not survive', async () => {
|
||||
const withExif = jpegWithExif({ DateTimeOriginal: '2026:05:30 15:52:19', gps: { lat: 54.08, lng: 12.13 } });
|
||||
expect(withExif.includes(Buffer.from('Exif'))).toBe(true);
|
||||
const out = await contribJpeg(withExif);
|
||||
expect(out).not.toBeNull();
|
||||
expect(out?.includes(Buffer.from('Exif'))).toBe(false);
|
||||
});
|
||||
|
||||
it('PCI-004: what cannot be read is not sent', async () => {
|
||||
expect(await contribJpeg(Buffer.from('not a picture'))).toBeNull();
|
||||
const webp = Buffer.concat([Buffer.from('RIFF'), Buffer.alloc(4), Buffer.from('WEBPVP8 '), Buffer.alloc(32)]);
|
||||
expect(await contribJpeg(webp)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,429 @@
|
||||
/**
|
||||
* PlaceContribSender over the real tables on a migrated test db, with the TREK
|
||||
* Places API stubbed: what a run sends, what it keeps home, and what each kind
|
||||
* of answer does to the queue, the log and the pause.
|
||||
*
|
||||
* Replaced: the API client, the storage the pictures are read from, and the
|
||||
* deployment (a production instance at the public index).
|
||||
*/
|
||||
import type { AppEnv } from '../../../../src/app-config';
|
||||
import { PlaceContribLog } from '../../../../src/db/entities/PlaceContribLog.entity';
|
||||
import { PlaceContribOutbox } from '../../../../src/db/entities/PlaceContribOutbox.entity';
|
||||
import { PlaceFieldOrigin } from '../../../../src/db/entities/PlaceFieldOrigin.entity';
|
||||
import { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
|
||||
import { servicesConfig } from '../../../../src/nest/app-config/tokens';
|
||||
import { valueHash } from '../../../../src/nest/common/value-hash';
|
||||
import { PlaceContribSender } from '../../../../src/nest/place-contrib/place-contrib-sender.service';
|
||||
import { PlaceContribSettings } from '../../../../src/nest/place-contrib/place-contrib-settings';
|
||||
import { PlaceContribClient, type ContribAnswer } from '../../../../src/nest/place-contrib/place-contrib.client';
|
||||
import { MAX_ATTEMPTS, PLACES_PER_RUN } from '../../../../src/nest/place-contrib/place-contrib.constants';
|
||||
import { PlaceContribModule } from '../../../../src/nest/place-contrib/place-contrib.module';
|
||||
import { PlaceContribService } from '../../../../src/nest/place-contrib/place-contrib.service';
|
||||
import { StorageService } from '../../../../src/nest/storage/storage.service';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makePlace } from '../../../helpers/factories/places';
|
||||
import { countRows, findRow, findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
|
||||
import { readAppSetting } from '../../../helpers/factories/settings';
|
||||
import { makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import {
|
||||
PLACE_CONTRIB_TERMS_VERSION,
|
||||
placeContribCidSchema,
|
||||
type PlaceContribImageAnswer,
|
||||
type PlaceContribPlaceAnswer,
|
||||
type PlaceContribPlaceBody,
|
||||
} from '@trek/shared';
|
||||
|
||||
import { Jimp } from 'jimp';
|
||||
import { Readable } from 'node:stream';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
class ProductionEnv extends RuntimeEnvService {
|
||||
override env(): AppEnv {
|
||||
const env = super.env();
|
||||
return { ...env, maps: { ...env.maps, trekPlacesEnabled: true, trekPlacesUrl: undefined } };
|
||||
}
|
||||
|
||||
override isProduction(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
override isDemoMode(): boolean {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
type PlaceAnswer = ContribAnswer<PlaceContribPlaceAnswer>;
|
||||
type ImageAnswer = ContribAnswer<PlaceContribImageAnswer>;
|
||||
|
||||
const client = {
|
||||
hasKey: vi.fn(() => true),
|
||||
keyFingerprint: vi.fn(() => 'fp-1'),
|
||||
servedPlace: vi.fn(async (): Promise<unknown> => null),
|
||||
postPlace: vi.fn(async (_body: PlaceContribPlaceBody): Promise<PlaceAnswer> => accepted({})),
|
||||
postImage: vi.fn(async (): Promise<ImageAnswer> => ({
|
||||
kind: 'ok',
|
||||
body: { ok: true, result: { result: 'review' } },
|
||||
})),
|
||||
withdraw: vi.fn(),
|
||||
};
|
||||
const storage = { stat: vi.fn(), getStream: vi.fn() };
|
||||
|
||||
const GERS = 'gers:ceba0e62-172b-4343-bb3b-78b915a18383';
|
||||
const NOW = new Date('2026-10-30T12:00:00Z');
|
||||
const DUE = '2026-10-30 11:00:00';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
let jpeg: Buffer;
|
||||
|
||||
beforeAll(async () => {
|
||||
jpeg = Buffer.from(await new Jimp({ width: 40, height: 30, color: 0xff0000ff }).getBuffer('image/jpeg'));
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [PlaceContribModule],
|
||||
overrides: [
|
||||
{ provide: RuntimeEnvService, useValue: new ProductionEnv() },
|
||||
{
|
||||
provide: servicesConfig.KEY,
|
||||
useValue: { mode: 'auto', key: null, hosts: ['places.liketrek.com'], photonUrl: '', valhallaUrl: '' },
|
||||
},
|
||||
{ provide: PlaceContribClient, useValue: client },
|
||||
{ provide: StorageService, useValue: storage },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(async () => {
|
||||
resetTestDb(db);
|
||||
vi.clearAllMocks();
|
||||
client.hasKey.mockReturnValue(true);
|
||||
client.servedPlace.mockResolvedValue(null);
|
||||
client.postPlace.mockImplementation(async (body) => accepted(resultsFor(body, 'published')));
|
||||
storage.stat.mockResolvedValue({ key: 'k', size: jpeg.length, mtimeMs: 0 });
|
||||
storage.getStream.mockImplementation(async () => ({ stream: Readable.from([jpeg]), stat: {} }));
|
||||
await t
|
||||
.get(PlaceContribService)
|
||||
.decide(1, { action: 'agree', termsVersion: PLACE_CONTRIB_TERMS_VERSION, fields: allFields() }, NOW);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const sender = () => t.get(PlaceContribSender);
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
function allFields() {
|
||||
return { website: true, phone: true, email: true, opening_hours: true, description: true, image: true };
|
||||
}
|
||||
|
||||
function accepted(results: PlaceContribPlaceAnswer['results'], duplicate = false): PlaceAnswer {
|
||||
return { kind: 'ok', body: { ok: true, cid: 'c', duplicate, key: GERS, results } };
|
||||
}
|
||||
|
||||
function resultsFor(body: PlaceContribPlaceBody, result: 'published' | 'review'): PlaceContribPlaceAnswer['results'] {
|
||||
return Object.fromEntries(Object.keys(body.fields).map((field) => [field, { result }]));
|
||||
}
|
||||
|
||||
/**
|
||||
* A place holding the user's values, each with the origin row that vouches
|
||||
* for it and a due entry in the queue.
|
||||
*/
|
||||
async function seed(
|
||||
values: Record<string, string>,
|
||||
opts: { key?: string; queued?: Record<string, string>; created?: string; attempts?: number } = {},
|
||||
): Promise<{ placeId: number }> {
|
||||
const { user } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
const columns = Object.fromEntries(
|
||||
Object.entries(values).map(([field, value]) => [field === 'image' ? 'image_url' : field, value]),
|
||||
);
|
||||
const place = await makePlace(orm(), trip.id, { osm_id: GERS, name: 'Café Luna', ...columns });
|
||||
for (const [field, value] of Object.entries(values)) {
|
||||
await insertRow(orm(), PlaceFieldOrigin, { place: place.id, field, origin: 'user', value_hash: valueHash(value) });
|
||||
await insertRow(orm(), PlaceContribOutbox, {
|
||||
contrib_key: opts.key ?? GERS,
|
||||
field,
|
||||
value: opts.queued?.[field] ?? value,
|
||||
place: place.id,
|
||||
place_name: 'Café Luna',
|
||||
lat: 54.08,
|
||||
lng: 12.13,
|
||||
country: 'DE',
|
||||
cid: `cid-${field}-0001`,
|
||||
attempts: opts.attempts ?? 0,
|
||||
eligible_at: DUE,
|
||||
next_attempt_at: DUE,
|
||||
...(opts.created ? { created_at: opts.created } : {}),
|
||||
});
|
||||
}
|
||||
return { placeId: place.id };
|
||||
}
|
||||
|
||||
async function logLines() {
|
||||
return (await findRows(orm(), PlaceContribLog, {})).map(({ field, result, reason }) => ({ field, result, reason }));
|
||||
}
|
||||
|
||||
describe('when nothing may go', () => {
|
||||
it('PCSD-001: without an agreement in force the queue is left alone', async () => {
|
||||
await t.get(PlaceContribService).decide(1, { action: 'off' }, NOW);
|
||||
await seed({ website: 'https://cafe-luna.de' });
|
||||
expect(await sender().run(NOW)).toEqual({ skipped: 'inactive', places: 0, expired: 0 });
|
||||
expect(client.postPlace).not.toHaveBeenCalled();
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(1);
|
||||
});
|
||||
|
||||
it('PCSD-002: a pause holds the run', async () => {
|
||||
await seed({ website: 'https://cafe-luna.de' });
|
||||
await t.get(PlaceContribSettings).pauseFor('key_invalid', null);
|
||||
expect((await sender().run(NOW)).skipped).toBe('paused');
|
||||
expect(client.postPlace).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe('a place request', () => {
|
||||
it('PCSD-010: sends the due fields of a place in one request and logs what the service made of them', async () => {
|
||||
const hours = JSON.stringify([
|
||||
{ closed: false, open: '09:00', close: '18:00' },
|
||||
{ closed: false, open: '09:00', close: '18:00' },
|
||||
{ closed: false },
|
||||
{ closed: false },
|
||||
{ closed: false },
|
||||
{ closed: false },
|
||||
{ closed: true },
|
||||
]);
|
||||
await seed(
|
||||
{ website: 'https://cafe-luna.de', opening_hours: hours },
|
||||
{ queued: { opening_hours: 'Mo-Tu 09:00-18:00; Su off' } },
|
||||
);
|
||||
client.servedPlace.mockResolvedValue({
|
||||
website: 'https://old-luna.de',
|
||||
phone: null,
|
||||
email: null,
|
||||
opening_hours: null,
|
||||
description: null,
|
||||
});
|
||||
client.postPlace.mockResolvedValue(
|
||||
accepted({ website: { result: 'review', reason: null }, opening_hours: { result: 'published' } }),
|
||||
);
|
||||
|
||||
expect(await sender().run(NOW)).toEqual({ skipped: null, places: 1, expired: 0 });
|
||||
|
||||
expect(client.servedPlace).toHaveBeenCalledWith('ceba0e62-172b-4343-bb3b-78b915a18383');
|
||||
const body = client.postPlace.mock.calls[0]?.[0];
|
||||
expect(body).toMatchObject({
|
||||
v: 1,
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
key: GERS,
|
||||
fields: {
|
||||
website: { value: 'https://cafe-luna.de', baseHash: expect.stringMatching(/^[0-9a-f]{16}$/) },
|
||||
opening_hours: { value: 'Mo-Tu 09:00-18:00; Su off', baseHash: null },
|
||||
},
|
||||
place: { name: 'Café Luna', lat: 54.08, lng: 12.13, country: 'DE' },
|
||||
});
|
||||
expect(placeContribCidSchema.safeParse(body?.cid).success).toBe(true);
|
||||
expect(await logLines()).toEqual([
|
||||
{ field: 'website', result: 'accepted', reason: 'review' },
|
||||
{ field: 'opening_hours', result: 'accepted', reason: 'published' },
|
||||
]);
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
});
|
||||
|
||||
it('PCSD-011: a value the index already serves is not sent', async () => {
|
||||
await seed({ website: 'https://cafe-luna.de' });
|
||||
client.servedPlace.mockResolvedValue({
|
||||
website: 'cafe-luna.de',
|
||||
phone: null,
|
||||
email: null,
|
||||
opening_hours: null,
|
||||
description: null,
|
||||
});
|
||||
await sender().run(NOW);
|
||||
expect(client.postPlace).not.toHaveBeenCalled();
|
||||
expect(await logLines()).toEqual([{ field: 'website', result: 'withheld', reason: 'unchanged' }]);
|
||||
});
|
||||
|
||||
it('PCSD-012: a value that is no longer the user one stays home', async () => {
|
||||
const { placeId } = await seed({ website: 'https://cafe-luna.de', phone: '+49 1', email: 'a@luna.de' });
|
||||
// The assistant took the phone over; the e-mail changed on a path that recorded nothing.
|
||||
await updateRows(orm(), PlaceFieldOrigin, { place: placeId, field: 'phone' }, { origin: 'agent' });
|
||||
await updateRows(
|
||||
orm(),
|
||||
PlaceFieldOrigin,
|
||||
{ place: placeId, field: 'email' },
|
||||
{ value_hash: valueHash('b@luna.de') },
|
||||
);
|
||||
await sender().run(NOW);
|
||||
expect(client.postPlace.mock.calls[0]?.[0].fields).toEqual({
|
||||
website: { value: 'https://cafe-luna.de', baseHash: null },
|
||||
});
|
||||
expect(await logLines()).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ field: 'phone', result: 'withheld', reason: 'origin_changed' },
|
||||
{ field: 'email', result: 'withheld', reason: 'origin_stale' },
|
||||
{ field: 'website', result: 'accepted', reason: 'published' },
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
it('PCSD-013: a duplicate answer without a result is logged as one', async () => {
|
||||
await seed({ website: 'https://cafe-luna.de' });
|
||||
client.postPlace.mockResolvedValue(accepted({}, true));
|
||||
await sender().run(NOW);
|
||||
expect(await logLines()).toEqual([{ field: 'website', result: 'duplicate', reason: 'no_result' }]);
|
||||
});
|
||||
|
||||
it('PCSD-014: at most PLACES_PER_RUN places go in one run', async () => {
|
||||
for (let i = 0; i < PLACES_PER_RUN + 2; i += 1) {
|
||||
await seed({ website: `https://cafe-${i}.de` }, { key: `osm:node/${i + 1}` });
|
||||
}
|
||||
expect((await sender().run(NOW)).places).toBe(PLACES_PER_RUN);
|
||||
expect(client.postPlace).toHaveBeenCalledTimes(PLACES_PER_RUN);
|
||||
expect(client.servedPlace).not.toHaveBeenCalled();
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('refusals and failures', () => {
|
||||
it('PCSD-020: a refused key pauses sending and stops the run, counting no attempt', async () => {
|
||||
await seed({ website: 'https://a.de' }, { key: 'osm:node/1' });
|
||||
await seed({ website: 'https://b.de' }, { key: 'osm:node/2' });
|
||||
client.postPlace.mockResolvedValue({ kind: 'refused', status: 401, error: 'key_invalid', retryAfterMs: null });
|
||||
await sender().run(NOW);
|
||||
expect(client.postPlace).toHaveBeenCalledTimes(1);
|
||||
expect(JSON.parse((await readAppSetting(orm(), 'places_contribute_pause')) ?? '{}')).toMatchObject({
|
||||
reason: 'key_invalid',
|
||||
key: 'fp-1',
|
||||
});
|
||||
const rows = await findRows(orm(), PlaceContribOutbox, {});
|
||||
expect(rows.map((row) => row.attempts)).toEqual([0, 0]);
|
||||
expect(rows[0]?.next_attempt_at).toBe('2026-10-30 12:30:00');
|
||||
});
|
||||
|
||||
it('PCSD-021: a service not taking contributions is a pause until its Retry-After', async () => {
|
||||
await seed({ website: 'https://a.de' });
|
||||
client.postPlace.mockResolvedValue({
|
||||
kind: 'refused',
|
||||
status: 503,
|
||||
error: 'not_accepting',
|
||||
retryAfterMs: 3_600_000,
|
||||
});
|
||||
await sender().run(NOW);
|
||||
expect(JSON.parse((await readAppSetting(orm(), 'places_contribute_pause')) ?? '{}')).toMatchObject({
|
||||
reason: 'not_accepting',
|
||||
until: '2026-10-30T13:00:00.000Z',
|
||||
});
|
||||
expect((await findRow(orm(), PlaceContribOutbox, {}))?.next_attempt_at).toBe('2026-10-30 13:00:00');
|
||||
});
|
||||
|
||||
it('PCSD-022: no answer is tried again after 10 minutes, and given up after MAX_ATTEMPTS', async () => {
|
||||
await seed({ website: 'https://a.de' }, { key: 'osm:node/1' });
|
||||
await seed({ website: 'https://b.de' }, { key: 'osm:node/2', attempts: MAX_ATTEMPTS - 1 });
|
||||
client.postPlace.mockResolvedValue({ kind: 'failed', reason: 'TimeoutError', retryAfterMs: null });
|
||||
await sender().run(NOW);
|
||||
const rows = await findRows(orm(), PlaceContribOutbox, {});
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({ contrib_key: 'osm:node/1', attempts: 1, next_attempt_at: '2026-10-30 12:10:00' });
|
||||
expect(await logLines()).toEqual([{ field: 'website', result: 'withheld', reason: 'gave_up' }]);
|
||||
});
|
||||
|
||||
it('PCSD-023: a rate limit waits as long as the service says and stops the run', async () => {
|
||||
await seed({ website: 'https://a.de' }, { key: 'osm:node/1' });
|
||||
await seed({ website: 'https://b.de' }, { key: 'osm:node/2' });
|
||||
client.postPlace.mockResolvedValue({
|
||||
kind: 'refused',
|
||||
status: 429,
|
||||
error: 'field_allowance',
|
||||
retryAfterMs: 120_000,
|
||||
});
|
||||
await sender().run(NOW);
|
||||
expect(client.postPlace).toHaveBeenCalledTimes(1);
|
||||
expect(await findRow(orm(), PlaceContribOutbox, { contrib_key: 'osm:node/1' })).toMatchObject({
|
||||
attempts: 1,
|
||||
next_attempt_at: '2026-10-30 12:02:00',
|
||||
});
|
||||
});
|
||||
|
||||
it('PCSD-024: a field the service does not take is final; the others go again at once', async () => {
|
||||
await seed({ website: 'https://a.de', email: 'info@a.de' });
|
||||
client.postPlace.mockResolvedValue({
|
||||
kind: 'refused',
|
||||
status: 422,
|
||||
error: 'field_not_accepted:email',
|
||||
retryAfterMs: null,
|
||||
});
|
||||
await sender().run(NOW);
|
||||
expect(await logLines()).toEqual([{ field: 'email', result: 'rejected', reason: 'field_not_accepted:email' }]);
|
||||
expect(await findRow(orm(), PlaceContribOutbox, {})).toMatchObject({
|
||||
field: 'website',
|
||||
attempts: 0,
|
||||
next_attempt_at: '2026-10-30 12:00:00',
|
||||
});
|
||||
});
|
||||
|
||||
it('PCSD-025: any other refusal with a reason is final for the whole request', async () => {
|
||||
await seed({ website: 'https://a.de', phone: '+49 1' });
|
||||
client.postPlace.mockResolvedValue({ kind: 'refused', status: 422, error: 'unknown_place', retryAfterMs: null });
|
||||
await sender().run(NOW);
|
||||
expect(await logLines()).toEqual([
|
||||
{ field: 'website', result: 'rejected', reason: 'unknown_place' },
|
||||
{ field: 'phone', result: 'rejected', reason: 'unknown_place' },
|
||||
]);
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
});
|
||||
|
||||
it('PCSD-026: a field over its allowance is tried again, the rest is final', async () => {
|
||||
await seed({ website: 'https://a.de', phone: '+49 1' });
|
||||
client.postPlace.mockResolvedValue(accepted({ website: { result: 'published' }, phone: { result: 'quota' } }));
|
||||
await sender().run(NOW);
|
||||
expect(await logLines()).toEqual([{ field: 'website', result: 'accepted', reason: 'published' }]);
|
||||
expect(await findRow(orm(), PlaceContribOutbox, {})).toMatchObject({ field: 'phone', attempts: 1 });
|
||||
});
|
||||
|
||||
it('PCSD-027: a value queued for over 30 days is given up on', async () => {
|
||||
await seed({ website: 'https://a.de' }, { created: '2026-09-01 00:00:00' });
|
||||
expect((await sender().run(NOW)).expired).toBe(1);
|
||||
expect(client.postPlace).not.toHaveBeenCalled();
|
||||
expect(await logLines()).toEqual([{ field: 'website', result: 'withheld', reason: 'expired' }]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('a picture', () => {
|
||||
it('PCSD-030: images switched off on the service keep the picture home, out of the retry loop', async () => {
|
||||
await seed({ image: '/uploads/places/luna.jpg' });
|
||||
client.postImage.mockResolvedValue({ kind: 'refused', status: 503, error: 'images_disabled', retryAfterMs: null });
|
||||
await sender().run(NOW);
|
||||
expect(client.postImage).toHaveBeenCalledWith(GERS, expect.any(String), expect.any(Buffer));
|
||||
expect(storage.getStream).toHaveBeenCalledWith('places', 'luna.jpg');
|
||||
expect(await logLines()).toEqual([{ field: 'image', result: 'withheld', reason: 'images_disabled' }]);
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
expect(await readAppSetting(orm(), 'places_contribute_pause')).toBeNull();
|
||||
});
|
||||
|
||||
it('PCSD-031: a picture the service takes for review is logged as accepted', async () => {
|
||||
await seed({ image: '/uploads/places/luna.jpg' });
|
||||
await sender().run(NOW);
|
||||
const sent = client.postImage.mock.calls[0] as unknown as [string, string, Buffer] | undefined;
|
||||
expect(sent?.[2].subarray(0, 2)).toEqual(Buffer.from([0xff, 0xd8]));
|
||||
expect(await logLines()).toEqual([{ field: 'image', result: 'accepted', reason: 'review' }]);
|
||||
});
|
||||
|
||||
it('PCSD-032: a picture that is gone or unreadable stays home', async () => {
|
||||
await seed({ image: '/uploads/places/gone.jpg' });
|
||||
storage.stat.mockResolvedValueOnce(null);
|
||||
await sender().run(NOW);
|
||||
await seed({ image: '/uploads/places/garbage.jpg' }, { key: 'osm:node/9' });
|
||||
storage.getStream.mockImplementationOnce(async () => ({ stream: Readable.from([Buffer.from('nope')]), stat: {} }));
|
||||
await sender().run(NOW);
|
||||
expect(client.postImage).not.toHaveBeenCalled();
|
||||
expect(await logLines()).toEqual([
|
||||
{ field: 'image', result: 'withheld', reason: 'image_missing' },
|
||||
{ field: 'image', result: 'withheld', reason: 'image_unreadable' },
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,159 @@
|
||||
/**
|
||||
* The client of the contribution routes, with fetch stubbed: every request
|
||||
* carries the installation key or does not go, every answer is read with a
|
||||
* cap and checked against the service's wire format, and a refusal comes back
|
||||
* with the service's reason code.
|
||||
*/
|
||||
import { PlaceContribClient } from '../../../../src/nest/place-contrib/place-contrib.client';
|
||||
import { ServiceIdentityPort } from '../../../../src/nest/service-identity/service-identity.interface';
|
||||
import type { PlaceContribPlaceBody } from '@trek/shared';
|
||||
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const fetchMock = vi.fn();
|
||||
const identity = {
|
||||
headersFor: vi.fn((): Record<string, string> => ({ 'User-Agent': 'TREK/test', Authorization: 'Bearer tk1.key' })),
|
||||
observe: vi.fn(),
|
||||
};
|
||||
const client = new PlaceContribClient(identity as unknown as ServiceIdentityPort);
|
||||
|
||||
const BODY: PlaceContribPlaceBody = {
|
||||
v: 1,
|
||||
termsVersion: 1,
|
||||
cid: 'abcdefgh-1234',
|
||||
key: 'osm:node/1',
|
||||
fields: { website: { value: 'https://a.de', baseHash: null } },
|
||||
place: { name: 'A', lat: 1, lng: 2, country: 'DE' },
|
||||
};
|
||||
|
||||
function json(status: number, body: unknown, headers: Record<string, string> = {}): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json', ...headers } });
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
fetchMock.mockReset();
|
||||
identity.observe.mockClear();
|
||||
identity.headersFor.mockImplementation(() => ({ 'User-Agent': 'TREK/test', Authorization: 'Bearer tk1.key' }));
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
describe('PlaceContribClient', () => {
|
||||
it('PCC-001: posts a place with the key, a deadline and JSON, and reads the answer', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
json(200, {
|
||||
ok: true,
|
||||
cid: BODY.cid,
|
||||
duplicate: false,
|
||||
key: BODY.key,
|
||||
community: { version: 2 },
|
||||
results: { website: { result: 'published', flags: [] } },
|
||||
}),
|
||||
);
|
||||
const answer = await client.postPlace(BODY);
|
||||
expect(answer).toMatchObject({ kind: 'ok', body: { results: { website: { result: 'published' } } } });
|
||||
const [url, init] = fetchMock.mock.calls[0] as [URL, RequestInit & { headers: Record<string, string> }];
|
||||
expect(String(url)).toBe('https://places.liketrek.com/v1/contrib/place');
|
||||
expect(init.method).toBe('POST');
|
||||
expect(init.signal).toBeInstanceOf(AbortSignal);
|
||||
expect(init.headers.Authorization).toBe('Bearer tk1.key');
|
||||
expect(init.headers['Content-Type']).toBe('application/json');
|
||||
expect(JSON.parse(String(init.body))).toEqual(BODY);
|
||||
expect(identity.observe).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('PCC-002: without a key nothing leaves', async () => {
|
||||
identity.headersFor.mockImplementation(() => ({ 'User-Agent': 'TREK/test' }));
|
||||
expect(client.hasKey()).toBe(false);
|
||||
expect(client.keyFingerprint()).toBeNull();
|
||||
expect(await client.postPlace(BODY)).toEqual({ kind: 'refused', status: 401, error: 'no_key', retryAfterMs: null });
|
||||
expect(fetchMock).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('PCC-003: the key has a stable fingerprint that is not the key', () => {
|
||||
expect(client.hasKey()).toBe(true);
|
||||
const fingerprint = client.keyFingerprint();
|
||||
expect(fingerprint).toMatch(/^[0-9a-f]{16}$/);
|
||||
expect(fingerprint).toBe(client.keyFingerprint());
|
||||
expect(fingerprint).not.toContain('tk1');
|
||||
});
|
||||
|
||||
it('PCC-004: a refusal carries the service reason and its Retry-After', async () => {
|
||||
fetchMock.mockResolvedValue(json(429, { error: 'field_allowance' }, { 'retry-after': '30' }));
|
||||
expect(await client.postPlace(BODY)).toEqual({
|
||||
kind: 'refused',
|
||||
status: 429,
|
||||
error: 'field_allowance',
|
||||
retryAfterMs: 30_000,
|
||||
});
|
||||
fetchMock.mockResolvedValue(json(503, { error: 'not_accepting' }));
|
||||
expect(await client.postPlace(BODY)).toMatchObject({ kind: 'refused', status: 503, error: 'not_accepting' });
|
||||
fetchMock.mockResolvedValue(new Response('nope', { status: 403 }));
|
||||
expect(await client.postPlace(BODY)).toMatchObject({ kind: 'refused', status: 403, error: 'status_403' });
|
||||
});
|
||||
|
||||
it('PCC-005: no answer, a server error, an oversized or an unexpected answer is a failure to try again', async () => {
|
||||
fetchMock.mockRejectedValue(Object.assign(new Error('timed out'), { name: 'TimeoutError' }));
|
||||
expect(await client.postPlace(BODY)).toEqual({ kind: 'failed', reason: 'TimeoutError', retryAfterMs: null });
|
||||
fetchMock.mockResolvedValue(json(502, { error: 'bad_gateway' }));
|
||||
expect(await client.postPlace(BODY)).toMatchObject({ kind: 'failed', reason: 'status_502' });
|
||||
fetchMock.mockResolvedValue(json(200, { ok: true, cid: 'x' }));
|
||||
expect(await client.postPlace(BODY)).toMatchObject({ kind: 'failed', reason: 'answer_unreadable' });
|
||||
fetchMock.mockResolvedValue(
|
||||
new Response('{}', { status: 200, headers: { 'content-length': String(1024 * 1024) } }),
|
||||
);
|
||||
expect(await client.postPlace(BODY)).toMatchObject({ kind: 'failed', reason: 'answer_too_large' });
|
||||
});
|
||||
|
||||
it('PCC-006: posts a picture as raw JPEG with its key and id in headers', async () => {
|
||||
fetchMock.mockResolvedValue(json(200, { ok: true, result: { result: 'review', image: null } }));
|
||||
const answer = await client.postImage('gers:abc', 'cid-12345678', Buffer.from([0xff, 0xd8, 0xff]));
|
||||
expect(answer).toMatchObject({ kind: 'ok', body: { result: { result: 'review' } } });
|
||||
const [url, init] = fetchMock.mock.calls[0] as [URL, RequestInit & { headers: Record<string, string> }];
|
||||
expect(String(url)).toBe('https://places.liketrek.com/v1/contrib/image');
|
||||
expect(init.headers).toMatchObject({
|
||||
'Content-Type': 'image/jpeg',
|
||||
'X-TREK-Contrib-Key': 'gers:abc',
|
||||
'X-TREK-Contrib-Cid': 'cid-12345678',
|
||||
});
|
||||
expect(init.body).toBeInstanceOf(Uint8Array);
|
||||
});
|
||||
|
||||
it('PCC-007: withdraws everything, or one field', async () => {
|
||||
fetchMock.mockResolvedValue(json(200, { ok: true, withdrawn: { website: 2 } }));
|
||||
expect(await client.withdraw()).toEqual({ kind: 'ok', body: { ok: true, withdrawn: { website: 2 } } });
|
||||
await client.withdraw({ field: 'phone' });
|
||||
const urls = fetchMock.mock.calls.map(([url]) => String(url));
|
||||
expect(urls).toEqual([
|
||||
'https://places.liketrek.com/v1/contrib/install',
|
||||
'https://places.liketrek.com/v1/contrib/install?field=phone',
|
||||
]);
|
||||
expect((fetchMock.mock.calls[0] as [URL, RequestInit])[1].method).toBe('DELETE');
|
||||
});
|
||||
|
||||
it('PCC-008: reads what the index serves for a place, and null when it cannot say', async () => {
|
||||
fetchMock.mockResolvedValue(
|
||||
json(200, {
|
||||
place: {
|
||||
gers: 'abc',
|
||||
contact: { website: 'https://a.de', phone: '+49 1', email: null },
|
||||
hours: { osm: 'Mo-Fr 09:00-17:00', source: 'website' },
|
||||
description: { text: 'Text', source: 'website' },
|
||||
},
|
||||
}),
|
||||
);
|
||||
expect(await client.servedPlace('abc')).toEqual({
|
||||
website: 'https://a.de',
|
||||
phone: '+49 1',
|
||||
email: null,
|
||||
opening_hours: 'Mo-Fr 09:00-17:00',
|
||||
description: 'Text',
|
||||
});
|
||||
expect(String(fetchMock.mock.calls[0]?.[0])).toBe('https://places.liketrek.com/v1/place/abc');
|
||||
fetchMock.mockResolvedValue(json(404, { error: 'not_found' }));
|
||||
expect(await client.servedPlace('missing')).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
/**
|
||||
* /api/admin/places-contribute over a stub service: what each handler hands
|
||||
* the service, what it answers, which audit row it writes, the guards and
|
||||
* contracts it declares, and that the Zod pipe holds the contracts the
|
||||
* handlers rely on.
|
||||
*/
|
||||
import type { AuditService } from '../../../../src/nest/audit/audit.service';
|
||||
import { AdminGuard } from '../../../../src/nest/auth-core/admin.guard';
|
||||
import { JwtAuthGuard } from '../../../../src/nest/auth-core/jwt-auth.guard';
|
||||
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
|
||||
import { PlaceContribController } from '../../../../src/nest/place-contrib/place-contrib.controller';
|
||||
import {
|
||||
PlaceContribDecisionDto,
|
||||
PlaceContribLogQueryDto,
|
||||
PlaceContribWithdrawDto,
|
||||
} from '../../../../src/nest/place-contrib/place-contrib.dto';
|
||||
import type { PlaceContribService } from '../../../../src/nest/place-contrib/place-contrib.service';
|
||||
import type { User } from '../../../../src/types';
|
||||
import { GUARDS_METADATA } from '@nestjs/common/constants';
|
||||
import {
|
||||
placeContribDecisionRequestSchema,
|
||||
placeContribLogQuerySchema,
|
||||
placeContribLogResponseSchema,
|
||||
placeContribStateSchema,
|
||||
placeContribWithdrawRequestSchema,
|
||||
placeContribWithdrawResponseSchema,
|
||||
} from '@trek/shared';
|
||||
|
||||
import type { Request } from 'express';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const STATE = { termsVersion: 1, active: false };
|
||||
const contrib = {
|
||||
state: vi.fn(async () => STATE),
|
||||
decide: vi.fn(async () => STATE),
|
||||
logPage: vi.fn(async () => ({ entries: [], total: 0, page: 2, perPage: 10 })),
|
||||
withdrawAll: vi.fn(async () => ({ withdrawn: { website: 1 }, cleared: 4 })),
|
||||
};
|
||||
const audit = { writeAudit: vi.fn(async () => undefined) };
|
||||
const controller = new PlaceContribController(
|
||||
contrib as unknown as PlaceContribService,
|
||||
audit as unknown as AuditService,
|
||||
);
|
||||
const admin = { id: 3, role: 'admin' } as User;
|
||||
const req = { ip: '203.0.113.9', socket: {} } as unknown as Request;
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('PlaceContribController', () => {
|
||||
it('PCCT-001: the class answers to admins only', () => {
|
||||
expect(Reflect.getMetadata(GUARDS_METADATA, PlaceContribController)).toEqual([JwtAuthGuard, AdminGuard]);
|
||||
});
|
||||
|
||||
it('PCCT-002: every handler declares the shared response contract it answers with', () => {
|
||||
const contract = (name: keyof PlaceContribController) =>
|
||||
Reflect.getMetadata(RESPONSE_CONTRACT_KEY, PlaceContribController.prototype[name]);
|
||||
expect(contract('state')).toBe(placeContribStateSchema);
|
||||
expect(contract('decide')).toBe(placeContribStateSchema);
|
||||
expect(contract('log')).toBe(placeContribLogResponseSchema);
|
||||
expect(contract('withdraw')).toBe(placeContribWithdrawResponseSchema);
|
||||
});
|
||||
|
||||
it('PCCT-003: the state is the calling admin own', async () => {
|
||||
expect(await controller.state(admin)).toBe(STATE);
|
||||
expect(contrib.state).toHaveBeenCalledWith(3);
|
||||
});
|
||||
|
||||
it('PCCT-004: a decision is handed on whole and audited with what it named', async () => {
|
||||
const body = { action: 'agree', termsVersion: 1, fields: { website: true } } as unknown as PlaceContribDecisionDto;
|
||||
expect(await controller.decide(admin, body, req)).toBe(STATE);
|
||||
expect(contrib.decide).toHaveBeenCalledWith(3, body);
|
||||
expect(audit.writeAudit).toHaveBeenCalledWith({
|
||||
userId: 3,
|
||||
action: 'admin.places_contribute_decision',
|
||||
details: { action: 'agree', termsVersion: 1, fields: { website: true } },
|
||||
ip: '203.0.113.9',
|
||||
});
|
||||
await controller.decide(admin, { action: 'off', withdraw: true } as PlaceContribDecisionDto, req);
|
||||
expect(audit.writeAudit).toHaveBeenLastCalledWith(
|
||||
expect.objectContaining({ details: { action: 'off', withdraw: true } }),
|
||||
);
|
||||
});
|
||||
|
||||
it('PCCT-005: a refused decision writes no audit row', async () => {
|
||||
contrib.decide.mockRejectedValueOnce(new Error('terms'));
|
||||
await expect(controller.decide(admin, { action: 'snooze' } as PlaceContribDecisionDto, req)).rejects.toThrow();
|
||||
expect(audit.writeAudit).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('PCCT-006: the log query goes to the service as parsed', async () => {
|
||||
const query = { page: 2, perPage: 10, result: 'withheld' } as PlaceContribLogQueryDto;
|
||||
expect(await controller.log(query)).toEqual({ entries: [], total: 0, page: 2, perPage: 10 });
|
||||
expect(contrib.logPage).toHaveBeenCalledWith(query);
|
||||
});
|
||||
|
||||
it('PCCT-007: withdrawing answers what the service did and is audited', async () => {
|
||||
expect(await controller.withdraw(admin, { confirm: true } as PlaceContribWithdrawDto, req)).toEqual({
|
||||
withdrawn: { website: 1 },
|
||||
cleared: 4,
|
||||
});
|
||||
expect(audit.writeAudit).toHaveBeenCalledWith({
|
||||
userId: 3,
|
||||
action: 'admin.places_contribute_withdraw',
|
||||
details: { cleared: 4 },
|
||||
ip: '203.0.113.9',
|
||||
});
|
||||
});
|
||||
|
||||
it('PCCT-008: the DTOs validate against the shared contracts', () => {
|
||||
expect(PlaceContribDecisionDto.schema).toBe(placeContribDecisionRequestSchema);
|
||||
expect(PlaceContribLogQueryDto.schema).toBe(placeContribLogQuerySchema);
|
||||
expect(PlaceContribWithdrawDto.schema).toBe(placeContribWithdrawRequestSchema);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,186 @@
|
||||
/**
|
||||
* The pure halves of the community enrichment: which places can be keyed, what
|
||||
* a field sends (or why it stays home), the OSM rule a week of hours becomes,
|
||||
* and the retry clock.
|
||||
*/
|
||||
import {
|
||||
MAX_RETRY_AFTER_MS,
|
||||
RETRY_DELAYS_MS,
|
||||
ELIGIBLE_DELAY_MAX_MS,
|
||||
ELIGIBLE_DELAY_MIN_MS,
|
||||
} from '../../../../src/nest/place-contrib/place-contrib.constants';
|
||||
import {
|
||||
baseHashOf,
|
||||
contribKeyOf,
|
||||
dayOf,
|
||||
eligibleDelayMs,
|
||||
gersOf,
|
||||
logResultOf,
|
||||
newEntryCid,
|
||||
osmHoursOf,
|
||||
payloadOf,
|
||||
requestCid,
|
||||
retryAfterMs,
|
||||
retryDelayMs,
|
||||
summaryOf,
|
||||
} from '../../../../src/nest/place-contrib/place-contrib.helpers';
|
||||
import { placeContribCidSchema, type PlaceOpeningHours } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const UUID = 'ceba0e62-172b-4343-bb3b-78b915a18383';
|
||||
const open = (from: string, to: string) => ({ closed: false, open: from, close: to });
|
||||
const closed = { closed: true };
|
||||
const unset = { closed: false };
|
||||
|
||||
describe('contribKeyOf', () => {
|
||||
it('PCH-001: keys an index place by its gers id and an OSM element by type and id', () => {
|
||||
expect(contribKeyOf(`gers:${UUID}`)).toBe(`gers:${UUID}`);
|
||||
expect(contribKeyOf(`gers:${UUID.toUpperCase()}`)).toBe(`gers:${UUID}`);
|
||||
expect(contribKeyOf('gers:08f2a1b3c4d5e6f7a8b9c0d1e2f3a4b5')).toBe('gers:08f2a1b3c4d5e6f7a8b9c0d1e2f3a4b5');
|
||||
expect(contribKeyOf('node:123')).toBe('osm:node/123');
|
||||
expect(contribKeyOf('way:45')).toBe('osm:way/45');
|
||||
expect(contribKeyOf('relation:6')).toBe('osm:relation/6');
|
||||
});
|
||||
|
||||
it('PCH-002: a free pin, a Google or Amap place, or a malformed id has no key', () => {
|
||||
for (const id of [
|
||||
null,
|
||||
undefined,
|
||||
'',
|
||||
'ChIJd8BlQ2BZwokRAFUEcm_qrcA',
|
||||
'amap:B000A83M61',
|
||||
'gers:abc-123',
|
||||
'node:x',
|
||||
]) {
|
||||
expect(contribKeyOf(id), String(id)).toBeNull();
|
||||
}
|
||||
});
|
||||
|
||||
it('PCH-003: reads the gers id back out of a key', () => {
|
||||
expect(gersOf(`gers:${UUID}`)).toBe(UUID);
|
||||
expect(gersOf('osm:node/1')).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('osmHoursOf', () => {
|
||||
it('PCH-010: folds equal neighbours into a range and names the closed days', () => {
|
||||
const week: PlaceOpeningHours = [
|
||||
open('09:00', '18:00'),
|
||||
open('09:00', '18:00'),
|
||||
open('09:00', '18:00'),
|
||||
open('09:00', '18:00'),
|
||||
open('09:00', '18:00'),
|
||||
open('10:00', '14:00'),
|
||||
closed,
|
||||
];
|
||||
expect(osmHoursOf(week)).toBe('Mo-Fr 09:00-18:00; Sa 10:00-14:00; Su off');
|
||||
});
|
||||
|
||||
it('PCH-011: leaves out the days nobody set instead of calling them closed', () => {
|
||||
const week: PlaceOpeningHours = [open('08:00', '12:00'), unset, unset, unset, unset, unset, unset];
|
||||
expect(osmHoursOf(week)).toBe('Mo 08:00-12:00');
|
||||
expect(osmHoursOf([unset, unset, unset, unset, unset, unset, unset])).toBeNull();
|
||||
});
|
||||
|
||||
it('PCH-012: an interval past midnight stays one interval', () => {
|
||||
const week: PlaceOpeningHours = [unset, unset, unset, unset, open('22:00', '02:00'), open('22:00', '02:00'), unset];
|
||||
expect(osmHoursOf(week)).toBe('Fr-Sa 22:00-02:00');
|
||||
});
|
||||
});
|
||||
|
||||
describe('payloadOf', () => {
|
||||
it('PCH-020: normalizes what the service reads', () => {
|
||||
expect(payloadOf('website', 'cafe-luna.de')).toEqual({ value: 'https://cafe-luna.de' });
|
||||
expect(payloadOf('email', ' Info@Cafe-Luna.DE ')).toEqual({ value: 'info@cafe-luna.de' });
|
||||
expect(payloadOf('phone', ' +49 381 1234 ')).toEqual({ value: '+49 381 1234' });
|
||||
expect(payloadOf('description', ' A small café. ')).toEqual({ value: 'A small café.' });
|
||||
expect(payloadOf('image', '/uploads/places/abc.jpg')).toEqual({ value: '/uploads/places/abc.jpg' });
|
||||
});
|
||||
|
||||
it('PCH-021: turns stored hours into the OSM rule', () => {
|
||||
const week = JSON.stringify([closed, closed, closed, closed, closed, open('10:00', '16:00'), closed]);
|
||||
expect(payloadOf('opening_hours', week)).toEqual({ value: 'Mo-Fr off; Sa 10:00-16:00; Su off' });
|
||||
});
|
||||
|
||||
it('PCH-022: keeps home what the service would refuse, saying why', () => {
|
||||
expect(payloadOf('website', ' ')).toEqual({ withheld: 'empty' });
|
||||
expect(payloadOf('website', 'not a site')).toEqual({ withheld: 'website_invalid' });
|
||||
expect(payloadOf('opening_hours', '{bad')).toEqual({ withheld: 'hours_unreadable' });
|
||||
const allClosed = JSON.stringify(Array.from({ length: 7 }, () => closed));
|
||||
expect(payloadOf('opening_hours', allClosed)).toEqual({ withheld: 'hours_all_closed' });
|
||||
const nothingSet = JSON.stringify(Array.from({ length: 7 }, () => unset));
|
||||
expect(payloadOf('opening_hours', nothingSet)).toEqual({ withheld: 'hours_empty' });
|
||||
expect(payloadOf('image', 'https://photos.example/a.jpg')).toEqual({ withheld: 'image_not_uploaded' });
|
||||
expect(payloadOf('image', '/api/maps/place-photo/x')).toEqual({ withheld: 'image_not_uploaded' });
|
||||
expect(payloadOf('description', 'x'.repeat(4001))).toEqual({ withheld: 'too_long' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('the log and the request ids', () => {
|
||||
it('PCH-030: a summary is one short line, and a picture is just a picture', () => {
|
||||
expect(summaryOf('description', 'Line one\n\nline two')).toBe('Line one line two');
|
||||
expect(summaryOf('description', 'x'.repeat(200))).toHaveLength(80);
|
||||
expect(summaryOf('image', '/uploads/places/a.jpg')).toBe('image');
|
||||
});
|
||||
|
||||
it('PCH-031: the base hash is a hex prefix of the served value, null for none', () => {
|
||||
expect(baseHashOf('https://cafe-luna.de/')).toMatch(/^[0-9a-f]{16}$/);
|
||||
expect(baseHashOf(' https://cafe-luna.de/ ')).toBe(baseHashOf('https://cafe-luna.de/'));
|
||||
expect(baseHashOf(null)).toBeNull();
|
||||
expect(baseHashOf(' ')).toBeNull();
|
||||
});
|
||||
|
||||
it('PCH-032: a request id is stable for the same values and fits the service pattern', () => {
|
||||
const a = newEntryCid();
|
||||
const b = newEntryCid();
|
||||
expect(a).not.toBe(b);
|
||||
expect(requestCid([a, b])).toBe(requestCid([b, a]));
|
||||
expect(requestCid([a])).not.toBe(requestCid([a, b]));
|
||||
expect(placeContribCidSchema.safeParse(requestCid([a, b])).success).toBe(true);
|
||||
});
|
||||
|
||||
it('PCH-033: maps what the service made of a field onto the log', () => {
|
||||
expect(logResultOf('published')).toBe('accepted');
|
||||
expect(logResultOf('review')).toBe('accepted');
|
||||
expect(logResultOf('checking')).toBe('accepted');
|
||||
expect(logResultOf('unchanged')).toBe('duplicate');
|
||||
expect(logResultOf('rejected')).toBe('rejected');
|
||||
});
|
||||
|
||||
it('PCH-034: the day is the UTC date', () => {
|
||||
expect(dayOf(new Date('2026-10-30T23:30:00Z'))).toBe('2026-10-30');
|
||||
});
|
||||
});
|
||||
|
||||
describe('the clock', () => {
|
||||
it('PCH-040: a place waits a few minutes, never hours', () => {
|
||||
for (let i = 0; i < 50; i += 1) {
|
||||
const delay = eligibleDelayMs();
|
||||
expect(delay).toBeGreaterThanOrEqual(ELIGIBLE_DELAY_MIN_MS);
|
||||
expect(delay).toBeLessThanOrEqual(ELIGIBLE_DELAY_MAX_MS);
|
||||
}
|
||||
});
|
||||
|
||||
it('PCH-041: retries wait 10 min, 30 min, 2 h, then 6 h', () => {
|
||||
expect([1, 2, 3, 4, 5, 8].map(retryDelayMs)).toEqual([
|
||||
RETRY_DELAYS_MS[0],
|
||||
RETRY_DELAYS_MS[1],
|
||||
RETRY_DELAYS_MS[2],
|
||||
RETRY_DELAYS_MS[3],
|
||||
RETRY_DELAYS_MS[3],
|
||||
RETRY_DELAYS_MS[3],
|
||||
]);
|
||||
expect(retryDelayMs(0)).toBe(RETRY_DELAYS_MS[0]);
|
||||
});
|
||||
|
||||
it('PCH-042: reads Retry-After as seconds or a date, capped, and ignores nonsense', () => {
|
||||
const now = Date.parse('2026-10-30T12:00:00Z');
|
||||
expect(retryAfterMs('120', now)).toBe(120_000);
|
||||
expect(retryAfterMs('Fri, 30 Oct 2026 12:05:00 GMT', now)).toBe(300_000);
|
||||
expect(retryAfterMs(String(10 * 24 * 3600), now)).toBe(MAX_RETRY_AFTER_MS);
|
||||
expect(retryAfterMs(null, now)).toBeNull();
|
||||
expect(retryAfterMs('soon', now)).toBeNull();
|
||||
expect(retryAfterMs('Fri, 30 Oct 2026 11:00:00 GMT', now)).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,77 @@
|
||||
/**
|
||||
* The two crons of the community enrichment: registration behind the test
|
||||
* gate, the log retention cut-off, and that a failing run or sweep stays
|
||||
* inside its tick.
|
||||
*/
|
||||
import type { PlaceContribLogRepository } from '../../../../src/db/repositories/PlaceContribLog.repository';
|
||||
import type { PlaceContribSender } from '../../../../src/nest/place-contrib/place-contrib-sender.service';
|
||||
import { PlaceContribJob } from '../../../../src/nest/place-contrib/place-contrib.job';
|
||||
import type { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const logMock = vi.hoisted(() => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
}));
|
||||
vi.mock('../../../../src/nest/audit/audit-log.logger', () => logMock);
|
||||
|
||||
function make(enabled = true) {
|
||||
const sender = { run: vi.fn(async () => ({ skipped: null, places: 0, expired: 0 })) };
|
||||
const log = { purgeBefore: vi.fn(async () => 0) };
|
||||
const registrar = { isEnabled: vi.fn(() => enabled), register: vi.fn(() => enabled) };
|
||||
const job = new PlaceContribJob(
|
||||
sender as unknown as PlaceContribSender,
|
||||
log as unknown as PlaceContribLogRepository,
|
||||
registrar as unknown as CronRegistrarService,
|
||||
);
|
||||
return { job, sender, log, registrar };
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('PlaceContribJob', () => {
|
||||
it('PCJ-001: registers the sender every two minutes and the retention at night', () => {
|
||||
const { job, registrar } = make();
|
||||
job.onApplicationBootstrap();
|
||||
expect(registrar.register).toHaveBeenCalledWith('place-contrib-send', '*/2 * * * *', expect.any(Function));
|
||||
expect(registrar.register).toHaveBeenCalledWith('place-contrib-log-retention', '50 3 * * *', expect.any(Function));
|
||||
});
|
||||
|
||||
it('PCJ-002: registers nothing under the test gate', () => {
|
||||
const { job, registrar } = make(false);
|
||||
job.onApplicationBootstrap();
|
||||
expect(registrar.register).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('PCJ-003: the registered ticks run the sender and the sweep', async () => {
|
||||
const { job, registrar, sender, log } = make();
|
||||
job.onApplicationBootstrap();
|
||||
const ticks = registrar.register.mock.calls.map((call) => (call as unknown[])[2] as () => Promise<void>);
|
||||
for (const tick of ticks) await tick();
|
||||
expect(sender.run).toHaveBeenCalledTimes(1);
|
||||
expect(log.purgeBefore).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('PCJ-004: keeps 90 days of log and says so only when it removed something', async () => {
|
||||
const { job, log } = make();
|
||||
await job.retain(new Date('2026-10-30T03:50:00Z'));
|
||||
expect(log.purgeBefore).toHaveBeenCalledWith('2026-08-01');
|
||||
expect(logMock.logInfo).not.toHaveBeenCalled();
|
||||
log.purgeBefore.mockResolvedValueOnce(4);
|
||||
await job.retain(new Date('2026-10-30T03:50:00Z'));
|
||||
expect(logMock.logInfo).toHaveBeenCalledWith(expect.stringContaining('4'));
|
||||
});
|
||||
|
||||
it('PCJ-005: a failing run or sweep is logged, never thrown into the scheduler', async () => {
|
||||
const { job, sender, log } = make();
|
||||
sender.run.mockRejectedValueOnce(new Error('database is locked'));
|
||||
log.purgeBefore.mockRejectedValueOnce(new Error('disk full'));
|
||||
await expect(job.send()).resolves.toBeUndefined();
|
||||
await expect(job.retain()).resolves.toBeUndefined();
|
||||
expect(logMock.logError).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,472 @@
|
||||
/**
|
||||
* PlaceContribService over the real tables on a migrated test db: when an
|
||||
* installation may send at all, what the admin's decisions store and do to the
|
||||
* queue, what the admin state says, which place writes are queued, and the
|
||||
* withdrawal.
|
||||
*
|
||||
* Replaced: the client of the TREK Places API (no request leaves), the
|
||||
* deployment (a production instance with the index at the public address,
|
||||
* unless a case says otherwise) and the services identity config.
|
||||
*/
|
||||
import type { AppEnv } from '../../../../src/app-config';
|
||||
import { PlaceContribLog } from '../../../../src/db/entities/PlaceContribLog.entity';
|
||||
import { PlaceContribOutbox } from '../../../../src/db/entities/PlaceContribOutbox.entity';
|
||||
import { RuntimeEnvService } from '../../../../src/nest/app-config/runtime-env.service';
|
||||
import { servicesConfig } from '../../../../src/nest/app-config/tokens';
|
||||
import { DomainError } from '../../../../src/nest/common/domain-error';
|
||||
import { PlaceContribSettings } from '../../../../src/nest/place-contrib/place-contrib-settings';
|
||||
import { PlaceContribClient } from '../../../../src/nest/place-contrib/place-contrib.client';
|
||||
import { OUTBOX_CAP } from '../../../../src/nest/place-contrib/place-contrib.constants';
|
||||
import { PlaceContribModule } from '../../../../src/nest/place-contrib/place-contrib.module';
|
||||
import { PlaceContribService } from '../../../../src/nest/place-contrib/place-contrib.service';
|
||||
import type { ContribWrite } from '../../../../src/nest/place-contrib/place-contrib.types';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makePlace } from '../../../helpers/factories/places';
|
||||
import { countRows, findRow, findRows, insertRow } from '../../../helpers/factories/rows';
|
||||
import { readAppSetting, setAppSetting } from '../../../helpers/factories/settings';
|
||||
import { makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { PLACE_CONTRIB_TERMS_VERSION, type PlaceContribFieldSwitches } from '@trek/shared';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
/** The deployment a case runs on: production with the index on, unless it changes something. */
|
||||
const deployment = {
|
||||
production: true,
|
||||
demo: false,
|
||||
maps: {} as Partial<AppEnv['maps']>,
|
||||
};
|
||||
|
||||
class DeploymentEnv extends RuntimeEnvService {
|
||||
override env(): AppEnv {
|
||||
const env = super.env();
|
||||
return { ...env, maps: { ...env.maps, trekPlacesEnabled: true, trekPlacesUrl: undefined, ...deployment.maps } };
|
||||
}
|
||||
|
||||
override isProduction(): boolean {
|
||||
return deployment.production;
|
||||
}
|
||||
|
||||
override isDemoMode(): boolean {
|
||||
return deployment.demo;
|
||||
}
|
||||
}
|
||||
|
||||
const services = {
|
||||
mode: 'auto' as 'auto' | 'off',
|
||||
key: null,
|
||||
hosts: ['places.liketrek.com'],
|
||||
photonUrl: 'https://photon.liketrek.com',
|
||||
valhallaUrl: 'https://valhalla.liketrek.com',
|
||||
};
|
||||
|
||||
const client = {
|
||||
hasKey: vi.fn(() => true),
|
||||
keyFingerprint: vi.fn(() => 'fp-1'),
|
||||
withdraw: vi.fn(async (): Promise<unknown> => ({
|
||||
kind: 'ok',
|
||||
body: { ok: true, withdrawn: { website: 3, phone: 0 } },
|
||||
})),
|
||||
};
|
||||
|
||||
const ALL: PlaceContribFieldSwitches = {
|
||||
website: true,
|
||||
phone: true,
|
||||
email: true,
|
||||
opening_hours: true,
|
||||
description: true,
|
||||
image: true,
|
||||
};
|
||||
const GERS = 'gers:ceba0e62-172b-4343-bb3b-78b915a18383';
|
||||
const ADMIN = 1;
|
||||
const NOW = new Date('2026-10-30T12:00:00Z');
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [PlaceContribModule],
|
||||
overrides: [
|
||||
{ provide: RuntimeEnvService, useValue: new DeploymentEnv() },
|
||||
{ provide: servicesConfig.KEY, useValue: services },
|
||||
{ provide: PlaceContribClient, useValue: client },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
vi.clearAllMocks();
|
||||
deployment.production = true;
|
||||
deployment.demo = false;
|
||||
deployment.maps = {};
|
||||
services.mode = 'auto';
|
||||
client.hasKey.mockReturnValue(true);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const service = () => t.get(PlaceContribService);
|
||||
const store = () => t.get(PlaceContribSettings);
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
async function agree(fields: PlaceContribFieldSwitches = ALL): Promise<void> {
|
||||
await service().decide(ADMIN, { action: 'agree', termsVersion: PLACE_CONTRIB_TERMS_VERSION, fields }, NOW);
|
||||
}
|
||||
|
||||
async function newPlace(): Promise<number> {
|
||||
const { user } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
return (await makePlace(orm(), trip.id, { osm_id: GERS })).id;
|
||||
}
|
||||
|
||||
function write(placeId: number, overrides: Partial<ContribWrite> = {}): ContribWrite {
|
||||
return {
|
||||
placeId,
|
||||
osmId: GERS,
|
||||
name: 'Café Luna',
|
||||
lat: 54.08,
|
||||
lng: 12.13,
|
||||
country: 'DE',
|
||||
values: [{ field: 'website', value: 'cafe-luna.de' }],
|
||||
dropped: [],
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
async function refusal(promise: Promise<unknown>): Promise<{ status: number; body: Record<string, unknown> }> {
|
||||
const err = await promise.then(
|
||||
() => null,
|
||||
(e: unknown) => e,
|
||||
);
|
||||
expect(err).toBeInstanceOf(DomainError);
|
||||
return { status: (err as DomainError).getStatus(), body: (err as DomainError).toBody() };
|
||||
}
|
||||
|
||||
describe('eligibility', () => {
|
||||
it('PCS-001: a production instance with a key at the public index may send', () => {
|
||||
expect(store().eligibility()).toEqual({ eligible: true, reason: null });
|
||||
});
|
||||
|
||||
it('PCS-002: names the first reason it may not, in order', () => {
|
||||
const reasons: Array<[() => void, string]> = [
|
||||
[() => client.hasKey.mockReturnValue(false), 'no_key'],
|
||||
[() => (services.mode = 'off'), 'services_off'],
|
||||
[() => (deployment.maps = { trekPlacesUrl: 'https://places.example.org/' }), 'custom_places_url'],
|
||||
[() => (deployment.maps = { ...deployment.maps, trekPlacesEnabled: false }), 'index_off'],
|
||||
[() => (deployment.demo = true), 'demo'],
|
||||
[() => (deployment.production = false), 'not_production'],
|
||||
[() => (deployment.maps = { ...deployment.maps, trekPlacesContribute: 'off' }), 'env_off'],
|
||||
];
|
||||
for (const [apply, reason] of reasons) {
|
||||
apply();
|
||||
expect(store().eligibility(), reason).toEqual({ eligible: false, reason });
|
||||
}
|
||||
});
|
||||
|
||||
it('PCS-003: the public address with a trailing slash is still the public address', () => {
|
||||
deployment.maps = { trekPlacesUrl: 'https://places.liketrek.com/' };
|
||||
expect(store().eligibility().eligible).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the admin state and the decisions', () => {
|
||||
it('PCS-010: undecided, the prompt shows with every field proposed, and nothing is active', async () => {
|
||||
const state = await service().state(ADMIN, NOW);
|
||||
expect(state).toMatchObject({
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
ceiling: 'admin',
|
||||
eligible: true,
|
||||
ineligibleReason: null,
|
||||
showPrompt: true,
|
||||
snoozedUntil: null,
|
||||
active: false,
|
||||
consent: { enabled: false, fields: ALL, decision: null },
|
||||
queue: { size: 0, cap: OUTBOX_CAP, full: false },
|
||||
pauseReason: null,
|
||||
registrationOpen: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('PCS-011: "Not now" keeps the prompt away from this admin for two weeks, not from another', async () => {
|
||||
const state = await service().decide(ADMIN, { action: 'snooze' }, NOW);
|
||||
expect(state.showPrompt).toBe(false);
|
||||
expect(state.snoozedUntil).toBe('2026-11-13T12:00:00.000Z');
|
||||
expect((await service().state(2, NOW)).showPrompt).toBe(true);
|
||||
expect((await service().state(ADMIN, new Date('2026-11-14T00:00:00Z'))).showPrompt).toBe(true);
|
||||
});
|
||||
|
||||
it('PCS-012: "Agree" stores the switches, the terms and who decided, and switches sending on', async () => {
|
||||
await agree({ ...ALL, email: false });
|
||||
const state = await service().state(ADMIN, NOW);
|
||||
expect(state).toMatchObject({ active: true, showPrompt: false });
|
||||
expect(state.consent).toEqual({
|
||||
enabled: true,
|
||||
fields: { ...ALL, email: false },
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
decision: 'agreed',
|
||||
decidedBy: ADMIN,
|
||||
decidedAt: NOW.toISOString(),
|
||||
});
|
||||
expect(await store().activeFields()).toEqual(['website', 'phone', 'opening_hours', 'description', 'image']);
|
||||
});
|
||||
|
||||
it('PCS-013: a dialog built for other terms is refused with 409, and nothing is stored', async () => {
|
||||
const res = await refusal(
|
||||
service().decide(ADMIN, { action: 'agree', termsVersion: PLACE_CONTRIB_TERMS_VERSION + 1, fields: ALL }, NOW),
|
||||
);
|
||||
expect(res).toEqual({
|
||||
status: 409,
|
||||
body: {
|
||||
error: 'The contribution terms changed',
|
||||
reason: 'terms_outdated',
|
||||
termsVersion: PLACE_CONTRIB_TERMS_VERSION,
|
||||
},
|
||||
});
|
||||
expect(await readAppSetting(orm(), 'places_contribute')).toBeNull();
|
||||
});
|
||||
|
||||
it('PCS-014: an agreement to no field at all is refused', async () => {
|
||||
const none = { website: false, phone: false, email: false, opening_hours: false, description: false, image: false };
|
||||
const res = await refusal(
|
||||
service().decide(ADMIN, { action: 'agree', termsVersion: PLACE_CONTRIB_TERMS_VERSION, fields: none }, NOW),
|
||||
);
|
||||
expect(res.status).toBe(400);
|
||||
expect(res.body.reason).toBe('no_field');
|
||||
});
|
||||
|
||||
it('PCS-015: "No" is a decision for these terms: no prompt, nothing active, the queue empty', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
await service().enqueue(write(placeId), NOW);
|
||||
const state = await service().decide(ADMIN, { action: 'decline', termsVersion: PLACE_CONTRIB_TERMS_VERSION }, NOW);
|
||||
expect(state).toMatchObject({
|
||||
showPrompt: false,
|
||||
active: false,
|
||||
consent: { decision: 'declined', enabled: false },
|
||||
});
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
});
|
||||
|
||||
it('PCS-016: switching a field off drops what waits for it and withdraws it when asked', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
await service().enqueue(
|
||||
write(placeId, {
|
||||
values: [
|
||||
{ field: 'website', value: 'cafe-luna.de' },
|
||||
{ field: 'phone', value: '+49 381 1' },
|
||||
],
|
||||
}),
|
||||
NOW,
|
||||
);
|
||||
await service().decide(ADMIN, { action: 'fields', fields: { ...ALL, phone: false }, withdraw: true }, NOW);
|
||||
expect((await findRows(orm(), PlaceContribOutbox, {})).map((row) => row.field)).toEqual(['website']);
|
||||
expect(client.withdraw).toHaveBeenCalledWith({ field: 'phone' });
|
||||
expect(await store().activeFields()).not.toContain('phone');
|
||||
});
|
||||
|
||||
it('PCS-017: changing the switches needs a standing agreement', async () => {
|
||||
const res = await refusal(service().decide(ADMIN, { action: 'fields', fields: ALL }, NOW));
|
||||
expect(res.status).toBe(409);
|
||||
expect(res.body.reason).toBe('not_agreed');
|
||||
});
|
||||
|
||||
it('PCS-018: the master switch off empties the queue and, when asked, withdraws everything', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
await service().enqueue(write(placeId), NOW);
|
||||
const state = await service().decide(ADMIN, { action: 'off', withdraw: true }, NOW);
|
||||
expect(state).toMatchObject({ active: false, consent: { decision: 'off', enabled: false } });
|
||||
expect(client.withdraw).toHaveBeenCalledWith();
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
});
|
||||
|
||||
it('PCS-019: an ineligible installation shows no prompt, and says why', async () => {
|
||||
deployment.production = false;
|
||||
expect(await service().state(ADMIN, NOW)).toMatchObject({
|
||||
eligible: false,
|
||||
ineligibleReason: 'not_production',
|
||||
showPrompt: false,
|
||||
active: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('PCS-020: a refused key is a pause until there is another key', async () => {
|
||||
await agree();
|
||||
await store().pauseFor('key_invalid', null);
|
||||
expect((await service().state(ADMIN, NOW)).pauseReason).toBe('key_invalid');
|
||||
client.keyFingerprint.mockReturnValue('fp-2');
|
||||
expect((await service().state(ADMIN, NOW)).pauseReason).toBeNull();
|
||||
client.keyFingerprint.mockReturnValue('fp-1');
|
||||
await agree();
|
||||
expect(await readAppSetting(orm(), 'places_contribute_pause')).toBeNull();
|
||||
});
|
||||
|
||||
it('PCS-021: the service asking to wait is a pause until the time it named', async () => {
|
||||
await agree();
|
||||
await store().pauseFor('not_accepting', new Date('2026-10-30T13:00:00Z'));
|
||||
expect((await service().state(ADMIN, NOW)).pauseReason).toBe('not_accepting');
|
||||
expect((await service().state(ADMIN, new Date('2026-10-30T13:01:00Z'))).pauseReason).toBeNull();
|
||||
});
|
||||
|
||||
it('PCS-022: a broken stored decision reads as undecided and off', async () => {
|
||||
await setAppSetting(orm(), 'places_contribute', '{"enabled":"yes"}');
|
||||
expect((await service().state(ADMIN, NOW)).consent).toMatchObject({ enabled: false, decision: null });
|
||||
expect(await store().activeFields()).toEqual([]);
|
||||
});
|
||||
|
||||
it('PCS-023: closed registration is reported, so the prompt can leave its warning out', async () => {
|
||||
await setAppSetting(orm(), 'allow_registration', 'false');
|
||||
expect((await service().state(ADMIN, NOW)).registrationOpen).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('enqueue', () => {
|
||||
it('PCS-030: nothing is queued before an admin agreed, but values no longer the user own still leave', async () => {
|
||||
const placeId = await newPlace();
|
||||
await insertRow(orm(), PlaceContribOutbox, outboxRow(placeId, 'phone'));
|
||||
await service().enqueue(write(placeId, { dropped: ['phone'] }), NOW);
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
expect(await countRows(orm(), PlaceContribLog)).toBe(0);
|
||||
});
|
||||
|
||||
it('PCS-031: a user value of a keyed place is queued, normalized, a few minutes out', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
await service().enqueue(write(placeId), NOW);
|
||||
const row = await findRow(orm(), PlaceContribOutbox, { field: 'website' });
|
||||
expect(row).toMatchObject({
|
||||
contrib_key: GERS,
|
||||
value: 'https://cafe-luna.de',
|
||||
place_name: 'Café Luna',
|
||||
country: 'DE',
|
||||
});
|
||||
const due = Date.parse(`${row?.eligible_at.replace(' ', 'T')}Z`);
|
||||
expect(due - NOW.getTime()).toBeGreaterThanOrEqual(2 * 60_000 - 1000);
|
||||
expect(due - NOW.getTime()).toBeLessThanOrEqual(10 * 60_000 + 1000);
|
||||
});
|
||||
|
||||
it('PCS-032: the newest value replaces the queued one, attempts and all', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
await insertRow(orm(), PlaceContribOutbox, { ...outboxRow(placeId, 'website'), attempts: 3 });
|
||||
await service().enqueue(write(placeId, { values: [{ field: 'website', value: 'https://new.example' }] }), NOW);
|
||||
const rows = await findRows(orm(), PlaceContribOutbox, {});
|
||||
expect(rows).toHaveLength(1);
|
||||
expect(rows[0]).toMatchObject({ value: 'https://new.example', attempts: 0 });
|
||||
});
|
||||
|
||||
it('PCS-033: a field switched off is not queued; a place without a key is logged as withheld', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree({ ...ALL, website: false });
|
||||
await service().enqueue(write(placeId), NOW);
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
await agree();
|
||||
await service().enqueue(write(placeId, { osmId: 'ChIJd8BlQ2BZwokRAFUEcm_qrcA' }), NOW);
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
expect(await findRow(orm(), PlaceContribLog, {})).toMatchObject({
|
||||
contrib_key: '-',
|
||||
field: 'website',
|
||||
result: 'withheld',
|
||||
reason: 'no_contrib_key',
|
||||
day: '2026-10-30',
|
||||
});
|
||||
});
|
||||
|
||||
it('PCS-034: a value the service would refuse stays home, and the log says why', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
await service().enqueue(
|
||||
write(placeId, { values: [{ field: 'image', value: 'https://photos.example/a.jpg' }] }),
|
||||
NOW,
|
||||
);
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
expect(await findRow(orm(), PlaceContribLog, {})).toMatchObject({
|
||||
result: 'withheld',
|
||||
reason: 'image_not_uploaded',
|
||||
});
|
||||
});
|
||||
|
||||
it('PCS-035: an ineligible installation queues nothing even after an agreement', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
deployment.demo = true;
|
||||
await service().enqueue(write(placeId), NOW);
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('withdrawAll and the log', () => {
|
||||
it('PCS-040: a confirmed withdrawal empties the queue and logs what the service took back', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
await service().enqueue(write(placeId), NOW);
|
||||
expect(await service().withdrawAll(NOW)).toEqual({ withdrawn: { website: 3, phone: 0 }, cleared: 1 });
|
||||
expect(await findRows(orm(), PlaceContribLog, {})).toEqual([
|
||||
expect.objectContaining({ contrib_key: '*', field: 'website', value_summary: '3', result: 'retracted' }),
|
||||
]);
|
||||
expect((await service().state(ADMIN, NOW)).counts.retracted).toBe(1);
|
||||
});
|
||||
|
||||
it('PCS-041: an unconfirmed withdrawal is a 502, and the queue stays', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
await service().enqueue(write(placeId), NOW);
|
||||
client.withdraw.mockResolvedValueOnce({ kind: 'failed', reason: 'TimeoutError', retryAfterMs: null });
|
||||
const res = await refusal(service().withdrawAll(NOW));
|
||||
expect(res).toEqual({
|
||||
status: 502,
|
||||
body: { error: 'The TREK Places API did not confirm the withdrawal', reason: 'TimeoutError' },
|
||||
});
|
||||
expect(await countRows(orm(), PlaceContribOutbox)).toBe(1);
|
||||
});
|
||||
|
||||
it('PCS-042: the log pages newest first and filters by result and field', async () => {
|
||||
const placeId = await newPlace();
|
||||
await agree();
|
||||
await service().enqueue(write(placeId, { osmId: null }), NOW);
|
||||
await service().enqueue(
|
||||
write(placeId, { osmId: null, values: [{ field: 'phone', value: '+49 1' }] }),
|
||||
new Date('2026-10-31T09:00:00Z'),
|
||||
);
|
||||
const all = await service().logPage({ page: 1, perPage: 1 });
|
||||
expect(all).toMatchObject({ total: 2, page: 1, perPage: 1 });
|
||||
expect(all.entries).toEqual([
|
||||
{
|
||||
id: expect.any(Number),
|
||||
day: '2026-10-31',
|
||||
key: '-',
|
||||
placeName: 'Café Luna',
|
||||
field: 'phone',
|
||||
valueSummary: '+49 1',
|
||||
result: 'withheld',
|
||||
reason: 'no_contrib_key',
|
||||
},
|
||||
]);
|
||||
expect((await service().logPage({ page: 1, perPage: 50, field: 'website' })).total).toBe(1);
|
||||
expect((await service().logPage({ page: 1, perPage: 50, result: 'accepted' })).total).toBe(0);
|
||||
expect((await service().state(ADMIN, NOW)).counts.withheld).toBe(2);
|
||||
});
|
||||
});
|
||||
|
||||
function outboxRow(placeId: number, field: string) {
|
||||
return {
|
||||
contrib_key: GERS,
|
||||
field,
|
||||
value: 'x',
|
||||
place: placeId,
|
||||
place_name: 'Café Luna',
|
||||
cid: 'entry-cid-0001',
|
||||
eligible_at: '2026-10-30 12:05:00',
|
||||
next_attempt_at: '2026-10-30 12:05:00',
|
||||
};
|
||||
}
|
||||
@@ -713,6 +713,34 @@ describe('result cache', () => {
|
||||
expect(written.expanded).toBe(2);
|
||||
});
|
||||
|
||||
it('ENRICH-027: a gers place is read again once the index serves another community version', async () => {
|
||||
const GERS_REQ = { ...REQ, placeId: 'gers:ceba0e62-172b-4343-bb3b-78b915a18383' };
|
||||
const row = {
|
||||
payload_json: JSON.stringify({ photos: [], description: null, facts: [], v: 4, cv: 1 }),
|
||||
fetched_at: Date.now(),
|
||||
};
|
||||
const maps = mapsStub({ fetchCommonsCandidates: vi.fn(async () => [commonsCandidate()]) });
|
||||
|
||||
mockFindEntry.mockResolvedValue(row);
|
||||
await make(maps, cacheStub()).enrich(1, { ...GERS_REQ, details: { community_version: 1 } });
|
||||
expect(maps.fetchCommonsCandidates).not.toHaveBeenCalled();
|
||||
|
||||
await make(maps, cacheStub()).enrich(1, { ...GERS_REQ, details: { community_version: 2 } });
|
||||
expect(maps.fetchCommonsCandidates).toHaveBeenCalled();
|
||||
const [written] = mockUpsertEntry.mock.calls.at(-1) as [{ payload_json: string }];
|
||||
expect(JSON.parse(written.payload_json).cv).toBe(2);
|
||||
});
|
||||
|
||||
it('ENRICH-028: any other place keeps its week, whatever a request says about versions', async () => {
|
||||
const maps = mapsStub();
|
||||
mockFindEntry.mockResolvedValue({
|
||||
payload_json: JSON.stringify({ photos: [], description: null, facts: [], v: 4 }),
|
||||
fetched_at: Date.now(),
|
||||
});
|
||||
await make(maps, cacheStub()).enrich(1, { ...REQ, details: { community_version: 9 } });
|
||||
expect(maps.fetchCommonsCandidates).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('ENRICH-026: keeps working when the cache write fails', async () => {
|
||||
const maps = mapsStub({ fetchCommonsCandidates: vi.fn(async () => [commonsCandidate()]) });
|
||||
mockUpsertEntry.mockRejectedValue(new Error('db locked'));
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
/**
|
||||
* The origin rules: which fields a write changed, what a provider handed out
|
||||
* for a place according to the cached records, and which origin a changed
|
||||
* value is stored with for each kind of writer.
|
||||
*/
|
||||
import type { PlaceShareableRow } from '../../../../src/db/repositories/PlaceFieldOrigin.repository';
|
||||
import {
|
||||
changedFields,
|
||||
needsProviders,
|
||||
originFor,
|
||||
providerIdsOf,
|
||||
providerValuesOf,
|
||||
sameValue,
|
||||
snapshotOf,
|
||||
type OriginWriter,
|
||||
type ProviderValue,
|
||||
} from '../../../../src/nest/places/place-origins.helpers';
|
||||
import type { PlaceFieldOrigins } from '@trek/shared';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const ROW: PlaceShareableRow = {
|
||||
id: 7,
|
||||
name: 'Café Luna',
|
||||
lat: 54.08,
|
||||
lng: 12.13,
|
||||
address: 'Strandstraße 1, Rostock',
|
||||
osm_id: 'gers:ceba0e62-172b-4343-bb3b-78b915a18383',
|
||||
google_place_id: null,
|
||||
amap_poi_id: null,
|
||||
website: 'https://cafe-luna.de/',
|
||||
phone: '+49 381 1234',
|
||||
email: '',
|
||||
opening_hours: null,
|
||||
description: 'Coffee by the sea.',
|
||||
image_url: '/uploads/places/luna.jpg',
|
||||
};
|
||||
|
||||
const client = (claims: PlaceFieldOrigins | undefined): OriginWriter => ({ kind: 'client', claims });
|
||||
|
||||
describe('snapshots and changes', () => {
|
||||
it('POH-001: reads the six shareable columns, an empty text as none', () => {
|
||||
expect(snapshotOf(ROW)).toEqual({
|
||||
website: 'https://cafe-luna.de/',
|
||||
phone: '+49 381 1234',
|
||||
email: null,
|
||||
opening_hours: null,
|
||||
description: 'Coffee by the sea.',
|
||||
image: '/uploads/places/luna.jpg',
|
||||
});
|
||||
});
|
||||
|
||||
it('POH-002: a new place changed every field it holds; an update only what moved', () => {
|
||||
const after = snapshotOf(ROW);
|
||||
expect(changedFields(null, after)).toEqual(['website', 'phone', 'description', 'image']);
|
||||
expect(changedFields(after, { ...after, phone: '+49 381 9999', email: 'hi@cafe-luna.de' })).toEqual([
|
||||
'phone',
|
||||
'email',
|
||||
]);
|
||||
expect(changedFields(after, { ...after, image: null })).toEqual(['image']);
|
||||
expect(changedFields(after, after)).toEqual([]);
|
||||
});
|
||||
|
||||
it('POH-003: the provider ids are the ones the place carries', () => {
|
||||
expect(providerIdsOf(ROW)).toEqual(['gers:ceba0e62-172b-4343-bb3b-78b915a18383']);
|
||||
expect(providerIdsOf({ ...ROW, google_place_id: 'ChIJ1', amap_poi_id: ' ', osm_id: null })).toEqual(['ChIJ1']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('providerValuesOf', () => {
|
||||
it('POH-010: reads contact details from a details record, by the provider its id names', () => {
|
||||
const values = providerValuesOf([
|
||||
{
|
||||
place_id: 'ChIJ1',
|
||||
expanded: 0,
|
||||
payload_json: JSON.stringify({ website: 'https://a.example', phone: '+1 555', email: null }),
|
||||
},
|
||||
{ place_id: 'node:5', expanded: 0, payload_json: JSON.stringify({ phone: '+49 1' }) },
|
||||
{ place_id: 'amap:B1', expanded: 0, payload_json: JSON.stringify({ email: 'x@y.cn' }) },
|
||||
{ place_id: 'gers:abc', expanded: 0, payload_json: JSON.stringify({ description: 'Index text' }) },
|
||||
]);
|
||||
expect(values).toEqual([
|
||||
{ field: 'website', value: 'https://a.example', origin: 'google' },
|
||||
{ field: 'phone', value: '+1 555', origin: 'google' },
|
||||
{ field: 'phone', value: '+49 1', origin: 'osm' },
|
||||
{ field: 'email', value: 'x@y.cn', origin: 'amap' },
|
||||
{ field: 'description', value: 'Index text', origin: 'trek' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('POH-011: an enrichment record names the source of its description', () => {
|
||||
const values = providerValuesOf([
|
||||
{
|
||||
place_id: 'gers:abc',
|
||||
expanded: 2,
|
||||
payload_json: JSON.stringify({ description: { text: 'From the article', source: 'wikipedia' } }),
|
||||
},
|
||||
{
|
||||
place_id: 'gers:abc',
|
||||
expanded: 2,
|
||||
payload_json: JSON.stringify({ description: { text: 'From the site', source: 'website' } }),
|
||||
},
|
||||
{
|
||||
place_id: 'node:1',
|
||||
expanded: 2,
|
||||
payload_json: JSON.stringify({ description: { text: 'Something', source: 'mystery' } }),
|
||||
},
|
||||
]);
|
||||
expect(values.map((value) => value.origin)).toEqual(['wikimedia', 'website', 'enrichment']);
|
||||
});
|
||||
|
||||
it('POH-012: a broken record adds nothing', () => {
|
||||
expect(providerValuesOf([{ place_id: 'ChIJ1', expanded: 0, payload_json: '{not json' }])).toEqual([]);
|
||||
expect(providerValuesOf([{ place_id: 'ChIJ1', expanded: 0, payload_json: '[1,2]' }])).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('sameValue', () => {
|
||||
it('POH-020: compares values the way they are read', () => {
|
||||
expect(sameValue('website', 'cafe-luna.de', 'https://cafe-luna.de')).toBe(true);
|
||||
expect(sameValue('phone', '+49 (381) 12-34', '+493811234')).toBe(true);
|
||||
expect(sameValue('email', 'Info@Luna.de ', 'info@luna.de')).toBe(true);
|
||||
expect(sameValue('description', 'Coffee by\nthe sea.', 'Coffee by the sea.')).toBe(true);
|
||||
expect(sameValue('phone', '+49 381 1', '+49 381 2')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('originFor', () => {
|
||||
const providers: ProviderValue[] = [{ field: 'website', value: 'https://cafe-luna.de/', origin: 'trek' }];
|
||||
|
||||
it('POH-030: a deciding path gives its own origin to everything it changed', () => {
|
||||
expect(originFor('website', 'https://x.example', { kind: 'fixed', origin: 'agent' }, providers)).toBe('agent');
|
||||
expect(originFor('image', '/uploads/places/a.jpg', { kind: 'fixed', origin: 'user' }, [])).toBe('user');
|
||||
});
|
||||
|
||||
it('POH-031: a client is believed for a provider and for what no provider handed out', () => {
|
||||
expect(originFor('phone', '+49 1', client({ phone: 'google' }), providers)).toBe('google');
|
||||
expect(originFor('website', 'https://other.example', client({ website: 'user' }), providers)).toBe('user');
|
||||
});
|
||||
|
||||
it('POH-032: a value claimed as typed that a provider handed out is the provider', () => {
|
||||
expect(originFor('website', 'cafe-luna.de/', client({ website: 'user' }), providers)).toBe('trek');
|
||||
});
|
||||
|
||||
it('POH-033: no claim is unknown, and so is a picture a client calls its own', () => {
|
||||
expect(originFor('website', 'https://x.example', client(undefined), providers)).toBe('unknown');
|
||||
expect(originFor('phone', '+49 1', client({ website: 'user' }), providers)).toBe('unknown');
|
||||
expect(originFor('image', '/uploads/places/a.jpg', client({ image: 'user' }), [])).toBe('unknown');
|
||||
expect(originFor('image', '/api/maps/place-photo/x', client({ image: 'enrichment' }), [])).toBe('enrichment');
|
||||
});
|
||||
|
||||
it('POH-034: the cached records are read only for a client claiming a typed value', () => {
|
||||
expect(needsProviders(client({ website: 'user' }), ['website'])).toBe(true);
|
||||
expect(needsProviders(client({ website: 'user' }), ['phone'])).toBe(false);
|
||||
expect(needsProviders(client({ website: 'trek' }), ['website'])).toBe(false);
|
||||
expect(needsProviders({ kind: 'fixed', origin: 'agent' }, ['website'])).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* The REST side of the origin tracking: the interceptor reads a place before
|
||||
* its route runs and records after the route answered, with the writer the
|
||||
* route's decorator names, and records nothing for a route that threw.
|
||||
*/
|
||||
import { PlaceOriginsInterceptor, TrackPlaceOrigins } from '../../../../src/nest/places/place-origins.interceptor';
|
||||
import type { PlaceOriginsService } from '../../../../src/nest/places/place-origins.service';
|
||||
import type { CallHandler, ExecutionContext } from '@nestjs/common';
|
||||
import { Reflector } from '@nestjs/core';
|
||||
|
||||
import { lastValueFrom, of, throwError } from 'rxjs';
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
class Routes {
|
||||
@TrackPlaceOrigins('client')
|
||||
update(): void {}
|
||||
|
||||
@TrackPlaceOrigins('upload')
|
||||
upload(): void {}
|
||||
|
||||
@TrackPlaceOrigins('attachment')
|
||||
fromFile(): void {}
|
||||
|
||||
@TrackPlaceOrigins('import')
|
||||
importList(): void {}
|
||||
}
|
||||
|
||||
const BEFORE = {
|
||||
website: 'https://old.example',
|
||||
phone: null,
|
||||
email: null,
|
||||
opening_hours: null,
|
||||
description: null,
|
||||
image: null,
|
||||
};
|
||||
const origins = {
|
||||
valuesBefore: vi.fn(async () => BEFORE),
|
||||
record: vi.fn(async () => undefined),
|
||||
recordImported: vi.fn(async () => undefined),
|
||||
};
|
||||
const interceptor = new PlaceOriginsInterceptor(origins as unknown as PlaceOriginsService, new Reflector());
|
||||
|
||||
function context(handler: keyof Routes, req: { params?: Record<string, string>; body?: unknown }): ExecutionContext {
|
||||
return {
|
||||
getHandler: () => Routes.prototype[handler],
|
||||
getClass: () => Routes,
|
||||
switchToHttp: () => ({ getRequest: () => req }),
|
||||
} as unknown as ExecutionContext;
|
||||
}
|
||||
|
||||
async function run(handler: keyof Routes, req: { params?: Record<string, string>; body?: unknown }, answer: unknown) {
|
||||
const next: CallHandler = { handle: () => of(answer) };
|
||||
return lastValueFrom(await interceptor.intercept(context(handler, req), next));
|
||||
}
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('PlaceOriginsInterceptor', () => {
|
||||
it('POI-001: an update reads the place first and records what the client reported', async () => {
|
||||
const body = { website: 'https://new.example', fieldOrigins: { website: 'user' } };
|
||||
const answer = { place: { id: 12 } };
|
||||
expect(await run('update', { params: { id: '12' }, body }, answer)).toBe(answer);
|
||||
expect(origins.valuesBefore).toHaveBeenCalledWith(12);
|
||||
expect(origins.record).toHaveBeenCalledWith(12, BEFORE, { kind: 'client', claims: { website: 'user' } });
|
||||
});
|
||||
|
||||
it('POI-002: a create has no place before it; a malformed report counts as none', async () => {
|
||||
await run(
|
||||
'update',
|
||||
{ params: {}, body: { name: 'New', fieldOrigins: { website: 'agent' } } },
|
||||
{ place: { id: 5 } },
|
||||
);
|
||||
expect(origins.valuesBefore).not.toHaveBeenCalled();
|
||||
expect(origins.record).toHaveBeenCalledWith(5, null, { kind: 'client', claims: undefined });
|
||||
});
|
||||
|
||||
it('POI-003: the upload is the user own picture, a trip file the attachment', async () => {
|
||||
await run('upload', { params: { id: '3' } }, { place: { id: 3 } });
|
||||
expect(origins.record).toHaveBeenLastCalledWith(3, BEFORE, { kind: 'fixed', origin: 'user' });
|
||||
await run('fromFile', { params: { id: '3' } }, { place: { id: 3 } });
|
||||
expect(origins.record).toHaveBeenLastCalledWith(3, BEFORE, { kind: 'fixed', origin: 'attachment' });
|
||||
});
|
||||
|
||||
it('POI-004: an import records the places it answered with, in one pass', async () => {
|
||||
await run('importList', { params: {} }, { places: [{ id: 1 }, { id: 2 }, { id: 'x' }], count: 2 });
|
||||
expect(origins.recordImported).toHaveBeenCalledWith([1, 2]);
|
||||
expect(origins.record).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('POI-005: an answer without a place records nothing; a route that threw neither', async () => {
|
||||
await run('update', { params: { id: '4' } }, { deleted: true });
|
||||
expect(origins.record).not.toHaveBeenCalled();
|
||||
const failing: CallHandler = { handle: () => throwError(() => new Error('409')) };
|
||||
const observable = await interceptor.intercept(context('update', { params: { id: '4' } }), failing);
|
||||
await expect(lastValueFrom(observable)).rejects.toThrow('409');
|
||||
expect(origins.record).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* PlaceOriginsService over the real tables on a migrated test db: a write
|
||||
* records an origin per changed field with the hash of its value, a cleared
|
||||
* value loses its row, an unchanged one keeps what it had, a value claimed as
|
||||
* typed that a provider handed out is the provider's, and only the user's
|
||||
* values go on to the contribution queue.
|
||||
*
|
||||
* Replaced: PlaceContribService, so what reaches the queue is read off a spy.
|
||||
*/
|
||||
import { PlaceDetailsCache } from '../../../../src/db/entities/PlaceDetailsCache.entity';
|
||||
import { PlaceFieldOrigin } from '../../../../src/db/entities/PlaceFieldOrigin.entity';
|
||||
import { Places } from '../../../../src/db/entities/Places.entity';
|
||||
import { valueHash } from '../../../../src/nest/common/value-hash';
|
||||
import { PlaceContribService } from '../../../../src/nest/place-contrib/place-contrib.service';
|
||||
import { PlaceOriginsService } from '../../../../src/nest/places/place-origins.service';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makePlace } from '../../../helpers/factories/places';
|
||||
import { findRows, insertRow, updateRows } from '../../../helpers/factories/rows';
|
||||
import { makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestModule, type TestModule } from '../../../helpers/test-module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
let t: TestModule;
|
||||
const contrib = { enqueue: vi.fn(async () => undefined) };
|
||||
const GERS = 'gers:ceba0e62-172b-4343-bb3b-78b915a18383';
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestModule({
|
||||
db,
|
||||
imports: [MikroOrmModule.forFeature([PlaceFieldOrigin])],
|
||||
providers: [PlaceOriginsService, { provide: PlaceContribService, useValue: contrib }],
|
||||
});
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
resetTestDb(db);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
const service = () => t.get(PlaceOriginsService);
|
||||
const orm = () => t.get(MikroORM);
|
||||
|
||||
async function place(overrides: Record<string, unknown> = {}): Promise<number> {
|
||||
const { user } = await makeUser(orm());
|
||||
const trip = await makeTrip(orm(), user.id);
|
||||
return (await makePlace(orm(), trip.id, { osm_id: GERS, ...overrides })).id;
|
||||
}
|
||||
|
||||
async function origins(placeId: number): Promise<Record<string, { origin: string; value_hash: string }>> {
|
||||
const rows = await findRows(orm(), PlaceFieldOrigin, { place: placeId });
|
||||
return Object.fromEntries(rows.map((row) => [row.field, { origin: row.origin, value_hash: row.value_hash }]));
|
||||
}
|
||||
|
||||
describe('a new place', () => {
|
||||
it('POS-001: records the client origins, the hash of each value, and unknown for an unreported field', async () => {
|
||||
const id = await place({ website: 'https://cafe-luna.de/', phone: '+49 381 1', description: 'By the sea.' });
|
||||
await service().record(id, null, { kind: 'client', claims: { website: 'user', phone: 'trek' } });
|
||||
expect(await origins(id)).toEqual({
|
||||
website: { origin: 'user', value_hash: valueHash('https://cafe-luna.de/') },
|
||||
phone: { origin: 'trek', value_hash: valueHash('+49 381 1') },
|
||||
description: { origin: 'unknown', value_hash: valueHash('By the sea.') },
|
||||
});
|
||||
expect(contrib.enqueue).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
placeId: id,
|
||||
osmId: GERS,
|
||||
name: 'Test Place',
|
||||
country: 'FR',
|
||||
values: [{ field: 'website', value: 'https://cafe-luna.de/' }],
|
||||
dropped: ['phone', 'description'],
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('POS-002: a deciding path gives its origin to every value', async () => {
|
||||
const id = await place({ website: 'https://agent.example', image_url: '/uploads/places/a.jpg' });
|
||||
await service().record(id, null, { kind: 'fixed', origin: 'agent' });
|
||||
expect(Object.values(await origins(id)).map((row) => row.origin)).toEqual(['agent', 'agent']);
|
||||
expect(contrib.enqueue).toHaveBeenCalledWith(expect.objectContaining({ values: [] }));
|
||||
});
|
||||
|
||||
it('POS-003: a typed value a provider handed out for the place is the provider', async () => {
|
||||
const id = await place({ website: 'cafe-luna.de' });
|
||||
await insertRow(orm(), PlaceDetailsCache, {
|
||||
place_id: GERS,
|
||||
lang: 'de',
|
||||
expanded: 0,
|
||||
payload_json: JSON.stringify({ website: 'https://cafe-luna.de' }),
|
||||
fetched_at: Date.now(),
|
||||
});
|
||||
await service().record(id, null, { kind: 'client', claims: { website: 'user' } });
|
||||
expect((await origins(id)).website?.origin).toBe('trek');
|
||||
expect(contrib.enqueue).toHaveBeenCalledWith(expect.objectContaining({ values: [], dropped: ['website'] }));
|
||||
});
|
||||
});
|
||||
|
||||
describe('an update', () => {
|
||||
it('POS-010: only what moved gets an origin; a value from before the tracking stays without one', async () => {
|
||||
const id = await place({ website: 'https://old.example', phone: '+49 1' });
|
||||
const before = await service().valuesBefore(id);
|
||||
await updateRows(orm(), Places, { id }, { phone: '+49 2' });
|
||||
await service().record(id, before, { kind: 'client', claims: { website: 'user', phone: 'user' } });
|
||||
const rows = await origins(id);
|
||||
expect(rows.phone?.origin).toBe('user');
|
||||
expect(rows.website).toBeUndefined();
|
||||
expect(contrib.enqueue).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ values: [{ field: 'phone', value: '+49 2' }], dropped: [] }),
|
||||
);
|
||||
});
|
||||
|
||||
it('POS-011: a cleared value loses its origin and leaves the queue', async () => {
|
||||
const id = await place({ email: 'info@luna.de' });
|
||||
await service().record(id, null, { kind: 'client', claims: { email: 'user' } });
|
||||
const before = await service().valuesBefore(id);
|
||||
await updateRows(orm(), Places, { id }, { email: null });
|
||||
await service().record(id, before, { kind: 'client', claims: {} });
|
||||
expect(await origins(id)).toEqual({});
|
||||
expect(contrib.enqueue).toHaveBeenLastCalledWith(expect.objectContaining({ values: [], dropped: ['email'] }));
|
||||
});
|
||||
|
||||
it('POS-012: a user value overwritten by the assistant is the agent', async () => {
|
||||
const id = await place({ website: 'https://mine.example' });
|
||||
await service().record(id, null, { kind: 'client', claims: { website: 'user' } });
|
||||
const before = await service().valuesBefore(id);
|
||||
await updateRows(orm(), Places, { id }, { website: 'https://agent.example' });
|
||||
await service().record(id, before, { kind: 'fixed', origin: 'agent' });
|
||||
expect((await origins(id)).website).toEqual({ origin: 'agent', value_hash: valueHash('https://agent.example') });
|
||||
});
|
||||
|
||||
it('POS-013: nothing changed, nothing is recorded or queued', async () => {
|
||||
const id = await place({ website: 'https://same.example' });
|
||||
const before = await service().valuesBefore(id);
|
||||
await service().record(id, before, { kind: 'client', claims: { website: 'user' } });
|
||||
expect(await origins(id)).toEqual({});
|
||||
expect(contrib.enqueue).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('POS-014: a failure is logged, never raised into the write it follows', async () => {
|
||||
contrib.enqueue.mockRejectedValueOnce(new Error('queue down'));
|
||||
const id = await place({ website: 'https://x.example' });
|
||||
await expect(service().record(id, null, { kind: 'client', claims: { website: 'user' } })).resolves.toBeUndefined();
|
||||
expect(await service().valuesBefore('not-an-id')).toBeNull();
|
||||
await expect(service().record(999_999, null, { kind: 'fixed', origin: 'agent' })).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('an import', () => {
|
||||
it('POS-020: records every value of the new places as the import, in one pass', async () => {
|
||||
const a = await place({ website: 'https://a.example' });
|
||||
const b = await place({ phone: '+1 2', description: 'Imported text' });
|
||||
await service().recordImported([a, b]);
|
||||
expect((await origins(a)).website?.origin).toBe('import');
|
||||
expect(Object.values(await origins(b)).map((row) => row.origin)).toEqual(['import', 'import']);
|
||||
expect(contrib.enqueue).not.toHaveBeenCalled();
|
||||
await expect(service().recordImported([])).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
/**
|
||||
* The MCP side of the origin tracking, beside the REST interceptor: what the
|
||||
* assistant writes into a place is recorded as the agent's, a trip file made
|
||||
* the picture as an attachment, and an import as the import, so none of it is
|
||||
* ever shared as a user's correction.
|
||||
*/
|
||||
import type { McpContext } from '../../../../src/nest-mcp';
|
||||
import { PlacesMcp } from '../../../../src/nest/places/places.mcp';
|
||||
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const ctx = { userId: 5 } as McpContext;
|
||||
const BEFORE = { website: null, phone: null, email: null, opening_hours: null, description: null, image: null };
|
||||
|
||||
const places = {
|
||||
create: vi.fn(async (_trip: string, input: Record<string, unknown>) => ({ id: 21, ...input })),
|
||||
update: vi.fn(async (_trip: string, id: string) => ({ id: Number(id), name: 'Updated' })),
|
||||
setImageFromFile: vi.fn(async (_trip: string, id: string) => ({ id: Number(id) })),
|
||||
updateMany: vi.fn(async (_trip: string, ids: number[]) => ids.map((id) => ({ id }))),
|
||||
importGpx: vi.fn(async () => ({ places: [{ id: 31 }, { id: 32 }], count: 2, skipped: 0 })),
|
||||
onCreated: vi.fn(async () => undefined),
|
||||
onUpdated: vi.fn(async () => undefined),
|
||||
};
|
||||
const origins = {
|
||||
valuesBefore: vi.fn(async () => BEFORE),
|
||||
record: vi.fn(async () => undefined),
|
||||
recordImported: vi.fn(async () => undefined),
|
||||
};
|
||||
const guards = { hasTripPermission: vi.fn(async () => true), safeBroadcast: vi.fn() };
|
||||
const tripAccess = { findAccessible: vi.fn(async () => ({ id: 1, user_id: 5 })) };
|
||||
|
||||
const mcp = new PlacesMcp(
|
||||
places as never,
|
||||
{} as never,
|
||||
tripAccess as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
guards as never,
|
||||
{} as never,
|
||||
origins as never,
|
||||
);
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
describe('PlacesMcp origin tracking', () => {
|
||||
it('PMO-001: a place the assistant creates is the agent own', async () => {
|
||||
await mcp.createPlace({ tripId: 1, name: 'Café', website: 'https://cafe.example' }, ctx);
|
||||
expect(origins.record).toHaveBeenCalledWith(21, null, { kind: 'fixed', origin: 'agent' });
|
||||
});
|
||||
|
||||
it('PMO-002: an update reads the place first and records the agent', async () => {
|
||||
await mcp.updatePlace({ tripId: 1, placeId: 8, phone: '+49 1' }, ctx);
|
||||
expect(origins.valuesBefore).toHaveBeenCalledWith(8);
|
||||
expect(origins.record).toHaveBeenCalledWith(8, BEFORE, { kind: 'fixed', origin: 'agent' });
|
||||
});
|
||||
|
||||
it('PMO-003: a trip file made the picture is an attachment', async () => {
|
||||
await mcp.setPlaceImageFromFile({ tripId: 1, placeId: 8, fileId: 4 }, ctx);
|
||||
expect(origins.record).toHaveBeenCalledWith(8, BEFORE, { kind: 'fixed', origin: 'attachment' });
|
||||
});
|
||||
|
||||
it('PMO-004: a bulk update records every place it changed as the agent', async () => {
|
||||
await mcp.bulkUpdatePlaces({ tripId: 1, placeIds: [8, 9], website: 'https://all.example' }, ctx);
|
||||
expect(origins.valuesBefore).toHaveBeenCalledTimes(2);
|
||||
expect(origins.record).toHaveBeenCalledWith(9, BEFORE, { kind: 'fixed', origin: 'agent' });
|
||||
});
|
||||
|
||||
it('PMO-005: an imported GPX is the import', async () => {
|
||||
await mcp.importGpx(
|
||||
{ tripId: 1, gpx: '<gpx/>', name: 'Track', importTracks: true, importRoutes: false, importWaypoints: true },
|
||||
ctx,
|
||||
);
|
||||
expect(origins.recordImported).toHaveBeenCalledWith([31, 32]);
|
||||
});
|
||||
|
||||
it('PMO-006: no access, no permission: nothing is recorded', async () => {
|
||||
guards.hasTripPermission.mockResolvedValueOnce(false);
|
||||
await mcp.createPlace({ tripId: 1, name: 'Café' }, ctx);
|
||||
expect(origins.record).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
@@ -372,6 +372,7 @@ describe('Roadtrip MCP registration and search', () => {
|
||||
{} as never,
|
||||
guards as never,
|
||||
{} as never,
|
||||
{ recordImported: vi.fn(async () => undefined) } as never,
|
||||
);
|
||||
const input = {
|
||||
tripId: 1,
|
||||
|
||||
@@ -840,6 +840,12 @@ describe('toPlaceRecord', () => {
|
||||
expect(r.brand).toBe("L'Osteria");
|
||||
});
|
||||
|
||||
it('carries the community version the service overlays, null when it names none', () => {
|
||||
expect(toPlaceRecord({ ...PLACE, community: { version: 4 } }).community_version).toBe(4);
|
||||
expect(toPlaceRecord(PLACE).community_version).toBeNull();
|
||||
expect(toPlaceRecord({ ...PLACE, community: null }).community_version).toBeNull();
|
||||
});
|
||||
|
||||
it('reports no rating rather than a made-up one', () => {
|
||||
// Ratings exist in no open dataset. Null says so; 0 would be a claim.
|
||||
expect(toPlaceRecord(PLACE).rating).toBeNull();
|
||||
|
||||
@@ -13,6 +13,7 @@ import { createTestPluginRegistry } from '../../../src/nest-rpc/rpc-kit/testing'
|
||||
import type { AddonsService } from '../../../src/nest/addons/addons.service';
|
||||
import type { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service';
|
||||
import type { PermissionsService } from '../../../src/nest/permissions/permissions.service';
|
||||
import type { PlaceOriginsService } from '../../../src/nest/places/place-origins.service';
|
||||
import { PlacesModule } from '../../../src/nest/places/places.module';
|
||||
import { PlacesRpc } from '../../../src/nest/places/places.rpc';
|
||||
import type { PlacesService } from '../../../src/nest/places/places.service';
|
||||
@@ -75,15 +76,17 @@ function build(opts: { canEdit?: boolean; journeyThrows?: boolean } = {}) {
|
||||
{ getRole: vi.fn(async () => 'user') } as unknown as UsersRepository,
|
||||
);
|
||||
// Each double covers only the methods PlacesRpc reaches for, hence the cast.
|
||||
const origins = { valuesBefore: vi.fn(async () => null), record: vi.fn(async () => undefined) };
|
||||
const rpc = new PlacesRpc(
|
||||
places as unknown as PlacesService,
|
||||
journey as unknown as JourneyDomainService,
|
||||
realtime as unknown as RealtimeService,
|
||||
guards,
|
||||
origins as unknown as PlaceOriginsService,
|
||||
);
|
||||
const host = (...grants: string[]) =>
|
||||
new PluginRpcHost('p', new Set(grants), makeDeps(), createTestPluginRegistry([rpc]));
|
||||
return { places, journey, realtime, host };
|
||||
return { places, journey, realtime, host, origins };
|
||||
}
|
||||
|
||||
describe('PlacesRpc', () => {
|
||||
@@ -242,4 +245,17 @@ describe('PlacesRpc', () => {
|
||||
expect(refused.error.message).toBe('invalid place: website must be an http or https URL');
|
||||
expect(f.places.create).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('PLACES-RPC-013 what a plugin writes is recorded as the plugin, never as a user', async () => {
|
||||
const f = build();
|
||||
const host = f.host('db:write:places');
|
||||
await host.dispatch(
|
||||
req('places.create', { tripId: 1, input: { name: 'Shrine', website: 'https://shrine.jp' } }),
|
||||
42,
|
||||
);
|
||||
expect(f.origins.record).toHaveBeenCalledWith(10, null, { kind: 'fixed', origin: 'plugin' });
|
||||
await host.dispatch(req('places.update', { tripId: 1, placeId: 7, input: { phone: '+81 1' } }), 42);
|
||||
expect(f.origins.valuesBefore).toHaveBeenCalledWith(7);
|
||||
expect(f.origins.record).toHaveBeenLastCalledWith(7, null, { kind: 'fixed', origin: 'plugin' });
|
||||
});
|
||||
});
|
||||
|
||||
@@ -154,6 +154,9 @@ export default defineConfig({
|
||||
// Landed on dev without an entry, so it sat on the 80 catch-all while
|
||||
// measuring 99.5/99.0/97.4/100 — the gap the per-domain ratchet exists to
|
||||
// close. Set with a few points of slack against the Linux/Windows drift.
|
||||
// New domain: community enrichment of place details. On the floor until a
|
||||
// full CI run measures it; raise it with scripts/coverage-thresholds.mjs then.
|
||||
'src/nest/place-contrib/**/*.ts': { statements: 80, branches: 80, functions: 80, lines: 80 },
|
||||
'src/nest/place-enrichment/**/*.ts': { statements: 96, branches: 95, functions: 94, lines: 97 },
|
||||
// New domain: the file and list readers that moved out of places/ and
|
||||
// collections/. On the floor until a full CI run measures it; raise it
|
||||
|
||||
@@ -116,6 +116,7 @@ export * from './collection/collection-file.schema';
|
||||
export * from './trip/trip.schema';
|
||||
export * from './place/place-hours';
|
||||
export * from './place/place-kind';
|
||||
export * from './place/place-contrib.schema';
|
||||
export * from './trip/day-grid';
|
||||
export * from './trip-invite/trip-invite.schema';
|
||||
export * from './collab/collab.schema';
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import {
|
||||
PLACE_CLIENT_ORIGINS,
|
||||
PLACE_FIELD_ORIGINS,
|
||||
placeContribDecisionRequestSchema,
|
||||
placeContribErrorSchema,
|
||||
placeContribImageAnswerSchema,
|
||||
placeContribLogQuerySchema,
|
||||
placeContribPlaceAnswerSchema,
|
||||
placeContribPlaceBodySchema,
|
||||
placeContribStateSchema,
|
||||
placeContribWithdrawRequestSchema,
|
||||
placeFieldOriginsSchema,
|
||||
} from './place-contrib.schema';
|
||||
import { placeCreateRequestSchema, placeUpdateRequestSchema } from './place.schema';
|
||||
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
const SWITCHES = { website: true, phone: true, email: false, opening_hours: true, description: true, image: false };
|
||||
|
||||
describe('placeFieldOriginsSchema', () => {
|
||||
it('takes a partial map of the client origins', () => {
|
||||
expect(placeFieldOriginsSchema.safeParse({}).success).toBe(true);
|
||||
expect(
|
||||
placeFieldOriginsSchema.safeParse({ website: 'user', phone: 'google', description: 'enrichment' }).success,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses the origins only the server decides', () => {
|
||||
for (const origin of ['agent', 'plugin', 'import', 'attachment', 'unknown']) {
|
||||
expect(placeFieldOriginsSchema.safeParse({ website: origin }).success, origin).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps the client list a subset of the stored one', () => {
|
||||
for (const origin of PLACE_CLIENT_ORIGINS) expect(PLACE_FIELD_ORIGINS).toContain(origin);
|
||||
});
|
||||
|
||||
it('rides on the place create and update contracts and is checked there', () => {
|
||||
expect(placeCreateRequestSchema.safeParse({ name: 'Café', fieldOrigins: { website: 'user' } }).success).toBe(true);
|
||||
expect(placeUpdateRequestSchema.safeParse({ fieldOrigins: { phone: 'osm' } }).success).toBe(true);
|
||||
expect(placeUpdateRequestSchema.safeParse({ fieldOrigins: { phone: 'agent' } }).success).toBe(false);
|
||||
expect(placeUpdateRequestSchema.safeParse({ fieldOrigins: 'user' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('placeContribDecisionRequestSchema', () => {
|
||||
it('takes each action with what it needs', () => {
|
||||
expect(
|
||||
placeContribDecisionRequestSchema.safeParse({ action: 'agree', termsVersion: 1, fields: SWITCHES }).success,
|
||||
).toBe(true);
|
||||
expect(placeContribDecisionRequestSchema.safeParse({ action: 'snooze' }).success).toBe(true);
|
||||
expect(placeContribDecisionRequestSchema.safeParse({ action: 'decline', termsVersion: 1 }).success).toBe(true);
|
||||
expect(
|
||||
placeContribDecisionRequestSchema.safeParse({ action: 'fields', fields: SWITCHES, withdraw: true }).success,
|
||||
).toBe(true);
|
||||
expect(placeContribDecisionRequestSchema.safeParse({ action: 'off' }).success).toBe(true);
|
||||
});
|
||||
|
||||
it('refuses an agreement without terms or with a partial set of switches', () => {
|
||||
expect(placeContribDecisionRequestSchema.safeParse({ action: 'agree', fields: SWITCHES }).success).toBe(false);
|
||||
expect(
|
||||
placeContribDecisionRequestSchema.safeParse({ action: 'agree', termsVersion: 1, fields: { website: true } })
|
||||
.success,
|
||||
).toBe(false);
|
||||
expect(placeContribDecisionRequestSchema.safeParse({ action: 'maybe' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('placeContribLogQuerySchema', () => {
|
||||
it('coerces the query strings and defaults the page', () => {
|
||||
expect(placeContribLogQuerySchema.parse({})).toEqual({ page: 1, perPage: 50 });
|
||||
expect(placeContribLogQuerySchema.parse({ page: '2', perPage: '10', result: 'withheld', field: 'phone' })).toEqual({
|
||||
page: 2,
|
||||
perPage: 10,
|
||||
result: 'withheld',
|
||||
field: 'phone',
|
||||
});
|
||||
expect(placeContribLogQuerySchema.safeParse({ result: 'sent' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('placeContribWithdrawRequestSchema', () => {
|
||||
it('needs the explicit confirmation', () => {
|
||||
expect(placeContribWithdrawRequestSchema.safeParse({ confirm: true }).success).toBe(true);
|
||||
expect(placeContribWithdrawRequestSchema.safeParse({}).success).toBe(false);
|
||||
expect(placeContribWithdrawRequestSchema.safeParse({ confirm: 'yes' }).success).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('placeContribStateSchema', () => {
|
||||
it('describes an undecided, eligible installation', () => {
|
||||
const state = {
|
||||
termsVersion: 1,
|
||||
ceiling: 'admin',
|
||||
eligible: true,
|
||||
ineligibleReason: null,
|
||||
consent: {
|
||||
enabled: false,
|
||||
fields: SWITCHES,
|
||||
termsVersion: null,
|
||||
decision: null,
|
||||
decidedBy: null,
|
||||
decidedAt: null,
|
||||
},
|
||||
showPrompt: true,
|
||||
snoozedUntil: null,
|
||||
active: false,
|
||||
counts: { accepted: 0, duplicate: 0, rejected: 0, withheld: 0, retracted: 0 },
|
||||
lastSuccessDay: null,
|
||||
queue: { size: 0, cap: 5000, full: false },
|
||||
pauseReason: null,
|
||||
registrationOpen: false,
|
||||
};
|
||||
expect(placeContribStateSchema.safeParse(state).success).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the central wire format', () => {
|
||||
it('builds a place body of at most the shareable text fields', () => {
|
||||
const body = {
|
||||
v: 1,
|
||||
termsVersion: 1,
|
||||
cid: 'c0ffee-1234',
|
||||
key: 'gers:08f2a1b3c4d5e6f7a8b9c0d1e2f3a4b5',
|
||||
fields: { website: { value: 'https://cafe-luna.de/', baseHash: 'a91e3f00' } },
|
||||
place: { name: 'Café Luna', lat: 54.08, lng: 12.13, country: 'DE' },
|
||||
};
|
||||
expect(placeContribPlaceBodySchema.safeParse(body).success).toBe(true);
|
||||
expect(placeContribPlaceBodySchema.safeParse({ ...body, cid: 'short' }).success).toBe(false);
|
||||
expect(
|
||||
placeContribPlaceBodySchema.safeParse({ ...body, fields: { image: { value: 'x', baseHash: null } } }).success,
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
it('reads the answers the service gives', () => {
|
||||
expect(
|
||||
placeContribPlaceAnswerSchema.safeParse({
|
||||
ok: true,
|
||||
cid: 'c0ffee-1234',
|
||||
duplicate: false,
|
||||
key: 'osm:node/42',
|
||||
community: { version: 3 },
|
||||
results: { website: { result: 'published', reason: null, flags: [] }, phone: { result: 'review' } },
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(
|
||||
placeContribPlaceAnswerSchema.safeParse({
|
||||
ok: true,
|
||||
cid: 'x',
|
||||
duplicate: false,
|
||||
key: 'k',
|
||||
results: { website: { result: 'sent' } },
|
||||
}).success,
|
||||
).toBe(false);
|
||||
expect(
|
||||
placeContribImageAnswerSchema.safeParse({
|
||||
ok: true,
|
||||
result: { result: 'review', image: '0123456789abcdef0123456789abcdef', sameAs: false },
|
||||
}).success,
|
||||
).toBe(true);
|
||||
expect(placeContribErrorSchema.safeParse({ error: 'field_not_accepted:email' }).success).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,320 @@
|
||||
import { paginationQuerySchema } from '../common/pagination.schema';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
/**
|
||||
* Community enrichment of place details: an installation sends the details its
|
||||
* users typed in (never what a provider, the assistant, a plugin or an import
|
||||
* filled) to the TREK Places API, so every installation gets better details
|
||||
* over time. Off until an admin agrees, for the whole installation.
|
||||
*
|
||||
* Three groups live here: where a place's value came from (origin tracking,
|
||||
* which the place write contracts carry), the admin surface under
|
||||
* /api/admin/places-contribute, and the wire format of the central service,
|
||||
* which the server validates every answer against.
|
||||
*/
|
||||
|
||||
/** The place details that can be shared. `image` is the place's own picture, the `image_url` column. */
|
||||
export const PLACE_CONTRIB_FIELDS = ['website', 'phone', 'email', 'opening_hours', 'description', 'image'] as const;
|
||||
export const placeContribFieldSchema = z.enum(PLACE_CONTRIB_FIELDS);
|
||||
export type PlaceContribField = z.infer<typeof placeContribFieldSchema>;
|
||||
|
||||
/**
|
||||
* Where the current value of a field came from. Only `user` is ever shared, and
|
||||
* only while the stored hash still matches the value. The server decides
|
||||
* `agent` (MCP), `plugin` (plugin RPC), `import` (file and list imports) and
|
||||
* `attachment` (a trip file made the picture); `unknown` is a changed value
|
||||
* nobody vouched for.
|
||||
*/
|
||||
export const PLACE_FIELD_ORIGINS = [
|
||||
'user',
|
||||
'attachment',
|
||||
'agent',
|
||||
'plugin',
|
||||
'import',
|
||||
'google',
|
||||
'amap',
|
||||
'osm',
|
||||
'trek',
|
||||
'wikimedia',
|
||||
'website',
|
||||
'unsplash',
|
||||
'enrichment',
|
||||
'unknown',
|
||||
] as const;
|
||||
export const placeFieldOriginSchema = z.enum(PLACE_FIELD_ORIGINS);
|
||||
export type PlaceFieldOrigin = z.infer<typeof placeFieldOriginSchema>;
|
||||
|
||||
/** The origins a client may report: the user, or the provider a search pick or a details lookup came from. */
|
||||
export const PLACE_CLIENT_ORIGINS = [
|
||||
'user',
|
||||
'google',
|
||||
'amap',
|
||||
'osm',
|
||||
'trek',
|
||||
'wikimedia',
|
||||
'website',
|
||||
'unsplash',
|
||||
'enrichment',
|
||||
] as const;
|
||||
export const placeClientOriginSchema = z.enum(PLACE_CLIENT_ORIGINS);
|
||||
export type PlaceClientOrigin = z.infer<typeof placeClientOriginSchema>;
|
||||
|
||||
/**
|
||||
* `fieldOrigins` on a place create or update: which fields of this write the
|
||||
* user typed and which a provider filled. Optional and partial; a changed field
|
||||
* without an entry is stored as `unknown`, and the server keeps the provider's
|
||||
* origin when a value claimed as typed equals what a provider supplied.
|
||||
*/
|
||||
export const placeFieldOriginsSchema = z.object({
|
||||
website: placeClientOriginSchema.optional(),
|
||||
phone: placeClientOriginSchema.optional(),
|
||||
email: placeClientOriginSchema.optional(),
|
||||
opening_hours: placeClientOriginSchema.optional(),
|
||||
description: placeClientOriginSchema.optional(),
|
||||
image: placeClientOriginSchema.optional(),
|
||||
});
|
||||
export type PlaceFieldOrigins = z.infer<typeof placeFieldOriginsSchema>;
|
||||
|
||||
// ── Consent and the admin surface ───────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* The version of the contribution terms the admin agrees to. Raised when the
|
||||
* text or the set of fields changes; sending stops until an admin agrees again.
|
||||
*/
|
||||
export const PLACE_CONTRIB_TERMS_VERSION = 1;
|
||||
|
||||
/** One switch per field. */
|
||||
export const placeContribFieldSwitchesSchema = z.object({
|
||||
website: z.boolean(),
|
||||
phone: z.boolean(),
|
||||
email: z.boolean(),
|
||||
opening_hours: z.boolean(),
|
||||
description: z.boolean(),
|
||||
image: z.boolean(),
|
||||
});
|
||||
export type PlaceContribFieldSwitches = z.infer<typeof placeContribFieldSwitchesSchema>;
|
||||
|
||||
/**
|
||||
* The installation's decision, as the `places_contribute` app setting holds it
|
||||
* and the admin state answers it. `decision` is null until an admin chose,
|
||||
* `declined` keeps the prompt away until the terms change, `off` is an
|
||||
* agreement taken back.
|
||||
*/
|
||||
export const placeContribConsentSchema = z.object({
|
||||
enabled: z.boolean(),
|
||||
fields: placeContribFieldSwitchesSchema,
|
||||
termsVersion: z.number().int().nonnegative().nullable(),
|
||||
decision: z.enum(['agreed', 'declined', 'off']).nullable(),
|
||||
decidedBy: z.number().int().positive().nullable(),
|
||||
decidedAt: z.string().nullable(),
|
||||
});
|
||||
export type PlaceContribConsent = z.infer<typeof placeContribConsentSchema>;
|
||||
|
||||
/**
|
||||
* Why this installation cannot send, checked in this order: the environment
|
||||
* ceiling, a non-production or demo instance, the index switched off, an own
|
||||
* TREK_PLACES_URL, TREK_SERVICES=off, no installation key (yet).
|
||||
*/
|
||||
export const placeContribIneligibleReasonSchema = z.enum([
|
||||
'env_off',
|
||||
'not_production',
|
||||
'demo',
|
||||
'index_off',
|
||||
'custom_places_url',
|
||||
'services_off',
|
||||
'no_key',
|
||||
]);
|
||||
export type PlaceContribIneligibleReason = z.infer<typeof placeContribIneligibleReasonSchema>;
|
||||
|
||||
/** Why sending waits although the admin agreed: a refused key, or the service not taking contributions now. */
|
||||
export const placeContribPauseReasonSchema = z.enum(['key_invalid', 'key_refused', 'not_accepting']);
|
||||
export type PlaceContribPauseReason = z.infer<typeof placeContribPauseReasonSchema>;
|
||||
|
||||
/** What became of one field, as the transmission log keeps it. */
|
||||
export const placeContribLogResultSchema = z.enum(['accepted', 'duplicate', 'rejected', 'withheld', 'retracted']);
|
||||
export type PlaceContribLogResult = z.infer<typeof placeContribLogResultSchema>;
|
||||
|
||||
const count = z.number().int().nonnegative();
|
||||
|
||||
/** GET /api/admin/places-contribute */
|
||||
export const placeContribStateSchema = z.object({
|
||||
/** The terms an agreement has to name. */
|
||||
termsVersion: z.number().int().positive(),
|
||||
/** TREK_PLACES_CONTRIBUTE. */
|
||||
ceiling: z.enum(['off', 'admin']),
|
||||
eligible: z.boolean(),
|
||||
ineligibleReason: placeContribIneligibleReasonSchema.nullable(),
|
||||
consent: placeContribConsentSchema,
|
||||
/** Whether this admin gets the prompt now: eligible, undecided for these terms, not snoozed. */
|
||||
showPrompt: z.boolean(),
|
||||
/** When this admin's "not now" ends (ISO), or null. */
|
||||
snoozedUntil: z.string().nullable(),
|
||||
/** Whether sending is on right now: eligible, agreed to the current terms, at least one field. */
|
||||
active: z.boolean(),
|
||||
/** Log rows of the last 30 days, per result. */
|
||||
counts: z.object({ accepted: count, duplicate: count, rejected: count, withheld: count, retracted: count }),
|
||||
/** The day (YYYY-MM-DD) of the last accepted field, or null. */
|
||||
lastSuccessDay: z.string().nullable(),
|
||||
queue: z.object({ size: count, cap: count, full: z.boolean() }),
|
||||
pauseReason: placeContribPauseReasonSchema.nullable(),
|
||||
/** Open registration: anyone can make an account and type details, which the prompt warns about. */
|
||||
registrationOpen: z.boolean(),
|
||||
});
|
||||
export type PlaceContribState = z.infer<typeof placeContribStateSchema>;
|
||||
|
||||
/**
|
||||
* PUT /api/admin/places-contribute/decision
|
||||
*
|
||||
* - `agree`: the prompt's "Agree", with the field switches it showed and the
|
||||
* terms version it was built for (a stale dialog answers 409).
|
||||
* - `snooze`: "Not now", for this admin, 14 days.
|
||||
* - `decline`: "No"; the prompt comes back only with new terms.
|
||||
* - `fields`: change the switches of an agreement; a field switched off drops
|
||||
* its queued values, and with `withdraw` also what was sent of it.
|
||||
* - `off`: the master switch off; the queue is emptied, and with `withdraw`
|
||||
* everything this installation sent is withdrawn.
|
||||
*/
|
||||
export const placeContribDecisionRequestSchema = z.discriminatedUnion('action', [
|
||||
z.object({
|
||||
action: z.literal('agree'),
|
||||
termsVersion: z.number().int().positive(),
|
||||
fields: placeContribFieldSwitchesSchema,
|
||||
}),
|
||||
z.object({ action: z.literal('snooze') }),
|
||||
z.object({ action: z.literal('decline'), termsVersion: z.number().int().positive() }),
|
||||
z.object({
|
||||
action: z.literal('fields'),
|
||||
fields: placeContribFieldSwitchesSchema,
|
||||
withdraw: z.boolean().optional(),
|
||||
}),
|
||||
z.object({ action: z.literal('off'), withdraw: z.boolean().optional() }),
|
||||
]);
|
||||
export type PlaceContribDecisionRequest = z.infer<typeof placeContribDecisionRequestSchema>;
|
||||
|
||||
/** GET /api/admin/places-contribute/log?page=&perPage=&result=&field= */
|
||||
export const placeContribLogQuerySchema = paginationQuerySchema.extend({
|
||||
result: placeContribLogResultSchema.optional(),
|
||||
field: placeContribFieldSchema.optional(),
|
||||
});
|
||||
export type PlaceContribLogQuery = z.infer<typeof placeContribLogQuerySchema>;
|
||||
|
||||
/** One line of the transmission log. No user, trip or row ids: the place's key and name, the field, what it said. */
|
||||
export const placeContribLogEntrySchema = z.object({
|
||||
id: z.number().int().positive(),
|
||||
day: z.string(),
|
||||
key: z.string(),
|
||||
placeName: z.string(),
|
||||
field: placeContribFieldSchema,
|
||||
valueSummary: z.string().nullable(),
|
||||
result: placeContribLogResultSchema,
|
||||
reason: z.string().nullable(),
|
||||
});
|
||||
export type PlaceContribLogEntry = z.infer<typeof placeContribLogEntrySchema>;
|
||||
|
||||
export const placeContribLogResponseSchema = z.object({
|
||||
entries: z.array(placeContribLogEntrySchema),
|
||||
total: count,
|
||||
page: z.number().int().positive(),
|
||||
perPage: z.number().int().positive(),
|
||||
});
|
||||
export type PlaceContribLogResponse = z.infer<typeof placeContribLogResponseSchema>;
|
||||
|
||||
/** POST /api/admin/places-contribute/withdraw: the confirmation the button sends. */
|
||||
export const placeContribWithdrawRequestSchema = z.object({ confirm: z.literal(true) });
|
||||
export type PlaceContribWithdrawRequest = z.infer<typeof placeContribWithdrawRequestSchema>;
|
||||
|
||||
/** What the service withdrew, per kind as it counts them, and how many queued values were dropped here. */
|
||||
export const placeContribWithdrawResponseSchema = z.object({
|
||||
withdrawn: z.record(z.string(), count),
|
||||
cleared: count,
|
||||
});
|
||||
export type PlaceContribWithdrawResponse = z.infer<typeof placeContribWithdrawResponseSchema>;
|
||||
|
||||
// ── The central service's wire format ───────────────────────────────────────
|
||||
|
||||
/** What the service made of one field. */
|
||||
export const placeContribFieldResultSchema = z.enum([
|
||||
'published',
|
||||
'checking',
|
||||
'review',
|
||||
'unchanged',
|
||||
'rejected',
|
||||
'quota',
|
||||
]);
|
||||
export type PlaceContribFieldResult = z.infer<typeof placeContribFieldResultSchema>;
|
||||
|
||||
/** The idempotency id of one request. */
|
||||
export const placeContribCidSchema = z.string().regex(/^[A-Za-z0-9_-]{8,64}$/);
|
||||
|
||||
const shortText = z.string().max(200);
|
||||
|
||||
/** POST /v1/contrib/place: one place, the fields of it this installation's users typed in. */
|
||||
export const placeContribPlaceBodySchema = z.object({
|
||||
v: z.literal(1),
|
||||
termsVersion: z.number().int().positive(),
|
||||
cid: placeContribCidSchema,
|
||||
key: z.string().max(80),
|
||||
fields: z.partialRecord(
|
||||
placeContribFieldSchema.exclude(['image']),
|
||||
z.object({
|
||||
value: z.string().min(1).max(4000),
|
||||
baseHash: z
|
||||
.string()
|
||||
.regex(/^[0-9a-f]{8,64}$/)
|
||||
.nullable(),
|
||||
}),
|
||||
),
|
||||
place: z.object({
|
||||
name: z.string().max(200),
|
||||
lat: z.number().nullable(),
|
||||
lng: z.number().nullable(),
|
||||
country: z.string().length(2).nullable(),
|
||||
}),
|
||||
});
|
||||
export type PlaceContribPlaceBody = z.infer<typeof placeContribPlaceBodySchema>;
|
||||
|
||||
/** Its 200 answer. */
|
||||
export const placeContribPlaceAnswerSchema = z.object({
|
||||
ok: z.literal(true),
|
||||
cid: z.string().max(64),
|
||||
duplicate: z.boolean(),
|
||||
key: z.string().max(80),
|
||||
community: z.object({ version: z.number().int().nonnegative() }).nullable().optional(),
|
||||
results: z.partialRecord(
|
||||
placeContribFieldSchema,
|
||||
z.object({
|
||||
result: placeContribFieldResultSchema,
|
||||
reason: shortText.nullable().optional(),
|
||||
flags: z.array(z.string().max(64)).max(32).optional(),
|
||||
}),
|
||||
),
|
||||
});
|
||||
export type PlaceContribPlaceAnswer = z.infer<typeof placeContribPlaceAnswerSchema>;
|
||||
|
||||
/** POST /v1/contrib/image's 200 answer. */
|
||||
export const placeContribImageAnswerSchema = z.object({
|
||||
ok: z.literal(true),
|
||||
result: z.object({
|
||||
result: z.enum(['review', 'published', 'rejected', 'quota']),
|
||||
image: z
|
||||
.string()
|
||||
.regex(/^[0-9a-f]{32}$/)
|
||||
.nullable()
|
||||
.optional(),
|
||||
sameAs: z.boolean().optional(),
|
||||
reason: shortText.nullable().optional(),
|
||||
}),
|
||||
});
|
||||
export type PlaceContribImageAnswer = z.infer<typeof placeContribImageAnswerSchema>;
|
||||
|
||||
/** DELETE /v1/contrib/install's 200 answer. */
|
||||
export const placeContribWithdrawAnswerSchema = z.object({
|
||||
ok: z.literal(true),
|
||||
withdrawn: z.record(z.string(), z.unknown()).optional(),
|
||||
});
|
||||
export type PlaceContribWithdrawAnswer = z.infer<typeof placeContribWithdrawAnswerSchema>;
|
||||
|
||||
/** Every refusal: `{ error: "<code>" }`, `field_not_accepted:<name>` naming the field. */
|
||||
export const placeContribErrorSchema = z.object({ error: shortText });
|
||||
export type PlaceContribError = z.infer<typeof placeContribErrorSchema>;
|
||||
@@ -1,4 +1,5 @@
|
||||
import { tagSchema } from '../tag/tag.schema';
|
||||
import { placeFieldOriginsSchema } from './place-contrib.schema';
|
||||
import { placeEmailField, placeOpeningHoursField } from './place-hours';
|
||||
import { PLACE_WEBSITE_MAX_LENGTH, normalizePlaceWebsite } from './place-website';
|
||||
|
||||
@@ -267,6 +268,9 @@ const stopTypeField = z.object({
|
||||
// outside it on purpose — a stop that fills nothing is not a stop, and letting one
|
||||
// through would leave a range budget that never resets.
|
||||
fill_percent: fillPercentSchema,
|
||||
// Which fields of this write the user typed and which a provider filled, for the
|
||||
// community enrichment (place-contrib.schema.ts). Never stored on the place itself.
|
||||
fieldOrigins: placeFieldOriginsSchema.optional(),
|
||||
});
|
||||
|
||||
export const placeCreateRequestSchema = open.and(z.object({ name: z.string().min(1) })).and(stopTypeField);
|
||||
|
||||
Reference in New Issue
Block a user