From 382ba79584e460a71d6e4da14a083fce9de381cc Mon Sep 17 00:00:00 2001 From: Maurice Date: Sun, 29 Nov 2026 21:16:30 +0100 Subject: [PATCH] feat(places): visits read from trips, change history, linked tours and bookings, personal tags A visit is a place planned on a day of one of the reader's trips; nothing is kept or confirmed by hand. A place keeps a log of changes to its details, links the tours and bookings it is about, and carries tags private to the reader, which a copy into a trip takes along only when picked. Contracts, routes, MCP tools and migrations for both engines. --- server/scripts/repository-owners.json | 3 + server/scripts/size-baseline.json | 2 +- .../db/entities/CollectionPlaces.entity.ts | 9 + .../src/db/entities/CollectionTours.entity.ts | 5 +- server/src/db/entities/Collections.entity.ts | 3 + .../db/entities/PersonalPlaceTags.entity.ts | 49 +++ .../db/entities/PlaceActivityLinks.entity.ts | 59 +++ .../src/db/entities/PlaceChangeLog.entity.ts | 52 +++ server/src/db/entities/Places.entity.ts | 9 + server/src/db/entities/Reservations.entity.ts | 3 + server/src/db/entities/Tags.entity.ts | 3 + server/src/db/entities/Tours.entity.ts | 3 + server/src/db/entities/UserPlaces.entity.ts | 3 + server/src/db/entities/Users.entity.ts | 6 + server/src/db/entities/index.ts | 6 + .../src/db/kysely/PersonalPlaceTags.table.ts | 12 + .../src/db/kysely/PlaceActivityLinks.table.ts | 14 + server/src/db/kysely/PlaceChangeLog.table.ts | 16 + server/src/db/kysely/db.ts | 6 + ..._place_keeps_the_history_of_its_details.ts | 61 +++ ...inks_the_tours_and_bookings_it_is_about.ts | 63 +++ ...6580_a_person_tags_the_places_they_keep.ts | 57 +++ .../PersonalPlaceTags.repository.ts | 119 ++++++ .../PlaceActivityLinks.repository.ts | 391 ++++++++++++++++++ .../repositories/PlaceChangeLog.repository.ts | 232 +++++++++++ .../PlaceVisitContext.repository.ts | 293 +++++++++++++ .../repositories/PlacesLibrary.repository.ts | 140 ++++++- server/src/nest/app.module.ts | 6 + .../nest/assistant/assistant-tool-offer.ts | 29 +- .../nest/collections/collections.helpers.ts | 39 ++ .../src/nest/collections/collections.mcp.ts | 2 +- .../nest/collections/collections.module.ts | 3 + .../nest/collections/collections.service.ts | 27 +- server/src/nest/maps/maps.module.ts | 2 + server/src/nest/maps/place-photo.resolver.ts | 10 +- .../place-activities-library.controller.ts | 35 ++ .../place-activities-library.service.ts | 71 ++++ .../place-activities.controller.ts | 96 +++++ .../place-activities/place-activities.dto.ts | 7 + .../place-activities.helpers.ts | 192 +++++++++ .../place-activities/place-activities.mcp.ts | 94 +++++ .../place-activities.module.ts | 38 ++ .../place-activities.service.ts | 304 ++++++++++++++ .../saved-place-activities.controller.ts | 61 +++ .../saved-place-activities.mcp.ts | 120 ++++++ .../place-changes/place-changes.helpers.ts | 88 ++++ .../place-changes/place-changes.module.ts | 16 + .../place-changes/place-changes.service.ts | 120 ++++++ .../nest/place-changes/place-changes.types.ts | 14 + .../place-history.controller.ts | 45 ++ .../nest/places-library/place-history.dto.ts | 5 + .../nest/places-library/place-history.mcp.ts | 48 +++ .../places-library/place-history.module.ts | 22 + .../places-library/place-history.service.ts | 105 +++++ .../places-library/place-media.controller.ts | 35 ++ .../places-library/place-media.service.ts | 145 +++++++ .../places-library/place-tags.controller.ts | 38 ++ .../nest/places-library/place-tags.helpers.ts | 70 ++++ .../src/nest/places-library/place-tags.mcp.ts | 65 +++ .../nest/places-library/place-tags.service.ts | 99 +++++ .../place-visits-reader.service.ts | 93 +++++ .../place-visits-trip.controller.ts | 27 ++ .../nest/places-library/place-visits.clock.ts | 12 + .../places-library/place-visits.controller.ts | 32 ++ .../nest/places-library/place-visits.dto.ts | 6 + .../places-library/place-visits.helpers.ts | 163 ++++++++ .../nest/places-library/place-visits.mcp.ts | 90 ++++ .../places-library/place-visits.module.ts | 34 ++ .../places-library/place-visits.service.ts | 121 ++++++ .../nest/places-library/places-library.dto.ts | 6 + .../places-library/places-library.helpers.ts | 3 + .../nest/places-library/places-library.mcp.ts | 2 +- .../places-library/places-library.module.ts | 35 +- .../places-library/places-library.service.ts | 27 +- server/src/nest/places/places.controller.ts | 19 +- server/src/nest/places/places.mcp.ts | 6 +- server/src/nest/places/places.module.ts | 3 + server/src/nest/places/places.rpc.ts | 8 +- server/src/nest/places/places.service.ts | 65 ++- server/src/nest/tags/tag-writes.service.ts | 8 +- server/src/nest/tags/tags.mcp.ts | 3 +- server/src/nest/tags/tags.service.ts | 51 ++- server/tests/e2e/place-activities.e2e.test.ts | 197 +++++++++ server/tests/e2e/place-history.e2e.test.ts | 242 +++++++++++ server/tests/e2e/place-tags.e2e.test.ts | 201 +++++++++ server/tests/e2e/place-visits.e2e.test.ts | 183 ++++++++ .../helpers/factories/place-activities.ts | 46 +++ server/tests/helpers/maps-service.ts | 3 +- .../tests/helpers/place-activities-fixture.ts | 52 +++ server/tests/helpers/place-changes.ts | 13 + server/tests/helpers/plugin-host.ts | 5 +- .../broadcast-parity/plan.cases.ts | 26 ++ .../broadcast-parity/user.cases.ts | 53 +++ server/tests/unit/db/entities-index.test.ts | 9 +- .../tests/unit/db/entity-class-fields.test.ts | 5 +- server/tests/unit/db/legacy-baseline.test.ts | 3 + .../PlaceActivityLinks.repository.test.ts | 183 ++++++++ .../PlaceChangeLog.repository.test.ts | 179 ++++++++ .../unit/nest/collections.service.test.ts | 6 +- .../nest/collections.tags-to-carry.test.ts | 55 +++ .../unit/nest/common/conflictUpdate.test.ts | 2 + .../nest/maps.place-photo-resolver.test.ts | 2 + .../place-activities.controller.test.ts | 105 +++++ .../place-activities.helpers.test.ts | 145 +++++++ .../place-activities.mcp.test.ts | 142 +++++++ .../place-activities.service.test.ts | 339 +++++++++++++++ .../place-changes.helpers.test.ts | 109 +++++ .../place-changes.service.test.ts | 145 +++++++ .../place-history.service.test.ts | 185 +++++++++ .../place-tags.controller.test.ts | 33 ++ .../places-library/place-tags.helpers.test.ts | 90 ++++ .../places-library/place-tags.mcp.test.ts | 106 +++++ .../places-library/place-tags.service.test.ts | 251 +++++++++++ .../place-visits.controller.test.ts | 66 +++ .../place-visits.helpers.test.ts | 150 +++++++ .../places-library/place-visits.mcp.test.ts | 112 +++++ .../place-visits.service.test.ts | 283 +++++++++++++ .../places-library.service.test.ts | 11 +- .../tests/unit/nest/places.directions.test.ts | 2 + server/tests/unit/nest/places.service.test.ts | 4 +- .../unit/nest/tag-writes.service.test.ts | 71 ++++ server/tests/unit/nest/tags.service.test.ts | 33 +- .../tests/unit/nest/tours.gpx.atomic.test.ts | 2 + .../unit/nest/trip-read-model.service.test.ts | 2 + server/tests/unit/nest/trips.service.test.ts | 6 +- server/vitest.config.ts | 6 + shared/src/collection/collection.schema.ts | 7 + shared/src/index.ts | 8 + .../place-activities.schema.spec.ts | 123 ++++++ .../places-library/place-activities.schema.ts | 160 +++++++ .../place-history.schema.spec.ts | 68 +++ .../places-library/place-history.schema.ts | 119 ++++++ .../places-library/place-tags.schema.spec.ts | 87 ++++ .../src/places-library/place-tags.schema.ts | 67 +++ .../place-visits.schema.spec.ts | 92 +++++ .../src/places-library/place-visits.schema.ts | 166 ++++++++ .../places-library/places-library.schema.ts | 54 ++- shared/src/realtime/events.schema.spec.ts | 9 +- shared/src/realtime/events.schema.ts | 5 + 139 files changed, 9196 insertions(+), 116 deletions(-) create mode 100644 server/src/db/entities/PersonalPlaceTags.entity.ts create mode 100644 server/src/db/entities/PlaceActivityLinks.entity.ts create mode 100644 server/src/db/entities/PlaceChangeLog.entity.ts create mode 100644 server/src/db/kysely/PersonalPlaceTags.table.ts create mode 100644 server/src/db/kysely/PlaceActivityLinks.table.ts create mode 100644 server/src/db/kysely/PlaceChangeLog.table.ts create mode 100644 server/src/db/migrations/Migration20200101046550_a_place_keeps_the_history_of_its_details.ts create mode 100644 server/src/db/migrations/Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about.ts create mode 100644 server/src/db/migrations/Migration20200101046580_a_person_tags_the_places_they_keep.ts create mode 100644 server/src/db/repositories/PersonalPlaceTags.repository.ts create mode 100644 server/src/db/repositories/PlaceActivityLinks.repository.ts create mode 100644 server/src/db/repositories/PlaceChangeLog.repository.ts create mode 100644 server/src/db/repositories/PlaceVisitContext.repository.ts create mode 100644 server/src/nest/place-activities/place-activities-library.controller.ts create mode 100644 server/src/nest/place-activities/place-activities-library.service.ts create mode 100644 server/src/nest/place-activities/place-activities.controller.ts create mode 100644 server/src/nest/place-activities/place-activities.dto.ts create mode 100644 server/src/nest/place-activities/place-activities.helpers.ts create mode 100644 server/src/nest/place-activities/place-activities.mcp.ts create mode 100644 server/src/nest/place-activities/place-activities.module.ts create mode 100644 server/src/nest/place-activities/place-activities.service.ts create mode 100644 server/src/nest/place-activities/saved-place-activities.controller.ts create mode 100644 server/src/nest/place-activities/saved-place-activities.mcp.ts create mode 100644 server/src/nest/place-changes/place-changes.helpers.ts create mode 100644 server/src/nest/place-changes/place-changes.module.ts create mode 100644 server/src/nest/place-changes/place-changes.service.ts create mode 100644 server/src/nest/place-changes/place-changes.types.ts create mode 100644 server/src/nest/places-library/place-history.controller.ts create mode 100644 server/src/nest/places-library/place-history.dto.ts create mode 100644 server/src/nest/places-library/place-history.mcp.ts create mode 100644 server/src/nest/places-library/place-history.module.ts create mode 100644 server/src/nest/places-library/place-history.service.ts create mode 100644 server/src/nest/places-library/place-media.controller.ts create mode 100644 server/src/nest/places-library/place-media.service.ts create mode 100644 server/src/nest/places-library/place-tags.controller.ts create mode 100644 server/src/nest/places-library/place-tags.helpers.ts create mode 100644 server/src/nest/places-library/place-tags.mcp.ts create mode 100644 server/src/nest/places-library/place-tags.service.ts create mode 100644 server/src/nest/places-library/place-visits-reader.service.ts create mode 100644 server/src/nest/places-library/place-visits-trip.controller.ts create mode 100644 server/src/nest/places-library/place-visits.clock.ts create mode 100644 server/src/nest/places-library/place-visits.controller.ts create mode 100644 server/src/nest/places-library/place-visits.dto.ts create mode 100644 server/src/nest/places-library/place-visits.helpers.ts create mode 100644 server/src/nest/places-library/place-visits.mcp.ts create mode 100644 server/src/nest/places-library/place-visits.module.ts create mode 100644 server/src/nest/places-library/place-visits.service.ts create mode 100644 server/tests/e2e/place-activities.e2e.test.ts create mode 100644 server/tests/e2e/place-history.e2e.test.ts create mode 100644 server/tests/e2e/place-tags.e2e.test.ts create mode 100644 server/tests/e2e/place-visits.e2e.test.ts create mode 100644 server/tests/helpers/factories/place-activities.ts create mode 100644 server/tests/helpers/place-activities-fixture.ts create mode 100644 server/tests/helpers/place-changes.ts create mode 100644 server/tests/unit/db/repositories/PlaceActivityLinks.repository.test.ts create mode 100644 server/tests/unit/db/repositories/PlaceChangeLog.repository.test.ts create mode 100644 server/tests/unit/nest/collections.tags-to-carry.test.ts create mode 100644 server/tests/unit/nest/place-activities/place-activities.controller.test.ts create mode 100644 server/tests/unit/nest/place-activities/place-activities.helpers.test.ts create mode 100644 server/tests/unit/nest/place-activities/place-activities.mcp.test.ts create mode 100644 server/tests/unit/nest/place-activities/place-activities.service.test.ts create mode 100644 server/tests/unit/nest/place-changes/place-changes.helpers.test.ts create mode 100644 server/tests/unit/nest/place-changes/place-changes.service.test.ts create mode 100644 server/tests/unit/nest/places-library/place-history.service.test.ts create mode 100644 server/tests/unit/nest/places-library/place-tags.controller.test.ts create mode 100644 server/tests/unit/nest/places-library/place-tags.helpers.test.ts create mode 100644 server/tests/unit/nest/places-library/place-tags.mcp.test.ts create mode 100644 server/tests/unit/nest/places-library/place-tags.service.test.ts create mode 100644 server/tests/unit/nest/places-library/place-visits.controller.test.ts create mode 100644 server/tests/unit/nest/places-library/place-visits.helpers.test.ts create mode 100644 server/tests/unit/nest/places-library/place-visits.mcp.test.ts create mode 100644 server/tests/unit/nest/places-library/place-visits.service.test.ts create mode 100644 server/tests/unit/nest/tag-writes.service.test.ts create mode 100644 shared/src/places-library/place-activities.schema.spec.ts create mode 100644 shared/src/places-library/place-activities.schema.ts create mode 100644 shared/src/places-library/place-history.schema.spec.ts create mode 100644 shared/src/places-library/place-history.schema.ts create mode 100644 shared/src/places-library/place-tags.schema.spec.ts create mode 100644 shared/src/places-library/place-tags.schema.ts create mode 100644 shared/src/places-library/place-visits.schema.spec.ts create mode 100644 shared/src/places-library/place-visits.schema.ts diff --git a/server/scripts/repository-owners.json b/server/scripts/repository-owners.json index 55e2a81be..26cacd76d 100644 --- a/server/scripts/repository-owners.json +++ b/server/scripts/repository-owners.json @@ -82,9 +82,12 @@ "PaddleRegions": "paddle-obstacles", "PaddleWaterGraphs": "paddle-routing", "PasswordResetTokens": "auth", + "PersonalPlaceTags": "places-library", "PhotoProviderFields": "addons", "PhotoProviders": "addons", "Photos": "photos", + "PlaceActivityLinks": "place-activities", + "PlaceChangeLog": "place-changes", "PlaceContribLog": "place-contrib", "PlaceContribOutbox": "place-contrib", "PlaceDetailsCache": "maps", diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index 2c51dbcc1..c421476d6 100644 --- a/server/scripts/size-baseline.json +++ b/server/scripts/size-baseline.json @@ -8,7 +8,7 @@ "src/nest/atlas/atlas.service.ts": 1166, "src/nest/auth/auth.service.ts": 1115, "src/nest/budget/budget.service.ts": 1607, - "src/nest/collections/collections.service.ts": 1398, + "src/nest/collections/collections.service.ts": 1397, "src/nest/doc-sync/doc-sync.service.ts": 1060, "src/nest/doc-sync/providers/synology-drive.client.ts": 1160, "src/nest/journey/journey-domain.service.ts": 1659, diff --git a/server/src/db/entities/CollectionPlaces.entity.ts b/server/src/db/entities/CollectionPlaces.entity.ts index cb8e2448c..88cdeae31 100644 --- a/server/src/db/entities/CollectionPlaces.entity.ts +++ b/server/src/db/entities/CollectionPlaces.entity.ts @@ -5,6 +5,9 @@ import { Categories } from './Categories.entity'; import { CollectionLabels } from './CollectionLabels.entity'; import { CollectionPlaceRatings } from './CollectionPlaceRatings.entity'; import { Collections } from './Collections.entity'; +import { PersonalPlaceTags } from './PersonalPlaceTags.entity'; +import { PlaceActivityLinks } from './PlaceActivityLinks.entity'; +import { PlaceChangeLog } from './PlaceChangeLog.entity'; import { Tags } from './Tags.entity'; import { UserPlaceLinks } from './UserPlaceLinks.entity'; import { Users } from './Users.entity'; @@ -44,6 +47,9 @@ export class CollectionPlaces { collection_place_labels = new Collection(this); collection_place_tags = new Collection(this); collection_place_ratings_collection = new Collection(this); + personal_place_tags_collection = new Collection(this); + place_activity_links_collection = new Collection(this); + place_change_log_collection = new Collection(this); user_place_links_collection = new Collection(this); } @@ -84,6 +90,9 @@ export const CollectionPlacesSchema = defineEntity({ collection_place_labels: () => p.manyToMany(CollectionLabels).pivotTable('collection_place_labels').joinColumn('collection_place_id').inverseJoinColumn('label_id').hidden(), collection_place_tags: () => p.manyToMany(Tags).pivotTable('collection_place_tags').joinColumn('collection_place_id').inverseJoinColumn('tag_id').hidden(), collection_place_ratings_collection: () => p.oneToMany(CollectionPlaceRatings).mappedBy('collectionPlace').hidden(), + personal_place_tags_collection: () => p.oneToMany(PersonalPlaceTags).mappedBy('collectionPlace').hidden(), + place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('collectionPlace').hidden(), + place_change_log_collection: () => p.oneToMany(PlaceChangeLog).mappedBy('collectionPlace').hidden(), user_place_links_collection: () => p.oneToMany(UserPlaceLinks).mappedBy('collectionPlace').hidden(), }, }); diff --git a/server/src/db/entities/CollectionTours.entity.ts b/server/src/db/entities/CollectionTours.entity.ts index 960f3f8bb..976bc46fe 100644 --- a/server/src/db/entities/CollectionTours.entity.ts +++ b/server/src/db/entities/CollectionTours.entity.ts @@ -1,7 +1,8 @@ -import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core'; +import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core'; import { CollectionToursRepository } from '../repositories/CollectionTours.repository'; import { DbTimestampType } from '../types'; import { Collections } from './Collections.entity'; +import { PlaceActivityLinks } from './PlaceActivityLinks.entity'; import { TourTypes } from './TourTypes.entity'; import { Users } from './Users.entity'; @@ -49,6 +50,7 @@ export class CollectionTours { ski_options?: string | null; tourTypeRef!: Ref; savedByRef?: Ref | null; + place_activity_links_collection = new Collection(this); } export const CollectionToursSchema = defineEntity({ @@ -97,5 +99,6 @@ export const CollectionToursSchema = defineEntity({ ski_options: p.text().nullable(), tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_collection_tours_tour_type'), savedByRef: () => p.manyToOne(Users).ref().joinColumn('saved_by').nullable().hidden().index('idx_collection_tours_saved_by'), + place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('collectionTour').hidden(), }, }); diff --git a/server/src/db/entities/Collections.entity.ts b/server/src/db/entities/Collections.entity.ts index 712f344f5..79c374d7e 100644 --- a/server/src/db/entities/Collections.entity.ts +++ b/server/src/db/entities/Collections.entity.ts @@ -5,6 +5,7 @@ import { CollectionLabels } from './CollectionLabels.entity'; import { CollectionMembers } from './CollectionMembers.entity'; import { CollectionPlaces } from './CollectionPlaces.entity'; import { CollectionTours } from './CollectionTours.entity'; +import { PlaceChangeLog } from './PlaceChangeLog.entity'; import { TripCollectionLinks } from './TripCollectionLinks.entity'; import { Users } from './Users.entity'; @@ -26,6 +27,7 @@ export class Collections { collection_members_collection = new Collection(this); collection_places_collection = new Collection(this); collection_tours_collection = new Collection(this); + place_change_log_collection = new Collection(this); trip_collection_links_collection = new Collection(this); } @@ -49,6 +51,7 @@ export const CollectionsSchema = defineEntity({ collection_members_collection: () => p.oneToMany(CollectionMembers).mappedBy('collection').hidden(), collection_places_collection: () => p.oneToMany(CollectionPlaces).mappedBy('collection').hidden(), collection_tours_collection: () => p.oneToMany(CollectionTours).mappedBy('collection').hidden(), + place_change_log_collection: () => p.oneToMany(PlaceChangeLog).mappedBy('collection').hidden(), trip_collection_links_collection: () => p.oneToMany(TripCollectionLinks).mappedBy('collection').hidden(), }, }); diff --git a/server/src/db/entities/PersonalPlaceTags.entity.ts b/server/src/db/entities/PersonalPlaceTags.entity.ts new file mode 100644 index 000000000..17569a53f --- /dev/null +++ b/server/src/db/entities/PersonalPlaceTags.entity.ts @@ -0,0 +1,49 @@ +import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core'; +import { PersonalPlaceTagsRepository } from '../repositories/PersonalPlaceTags.repository'; +import { DbTimestampType } from '../types'; +import { CollectionPlaces } from './CollectionPlaces.entity'; +import { Places } from './Places.entity'; +import { Tags } from './Tags.entity'; +import { UserPlaces } from './UserPlaces.entity'; + +export class PersonalPlaceTags { + [EntityRepositoryType]?: PersonalPlaceTagsRepository; + id!: number & Opt; + tag!: Ref; + tag_id!: number; + userPlace?: Ref | null; + user_place_id?: number | null; + place?: Ref | null; + place_id?: number | null; + collectionPlace?: Ref | null; + collection_place_id?: number | null; + created_at?: string | null; +} + +export const PersonalPlaceTagsSchema = defineEntity({ + class: PersonalPlaceTags, + repository: () => PersonalPlaceTagsRepository, + uniques: [ + { properties: ['tag', 'collectionPlace'] }, + { properties: ['tag', 'place'] }, + { properties: ['tag', 'userPlace'] }, + ], + checks: [ + { + name: 'personal_place_tags_collection_place_id_check', + expression: '(user_place_id IS NOT NULL AND place_id IS NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NOT NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NULL AND collection_place_id IS NOT NULL)', + }, + ], + properties: { + id: p.integer().primary(), + tag: () => p.manyToOne(Tags).ref().deleteRule('cascade').hidden(), + tag_id: p.integer().persist(false), + userPlace: () => p.manyToOne(UserPlaces).ref().deleteRule('cascade').nullable().hidden().index('idx_personal_place_tags_user_place_id'), + user_place_id: p.integer().nullable().persist(false).index('idx_personal_place_tags_user_place_id'), + place: () => p.manyToOne(Places).ref().deleteRule('cascade').nullable().hidden().index('idx_personal_place_tags_place_id'), + place_id: p.integer().nullable().persist(false).index('idx_personal_place_tags_place_id'), + collectionPlace: () => p.manyToOne(CollectionPlaces).ref().deleteRule('cascade').nullable().hidden().index('idx_personal_place_tags_collection_place_id'), + collection_place_id: p.integer().nullable().persist(false).index('idx_personal_place_tags_collection_place_id'), + created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), + }, +}); diff --git a/server/src/db/entities/PlaceActivityLinks.entity.ts b/server/src/db/entities/PlaceActivityLinks.entity.ts new file mode 100644 index 000000000..2fcb1f733 --- /dev/null +++ b/server/src/db/entities/PlaceActivityLinks.entity.ts @@ -0,0 +1,59 @@ +import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core'; +import { PlaceActivityLinksRepository } from '../repositories/PlaceActivityLinks.repository'; +import { DbTimestampType } from '../types'; +import { CollectionPlaces } from './CollectionPlaces.entity'; +import { CollectionTours } from './CollectionTours.entity'; +import { Places } from './Places.entity'; +import { Reservations } from './Reservations.entity'; +import { Tours } from './Tours.entity'; +import { Users } from './Users.entity'; + +export class PlaceActivityLinks { + [EntityRepositoryType]?: PlaceActivityLinksRepository; + id!: number & Opt; + place?: Ref | null; + place_id?: number | null; + reservation?: Ref | null; + reservation_id?: number | null; + tourPlace?: Ref | null; + tour_place_id?: number | null; + collectionPlace?: Ref | null; + collection_place_id?: number | null; + collectionTour?: Ref | null; + collection_tour_id?: number | null; + linked_by?: number | null; + created_at?: string | null; + linkedByRef?: Ref | null; +} + +export const PlaceActivityLinksSchema = defineEntity({ + class: PlaceActivityLinks, + repository: () => PlaceActivityLinksRepository, + uniques: [ + { properties: ['collectionPlace', 'collectionTour'] }, + { properties: ['place', 'tourPlace'] }, + { properties: ['place', 'reservation'] }, + ], + checks: [ + { + name: 'place_activity_links_collection_tour_id_check', + expression: '(place_id IS NOT NULL AND collection_place_id IS NULL AND collection_tour_id IS NULL AND (reservation_id IS NULL) <> (tour_place_id IS NULL)) OR (place_id IS NULL AND reservation_id IS NULL AND tour_place_id IS NULL AND collection_place_id IS NOT NULL AND collection_tour_id IS NOT NULL)', + }, + ], + properties: { + id: p.integer().primary(), + place: () => p.manyToOne(Places).ref().deleteRule('cascade').nullable().hidden(), + place_id: p.integer().nullable().persist(false), + reservation: () => p.manyToOne(Reservations).ref().deleteRule('cascade').nullable().hidden().index('idx_place_activity_links_reservation_id'), + reservation_id: p.integer().nullable().persist(false).index('idx_place_activity_links_reservation_id'), + tourPlace: () => p.manyToOne(Tours).ref().joinColumn('tour_place_id').deleteRule('cascade').nullable().hidden().index('idx_place_activity_links_tour_place_id'), + tour_place_id: p.integer().nullable().persist(false).index('idx_place_activity_links_tour_place_id'), + collectionPlace: () => p.manyToOne(CollectionPlaces).ref().deleteRule('cascade').nullable().hidden(), + collection_place_id: p.integer().nullable().persist(false), + collectionTour: () => p.manyToOne(CollectionTours).ref().deleteRule('cascade').nullable().hidden().index('idx_place_activity_links_collection_tour_id'), + collection_tour_id: p.integer().nullable().persist(false).index('idx_place_activity_links_collection_tour_id'), + linked_by: p.integer().nullable().persist(false).index('idx_place_activity_links_linked_by'), + created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), + linkedByRef: () => p.manyToOne(Users).ref().joinColumn('linked_by').nullable().hidden().index('idx_place_activity_links_linked_by'), + }, +}); diff --git a/server/src/db/entities/PlaceChangeLog.entity.ts b/server/src/db/entities/PlaceChangeLog.entity.ts new file mode 100644 index 000000000..924a96d1c --- /dev/null +++ b/server/src/db/entities/PlaceChangeLog.entity.ts @@ -0,0 +1,52 @@ +import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core'; +import { PlaceChangeLogRepository } from '../repositories/PlaceChangeLog.repository'; +import { DbTimestampType } from '../types'; +import { CollectionPlaces } from './CollectionPlaces.entity'; +import { Collections } from './Collections.entity'; +import { Places } from './Places.entity'; +import { Users } from './Users.entity'; + +export class PlaceChangeLog { + [EntityRepositoryType]?: PlaceChangeLogRepository; + id!: number & Opt; + place?: Ref | null; + place_id?: number | null; + collectionPlace?: Ref | null; + collection_place_id?: number | null; + collection?: Ref | null; + collection_id?: number | null; + field!: string; + old_value?: string | null; + new_value?: string | null; + user?: Ref | null; + user_id?: number | null; + automatic: number & Opt = 0; + created_at?: string | null; +} + +export const PlaceChangeLogSchema = defineEntity({ + class: PlaceChangeLog, + repository: () => PlaceChangeLogRepository, + checks: [ + { + name: 'place_change_log_collection_id_check', + expression: '(place_id IS NULL) <> (collection_place_id IS NULL) AND (collection_id IS NULL) = (collection_place_id IS NULL)', + }, + ], + properties: { + id: p.integer().primary(), + place: () => p.manyToOne(Places).ref().deleteRule('cascade').nullable().hidden().index('idx_place_change_log_place_id'), + place_id: p.integer().nullable().persist(false).index('idx_place_change_log_place_id'), + collectionPlace: () => p.manyToOne(CollectionPlaces).ref().deleteRule('cascade').nullable().hidden().index('idx_place_change_log_collection_place_id'), + collection_place_id: p.integer().nullable().persist(false).index('idx_place_change_log_collection_place_id'), + collection: () => p.manyToOne(Collections).ref().deleteRule('cascade').nullable().hidden().index('idx_place_change_log_collection_id'), + collection_id: p.integer().nullable().persist(false).index('idx_place_change_log_collection_id'), + field: p.text(), + old_value: p.text().nullable(), + new_value: p.text().nullable(), + user: () => p.manyToOne(Users).ref().nullable().hidden().index('idx_place_change_log_user_id'), + user_id: p.integer().nullable().persist(false).index('idx_place_change_log_user_id'), + automatic: p.integer().default(0), + created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), + }, +}); diff --git a/server/src/db/entities/Places.entity.ts b/server/src/db/entities/Places.entity.ts index ac626953c..e034019f7 100644 --- a/server/src/db/entities/Places.entity.ts +++ b/server/src/db/entities/Places.entity.ts @@ -8,7 +8,10 @@ import { DayAccommodations } from './DayAccommodations.entity'; import { DayAssignments } from './DayAssignments.entity'; import { FileLinks } from './FileLinks.entity'; import { JourneyEntries } from './JourneyEntries.entity'; +import { PersonalPlaceTags } from './PersonalPlaceTags.entity'; import { Photos } from './Photos.entity'; +import { PlaceActivityLinks } from './PlaceActivityLinks.entity'; +import { PlaceChangeLog } from './PlaceChangeLog.entity'; import { PlaceContribOutbox } from './PlaceContribOutbox.entity'; import { PlaceFieldOrigin } from './PlaceFieldOrigin.entity'; import { PlaceRatings } from './PlaceRatings.entity'; @@ -67,7 +70,10 @@ export class Places { day_assignments_collection = new Collection(this); file_links_collection = new Collection(this); journey_entries_collection = new Collection(this); + personal_place_tags_collection = new Collection(this); photos_collection = new Collection(this); + place_activity_links_collection = new Collection(this); + place_change_log_collection = new Collection(this); place_contrib_outbox_collection = new Collection(this); place_field_origin_collection = new Collection(this); place_ratings_collection = new Collection(this); @@ -128,7 +134,10 @@ export const PlacesSchema = defineEntity({ day_assignments_collection: () => p.oneToMany(DayAssignments).mappedBy('place').hidden(), file_links_collection: () => p.oneToMany(FileLinks).mappedBy('place').hidden(), journey_entries_collection: () => p.oneToMany(JourneyEntries).mappedBy('sourcePlace').hidden(), + personal_place_tags_collection: () => p.oneToMany(PersonalPlaceTags).mappedBy('place').hidden(), photos_collection: () => p.oneToMany(Photos).mappedBy('place').hidden(), + place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('place').hidden(), + place_change_log_collection: () => p.oneToMany(PlaceChangeLog).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(), diff --git a/server/src/db/entities/Reservations.entity.ts b/server/src/db/entities/Reservations.entity.ts index 2240fc19c..5631e543c 100644 --- a/server/src/db/entities/Reservations.entity.ts +++ b/server/src/db/entities/Reservations.entity.ts @@ -5,6 +5,7 @@ import { BudgetItems } from './BudgetItems.entity'; import { DayAssignments } from './DayAssignments.entity'; import { Days } from './Days.entity'; import { FileLinks } from './FileLinks.entity'; +import { PlaceActivityLinks } from './PlaceActivityLinks.entity'; import { Places } from './Places.entity'; import { ReservationDayPositions } from './ReservationDayPositions.entity'; import { ReservationEndpoints } from './ReservationEndpoints.entity'; @@ -48,6 +49,7 @@ export class Reservations { ingest_state: string & Opt = 'live'; budget_items_collection = new Collection(this); file_links_collection = new Collection(this); + place_activity_links_collection = new Collection(this); reservation_day_positions_collection = new Collection(this); reservation_endpoints_collection = new Collection(this); reservation_travelers_collection = new Collection(this); @@ -98,6 +100,7 @@ export const ReservationsSchema = defineEntity({ ingest_state: p.text().default('live'), budget_items_collection: () => p.oneToMany(BudgetItems).mappedBy('reservation').hidden(), file_links_collection: () => p.oneToMany(FileLinks).mappedBy('reservation').hidden(), + place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('reservation').hidden(), reservation_day_positions_collection: () => p.oneToMany(ReservationDayPositions).mappedBy('reservation').hidden(), reservation_endpoints_collection: () => p.oneToMany(ReservationEndpoints).mappedBy('reservation').hidden(), reservation_travelers_collection: () => p.oneToMany(ReservationTravelers).mappedBy('reservation').hidden(), diff --git a/server/src/db/entities/Tags.entity.ts b/server/src/db/entities/Tags.entity.ts index efadd8919..2a8a94827 100644 --- a/server/src/db/entities/Tags.entity.ts +++ b/server/src/db/entities/Tags.entity.ts @@ -2,6 +2,7 @@ import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } import { TagsRepository } from '../repositories/Tags.repository'; import { DbTimestampType } from '../types'; import { CollectionPlaces } from './CollectionPlaces.entity'; +import { PersonalPlaceTags } from './PersonalPlaceTags.entity'; import { Places } from './Places.entity'; import { Trips } from './Trips.entity'; import { Users } from './Users.entity'; @@ -17,6 +18,7 @@ export class Tags { trip?: Ref | null; trip_id?: number | null; collection_place_tags_inverse = new Collection(this); + personal_place_tags_collection = new Collection(this); place_tags_inverse = new Collection(this); } @@ -33,6 +35,7 @@ export const TagsSchema = defineEntity({ trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').nullable().hidden().index('idx_tags_trip_id'), trip_id: p.integer().nullable().persist(false).index('idx_tags_trip_id'), collection_place_tags_inverse: () => p.manyToMany(CollectionPlaces).mappedBy('collection_place_tags').hidden(), + personal_place_tags_collection: () => p.oneToMany(PersonalPlaceTags).mappedBy('tag').hidden(), place_tags_inverse: () => p.manyToMany(Places).mappedBy('place_tags').hidden(), }, }); diff --git a/server/src/db/entities/Tours.entity.ts b/server/src/db/entities/Tours.entity.ts index 7f42572a5..808d1ec02 100644 --- a/server/src/db/entities/Tours.entity.ts +++ b/server/src/db/entities/Tours.entity.ts @@ -1,6 +1,7 @@ import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core'; import { ToursRepository } from '../repositories/Tours.repository'; import { DbTimestampType } from '../types'; +import { PlaceActivityLinks } from './PlaceActivityLinks.entity'; import { Places } from './Places.entity'; import { TourActivities } from './TourActivities.entity'; import { TourActivityExclusions } from './TourActivityExclusions.entity'; @@ -52,6 +53,7 @@ export class Tours { ski_discipline?: TToursSkiDiscipline | null; ski_options?: string | null; tourTypeRef!: Ref; + place_activity_links_collection = new Collection(this); tour_activities_collection = new Collection(this); tour_activities_collection1 = new Collection(this); tour_activity_exclusions_collection = new Collection(this); @@ -184,6 +186,7 @@ export const ToursSchema = defineEntity({ ski_discipline: p.enum(() => ToursSkiDiscipline).nullable(), ski_options: p.text().nullable(), tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'), + place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('tourPlace').hidden(), tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('place').hidden(), tour_activities_collection1: () => p.oneToMany(TourActivities).mappedBy('trackPlace').hidden(), tour_activity_exclusions_collection: () => p.oneToMany(TourActivityExclusions).mappedBy('place').hidden(), diff --git a/server/src/db/entities/UserPlaces.entity.ts b/server/src/db/entities/UserPlaces.entity.ts index f4028e96b..3dadab874 100644 --- a/server/src/db/entities/UserPlaces.entity.ts +++ b/server/src/db/entities/UserPlaces.entity.ts @@ -2,6 +2,7 @@ import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } import { UserPlacesRepository } from '../repositories/UserPlaces.repository'; import { DbTimestampType } from '../types'; import { Categories } from './Categories.entity'; +import { PersonalPlaceTags } from './PersonalPlaceTags.entity'; import { UserPlaceLinks } from './UserPlaceLinks.entity'; import { UserPlaceMerges } from './UserPlaceMerges.entity'; import { Users } from './Users.entity'; @@ -24,6 +25,7 @@ export class UserPlaces { merged_into_id?: number | null; created_at?: string | null; updated_at?: string | null; + personal_place_tags_collection = new Collection(this); user_place_links_collection = new Collection(this); user_place_merges_collection = new Collection(this); user_place_merges_collection1 = new Collection(this); @@ -50,6 +52,7 @@ export const UserPlacesSchema = defineEntity({ merged_into_id: p.integer().nullable().persist(false).index('idx_user_places_merged_into_id'), created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), + personal_place_tags_collection: () => p.oneToMany(PersonalPlaceTags).mappedBy('userPlace').hidden(), user_place_links_collection: () => p.oneToMany(UserPlaceLinks).mappedBy('userPlace').hidden(), user_place_merges_collection: () => p.oneToMany(UserPlaceMerges).mappedBy('leading').hidden(), user_place_merges_collection1: () => p.oneToMany(UserPlaceMerges).mappedBy('merged').hidden(), diff --git a/server/src/db/entities/Users.entity.ts b/server/src/db/entities/Users.entity.ts index 86f9e08c5..97c313d8d 100644 --- a/server/src/db/entities/Users.entity.ts +++ b/server/src/db/entities/Users.entity.ts @@ -55,6 +55,8 @@ import { PackingItemContributors } from './PackingItemContributors.entity'; import { PackingItems } from './PackingItems.entity'; import { PackingTemplates } from './PackingTemplates.entity'; import { PasswordResetTokens } from './PasswordResetTokens.entity'; +import { PlaceActivityLinks } from './PlaceActivityLinks.entity'; +import { PlaceChangeLog } from './PlaceChangeLog.entity'; import { PlaceRatings } from './PlaceRatings.entity'; import { PushSubscriptions } from './PushSubscriptions.entity'; import { ReservationTravelers } from './ReservationTravelers.entity'; @@ -205,6 +207,8 @@ export class Users { packing_item_recipients_inverse = new Collection(this); packing_templates_collection = new Collection(this); password_reset_tokens_collection = new Collection(this); + place_activity_links_collection = new Collection(this); + place_change_log_collection = new Collection(this); place_ratings_collection = new Collection(this); push_subscriptions_collection = new Collection(this); reservation_travelers_collection = new Collection(this); @@ -373,6 +377,8 @@ export const UsersSchema = defineEntity({ packing_item_recipients_inverse: () => p.manyToMany(PackingItems).mappedBy('packing_item_recipients').hidden(), packing_templates_collection: () => p.oneToMany(PackingTemplates).mappedBy('createdByRef').hidden(), password_reset_tokens_collection: () => p.oneToMany(PasswordResetTokens).mappedBy('user').hidden(), + place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('linkedByRef').hidden(), + place_change_log_collection: () => p.oneToMany(PlaceChangeLog).mappedBy('user').hidden(), place_ratings_collection: () => p.oneToMany(PlaceRatings).mappedBy('user').hidden(), push_subscriptions_collection: () => p.oneToMany(PushSubscriptions).mappedBy('user').hidden(), reservation_travelers_collection: () => p.oneToMany(ReservationTravelers).mappedBy('user').hidden(), diff --git a/server/src/db/entities/index.ts b/server/src/db/entities/index.ts index fefc7f7b1..ba059a1cf 100644 --- a/server/src/db/entities/index.ts +++ b/server/src/db/entities/index.ts @@ -83,9 +83,12 @@ import { PaddleRegionRequestsSchema } from './PaddleRegionRequests.entity'; import { PaddleRegionsSchema } from './PaddleRegions.entity'; import { PaddleWaterGraphsSchema } from './PaddleWaterGraphs.entity'; import { PasswordResetTokensSchema } from './PasswordResetTokens.entity'; +import { PersonalPlaceTagsSchema } from './PersonalPlaceTags.entity'; import { PhotoProviderFieldsSchema } from './PhotoProviderFields.entity'; import { PhotoProvidersSchema } from './PhotoProviders.entity'; import { PhotosSchema } from './Photos.entity'; +import { PlaceActivityLinksSchema } from './PlaceActivityLinks.entity'; +import { PlaceChangeLogSchema } from './PlaceChangeLog.entity'; import { PlaceContribLogSchema } from './PlaceContribLog.entity'; import { PlaceContribOutboxSchema } from './PlaceContribOutbox.entity'; import { PlaceDetailsCacheSchema } from './PlaceDetailsCache.entity'; @@ -264,9 +267,12 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [ PaddleRegionsSchema, PaddleWaterGraphsSchema, PasswordResetTokensSchema, + PersonalPlaceTagsSchema, PhotoProviderFieldsSchema, PhotoProvidersSchema, PhotosSchema, + PlaceActivityLinksSchema, + PlaceChangeLogSchema, PlaceContribLogSchema, PlaceContribOutboxSchema, PlaceDetailsCacheSchema, diff --git a/server/src/db/kysely/PersonalPlaceTags.table.ts b/server/src/db/kysely/PersonalPlaceTags.table.ts new file mode 100644 index 000000000..8409d9bf1 --- /dev/null +++ b/server/src/db/kysely/PersonalPlaceTags.table.ts @@ -0,0 +1,12 @@ +// 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 PersonalPlaceTagsTable { + id: InsertOptional; + tag_id: number; + user_place_id: InsertOptional; + place_id: InsertOptional; + collection_place_id: InsertOptional; + created_at: InsertOptional; +} diff --git a/server/src/db/kysely/PlaceActivityLinks.table.ts b/server/src/db/kysely/PlaceActivityLinks.table.ts new file mode 100644 index 000000000..b66e0af03 --- /dev/null +++ b/server/src/db/kysely/PlaceActivityLinks.table.ts @@ -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 PlaceActivityLinksTable { + id: InsertOptional; + place_id: InsertOptional; + reservation_id: InsertOptional; + tour_place_id: InsertOptional; + collection_place_id: InsertOptional; + collection_tour_id: InsertOptional; + linked_by: InsertOptional; + created_at: InsertOptional; +} diff --git a/server/src/db/kysely/PlaceChangeLog.table.ts b/server/src/db/kysely/PlaceChangeLog.table.ts new file mode 100644 index 000000000..1f6ad9e50 --- /dev/null +++ b/server/src/db/kysely/PlaceChangeLog.table.ts @@ -0,0 +1,16 @@ +// 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 PlaceChangeLogTable { + id: InsertOptional; + place_id: InsertOptional; + collection_place_id: InsertOptional; + collection_id: InsertOptional; + field: string; + old_value: InsertOptional; + new_value: InsertOptional; + user_id: InsertOptional; + automatic: InsertOptional; + created_at: InsertOptional; +} diff --git a/server/src/db/kysely/db.ts b/server/src/db/kysely/db.ts index 9a3413bf1..450e5f2b3 100644 --- a/server/src/db/kysely/db.ts +++ b/server/src/db/kysely/db.ts @@ -88,9 +88,12 @@ import type { PaddleRegionRequestsTable } from './PaddleRegionRequests.table'; import type { PaddleRegionsTable } from './PaddleRegions.table'; import type { PaddleWaterGraphsTable } from './PaddleWaterGraphs.table'; import type { PasswordResetTokensTable } from './PasswordResetTokens.table'; +import type { PersonalPlaceTagsTable } from './PersonalPlaceTags.table'; import type { PhotoProviderFieldsTable } from './PhotoProviderFields.table'; import type { PhotoProvidersTable } from './PhotoProviders.table'; import type { PhotosTable } from './Photos.table'; +import type { PlaceActivityLinksTable } from './PlaceActivityLinks.table'; +import type { PlaceChangeLogTable } from './PlaceChangeLog.table'; import type { PlaceContribLogTable } from './PlaceContribLog.table'; import type { PlaceContribOutboxTable } from './PlaceContribOutbox.table'; import type { PlaceDetailsCacheTable } from './PlaceDetailsCache.table'; @@ -275,9 +278,12 @@ export interface DB { paddle_regions: PaddleRegionsTable; paddle_water_graphs: PaddleWaterGraphsTable; password_reset_tokens: PasswordResetTokensTable; + personal_place_tags: PersonalPlaceTagsTable; photo_provider_fields: PhotoProviderFieldsTable; photo_providers: PhotoProvidersTable; photos: PhotosTable; + place_activity_links: PlaceActivityLinksTable; + place_change_log: PlaceChangeLogTable; place_contrib_log: PlaceContribLogTable; place_contrib_outbox: PlaceContribOutboxTable; place_details_cache: PlaceDetailsCacheTable; diff --git a/server/src/db/migrations/Migration20200101046550_a_place_keeps_the_history_of_its_details.ts b/server/src/db/migrations/Migration20200101046550_a_place_keeps_the_history_of_its_details.ts new file mode 100644 index 000000000..35d5c3e07 --- /dev/null +++ b/server/src/db/migrations/Migration20200101046550_a_place_keeps_the_history_of_its_details.ts @@ -0,0 +1,61 @@ +import { engineDdl } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * PLC-14: what changed in the details of a place, and who changed it. One row + * is one field of one place that went from one value to another: of a trip + * place (`place_id`) or of a saved place (`collection_place_id`), exactly one + * of the two, as the CHECK holds. A saved place's change also names the list + * it was made in (`collection_id`): a place moved to another list shows the + * new list's members only what was changed there, never who edited it in the + * old one, and the old changes come back with a move back. + * + * The rows go with their place, so a deleted place takes its history along, + * and with their list, so a deleted list takes the changes made in it. + * `user_id` names who made the change and is kept as unknown when that + * account goes; `automatic` marks a value TREK filled in itself (a lookup + * after an import, a picture from the photo cache), which nobody typed. + * + * A value that was cleared is no row of its own: clearing a field removes the + * rows of that field, so what was deleted on purpose does not live on here. + * Nothing existing is read or rewritten, so the history starts empty. + */ +export class Migration20200101046550_a_place_keeps_the_history_of_its_details extends Migration { + override name = 'Migration20200101046550_a_place_keeps_the_history_of_its_details'; + + override up(): void { + engineDdl(this, { + sqlite: [ + `CREATE TABLE place_change_log ( + id INTEGER PRIMARY KEY, + place_id INTEGER REFERENCES places(id) ON DELETE CASCADE, + collection_place_id INTEGER REFERENCES collection_places(id) ON DELETE CASCADE, + collection_id INTEGER REFERENCES collections(id) ON DELETE CASCADE + CHECK ((place_id IS NULL) <> (collection_place_id IS NULL) AND (collection_id IS NULL) = (collection_place_id IS NULL)), + field TEXT NOT NULL, + old_value TEXT, + new_value TEXT, + user_id INTEGER REFERENCES users(id) ON DELETE SET NULL, + automatic INTEGER NOT NULL DEFAULT 0, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP + )`, + 'CREATE INDEX idx_place_change_log_place_id ON place_change_log(place_id)', + 'CREATE INDEX idx_place_change_log_collection_place_id ON place_change_log(collection_place_id)', + 'CREATE INDEX idx_place_change_log_collection_id ON place_change_log(collection_id)', + 'CREATE INDEX idx_place_change_log_user_id ON place_change_log(user_id)', + ], + postgres: [ + 'create table "place_change_log" ("id" bigserial primary key, "place_id" bigint null, "collection_place_id" bigint null, "collection_id" bigint null, "field" text not null, "old_value" text null, "new_value" text null, "user_id" bigint null, "automatic" bigint not null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'))', + 'create index "idx_place_change_log_place_id" on "place_change_log" ("place_id")', + 'create index "idx_place_change_log_collection_place_id" on "place_change_log" ("collection_place_id")', + 'create index "idx_place_change_log_collection_id" on "place_change_log" ("collection_id")', + 'create index "idx_place_change_log_user_id" on "place_change_log" ("user_id")', + 'alter table "place_change_log" add constraint "place_change_log_collection_id_check" check ((place_id IS NULL) <> (collection_place_id IS NULL) AND (collection_id IS NULL) = (collection_place_id IS NULL))', + 'alter table "place_change_log" add constraint "place_change_log_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade', + 'alter table "place_change_log" add constraint "place_change_log_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on delete cascade', + 'alter table "place_change_log" add constraint "place_change_log_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade', + 'alter table "place_change_log" add constraint "place_change_log_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null', + ], + }); + } +} diff --git a/server/src/db/migrations/Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about.ts b/server/src/db/migrations/Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about.ts new file mode 100644 index 000000000..120f9b42a --- /dev/null +++ b/server/src/db/migrations/Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about.ts @@ -0,0 +1,63 @@ +import { engineDdl } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * PLC-18: a place names the bookings and tours it is about. One row ties one + * place to one activity of the same trip or the same list, never both kinds: + * a trip place (`place_id`) to a booking (`reservation_id`) or a tour + * (`tour_place_id`, the tour's own place) of its trip, or a saved place + * (`collection_place_id`) to a tour kept in its list (`collection_tour_id`). + * The CHECK holds that shape; that both ends belong to the same trip or list + * is checked by the write, which reads both. + * + * A row goes with either end, so deleting the place, the booking or the tour + * takes the link along and nothing else. `linked_by` names who linked it and + * is kept as unknown when that account goes. Nothing existing is read or + * rewritten: a booking that names its place already is shown from the + * booking itself, never copied in here. + */ +export class Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about extends Migration { + override name = 'Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about'; + + override up(): void { + engineDdl(this, { + sqlite: [ + `CREATE TABLE place_activity_links ( + id INTEGER PRIMARY KEY, + place_id INTEGER REFERENCES places(id) ON DELETE CASCADE, + reservation_id INTEGER REFERENCES reservations(id) ON DELETE CASCADE, + tour_place_id INTEGER REFERENCES tours(place_id) ON DELETE CASCADE, + collection_place_id INTEGER REFERENCES collection_places(id) ON DELETE CASCADE, + collection_tour_id INTEGER REFERENCES collection_tours(id) ON DELETE CASCADE + CHECK ((place_id IS NOT NULL AND collection_place_id IS NULL AND collection_tour_id IS NULL AND (reservation_id IS NULL) <> (tour_place_id IS NULL)) OR (place_id IS NULL AND reservation_id IS NULL AND tour_place_id IS NULL AND collection_place_id IS NOT NULL AND collection_tour_id IS NOT NULL)), + linked_by INTEGER REFERENCES users(id) ON DELETE SET NULL, + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE (place_id, reservation_id), + UNIQUE (place_id, tour_place_id), + UNIQUE (collection_place_id, collection_tour_id) + )`, + 'CREATE INDEX idx_place_activity_links_reservation_id ON place_activity_links(reservation_id)', + 'CREATE INDEX idx_place_activity_links_tour_place_id ON place_activity_links(tour_place_id)', + 'CREATE INDEX idx_place_activity_links_collection_tour_id ON place_activity_links(collection_tour_id)', + 'CREATE INDEX idx_place_activity_links_linked_by ON place_activity_links(linked_by)', + ], + postgres: [ + 'create table "place_activity_links" ("id" bigserial primary key, "place_id" bigint null, "reservation_id" bigint null, "tour_place_id" bigint null, "collection_place_id" bigint null, "collection_tour_id" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'), "linked_by" bigint null)', + 'create index "idx_place_activity_links_reservation_id" on "place_activity_links" ("reservation_id")', + 'create index "idx_place_activity_links_tour_place_id" on "place_activity_links" ("tour_place_id")', + 'create index "idx_place_activity_links_collection_tour_id" on "place_activity_links" ("collection_tour_id")', + 'create index "idx_place_activity_links_linked_by" on "place_activity_links" ("linked_by")', + 'alter table "place_activity_links" add constraint "place_activity_links_collection_place_id_collection_tour_id_unique" unique ("collection_place_id", "collection_tour_id")', + 'alter table "place_activity_links" add constraint "place_activity_links_place_id_tour_place_id_unique" unique ("place_id", "tour_place_id")', + 'alter table "place_activity_links" add constraint "place_activity_links_place_id_reservation_id_unique" unique ("place_id", "reservation_id")', + 'alter table "place_activity_links" add constraint "place_activity_links_collection_tour_id_check" check ((place_id IS NOT NULL AND collection_place_id IS NULL AND collection_tour_id IS NULL AND (reservation_id IS NULL) <> (tour_place_id IS NULL)) OR (place_id IS NULL AND reservation_id IS NULL AND tour_place_id IS NULL AND collection_place_id IS NOT NULL AND collection_tour_id IS NOT NULL))', + 'alter table "place_activity_links" add constraint "place_activity_links_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade', + 'alter table "place_activity_links" add constraint "place_activity_links_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete cascade', + 'alter table "place_activity_links" add constraint "place_activity_links_tour_place_id_foreign" foreign key ("tour_place_id") references "tours" ("place_id") on delete cascade', + 'alter table "place_activity_links" add constraint "place_activity_links_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on delete cascade', + 'alter table "place_activity_links" add constraint "place_activity_links_collection_tour_id_foreign" foreign key ("collection_tour_id") references "collection_tours" ("id") on delete cascade', + 'alter table "place_activity_links" add constraint "place_activity_links_linked_by_foreign" foreign key ("linked_by") references "users" ("id") on delete set null', + ], + }); + } +} diff --git a/server/src/db/migrations/Migration20200101046580_a_person_tags_the_places_they_keep.ts b/server/src/db/migrations/Migration20200101046580_a_person_tags_the_places_they_keep.ts new file mode 100644 index 000000000..f59cc036c --- /dev/null +++ b/server/src/db/migrations/Migration20200101046580_a_person_tags_the_places_they_keep.ts @@ -0,0 +1,57 @@ +import { engineDdl } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * PLC-21: a person puts their own tags on the entries of "All places". The + * tags are the personal ones `tags` already holds (`trip_id` null); this + * table says which entry carries which of them, and only ever for the person + * who owns the tag, so nobody else on a trip or a list sees it. + * + * One row ties one tag to exactly one target, the one the entry is known by: + * the person's own place (`user_place_id`, D5) where they put one together, + * else the trip place (`place_id`) or the saved place + * (`collection_place_id`) it stands for. The CHECK holds that shape, the + * UNIQUEs that a tag sits on a target once. Every row goes with its tag and + * with its target (ON DELETE CASCADE), so deleting a tag, an own place, a + * trip place or a saved place takes its tags along and nothing else. Nothing + * existing is read or rewritten. + */ +export class Migration20200101046580_a_person_tags_the_places_they_keep extends Migration { + override name = 'Migration20200101046580_a_person_tags_the_places_they_keep'; + + override up(): void { + engineDdl(this, { + sqlite: [ + `CREATE TABLE personal_place_tags ( + id INTEGER PRIMARY KEY, + tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE, + user_place_id INTEGER REFERENCES user_places(id) ON DELETE CASCADE, + place_id INTEGER REFERENCES places(id) ON DELETE CASCADE, + collection_place_id INTEGER REFERENCES collection_places(id) ON DELETE CASCADE + CHECK ((user_place_id IS NOT NULL AND place_id IS NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NOT NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NULL AND collection_place_id IS NOT NULL)), + created_at DATETIME DEFAULT CURRENT_TIMESTAMP, + UNIQUE (tag_id, user_place_id), + UNIQUE (tag_id, place_id), + UNIQUE (tag_id, collection_place_id) + )`, + 'CREATE INDEX idx_personal_place_tags_user_place_id ON personal_place_tags(user_place_id)', + 'CREATE INDEX idx_personal_place_tags_place_id ON personal_place_tags(place_id)', + 'CREATE INDEX idx_personal_place_tags_collection_place_id ON personal_place_tags(collection_place_id)', + ], + postgres: [ + 'create table "personal_place_tags" ("id" bigserial primary key, "tag_id" bigint not null, "user_place_id" bigint null, "place_id" bigint null, "collection_place_id" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'))', + 'create index "idx_personal_place_tags_user_place_id" on "personal_place_tags" ("user_place_id")', + 'create index "idx_personal_place_tags_place_id" on "personal_place_tags" ("place_id")', + 'create index "idx_personal_place_tags_collection_place_id" on "personal_place_tags" ("collection_place_id")', + 'alter table "personal_place_tags" add constraint "personal_place_tags_tag_id_collection_place_id_unique" unique ("tag_id", "collection_place_id")', + 'alter table "personal_place_tags" add constraint "personal_place_tags_tag_id_place_id_unique" unique ("tag_id", "place_id")', + 'alter table "personal_place_tags" add constraint "personal_place_tags_tag_id_user_place_id_unique" unique ("tag_id", "user_place_id")', + 'alter table "personal_place_tags" add constraint "personal_place_tags_collection_place_id_check" check ((user_place_id IS NOT NULL AND place_id IS NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NOT NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NULL AND collection_place_id IS NOT NULL))', + 'alter table "personal_place_tags" add constraint "personal_place_tags_tag_id_foreign" foreign key ("tag_id") references "tags" ("id") on delete cascade', + 'alter table "personal_place_tags" add constraint "personal_place_tags_user_place_id_foreign" foreign key ("user_place_id") references "user_places" ("id") on delete cascade', + 'alter table "personal_place_tags" add constraint "personal_place_tags_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade', + 'alter table "personal_place_tags" add constraint "personal_place_tags_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on delete cascade', + ], + }); + } +} diff --git a/server/src/db/repositories/PersonalPlaceTags.repository.ts b/server/src/db/repositories/PersonalPlaceTags.repository.ts new file mode 100644 index 000000000..a12bd974e --- /dev/null +++ b/server/src/db/repositories/PersonalPlaceTags.repository.ts @@ -0,0 +1,119 @@ +import type { PersonalPlaceTags } from '../entities/PersonalPlaceTags.entity'; +import type { DB } from '../kysely/db'; +import { TrekRepository } from './_shared/trek-repository'; + +type PersonalPlaceTagsDB = Pick; + +/** Kysely cannot bind an empty IN list and no row has the id 0, so none reads as this. */ +const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [0]); + +/** How many assignments one INSERT writes at most (four bound values each). */ +const INSERT_BLOCK = 500; + +/** A personal tag as the places library shows it. */ +interface PersonalTagRow { + id: number; + name: string; + color: string | null; +} + +/** + * What a tag sits on: the person's own places (and the ones merged into + * them), trip places and saved places. Each list may be empty. + */ +interface PersonalTagTargets { + identityIds: readonly number[]; + placeIds: readonly number[]; + collectionPlaceIds: readonly number[]; +} + +/** One tag on one target, exactly one of the three set. */ +export interface PersonalTagAssignment { + tag_id: number; + user_place_id: number | null; + place_id: number | null; + collection_place_id: number | null; +} + +/** + * PLC-21: which entry of "All places" carries which personal tag of its + * owner. Every statement is bounded by the owner: a tag counts only while it + * is `userId`'s and personal (`trip_id` null), so no call reaches another + * person's tags or a trip's. Which targets a person may tag is the caller's + * check (the library's reach); this class checks no access itself. + */ +export class PersonalPlaceTagsRepository extends TrekRepository { + private db() { + return this.kysely(); + } + + /** The personal tags of `userId` among `ids`, by name. */ + async ownTags(userId: number, ids: readonly number[]): Promise { + if (ids.length === 0) return []; + return await this.db() + .selectFrom('tags') + .select(['id', 'name', 'color']) + .where('user_id', '=', userId) + .where('trip_id', 'is', null) + .where('id', 'in', [...ids]) + .orderBy('name') + .orderBy('id') + .execute(); + } + + /** + * Puts the tags on their targets; one already there stays as it is. In + * blocks, one after the other, so a large change stays under the engines' + * limits on bound parameters. + */ + async add(rows: readonly PersonalTagAssignment[]): Promise { + const blocks = Array.from({ length: Math.ceil(rows.length / INSERT_BLOCK) }, (_, index) => + rows.slice(index * INSERT_BLOCK, (index + 1) * INSERT_BLOCK), + ); + await blocks.reduce>(async (previous, block) => { + await previous; + await this.db() + .insertInto('personal_place_tags') + .values(block.map((row) => ({ ...row }))) + .onConflict((oc) => oc.doNothing()) + .execute(); + }, Promise.resolve()); + } + + /** + * Takes `userId`'s tags (all of them, or `tagIds`) off the targets, an own + * place's included the ones merged into it. Returns how many came off. + */ + async remove(userId: number, targets: PersonalTagTargets, tagIds: readonly number[] | null): Promise { + if (tagIds !== null && tagIds.length === 0) return 0; + const db = this.db(); + const own = db + .selectFrom('tags') + .select('id') + .where('user_id', '=', userId) + .where('trip_id', 'is', null) + .$if(tagIds !== null, (qb) => qb.where('id', 'in', idsOrNone(tagIds ?? []))); + const identities = db + .selectFrom('user_places') + .select('id') + .where('user_id', '=', userId) + .where((eb) => + eb.or([ + eb('id', 'in', idsOrNone(targets.identityIds)), + eb('merged_into_id', 'in', idsOrNone(targets.identityIds)), + ]), + ); + const result = await db + .deleteFrom('personal_place_tags') + .where('tag_id', 'in', own) + .where((eb) => + eb.or([ + eb('user_place_id', 'in', identities), + eb('place_id', 'in', idsOrNone(targets.placeIds)), + eb('collection_place_id', 'in', idsOrNone(targets.collectionPlaceIds)), + ]), + ) + .executeTakeFirst(); + return Number(result.numDeletedRows); + } +} diff --git a/server/src/db/repositories/PlaceActivityLinks.repository.ts b/server/src/db/repositories/PlaceActivityLinks.repository.ts new file mode 100644 index 000000000..34ceaf75e --- /dev/null +++ b/server/src/db/repositories/PlaceActivityLinks.repository.ts @@ -0,0 +1,391 @@ +import type { PlaceActivityLinks } from '../entities/PlaceActivityLinks.entity'; +import type { DB } from '../kysely/db'; +import { accommodationIdMatches } from './_shared/reservation-accommodation'; +import { TrekRepository } from './_shared/trek-repository'; + +type PlaceActivityDB = Pick< + DB, + | 'place_activity_links' + | 'places' + | 'reservations' + | 'tours' + | 'days' + | 'day_assignments' + | 'day_accommodations' + | 'tour_waypoints' + | 'trips' + | 'collection_places' + | 'collection_tours' + | 'collections' +>; + +/** Kysely cannot bind an empty IN list and no row has the id 0, so none reads as this. */ +const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [0]); + +/** A booking as the place detail shows it, with the place it is shown for (`source_id`). */ +export interface ActivityBookingRow { + source_id: number; + trip_id: number; + trip_title: string; + reservation_id: number; + title: string; + type: string | null; + status: string | null; + reservation_time: string | null; + reservation_end_time: string | null; + date: string | null; + day_number: number | null; +} + +/** A tour of a trip (its own place) as the place detail shows it. */ +export interface ActivityTourRow { + source_id: number; + trip_id: number; + trip_title: string; + tour_id: number; + title: string; + tour_type: string; + date: string | null; + day_number: number | null; +} + +/** A tour kept in a list as the saved place detail shows it. */ +export interface ActivityKeptTourRow { + source_id: number; + collection_id: number; + collection_name: string; + collection_tour_id: number; + title: string; + tour_type: string; +} + +/** A trip place with the trip it is in. */ +interface ActivityTripPlaceRow { + id: number; + trip_id: number; +} + +/** A saved place with the list it is in. */ +export interface ActivitySavedPlaceRow { + id: number; + collection_id: number; +} + +/** Why a booking belongs to a place without a link: it names the place, its stay or its plan entry. */ +export type ImplicitVia = 'place' | 'stay' | 'plan'; + +const num = (value: unknown): number | null => (value === null || value === undefined ? null : Number(value)); + +function tourRowOf(row: { + source_id: unknown; + trip_id: number; + trip_title: string; + tour_id: number; + title: string; + tour_type: string; + date: string | null; + day_number: unknown; +}): ActivityTourRow { + return { ...row, source_id: Number(row.source_id), date: row.date ?? null, day_number: num(row.day_number) }; +} + +function bookingRowOf(row: { + source_id: unknown; + trip_id: number; + trip_title: string; + reservation_id: number; + title: string; + type: string | null; + status: string | null; + reservation_time: string | null; + reservation_end_time: string | null; + date: string | null; + day_number: unknown; +}): ActivityBookingRow { + return { ...row, source_id: Number(row.source_id), day_number: num(row.day_number) }; +} + +/** + * `place_activity_links` (PLC-18): the bookings and tours a place names, and + * the reads the place detail needs around them (the bookings that name the + * place themselves, the candidates of its trip or list). Every method takes + * ids the caller checked; who may see or change what is decided in the + * service, never here. + */ +export class PlaceActivityLinksRepository extends TrekRepository { + private db() { + return this.kysely(); + } + + /** The trip place `placeId` of the trip `tripId`, or undefined. */ + async tripPlace(tripId: number, placeId: number): Promise { + return this.db() + .selectFrom('places') + .select(['id', 'trip_id']) + .where('id', '=', placeId) + .where('trip_id', '=', tripId) + .executeTakeFirst(); + } + + /** The saved place `id` with its list, or undefined. */ + async savedPlace(id: number): Promise { + return this.db() + .selectFrom('collection_places') + .select(['id', 'collection_id']) + .where('id', '=', id) + .executeTakeFirst(); + } + + /** Whether the booking `reservationId` is one of the trip's. */ + async bookingInTrip(tripId: number, reservationId: number): Promise { + const row = await this.db() + .selectFrom('reservations') + .select('id') + .where('id', '=', reservationId) + .where('trip_id', '=', tripId) + .executeTakeFirst(); + return row !== undefined; + } + + /** Whether `tourId` is a tour (its own place) of the trip. */ + async tourInTrip(tripId: number, tourId: number): Promise { + const row = await this.db() + .selectFrom('tours as t') + .innerJoin('places as p', 'p.id', 't.place_id') + .select('t.place_id') + .where('t.place_id', '=', tourId) + .where('p.trip_id', '=', tripId) + .executeTakeFirst(); + return row !== undefined; + } + + /** Whether `tourId` is a tour kept in the list. */ + async keptTourInList(collectionId: number, tourId: number): Promise { + const row = await this.db() + .selectFrom('collection_tours') + .select('id') + .where('id', '=', tourId) + .where('collection_id', '=', collectionId) + .executeTakeFirst(); + return row !== undefined; + } + + /** Links an activity to the place; answers whether a new link was made (a second link of the same pair keeps the first). */ + async link( + target: + | { place_id: number; reservation_id: number } + | { place_id: number; tour_place_id: number } + | { collection_place_id: number; collection_tour_id: number }, + userId: number, + ): Promise { + const row = await this.db() + .insertInto('place_activity_links') + .values({ ...target, linked_by: userId }) + .onConflict((oc) => oc.doNothing()) + .returning('id') + .executeTakeFirst(); + return row !== undefined; + } + + /** Takes the link of the trip place to a booking or a tour off; answers whether there was one. */ + async unlinkTrip(placeId: number, target: { reservation_id: number } | { tour_place_id: number }): Promise { + let query = this.db().deleteFrom('place_activity_links').where('place_id', '=', placeId); + query = + 'reservation_id' in target + ? query.where('reservation_id', '=', target.reservation_id) + : query.where('tour_place_id', '=', target.tour_place_id); + const result = await query.executeTakeFirst(); + return Number(result.numDeletedRows) > 0; + } + + /** Takes the link of the saved place to a kept tour off; answers whether there was one. */ + async unlinkSaved(collectionPlaceId: number, collectionTourId: number): Promise { + const result = await this.db() + .deleteFrom('place_activity_links') + .where('collection_place_id', '=', collectionPlaceId) + .where('collection_tour_id', '=', collectionTourId) + .executeTakeFirst(); + return Number(result.numDeletedRows) > 0; + } + + /** The bookings the trip places `placeIds` are linked to. */ + async linkedBookings(placeIds: readonly number[]): Promise { + const rows = await this.bookingQuery() + .innerJoin('place_activity_links as l', 'l.reservation_id', 'r.id') + .select('l.place_id as source_id') + .where('l.place_id', 'in', idsOrNone(placeIds)) + .execute(); + return rows.map(bookingRowOf); + } + + /** + * The bookings that belong to the trip places `placeIds` without a link: + * one naming the place, one booked against a stay at the place, one tied + * to a plan entry of the place. A booking can belong for more than one reason. + */ + async implicitBookings(placeIds: readonly number[]): Promise<(ActivityBookingRow & { via: ImplicitVia })[]> { + const ids = idsOrNone(placeIds); + const platform = this.getEntityManager().getPlatform(); + const named = await this.bookingQuery().select('r.place_id as source_id').where('r.place_id', 'in', ids).execute(); + const stays = await this.bookingQuery() + .innerJoin('day_accommodations as a', (join) => + join.on((eb) => accommodationIdMatches(platform, eb, 'r.accommodation_id', 'a.id')), + ) + .select('a.place_id as source_id') + .where('a.place_id', 'in', ids) + .execute(); + const planned = await this.bookingQuery() + .innerJoin('day_assignments as da', 'da.id', 'r.assignment_id') + .select('da.place_id as source_id') + .where('da.place_id', 'in', ids) + .execute(); + const tag = (via: ImplicitVia) => (row: Parameters[0]) => ({ ...bookingRowOf(row), via }); + return [...named.map(tag('place')), ...stays.map(tag('stay')), ...planned.map(tag('plan'))]; + } + + /** Every booking of the trip, for the candidates; `source_id` is 0. */ + async tripBookings(tripId: number): Promise { + const rows = await this.bookingQuery().where('r.trip_id', '=', tripId).execute(); + return rows.map((row) => bookingRowOf({ ...row, source_id: 0 })); + } + + /** The tours the trip places `placeIds` are linked to. */ + async linkedTours(placeIds: readonly number[]): Promise { + const rows = await this.tourQuery() + .innerJoin('place_activity_links as l', 'l.tour_place_id', 't.place_id') + .select('l.place_id as source_id') + .where('l.place_id', 'in', idsOrNone(placeIds)) + .execute(); + return rows.map(tourRowOf); + } + + /** The tours with a station that stands for one of the trip places `placeIds`, once per tour and place. */ + async implicitTours(placeIds: readonly number[]): Promise { + const rows = await this.tourQuery() + .innerJoin('tour_waypoints as w', 'w.place_id', 't.place_id') + .select('w.linked_place_id as source_id') + .where('w.linked_place_id', 'in', idsOrNone(placeIds)) + .execute(); + // Several stations of one tour can stand for the same place; DISTINCT would + // refuse the ORDER BY on lower(name) on Postgres, so the pairs are kept once here. + const seen = new Set(); + return rows.map(tourRowOf).filter((row) => { + const key = `${row.tour_id}:${row.source_id}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }); + } + + /** Every tour of the trip, for the candidates; `source_id` is 0. */ + async tripTours(tripId: number): Promise { + const rows = await this.tourQuery().where('tp.trip_id', '=', tripId).execute(); + return rows.map((row) => tourRowOf({ ...row, source_id: 0 })); + } + + /** + * The kept tours the saved places `collectionPlaceIds` are linked to, of the + * list each place is in now: a place moved to another list keeps the links + * of its old one unread, and has them again when it moves back. + */ + async linkedKeptTours(collectionPlaceIds: readonly number[]): Promise { + const rows = await this.db() + .selectFrom('place_activity_links as l') + .innerJoin('collection_places as cp', 'cp.id', 'l.collection_place_id') + .innerJoin('collection_tours as ct', (join) => + join.onRef('ct.id', '=', 'l.collection_tour_id').onRef('ct.collection_id', '=', 'cp.collection_id'), + ) + .innerJoin('collections as c', 'c.id', 'ct.collection_id') + .select([ + 'l.collection_place_id as source_id', + 'ct.collection_id', + 'c.name as collection_name', + 'ct.id as collection_tour_id', + 'ct.name as title', + 'ct.tour_type', + ]) + .where('l.collection_place_id', 'in', idsOrNone(collectionPlaceIds)) + .orderBy((eb) => eb.fn('lower', ['ct.name'])) + .orderBy('ct.id') + .execute(); + return rows.map((row) => ({ ...row, source_id: Number(row.source_id) })); + } + + /** Every tour kept in the list, for the candidates; `source_id` is 0. */ + async keptTours(collectionId: number): Promise { + const rows = await this.db() + .selectFrom('collection_tours as ct') + .innerJoin('collections as c', 'c.id', 'ct.collection_id') + .select([ + 'ct.collection_id', + 'c.name as collection_name', + 'ct.id as collection_tour_id', + 'ct.name as title', + 'ct.tour_type', + ]) + .where('ct.collection_id', '=', collectionId) + .orderBy((eb) => eb.fn('lower', ['ct.name'])) + .orderBy('ct.id') + .execute(); + return rows.map((row) => ({ ...row, source_id: 0 })); + } + + /** The booking columns the place detail shows, by time (none last), then by id. */ + private bookingQuery() { + return ( + this.db() + .selectFrom('reservations as r') + .innerJoin('trips as tr', 'tr.id', 'r.trip_id') + .leftJoin('days as d', 'd.id', 'r.day_id') + .select([ + 'r.trip_id', + 'tr.title as trip_title', + 'r.id as reservation_id', + 'r.title', + 'r.type', + 'r.status', + 'r.reservation_time', + 'r.reservation_end_time', + 'd.date', + 'd.day_number', + ]) + // Without a time last on both engines (SQLite sorts NULL first, Postgres last). + .orderBy((eb) => eb.case().when('r.reservation_time', 'is', null).then(eb.lit(1)).else(eb.lit(0)).end()) + .orderBy('r.reservation_time') + .orderBy('r.id') + ); + } + + /** The tour columns the place detail shows, with the first day it is planned on, by name, then by id. */ + private tourQuery() { + return this.db() + .selectFrom('tours as t') + .innerJoin('places as tp', 'tp.id', 't.place_id') + .innerJoin('trips as tr', 'tr.id', 'tp.trip_id') + .select((eb) => [ + 'tp.trip_id', + 'tr.title as trip_title', + 't.place_id as tour_id', + 'tp.name as title', + 't.tour_type', + eb + .selectFrom('day_assignments as da') + .innerJoin('days as dd', 'dd.id', 'da.day_id') + .select('dd.date') + .whereRef('da.place_id', '=', 'tp.id') + .orderBy('dd.day_number') + .limit(1) + .as('date'), + eb + .selectFrom('day_assignments as da') + .innerJoin('days as dd', 'dd.id', 'da.day_id') + .select('dd.day_number') + .whereRef('da.place_id', '=', 'tp.id') + .orderBy('dd.day_number') + .limit(1) + .as('day_number'), + ]) + .orderBy((eb) => eb.fn('lower', ['tp.name'])) + .orderBy('t.place_id'); + } +} diff --git a/server/src/db/repositories/PlaceChangeLog.repository.ts b/server/src/db/repositories/PlaceChangeLog.repository.ts new file mode 100644 index 000000000..cf18c52ec --- /dev/null +++ b/server/src/db/repositories/PlaceChangeLog.repository.ts @@ -0,0 +1,232 @@ +import type { PlaceChangeLog } from '../entities/PlaceChangeLog.entity'; +import type { DB } from '../kysely/db'; +import { TrekRepository } from './_shared/trek-repository'; + +type PlaceChangeLogDB = Pick< + DB, + 'place_change_log' | 'places' | 'tours' | 'collection_places' | 'categories' | 'users' +>; + +/** Kysely cannot bind an empty IN list and no row has the id 0, so none reads as this. */ +const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [0]); + +/** The details of a place its history follows, as the row stores them, with its category's name. */ +export interface PlaceDetailsRow { + id: number; + name: string; + address: string | null; + lat: number | null; + lng: number | null; + category_name: string | null; + description: string | null; + notes: string | null; + website: string | null; + phone: string | null; + image_url: string | null; +} + +/** A trip place's details; only a trip place keeps opening hours. */ +export interface TripPlaceDetailsRow extends PlaceDetailsRow { + opening_hours: string | null; +} + +/** A saved place's details; only a saved place has a list status. */ +export interface SavedPlaceDetailsRow extends PlaceDetailsRow { + status: string; +} + +/** One change to write: one field of one trip place or saved place. */ +export interface PlaceChangeWrite { + place_id: number | null; + collection_place_id: number | null; + field: string; + old_value: string | null; + new_value: string | null; + user_id: number | null; + automatic: number; +} + +/** The fields cleared on one trip place or saved place, whose changes go. */ +export interface PlaceChangeClear { + place_id: number | null; + collection_place_id: number | null; + fields: string[]; +} + +/** A change as the history reads it, with who made it. */ +export interface PlaceChangeRow { + id: number; + place_id: number | null; + collection_place_id: number | null; + field: string; + old_value: string | null; + new_value: string | null; + user_id: number | null; + username: string | null; + avatar: string | null; + automatic: number; + created_at: string | null; +} + +/** + * `place_change_log` (PLC-14): what changed in the details of a trip place or + * a saved place. Every method takes ids the caller decided on; who may read + * which place is the caller's question, never this repository's. + */ +export class PlaceChangeLogRepository extends TrekRepository { + private db() { + return this.kysely(); + } + + /** + * The details of the trip places `ids` that still exist and are no tour. A + * tour keeps no history: All places leaves tours out, and the planner's save + * of a route rewrites its name and start as a whole, so a tour's details are + * the tour's own, read with the tour. + */ + async tripPlaceDetails(ids: readonly number[]): Promise { + return this.db() + .selectFrom('places as p') + .leftJoin('categories as c', 'c.id', 'p.category_id') + .select([ + 'p.id', + 'p.name', + 'p.address', + 'p.lat', + 'p.lng', + 'c.name as category_name', + 'p.description', + 'p.notes', + 'p.website', + 'p.phone', + 'p.image_url', + 'p.opening_hours', + ]) + .where('p.id', 'in', idsOrNone(ids)) + .where((eb) => + eb.not(eb.exists(eb.selectFrom('tours as t').select('t.place_id').whereRef('t.place_id', '=', 'p.id'))), + ) + .execute(); + } + + /** The details of the saved places `ids` that still exist. */ + async savedPlaceDetails(ids: readonly number[]): Promise { + return this.db() + .selectFrom('collection_places as cp') + .leftJoin('categories as c', 'c.id', 'cp.category_id') + .select([ + 'cp.id', + 'cp.name', + 'cp.address', + 'cp.lat', + 'cp.lng', + 'c.name as category_name', + 'cp.description', + 'cp.notes', + 'cp.website', + 'cp.phone', + 'cp.image_url', + 'cp.status', + ]) + .where('cp.id', 'in', idsOrNone(ids)) + .execute(); + } + + /** The trip places with this Google id and no picture, which the photo cache fills in (the write's own filter). */ + async tripPlaceIdsWithoutImage(googlePlaceId: string): Promise { + const rows = await this.db() + .selectFrom('places') + .select('id') + .where('google_place_id', '=', googlePlaceId) + .where((eb) => eb.or([eb('image_url', 'is', null), eb('image_url', '=', '')])) + .execute(); + return rows.map((row) => row.id); + } + + /** Writes the changes; a saved place's change names the list the place is in now, where it was made. */ + async insertChanges(rows: readonly PlaceChangeWrite[]): Promise { + if (rows.length === 0) return; + const savedIds = rows.flatMap((row) => (row.collection_place_id === null ? [] : [row.collection_place_id])); + const lists = savedIds.length + ? await this.db() + .selectFrom('collection_places') + .select(['id', 'collection_id']) + .where('id', 'in', savedIds) + .execute() + : []; + const listOf = new Map(lists.map((row) => [row.id, row.collection_id])); + await this.db() + .insertInto('place_change_log') + .values( + rows.map((row) => ({ + ...row, + collection_id: row.collection_place_id === null ? null : (listOf.get(row.collection_place_id) ?? null), + })), + ) + .execute(); + } + + /** Drops every change of the cleared fields, one statement for all of them. */ + async deleteCleared(clears: readonly PlaceChangeClear[]): Promise { + const wanted = clears.filter((clear) => clear.fields.length > 0); + if (wanted.length === 0) return; + await this.db() + .deleteFrom('place_change_log') + .where((eb) => + eb.or( + wanted.map((clear) => + eb.and([ + clear.place_id === null + ? eb('collection_place_id', '=', clear.collection_place_id ?? 0) + : eb('place_id', '=', clear.place_id), + eb('field', 'in', clear.fields), + ]), + ), + ), + ) + .execute(); + } + + /** + * The changes of the trip places `placeIds` and the saved places `savedIds`, + * newest first, before the change `beforeId` when given, `limit` at most. Of + * a saved place only the changes made in the list it is in now: one moved + * from another list does not bring along who edited it there. + */ + async page( + placeIds: readonly number[], + savedIds: readonly number[], + beforeId: number | null, + limit: number, + ): Promise { + if (placeIds.length === 0 && savedIds.length === 0) return []; + let query = this.db() + .selectFrom('place_change_log as l') + .leftJoin('users as u', 'u.id', 'l.user_id') + .leftJoin('collection_places as cp', 'cp.id', 'l.collection_place_id') + .select([ + 'l.id', + 'l.place_id', + 'l.collection_place_id', + 'l.field', + 'l.old_value', + 'l.new_value', + 'l.user_id', + 'u.username', + 'u.avatar', + 'l.automatic', + 'l.created_at', + ]) + .where((eb) => + eb.or([ + eb('l.place_id', 'in', idsOrNone(placeIds)), + eb.and([ + eb('l.collection_place_id', 'in', idsOrNone(savedIds)), + eb('l.collection_id', '=', eb.ref('cp.collection_id')), + ]), + ]), + ); + if (beforeId !== null) query = query.where('l.id', '<', beforeId); + return query.orderBy('l.id', 'desc').limit(limit).execute(); + } +} diff --git a/server/src/db/repositories/PlaceVisitContext.repository.ts b/server/src/db/repositories/PlaceVisitContext.repository.ts new file mode 100644 index 000000000..6bb89bbf8 --- /dev/null +++ b/server/src/db/repositories/PlaceVisitContext.repository.ts @@ -0,0 +1,293 @@ +import type { DB } from '../kysely/db'; +import type { EntityManager } from '@mikro-orm/core'; +import type { SqlEntityManager } from '@mikro-orm/sql'; + +import type { Kysely } from 'kysely'; + +type ContextDB = Pick< + DB, + | 'places' + | 'trips' + | 'trip_members' + | 'users' + | 'days' + | 'day_assignments' + | 'assignment_participants' + | 'journeys' + | 'journey_entries' + | 'journey_entry_photos' + | 'journey_photos' + | 'trek_photos' + | 'trip_files' + | 'file_links' +>; + +/** Kysely cannot bind an empty IN list and no row has the id 0, so none reads as this. */ +const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [0]); + +/** + * A place planned on a dated day of a trip up to a given day, one row per + * assignment: the raw material a visit is derived from. + */ +export interface PlannedVisitRow { + assignment_id: number; + place_id: number; + name: string; + trip_id: number; + trip_title: string; + day_id: number; + day_number: number; + date: string; + order_index: number | null; + assignment_time: string | null; + place_time: string | null; +} + +/** Someone an assignment names as taking part, or someone with an account on a trip. */ +export interface VisitPersonRow { + id: number; + username: string; + avatar: string | null; +} + +interface VisitAssignmentPersonRow extends VisitPersonRow { + assignment_id: number; +} + +interface VisitTripPersonRow extends VisitPersonRow { + trip_id: number; +} + +/** A photo of a journey entry made from one of the places. */ +interface VisitJourneyPhotoRow { + place_id: number; + journey_id: number; + journey_title: string; + entry_id: number; + entry_date: string; + journey_photo_id: number; + photo_id: number; + caption: string | null; + provider: string; + asset_id: string | null; + owner_id: number | null; + file_path: string | null; + thumbnail_path: string | null; + width: number | null; + height: number | null; + media_type: string; + taken_at: string | null; +} + +/** A trip file attached to one of the places, by a link or by its own place. */ +interface VisitFileRow { + file_id: number; + trip_id: number; + place_id: number; + original_name: string; + mime_type: string | null; + file_size: number | null; + created_at: string | null; +} + +/** + * What the visits of All places (D7, PLC-10, PLC-19, PLC-20, PLC-23) read: the + * places planned on the days of trips that have come, the people taking part, + * and the journey photos and files that hang on a trip place. Visits are not + * stored; they are read from the day plans every time. Not bound to an entity, + * like `PlacesLibraryRepository`; the places-library module provides it over + * the context-resolving EntityManager. Read only, and it checks no trip + * access: every trip and place id it takes is one the caller reaches. + */ +export class PlaceVisitContextRepository { + constructor(private readonly em: EntityManager) {} + + private db(): Kysely { + return (this.em.getContext() as SqlEntityManager).getKysely(); + } + + /** + * The assignments that count as a visit of `userId`: a place of the trip on + * a day with a date up to `today` (YYYY-MM-DD), the assignment naming no one + * or naming the user among who takes part. A day without a date never counts. + */ + private planned(userId: number, today: string) { + return this.db() + .selectFrom('day_assignments as da') + .innerJoin('days as d', 'd.id', 'da.day_id') + .innerJoin('places as p', 'p.id', 'da.place_id') + .innerJoin('trips as t', 't.id', 'd.trip_id') + .select([ + 'da.id as assignment_id', + 'p.id as place_id', + 'p.name', + 't.id as trip_id', + 't.title as trip_title', + 'd.id as day_id', + 'd.day_number', + 'd.date', + 'da.order_index', + 'da.assignment_time', + 'p.place_time', + ]) + .whereRef('p.trip_id', '=', 'd.trip_id') + .where('d.date', 'is not', null) + .where('d.date', '<=', today) + .where((eb) => + eb.or([ + eb.not( + eb.exists( + eb.selectFrom('assignment_participants as ap').select('ap.id').whereRef('ap.assignment_id', '=', 'da.id'), + ), + ), + eb.exists( + eb + .selectFrom('assignment_participants as ap') + .select('ap.id') + .whereRef('ap.assignment_id', '=', 'da.id') + .where('ap.user_id', '=', userId), + ), + ]), + ) + .orderBy('d.date', 'desc') + .orderBy('t.id') + .orderBy('d.day_number') + .orderBy('da.order_index') + .orderBy('da.id'); + } + + /** The visits of `userId` at the trip places `placeIds`, up to `today`. */ + async plannedAtPlaces(userId: number, today: string, placeIds: number[]): Promise { + const rows = await this.planned(userId, today).where('p.id', 'in', idsOrNone(placeIds)).execute(); + return rows.flatMap((row) => (row.date === null ? [] : [{ ...row, date: row.date }])); + } + + /** The visits of `userId` on the trips `tripIds`, up to `today`. */ + async plannedOnTrips(userId: number, today: string, tripIds: number[]): Promise { + const rows = await this.planned(userId, today).where('d.trip_id', 'in', idsOrNone(tripIds)).execute(); + return rows.flatMap((row) => (row.date === null ? [] : [{ ...row, date: row.date }])); + } + + /** Who the assignments name as taking part, by assignment. */ + async assignmentPeople(assignmentIds: number[]): Promise { + return await this.db() + .selectFrom('assignment_participants as ap') + .innerJoin('users as u', 'u.id', 'ap.user_id') + .select(['ap.assignment_id', 'u.id', 'u.username', 'u.avatar']) + .where('ap.assignment_id', 'in', idsOrNone(assignmentIds)) + .orderBy('ap.assignment_id') + .orderBy('ap.id') + .execute(); + } + + /** The owner and the members with an account of each trip, the owner first. */ + async tripPeople(tripIds: number[]): Promise { + const db = this.db(); + const owners = await db + .selectFrom('trips as t') + .innerJoin('users as u', 'u.id', 't.user_id') + .select(['t.id as trip_id', 'u.id', 'u.username', 'u.avatar']) + .where('t.id', 'in', idsOrNone(tripIds)) + .where('u.is_guest', '=', 0) + .execute(); + const members = await db + .selectFrom('trip_members as m') + .innerJoin('users as u', 'u.id', 'm.user_id') + .select(['m.trip_id', 'u.id', 'u.username', 'u.avatar']) + .where('m.trip_id', 'in', idsOrNone(tripIds)) + .where('u.is_guest', '=', 0) + .orderBy('m.added_at') + .orderBy('m.id') + .execute(); + return [...owners, ...members]; + } + + /** Every place id of the trip. */ + async tripPlaceIds(tripId: number): Promise { + const rows = await this.db().selectFrom('places').select('id').where('trip_id', '=', tripId).execute(); + return rows.map((row) => row.id); + } + + /** + * The photos of the journey entries made from the trip places, by entry + * date and photo order; none of an entry set aside or not filled yet. + */ + async journeyPhotosOfPlaces(placeIds: number[]): Promise { + const rows = await this.db() + .selectFrom('journey_entries as je') + .innerJoin('journeys as j', 'j.id', 'je.journey_id') + .innerJoin('journey_entry_photos as jep', 'jep.entry_id', 'je.id') + .innerJoin('journey_photos as gp', 'gp.id', 'jep.journey_photo_id') + .innerJoin('trek_photos as tp', 'tp.id', 'gp.photo_id') + .select([ + 'je.source_place_id as place_id', + 'j.id as journey_id', + 'j.title as journey_title', + 'je.id as entry_id', + 'je.entry_date', + 'gp.id as journey_photo_id', + 'gp.photo_id', + 'gp.caption', + 'tp.provider', + 'tp.asset_id', + 'tp.owner_id', + 'tp.file_path', + 'tp.thumbnail_path', + 'tp.width', + 'tp.height', + 'tp.media_type', + 'tp.taken_at', + ]) + .where('je.source_place_id', 'in', idsOrNone(placeIds)) + .where('je.dismissed', '=', 0) + .where('je.type', '!=', 'skeleton') + .orderBy('je.entry_date', 'desc') + .orderBy('je.id') + .orderBy('jep.sort_order') + .orderBy('gp.id') + .execute(); + return rows.flatMap((row) => (row.place_id === null ? [] : [{ ...row, place_id: row.place_id }])); + } + + /** + * The files not in the trash attached to the trip places: through a link + * (`file_links.place_id`) or as the file's own place (`trip_files.place_id`). + */ + async filesOfPlaces(placeIds: number[]): Promise { + const db = this.db(); + const columns = [ + 'f.id as file_id', + 'f.trip_id', + 'f.original_name', + 'f.mime_type', + 'f.file_size', + 'f.created_at', + ] as const; + const linked = await db + .selectFrom('file_links as l') + .innerJoin('trip_files as f', 'f.id', 'l.file_id') + .innerJoin('places as p', 'p.id', 'l.place_id') + .select([...columns, 'p.id as place_id']) + .where('l.place_id', 'in', idsOrNone(placeIds)) + .whereRef('p.trip_id', '=', 'f.trip_id') + .where('f.deleted_at', 'is', null) + .execute(); + const own = await db + .selectFrom('trip_files as f') + .innerJoin('places as p', 'p.id', 'f.place_id') + .select([...columns, 'p.id as place_id']) + .where('f.place_id', 'in', idsOrNone(placeIds)) + .whereRef('p.trip_id', '=', 'f.trip_id') + .where('f.deleted_at', 'is', null) + .execute(); + const seen = new Set(); + return [...linked, ...own] + .filter((row) => { + const key = `${row.file_id}:${row.place_id}`; + if (seen.has(key)) return false; + seen.add(key); + return true; + }) + .sort((a, b) => a.file_id - b.file_id || a.place_id - b.place_id); + } +} diff --git a/server/src/db/repositories/PlacesLibrary.repository.ts b/server/src/db/repositories/PlacesLibrary.repository.ts index 16b795d3a..3a5fe22fb 100644 --- a/server/src/db/repositories/PlacesLibrary.repository.ts +++ b/server/src/db/repositories/PlacesLibrary.repository.ts @@ -27,6 +27,8 @@ type LibraryDB = Pick< | 'days' | 'user_places' | 'user_place_links' + | 'tags' + | 'personal_place_tags' >; /** @@ -38,7 +40,7 @@ const NO_ROW = 0; const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [NO_ROW]); /** What reading an entry's uses matches: everything. */ -const NO_MATCH: LibraryMatch = { search: null, categoryId: null, status: null }; +const NO_MATCH: LibraryMatch = { search: null, categoryId: null, status: null, tags: null }; /** * The road trip stops that belong to the drive rather than to the places of @@ -79,6 +81,29 @@ export interface LibraryMatch { categoryId: number | null; /** A list's status; only saved places have one. */ status: string | null; + /** PLC-21: only entries carrying at least one of these personal tags of the user. */ + tags: LibraryTagMatch | null; +} + +/** + * The personal tags an entry must carry one of (PLC-21). `reach` is every trip + * and list the user can open: a tag on any use of an entry counts, also on a + * use another filter of the page leaves out. + */ +interface LibraryTagMatch { + tagIds: number[]; + reach: LibraryArms; +} + +/** One personal tag on one target, with the own place a merged one went into. */ +export interface LibraryEntryTagRow { + id: number; + name: string; + color: string | null; + user_place_id: number | null; + merged_into_id: number | null; + place_id: number | null; + collection_place_id: number | null; } /** Where an entry stands in the list's order: its sort value and its key. */ @@ -145,12 +170,17 @@ export interface LibraryTripPlaceRow extends PlaceFactsRow { trip_start: string | null; trip_end: string | null; trip_owner_id: number; + /** The trip's cover picture, for the card that names it. */ + trip_cover?: string | null; } export interface LibraryCollectionPlaceRow extends PlaceFactsRow { id: number; collection_id: number; collection_name: string; + /** The list's own colour and symbol, as its rail row shows them. */ + collection_color?: string | null; + collection_icon?: string | null; status: string; } @@ -424,11 +454,68 @@ export class PlacesLibraryRepository { .as('u'); } + /** The user's personal tags among `tagIds`, the only tags a statement here matches. */ + private ownTagIds(db: Kysely, userId: number, tagIds: readonly number[]) { + return db + .selectFrom('tags as tg') + .select('tg.id') + .where('tg.user_id', '=', userId) + .where('tg.trip_id', 'is', null) + .where('tg.id', 'in', idsOrNone(tagIds)); + } + + /** + * The entries that carry one of the tags (PLC-21): a tag on one of an + * entry's uses, or on its own place or one merged into that. + */ + private taggedAnchors(db: Kysely, tags: LibraryTagMatch) { + const onUses = db + .selectFrom(this.entries(db, tags.reach, NO_MATCH)) + .select('u.anchor_key') + .where((eb) => + eb.exists( + eb + .selectFrom('personal_place_tags as pt') + .select('pt.id') + .where('pt.tag_id', 'in', this.ownTagIds(db, tags.reach.userId, tags.tagIds)) + .where((inner) => + inner.or([ + inner.and([inner('u.from_list', '=', 0), inner('pt.place_id', '=', inner.ref('u.use_id'))]), + inner.and([inner('u.from_list', '=', 1), inner('pt.collection_place_id', '=', inner.ref('u.use_id'))]), + ]), + ), + ), + ) + .$castTo<{ anchor_key: number }>(); + const onIdentities = db + .selectFrom('personal_place_tags as pi') + .innerJoin('user_places as upi', 'upi.id', 'pi.user_place_id') + .select((eb) => + eb( + eb(eb.fn.coalesce('upi.merged_into_id', 'upi.id'), '*', eb.lit(ANCHOR_SPAN)).$castTo(), + '+', + eb.lit(ANCHOR_OWN), + ) + .$castTo() + .as('anchor_key'), + ) + .where('upi.user_id', '=', tags.reach.userId) + .where('pi.tag_id', 'in', this.ownTagIds(db, tags.reach.userId, tags.tagIds)) + .$castTo<{ anchor_key: number }>(); + return db.selectFrom(onUses.union(onIdentities).as('tagged')).select('tagged.anchor_key'); + } + + /** The union of the entries, narrowed to the ones carrying a tag when the match names tags. */ + private matching(db: Kysely, arms: LibraryArms, match: LibraryMatch) { + const tags = match.tags; + const all = db.selectFrom(this.entries(db, arms, match)); + return tags === null ? all : all.where('u.anchor_key', 'in', this.taggedAnchors(db, tags)); + } + /** How many entries match: all of them, those with a trip place, those with a saved place. */ async countEntries(arms: LibraryArms, match: LibraryMatch): Promise { const db = this.db(); - const row = await db - .selectFrom(this.entries(db, arms, match)) + const row = await this.matching(db, arms, match) .select((eb) => [ eb.fn.count('u.anchor_key').distinct().as('all'), eb.fn @@ -455,8 +542,7 @@ export class PlacesLibraryRepository { const db = this.db(); const value = after?.value ?? ''; const key = after?.key ?? 0; - const rows = await db - .selectFrom(this.entries(db, arms, match)) + const rows = await this.matching(db, arms, match) .select(['u.anchor_key', 'u.sort_name', 'u.sort_time']) .distinct() .$if(after !== null && sort === 'name', (qb) => @@ -525,6 +611,47 @@ export class PlacesLibraryRepository { return row ? Number(row.anchor_key) : null; } + /** + * The user's personal tags on the targets (PLC-21), by name: on their own + * places or ones merged into them, on trip places, on saved places. Only + * the user's own personal tags, so nobody reads another person's. + */ + async entryTags( + userId: number, + targets: { identityIds: number[]; placeIds: number[]; collectionPlaceIds: number[] }, + ): Promise { + const { identityIds, placeIds, collectionPlaceIds } = targets; + if (identityIds.length + placeIds.length + collectionPlaceIds.length === 0) return []; + return await this.db() + .selectFrom('personal_place_tags as pt') + .innerJoin('tags as tg', 'tg.id', 'pt.tag_id') + .leftJoin('user_places as upt', 'upt.id', 'pt.user_place_id') + .select([ + 'tg.id', + 'tg.name', + 'tg.color', + 'pt.user_place_id', + 'upt.merged_into_id', + 'pt.place_id', + 'pt.collection_place_id', + ]) + .where('tg.user_id', '=', userId) + .where('tg.trip_id', 'is', null) + .where((eb) => + eb.or([ + eb.and([ + eb('upt.user_id', '=', userId), + eb.or([eb('upt.id', 'in', idsOrNone(identityIds)), eb('upt.merged_into_id', 'in', idsOrNone(identityIds))]), + ]), + eb('pt.place_id', 'in', idsOrNone(placeIds)), + eb('pt.collection_place_id', 'in', idsOrNone(collectionPlaceIds)), + ]), + ) + .orderBy('tg.name') + .orderBy('tg.id') + .execute(); + } + /** The trip places with their trip and category, for the entries of a page. */ async tripPlaces(placeIds: number[], tripIds: number[]): Promise { return await this.db() @@ -554,6 +681,7 @@ export class PlacesLibraryRepository { 't.start_date as trip_start', 't.end_date as trip_end', 't.user_id as trip_owner_id', + 't.cover_image as trip_cover', ]) .where('p.id', 'in', idsOrNone(placeIds)) .where('p.trip_id', 'in', idsOrNone(tripIds)) @@ -571,6 +699,8 @@ export class PlacesLibraryRepository { 'cp.id', 'cp.collection_id', 'col.name as collection_name', + 'col.color as collection_color', + 'col.icon as collection_icon', 'cp.status', 'cp.name', 'cp.address', diff --git a/server/src/nest/app.module.ts b/server/src/nest/app.module.ts index bcd4e7d37..b3441c4eb 100644 --- a/server/src/nest/app.module.ts +++ b/server/src/nest/app.module.ts @@ -76,10 +76,13 @@ 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 { PlaceActivitiesModule } from './place-activities/place-activities.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'; +import { PlaceHistoryModule } from './places-library/place-history.module'; +import { PlaceVisitsModule } from './places-library/place-visits.module'; import { PlacesLibraryModule } from './places-library/places-library.module'; import { PlacesModule } from './places/places.module'; import { PlatformModule } from './platform/platform.module'; @@ -205,6 +208,9 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core'; TripJournalLinkModule, CollectionsModule, PlacesLibraryModule, + PlaceVisitsModule, + PlaceHistoryModule, + PlaceActivitiesModule, TripCollectionsModule, ShareModule, TripInviteModule, diff --git a/server/src/nest/assistant/assistant-tool-offer.ts b/server/src/nest/assistant/assistant-tool-offer.ts index 228634774..c11b4e620 100644 --- a/server/src/nest/assistant/assistant-tool-offer.ts +++ b/server/src/nest/assistant/assistant-tool-offer.ts @@ -306,8 +306,16 @@ const CORE_TOOL_GROUPS: ToolGroups = { bookings: { about: "The trip's bookings: flights, trains, stays and every other reservation, the hotels and other " + - 'accommodation, airports and the live status of a flight.', - controllers: ['ReservationsMcp', 'ReservationsReadMcp', 'AccommodationsMcp', 'AirportsMcp', 'FlightLiveMcp'], + 'accommodation, airports, the live status of a flight, and the bookings and tours a place of the trip is ' + + 'about (linking them to it).', + controllers: [ + 'ReservationsMcp', + 'ReservationsReadMcp', + 'AccommodationsMcp', + 'AirportsMcp', + 'FlightLiveMcp', + 'PlaceActivitiesMcp', + ], tripPart: true, }, packing: { @@ -398,9 +406,20 @@ const CORE_TOOL_GROUPS: ToolGroups = { collections: { about: 'Collections and all places: saved places across trips, their labels and ratings, every place of the user ' + - 'in one library, the places that are one and the same (linking, merging and undoing a merge, duplicates) ' + - 'and the lists linked to this trip.', - controllers: ['CollectionsMcp', 'PlacesLibraryMcp', 'PlaceIdentitiesMcp', 'TripCollectionsMcp'], + 'in one library, the places that are one and the same (linking, merging and undoing a merge, duplicates), ' + + 'your personal tags on them, the lists linked to this trip and the places visited on past trip days, with ' + + 'their photos and files, the history of who changed which detail of a place, and the bookings and tours ' + + 'a saved place or a place of the library is about.', + controllers: [ + 'CollectionsMcp', + 'PlacesLibraryMcp', + 'PlaceIdentitiesMcp', + 'PlaceTagsMcp', + 'TripCollectionsMcp', + 'PlaceVisitsMcp', + 'PlaceHistoryMcp', + 'SavedPlaceActivitiesMcp', + ], }, collab: { about: 'Trip chat: notes, polls, shared links and messages to the people on the trip.', diff --git a/server/src/nest/collections/collections.helpers.ts b/server/src/nest/collections/collections.helpers.ts index 0e1c63443..594a1d0c0 100644 --- a/server/src/nest/collections/collections.helpers.ts +++ b/server/src/nest/collections/collections.helpers.ts @@ -193,3 +193,42 @@ export async function tripTagIdsOf( return [...ids, id]; }, Promise.resolve([])); } + +/** A tag as a copy into a trip brings it along: the name and colour a trip tag of that name takes. */ +interface CarriedTag { + name: string; + color: string; +} + +/** The colour a personal tag stored without one comes along with, the tags' own default. */ +const DEFAULT_TAG_COLOR = '#10b981'; + +/** + * D9/PLC-21: the tags each copied saved place brings into the trip, by saved + * place id. A saved place's tags and the copier's personal tags stay where they + * are unless asked for: `tag_ids` names the list's tags to bring where the + * place carries them, `personal_tag_ids` the copier's own personal tags to + * share, which come along on every copy (an id that is not one of the + * copier's personal tags is ignored). Null when neither is asked for, so no + * tag is read or made. Each becomes a tag of the trip, independent of the tag + * it came from. + */ +export async function tagsToCarry( + body: { tag_ids?: number[]; personal_tag_ids?: number[] }, + placeIds: number[], + lists: { loadTagsByPlaceIds(ids: number[]): Promise<{ pid: number; id: number; name: string; color: string }[]> }, + personalTags: () => Promise<{ id: number; name: string; color: string | null; trip_id: number | null }[]>, +): Promise | null> { + const asked = new Set(body.tag_ids ?? []); + const shared = new Set(body.personal_tag_ids ?? []); + if (asked.size === 0 && shared.size === 0) return null; + const listed = asked.size ? (await lists.loadTagsByPlaceIds(placeIds)).filter((tag) => asked.has(tag.id)) : []; + const personal = shared.size + ? (await personalTags()) + .filter((tag) => tag.trip_id === null && shared.has(tag.id)) + // A legacy row can hold a number as its name, so it is read as text. + .map((tag) => ({ name: String(tag.name), color: tag.color ?? DEFAULT_TAG_COLOR })) + : []; + const byPlace = groupByPid(listed, (tag) => ({ name: tag.name, color: tag.color })); + return Object.fromEntries(placeIds.map((id) => [id, [...(byPlace[id] ?? []), ...personal]])); +} diff --git a/server/src/nest/collections/collections.mcp.ts b/server/src/nest/collections/collections.mcp.ts index a68d963b9..bd2232c55 100644 --- a/server/src/nest/collections/collections.mcp.ts +++ b/server/src/nest/collections/collections.mcp.ts @@ -447,7 +447,7 @@ export class CollectionsMcp { @Tool({ name: 'copy_collection_places_to_trip', description: - "Copy one or more saved collection places into a trip (dedup precheck on the server). Ratings (#1435) travel into the trip; trip members keep voting there. A saved place's notes and tags stay in the list unless asked for: include_notes: true copies the notes, tag_ids names the tags (of those the places carry) to bring, each as a tag of the trip, reusing a trip tag of the same name. Without either field, neither is copied. Requires edit access to the target trip.", + "Copy one or more saved collection places into a trip (dedup precheck on the server). Ratings (#1435) travel into the trip; trip members keep voting there. A saved place's notes and tags stay in the list unless asked for: include_notes: true copies the notes, tag_ids names the tags (of those the places carry) to bring, each as a tag of the trip, reusing a trip tag of the same name. Without either field, neither is copied. Your personal tags (list_tags) stay private too: personal_tag_ids names the ones to share, each put on every copied place as a tag of the trip the same way; the trip tag and your personal tag are separate from then on. Requires edit access to the target trip.", inputSchema: collectionCopyToTripRequestSchema.shape, annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT, when: collectionsAddonOn, diff --git a/server/src/nest/collections/collections.module.ts b/server/src/nest/collections/collections.module.ts index 4e8511155..38d94b635 100644 --- a/server/src/nest/collections/collections.module.ts +++ b/server/src/nest/collections/collections.module.ts @@ -16,6 +16,7 @@ import { AppConfigModule } from '../app-config/app-config.module'; import { McpSharedModule } from '../mcp-shared/mcp-shared.module'; import { NotificationsModule } from '../notifications/notifications.module'; import { PermissionsModule } from '../permissions/permissions.module'; +import { PlaceChangesModule } from '../place-changes/place-changes.module'; import { PlaceImportModule } from '../place-import/place-import.module'; import { PlacesModule } from '../places/places.module'; import { buildStorageUploadOptions } from '../storage/storage-upload.factory'; @@ -62,6 +63,8 @@ import { MulterModule } from '@nestjs/platform-express'; // Copying saved places into a trip runs the places domain's journey hook, and // the copy tool sends its place events the way every MCP tool does. PlacesModule, + // PLC-14: every write of a saved place's details keeps its history, in the write's transaction. + PlaceChangesModule, McpSharedModule, MikroOrmModule.forFeature([ Collections, diff --git a/server/src/nest/collections/collections.service.ts b/server/src/nest/collections/collections.service.ts index 9d143fef8..aeca9a375 100644 --- a/server/src/nest/collections/collections.service.ts +++ b/server/src/nest/collections/collections.service.ts @@ -69,11 +69,12 @@ import type { CollectionImportablesResponse, } from '@trek/shared'; import { NotificationsService } from '../notifications/notifications.service'; +import { PlaceChangesService, savedPlaceTarget } from '../place-changes/place-changes.service'; import { PlaceImportService, type ExportedCollectionFile } from '../place-import/place-import.service'; import { UnitOfWork } from '../database/unit-of-work'; import { - filePlaceOf, groupByPid, listingWriteOf, parseLinks, placeOrderOf, serializeLinks, tagKeyOf, tripDedupSet, tripPlaceFields, - tripTagIdsOf, + filePlaceOf, groupByPid, listingWriteOf, parseLinks, placeOrderOf, serializeLinks, tagKeyOf, tripDedupSet, + tagsToCarry, tripPlaceFields, tripTagIdsOf, } from './collections.helpers'; // Errors: a DomainError carrying a status; TrekExceptionFilter maps it to that code with an `{ error }` body. @@ -122,6 +123,7 @@ export class CollectionsService { @InjectRepository(Users) private readonly users: UsersRepository, private readonly placeImport: PlaceImportService, private readonly places: PlacesService, // the journey hook of every place copyToTrip adds + private readonly changes: PlaceChangesService, // PLC-14: the history of every details write, in its transaction ) {} // ------------------------------------------------------------------------- @@ -861,7 +863,7 @@ export class CollectionsService { // Field update + tag rewrite + label rewrite are one logical write, so one transaction. await this.uow.transactional(async () => { if (movedTo) write.sort_order = await this.nextPlaceOrder(movedTo); // a moved place joins the end of its new list - await this.collectionPlaces.updateFields(placeId, write); + await this.changes.track(savedPlaceTarget(placeId), userId, () => this.collectionPlaces.updateFields(placeId, write)); if (body.tag_ids !== undefined) { await this.collectionPlaces.deleteTags(placeId); @@ -883,7 +885,7 @@ export class CollectionsService { async setStatus(userId: number, placeId: number, status: CollectionStatus, socketId?: string): Promise { const collectionId = await this.collectionIdOfPlace(placeId); await this.assertCanEdit(userId, collectionId); - await this.collectionPlaces.setStatus(placeId, status); + await this.uow.transactional(() => this.changes.track(savedPlaceTarget(placeId), userId, () => this.collectionPlaces.setStatus(placeId, status))); await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated'); return this.getPlaceById(placeId); } @@ -957,7 +959,7 @@ export class CollectionsService { let updated = 0; await this.uow.transactional(async () => { for (const id of ids) { - updated += await this.collectionPlaces.setStatusIfChanged(id, status); + updated += await this.changes.track(savedPlaceTarget(id), userId, () => this.collectionPlaces.setStatusIfChanged(id, status)); } }); if (updated > 0) for (const cid of touched) await this.notifyCollectionUsers(cid, socketId, 'collections:updated'); @@ -1027,7 +1029,7 @@ export class CollectionsService { const collectionId = await this.collectionIdOfPlace(placeId); await this.assertCanEdit(userId, collectionId); const prev = (await this.collectionPlaces.imageUrl(placeId)) ?? null; - await this.collectionPlaces.setImageUrl(placeId, imageUrl); + await this.uow.transactional(() => this.changes.track(savedPlaceTarget(placeId), userId, () => this.collectionPlaces.setImageUrl(placeId, imageUrl))); await this.release.releaseValues([prev]); await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated'); return this.getPlaceById(placeId); @@ -1064,11 +1066,9 @@ export class CollectionsService { } const dedup = tripDedupSet(await this.tripPlaces.dedupCandidatesForTrip(body.trip_id)); - // D9: only the tags asked for, where the saved place carries them, and as tags of the trip, never the person's own. - const asked = new Set(body.tag_ids ?? []); - const carried = asked.size - ? groupByPid((await this.collectionsRepo.loadTagsByPlaceIds(sources.map(s => s.id))).filter(t => asked.has(t.id)), t => t) - : null; + // D9/PLC-21: only the tags asked for (the list's, the caller's own), as tags of the trip. + const mine = () => this.tags.listByUser(userId); + const carried = await tagsToCarry(body, sources.map(s => s.id), this.collectionsRepo, mine); const tripTags = new Map(); // by name, read in the transaction that adds to them let tagsBefore = 0; @@ -1079,10 +1079,7 @@ export class CollectionsService { if (carried) for (const t of await this.tags.listByTrip(body.trip_id)) tripTags.set(tagKeyOf(t.name), t.id); tagsBefore = tripTags.size; for (const s of sources) { - if (!body.force && isPlaceDuplicate({ - name: s.name, lat: s.lat, lng: s.lng, - google_place_id: s.google_place_id, google_ftid: s.google_ftid, osm_id: s.osm_id, - }, dedup)) { + if (!body.force && isPlaceDuplicate(s, dedup)) { // by its name, position and provider ids skipped.push({ id: s.id, name: s.name }); continue; } diff --git a/server/src/nest/maps/maps.module.ts b/server/src/nest/maps/maps.module.ts index cff91369c..53197c895 100644 --- a/server/src/nest/maps/maps.module.ts +++ b/server/src/nest/maps/maps.module.ts @@ -4,6 +4,7 @@ import { Places } from '../../db/entities/Places.entity'; import { Users } from '../../db/entities/Users.entity'; import { AppConfigModule } from '../app-config/app-config.module'; import { GoogleQuotaModule } from '../google-quota/google-quota.module'; +import { PlaceChangesModule } from '../place-changes/place-changes.module'; import { PlacePhotosModule } from '../place-photos/place-photos.module'; import { StorageModule } from '../storage/storage.module'; import { MapsUrlResolver } from './maps-url.resolver'; @@ -51,6 +52,7 @@ import { Module } from '@nestjs/common'; PlacePhotosModule, StorageModule, GoogleQuotaModule, + PlaceChangesModule, MikroOrmModule.forFeature([AppSettings, Users, PlaceDetailsCache, Places]), ], controllers: [MapsController], diff --git a/server/src/nest/maps/place-photo.resolver.ts b/server/src/nest/maps/place-photo.resolver.ts index 99725533a..74493cef0 100644 --- a/server/src/nest/maps/place-photo.resolver.ts +++ b/server/src/nest/maps/place-photo.resolver.ts @@ -10,6 +10,8 @@ */ import { Places } from '../../db/entities/Places.entity'; import type { PlacesRepository } from '../../db/repositories/Places.repository'; +import { PlaceChangesService } from '../place-changes/place-changes.service'; +import { AUTOMATIC_CHANGE, tripPlaceTarget } from '../place-changes/place-changes.types'; import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service'; import { isGooglePlaceId } from './maps.helpers'; import { withPhotoFetchSlot } from './photo-fetch-slot'; @@ -27,6 +29,8 @@ export class PlacePhotoResolver { private readonly googlePlaces: GooglePlacesClient, private readonly wiki: WikimediaClient, private readonly selector: PlacesProviderSelector, + // PLC-14: the picture filled in here is a change of each place it lands on. + private readonly changes: PlaceChangesService, ) {} /** @@ -109,7 +113,11 @@ export class PlacePhotoResolver { // Persist stable proxy URL to database try { - await this.placesRepo.setImageUrlIfUnset(placeId, cached.photoUrl); + await this.changes.track( + async () => (await this.changes.tripPlacesWithoutImage(placeId)).map(tripPlaceTarget), + AUTOMATIC_CHANGE, + () => this.placesRepo.setImageUrlIfUnset(placeId, cached.photoUrl), + ); } catch (dbErr) { console.error('Failed to persist photo URL to database:', dbErr); } diff --git a/server/src/nest/place-activities/place-activities-library.controller.ts b/server/src/nest/place-activities/place-activities-library.controller.ts new file mode 100644 index 000000000..362269dc2 --- /dev/null +++ b/server/src/nest/place-activities/place-activities-library.controller.ts @@ -0,0 +1,35 @@ +import { ADDON_IDS } from '../../addons'; +import type { User } from '../../types'; +import { AddonGuard } from '../addons/addon.guard'; +import { RequireAddon } from '../addons/require-addon.decorator'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ResponseContract } from '../common/response-contract'; +import { rowId } from '../common/row-id.pipe'; +import { PlaceActivitiesLibraryService } from './place-activities-library.service'; +import { Controller, Get, Param, UseGuards } from '@nestjs/common'; +import { placeLibraryActivitiesResponseSchema } from '@trek/shared'; + +/** + * PLC-18 beside the place detail of All places: the bookings and tours of the + * entry over the trips and lists the user reaches, with the origins to link + * more through. Read only; behind the Collections addon like the library. + */ +@Controller('api/addons/collections/library/places') +@UseGuards(AddonGuard, JwtAuthGuard) +@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections') +export class PlaceActivitiesLibraryController { + constructor(private readonly activities: PlaceActivitiesLibraryService) {} + + @Get('trip/:id/activities') + @ResponseContract(placeLibraryActivitiesResponseSchema) + async tripPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) { + return this.activities.entry({ id: user.id, role: user.role }, 'trip', id); + } + + @Get('list/:id/activities') + @ResponseContract(placeLibraryActivitiesResponseSchema) + async savedPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) { + return this.activities.entry({ id: user.id, role: user.role }, 'list', id); + } +} diff --git a/server/src/nest/place-activities/place-activities-library.service.ts b/server/src/nest/place-activities/place-activities-library.service.ts new file mode 100644 index 000000000..fa36a0f53 --- /dev/null +++ b/server/src/nest/place-activities/place-activities-library.service.ts @@ -0,0 +1,71 @@ +import { ADDON_IDS } from '../../addons'; +import { AddonsService } from '../addons/addons.service'; +import { PlacesLibraryService, placeNotFound, type LibraryUser } from '../places-library/places-library.service'; +import { oncePerTarget, savedPlaceActivities, tripPlaceActivities } from './place-activities.helpers'; +import { PlaceActivitiesService } from './place-activities.service'; +import { Injectable } from '@nestjs/common'; +import type { + PlaceActivity, + PlaceLibraryActivitiesResponse, + PlaceLibraryActivitySource, + PlacesLibraryKind, +} from '@trek/shared'; + +/** + * PLC-18 in All places: the bookings and tours of an entry over every origin + * of it the user reaches right now, read with the library's own reach for + * every call (a trip place of a trip they can open, a saved place of a list + * open to them). An activity of an origin out of reach is left out without + * a trace, and one that several origins name is shown once, under the first. + * With the entry come its origins and whether the user may link activities + * on each, so a link is made through the trip place or saved place it goes to. + * Read only. + */ +@Injectable() +export class PlaceActivitiesLibraryService { + constructor( + private readonly library: PlacesLibraryService, + private readonly activities: PlaceActivitiesService, + private readonly addons: AddonsService, + ) {} + + async entry(user: LibraryUser, kind: PlacesLibraryKind, id: number): Promise { + const reach = await this.library.reach(user.id); + const anchor = await this.library.anchorOfUse(reach, kind, id); + if (anchor === null) throw placeNotFound(); + const [rows] = await this.library.rows(reach, [anchor]); + if (!rows) throw placeNotFound(); + const access = await this.library.access(user, rows.trips, rows.saved); + const toursOn = await this.addons.isAddonEnabled(ADDON_IDS.TOURS); + + const tripRows = await this.activities.tripRows( + rows.trips.map((row) => row.id), + [...new Set(rows.trips.map((row) => row.trip_id))], + ); + const keptRows = await this.activities.savedRows(rows.saved.map((row) => row.id)); + + const activities: PlaceActivity[] = []; + const sources: PlaceLibraryActivitySource[] = []; + for (const row of rows.trips) { + const canLink = access.canEditTrip(row); + const source = { kind: 'trip', trip_id: row.trip_id, place_id: row.id } as const; + activities.push(...tripPlaceActivities(source, tripRows, canLink)); + sources.push({ + source, + origin: { kind: 'trip', trip_id: row.trip_id, trip_title: row.trip_title }, + can_link: canLink, + }); + } + for (const row of rows.saved) { + const canLink = access.canEditList(row) && toursOn; + const source = { kind: 'list', collection_id: row.collection_id, collection_place_id: row.id } as const; + activities.push(...savedPlaceActivities(source, keptRows, canLink)); + sources.push({ + source, + origin: { kind: 'list', collection_id: row.collection_id, collection_name: row.collection_name }, + can_link: canLink, + }); + } + return { activities: oncePerTarget(activities), sources }; + } +} diff --git a/server/src/nest/place-activities/place-activities.controller.ts b/server/src/nest/place-activities/place-activities.controller.ts new file mode 100644 index 000000000..846bc541b --- /dev/null +++ b/server/src/nest/place-activities/place-activities.controller.ts @@ -0,0 +1,96 @@ +import type { TripAccess } from '../../db/repositories/Trips.repository'; +import type { User } from '../../types'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ResponseContract } from '../common/response-contract'; +import { rowId } from '../common/row-id.pipe'; +import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard'; +import { Trip } from '../permissions/trip.decorator'; +import { TripPlaceActivityLinkDto } from './place-activities.dto'; +import { PlaceActivitiesService } from './place-activities.service'; +import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common'; +import { placeActivitiesResponseSchema, placeActivityCandidatesResponseSchema } from '@trek/shared'; + +/** + * PLC-18 at /api/trips/:tripId/places/:placeId/activities: the bookings and + * tours of the trip a place is about. Every member reads them; linking and + * unlinking take 'place_edit'. Unlinking takes only the link off, the + * booking or tour stays as it is. + */ +@Controller('api/trips/:tripId/places/:placeId/activities') +@UseGuards(JwtAuthGuard, TripAccessGuard) +export class PlaceActivitiesController { + constructor(private readonly activities: PlaceActivitiesService) {} + + @Get() + @ResponseContract(placeActivitiesResponseSchema) + async list( + @CurrentUser() user: User, + @Trip() trip: TripAccess, + @Param('placeId', rowId('Place not found')) placeId: number, + ) { + return this.activities.tripPlace(trip.id, placeId, { id: user.id, role: user.role }); + } + + @Get('candidates') + @ResponseContract(placeActivityCandidatesResponseSchema) + async candidates( + @CurrentUser() user: User, + @Trip() trip: TripAccess, + @Param('placeId', rowId('Place not found')) placeId: number, + ) { + return this.activities.tripCandidates(trip.id, placeId, { id: user.id, role: user.role }); + } + + @Post() + @HttpCode(200) + @RequirePermission('place_edit') + @ResponseContract(placeActivitiesResponseSchema) + async link( + @CurrentUser() user: User, + @Trip() trip: TripAccess, + @Param('placeId', rowId('Place not found')) placeId: number, + @Body() body: TripPlaceActivityLinkDto, + @Headers('x-socket-id') socketId?: string, + ) { + return this.activities.linkTrip(trip.id, placeId, body, this.activities.restWriter(trip.id, user, socketId)); + } + + @Delete('reservations/:reservationId') + @HttpCode(200) + @RequirePermission('place_edit') + @ResponseContract(placeActivitiesResponseSchema) + async unlinkBooking( + @CurrentUser() user: User, + @Trip() trip: TripAccess, + @Param('placeId', rowId('Place not found')) placeId: number, + @Param('reservationId', rowId('This activity is not linked to the place')) reservationId: number, + @Headers('x-socket-id') socketId?: string, + ) { + return this.activities.unlinkTrip( + trip.id, + placeId, + { reservation_id: reservationId }, + this.activities.restWriter(trip.id, user, socketId), + ); + } + + @Delete('tours/:tourId') + @HttpCode(200) + @RequirePermission('place_edit') + @ResponseContract(placeActivitiesResponseSchema) + async unlinkTour( + @CurrentUser() user: User, + @Trip() trip: TripAccess, + @Param('placeId', rowId('Place not found')) placeId: number, + @Param('tourId', rowId('This activity is not linked to the place')) tourId: number, + @Headers('x-socket-id') socketId?: string, + ) { + return this.activities.unlinkTrip( + trip.id, + placeId, + { tour_id: tourId }, + this.activities.restWriter(trip.id, user, socketId), + ); + } +} diff --git a/server/src/nest/place-activities/place-activities.dto.ts b/server/src/nest/place-activities/place-activities.dto.ts new file mode 100644 index 000000000..1875918ce --- /dev/null +++ b/server/src/nest/place-activities/place-activities.dto.ts @@ -0,0 +1,7 @@ +import { savedPlaceActivityLinkRequestSchema, tripPlaceActivityLinkRequestSchema } from '@trek/shared'; + +import { createZodDto } from 'nestjs-zod'; + +export class TripPlaceActivityLinkDto extends createZodDto(tripPlaceActivityLinkRequestSchema) {} + +export class SavedPlaceActivityLinkDto extends createZodDto(savedPlaceActivityLinkRequestSchema) {} diff --git a/server/src/nest/place-activities/place-activities.helpers.ts b/server/src/nest/place-activities/place-activities.helpers.ts new file mode 100644 index 000000000..5fb4c716c --- /dev/null +++ b/server/src/nest/place-activities/place-activities.helpers.ts @@ -0,0 +1,192 @@ +import type { + ActivityBookingRow, + ActivityKeptTourRow, + ActivityTourRow, + ImplicitVia, +} from '../../db/repositories/PlaceActivityLinks.repository'; +import { badRequest } from '../common/domain-error'; +import type { PlaceActivity, PlaceActivityCandidate, PlaceActivitySource } from '@trek/shared'; + +/** + * PLC-18, the pure half of the place activities: rows into the wire shape, + * one activity per target and source, and the candidates left to link. + */ + +const bookingKey = (reservationId: number) => `reservation:${reservationId}`; +const tourKey = (tourId: number) => `tour:${tourId}`; +const keptTourKey = (collectionTourId: number) => `collection_tour:${collectionTourId}`; + +export function bookingCandidate(row: ActivityBookingRow): PlaceActivityCandidate { + return { + key: bookingKey(row.reservation_id), + type: 'booking', + origin: { kind: 'trip', trip_id: row.trip_id, trip_title: row.trip_title }, + target: { kind: 'reservation', trip_id: row.trip_id, reservation_id: row.reservation_id }, + title: row.title, + booking_type: row.type, + booking_status: row.status, + tour_type: null, + starts_at: row.reservation_time, + ends_at: row.reservation_end_time, + date: row.date, + day_number: row.day_number, + }; +} + +export function tourCandidate(row: ActivityTourRow): PlaceActivityCandidate { + return { + key: tourKey(row.tour_id), + type: 'tour', + origin: { kind: 'trip', trip_id: row.trip_id, trip_title: row.trip_title }, + target: { kind: 'tour', trip_id: row.trip_id, tour_id: row.tour_id }, + title: row.title, + booking_type: null, + booking_status: null, + tour_type: row.tour_type, + starts_at: null, + ends_at: null, + date: row.date, + day_number: row.day_number, + }; +} + +export function keptTourCandidate(row: ActivityKeptTourRow): PlaceActivityCandidate { + return { + key: keptTourKey(row.collection_tour_id), + type: 'tour', + origin: { kind: 'list', collection_id: row.collection_id, collection_name: row.collection_name }, + target: { kind: 'collection_tour', collection_id: row.collection_id, collection_tour_id: row.collection_tour_id }, + title: row.title, + booking_type: null, + booking_status: null, + tour_type: row.tour_type, + starts_at: null, + ends_at: null, + date: null, + day_number: null, + }; +} + +/** What the trip side read for a set of trip places: links, bookings that belong on their own, and tours. */ +export interface TripActivityRows { + linkedBookings: ActivityBookingRow[]; + implicitBookings: (ActivityBookingRow & { via: ImplicitVia })[]; + linkedTours: ActivityTourRow[]; + /** Tours with a station that stands for the place. */ + stationTours: ActivityTourRow[]; +} + +/** The order an implicit reason is named in when a booking belongs for more than one. */ +const VIA_ORDER: readonly ImplicitVia[] = ['place', 'stay', 'plan']; + +/** + * The activities of the trip place `placeId`: every booking linked to it or + * belonging to it on its own (once, with both flags), then every tour linked + * to it or with a station for it, the same way. `canUnlink` is whether the + * reader may change the place's links; only a link can be taken off. + */ +export function tripPlaceActivities( + source: Extract, + rows: TripActivityRows, + canUnlink: boolean, +): PlaceActivity[] { + const ofPlace = (list: T[]) => + list.filter((row) => row.source_id === source.place_id); + const bookings = new Map(); + for (const row of ofPlace(rows.linkedBookings)) { + bookings.set(row.reservation_id, { row, explicit: true, via: null }); + } + for (const row of ofPlace(rows.implicitBookings)) { + const known = bookings.get(row.reservation_id); + const via = known?.via ?? null; + const first = via === null || VIA_ORDER.indexOf(row.via) < VIA_ORDER.indexOf(via) ? row.via : via; + bookings.set(row.reservation_id, { row: known?.row ?? row, explicit: known?.explicit ?? false, via: first }); + } + const sorted = [...bookings.values()].sort((a, b) => compareBookings(a.row, b.row)); + return [ + ...sorted.map(({ row, explicit, via }) => ({ + ...bookingCandidate(row), + source, + explicit, + implicit_via: via, + can_unlink: canUnlink && explicit, + })), + ...placeTours(ofPlace(rows.linkedTours), ofPlace(rows.stationTours)).map(({ row, explicit, station }) => ({ + ...tourCandidate(row), + source, + explicit, + implicit_via: station ? ('station' as const) : null, + can_unlink: canUnlink && explicit, + })), + ]; +} + +/** The tours of one place, each once: linked, with a station for the place, or both; by name as read. */ +function placeTours(linked: ActivityTourRow[], stations: ActivityTourRow[]) { + const tours = new Map(); + for (const row of linked) tours.set(row.tour_id, { row, explicit: true, station: false }); + for (const row of stations) { + const known = tours.get(row.tour_id); + tours.set(row.tour_id, { row: known?.row ?? row, explicit: known?.explicit ?? false, station: true }); + } + return [...tours.values()].sort((a, b) => a.row.title.localeCompare(b.row.title) || a.row.tour_id - b.row.tour_id); +} + +/** The kept tours linked to the saved place of `source`. */ +export function savedPlaceActivities( + source: Extract, + rows: ActivityKeptTourRow[], + canUnlink: boolean, +): PlaceActivity[] { + return rows + .filter((row) => row.source_id === source.collection_place_id) + .map((row) => ({ + ...keptTourCandidate(row), + source, + explicit: true, + implicit_via: null, + can_unlink: canUnlink, + })); +} + +/** By time as stored (no time last), then by id, the order the repository reads them in. */ +function compareBookings(a: ActivityBookingRow, b: ActivityBookingRow): number { + if (a.reservation_time !== b.reservation_time) { + if (a.reservation_time === null) return 1; + if (b.reservation_time === null) return -1; + return a.reservation_time < b.reservation_time ? -1 : 1; + } + return a.reservation_id - b.reservation_id; +} + +/** The candidates not yet related to the place: everything whose key is not among `taken`. */ +export function remainingCandidates( + candidates: PlaceActivityCandidate[], + taken: readonly PlaceActivity[], +): PlaceActivityCandidate[] { + const keys = new Set(taken.map((activity) => activity.key)); + return candidates.filter((candidate) => !keys.has(candidate.key)); +} + +/** Each activity once, under the first source it came with, so an entry of All places names it once. */ +export function oncePerTarget(activities: PlaceActivity[]): PlaceActivity[] { + const seen = new Set(); + return activities.filter((activity) => { + if (seen.has(activity.key)) return false; + seen.add(activity.key); + return true; + }); +} + +/** What a trip place's link points at: a booking or a tour (the tour's own place) of the trip. */ +export type TripActivityTarget = { reservation_id: number } | { tour_id: number }; + +/** Exactly one of the two ids: the request schema holds it on REST, this on every surface. */ +export function tripActivityTargetOf( + reservationId: number | undefined, + tourId: number | undefined, +): TripActivityTarget { + if (reservationId !== undefined && tourId === undefined) return { reservation_id: reservationId }; + if (tourId !== undefined && reservationId === undefined) return { tour_id: tourId }; + throw badRequest('Give either reservation_id or tour_id'); +} diff --git a/server/src/nest/place-activities/place-activities.mcp.ts b/server/src/nest/place-activities/place-activities.mcp.ts new file mode 100644 index 000000000..103f6efce --- /dev/null +++ b/server/src/nest/place-activities/place-activities.mcp.ts @@ -0,0 +1,94 @@ +import { canRead, canWrite } from '../../mcp/scopes'; +import { + McpController, + Tool, + TOOL_ANNOTATIONS_DELETE, + TOOL_ANNOTATIONS_READONLY, + TOOL_ANNOTATIONS_WRITE, + ok, + type McpContext, +} from '../../nest-mcp'; +import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; +import { tripActivityTargetOf } from './place-activities.helpers'; +import { PlaceActivitiesService } from './place-activities.service'; +import { idSchema, tripPlaceActivityLinkRequestSchema } from '@trek/shared'; + +/** Reading a place's activities reads its places and its bookings. */ +const readsActivities = (ctx: McpContext) => canRead(ctx.scopes, 'places') && canRead(ctx.scopes, 'reservations'); +/** Linking changes the trip's places and names a booking or tour the caller reads. */ +const linksActivities = (ctx: McpContext) => canWrite(ctx.scopes, 'places') && canRead(ctx.scopes, 'reservations'); + +const tripPlaceInput = { tripId: idSchema, placeId: idSchema }; +const tripLinkInput = { ...tripPlaceInput, ...tripPlaceActivityLinkRequestSchema.shape }; + +type TripPlaceInput = { tripId: number; placeId: number }; +type TripLinkInput = TripPlaceInput & { reservation_id?: number; tour_id?: number }; + +/** What every activity carries, shared with the list tools in saved-place-activities.mcp.ts. */ +export const ACTIVITY_FIELDS = + 'Each activity has key, type (booking or tour), origin (the trip or list it lives in), target (to open it: trip_id with reservation_id or tour_id, or collection_id with collection_tour_id), title, booking_type and booking_status (bookings), tour_type (tours), starts_at, ends_at, date and day_number, explicit (someone linked it), implicit_via (place, stay or plan for a booking, station for a tour: it belongs to the place by itself, which cannot be undone here) and can_unlink.'; + +/** + * PLC-18 over MCP, the trip side: the same service and permissions as + * `/api/trips/:tripId/places/:placeId/activities`. The assistant loads these + * with the bookings; the list and All places tools are SavedPlaceActivitiesMcp. + */ +@McpController() +export class PlaceActivitiesMcp { + constructor( + private readonly activities: PlaceActivitiesService, + private readonly guards: McpToolGuardsService, + ) {} + + @Tool({ + name: 'list_place_activities', + description: `The bookings and tours of a trip a place of that trip is about: the ones linked to it, the bookings that belong to it by themselves (they name the place, a stay at it or a plan entry of it) and the tours with a station standing for it. Tours only while the trip has Tours on. ${ACTIVITY_FIELDS} can_link says whether you may link more.`, + inputSchema: tripPlaceInput, + annotations: TOOL_ANNOTATIONS_READONLY, + access: readsActivities, + }) + async listPlaceActivities({ tripId, placeId }: TripPlaceInput, ctx: McpContext) { + const { role } = await this.guards.tripWriter(tripId, ctx.userId); + return ok(await this.activities.tripPlace(tripId, placeId, { id: ctx.userId, role })); + } + + @Tool({ + name: 'list_place_activity_candidates', + description: + 'The bookings and tours of the trip not related to the place yet, which link_place_activity can link: same fields as list_place_activities without the link flags. The place itself, when it is a tour, is left out.', + inputSchema: tripPlaceInput, + annotations: TOOL_ANNOTATIONS_READONLY, + access: readsActivities, + }) + async listPlaceActivityCandidates({ tripId, placeId }: TripPlaceInput, ctx: McpContext) { + const { role } = await this.guards.tripWriter(tripId, ctx.userId); + return ok(await this.activities.tripCandidates(tripId, placeId, { id: ctx.userId, role })); + } + + @Tool({ + name: 'link_place_activity', + description: + 'Link a booking (reservation_id) or a tour (tour_id, the id of its place) of the same trip to a place of the trip, exactly one of the two. Changes neither the booking nor the tour. A booking or tour that already belongs to the place by itself is refused. Needs the permission to edit the trip places.', + inputSchema: tripLinkInput, + annotations: TOOL_ANNOTATIONS_WRITE, + access: linksActivities, + }) + async linkPlaceActivity({ tripId, placeId, reservation_id, tour_id }: TripLinkInput, ctx: McpContext) { + const writer = await this.guards.tripWriter(tripId, ctx.userId); + return ok(await this.activities.linkTrip(tripId, placeId, { reservation_id, tour_id }, writer)); + } + + @Tool({ + name: 'unlink_place_activity', + description: + 'Take the link of a place to a booking (reservation_id) or a tour (tour_id) off, exactly one of the two. The booking or tour stays as it is; what belongs to the place by itself is changed on the booking or the tour, not here. Needs the permission to edit the trip places.', + inputSchema: tripLinkInput, + annotations: TOOL_ANNOTATIONS_DELETE, + access: linksActivities, + }) + async unlinkPlaceActivity({ tripId, placeId, reservation_id, tour_id }: TripLinkInput, ctx: McpContext) { + const writer = await this.guards.tripWriter(tripId, ctx.userId); + const target = tripActivityTargetOf(reservation_id, tour_id); + return ok(await this.activities.unlinkTrip(tripId, placeId, target, writer)); + } +} diff --git a/server/src/nest/place-activities/place-activities.module.ts b/server/src/nest/place-activities/place-activities.module.ts new file mode 100644 index 000000000..562a628a0 --- /dev/null +++ b/server/src/nest/place-activities/place-activities.module.ts @@ -0,0 +1,38 @@ +import { PlaceActivityLinks } from '../../db/entities/PlaceActivityLinks.entity'; +import { AddonsModule } from '../addons/addons.module'; +import { CollectionsModule } from '../collections/collections.module'; +import { McpSharedModule } from '../mcp-shared/mcp-shared.module'; +import { PermissionsModule } from '../permissions/permissions.module'; +import { PlacesLibraryModule } from '../places-library/places-library.module'; +import { RealtimeModule } from '../realtime/realtime.module'; +import { TripMembershipModule } from '../trip-membership/trip-membership.module'; +import { PlaceActivitiesLibraryController } from './place-activities-library.controller'; +import { PlaceActivitiesLibraryService } from './place-activities-library.service'; +import { PlaceActivitiesController } from './place-activities.controller'; +import { PlaceActivitiesMcp } from './place-activities.mcp'; +import { PlaceActivitiesService } from './place-activities.service'; +import { SavedPlaceActivitiesController } from './saved-place-activities.controller'; +import { SavedPlaceActivitiesMcp } from './saved-place-activities.mcp'; +import { MikroOrmModule } from '@mikro-orm/nestjs'; +import { Module } from '@nestjs/common'; + +/** + * PLC-18: the bookings and tours a place is about, linked to a trip place or + * a saved place, and read for an entry of All places over the library's + * reach (PlacesLibraryModule). Their routes and MCP tools. + */ +@Module({ + imports: [ + AddonsModule, + CollectionsModule, + TripMembershipModule, + PermissionsModule, + RealtimeModule, + McpSharedModule, + PlacesLibraryModule, + MikroOrmModule.forFeature([PlaceActivityLinks]), + ], + controllers: [PlaceActivitiesController, SavedPlaceActivitiesController, PlaceActivitiesLibraryController], + providers: [PlaceActivitiesService, PlaceActivitiesLibraryService, PlaceActivitiesMcp, SavedPlaceActivitiesMcp], +}) +export class PlaceActivitiesModule {} diff --git a/server/src/nest/place-activities/place-activities.service.ts b/server/src/nest/place-activities/place-activities.service.ts new file mode 100644 index 000000000..8516a499a --- /dev/null +++ b/server/src/nest/place-activities/place-activities.service.ts @@ -0,0 +1,304 @@ +import { ADDON_IDS } from '../../addons'; +import { PlaceActivityLinks } from '../../db/entities/PlaceActivityLinks.entity'; +import type { + ActivitySavedPlaceRow, + PlaceActivityLinksRepository, +} from '../../db/repositories/PlaceActivityLinks.repository'; +import type { User } from '../../types'; +import { AddonsService } from '../addons/addons.service'; +import { CollectionsService } from '../collections/collections.service'; +import { badRequest, conflict, forbidden, notFound } from '../common/domain-error'; +import { requireTripWrite, restTripWriter, tripNotFound, type TripWriter } from '../common/trip-writer'; +import { UnitOfWork } from '../database/unit-of-work'; +import { PermissionsService } from '../permissions/permissions.service'; +import { RealtimeService } from '../realtime/realtime.service'; +import { TripAccessService } from '../trip-membership/trip-access.service'; +import { + bookingCandidate, + keptTourCandidate, + remainingCandidates, + savedPlaceActivities, + tourCandidate, + tripActivityTargetOf, + tripPlaceActivities, + type TripActivityRows, + type TripActivityTarget, +} from './place-activities.helpers'; +import { InjectRepository } from '@mikro-orm/nestjs'; +import { Injectable } from '@nestjs/common'; +import type { + PlaceActivitiesResponse, + PlaceActivity, + PlaceActivityCandidatesResponse, + PlaceActivitySource, + SavedPlaceActivityLinkRequest, + TripPlaceActivityLinkRequest, +} from '@trek/shared'; + +/** Who reads: their id and their account role, for the admin bypass of trip permissions. */ +interface PlaceActivitiesReader { + id: number; + role: string; +} + +/** + * Linking a booking or a tour to a place changes what the place shows to + * everyone on the trip, so it takes the right to change the trip's places. + * Seeing the booking or the tour is the trip itself: every member sees every + * booking and, while the trip has Tours on, every tour. + */ +const LINK_PERMISSION = 'place_edit'; + +const placeNotFound = () => notFound('Place not found'); +const bookingNotFound = () => notFound('Booking not found'); +const tourNotFound = () => notFound('Tour not found', { code: 'tour_not_found' }); +const notLinked = () => notFound('This activity is not linked to the place'); + +/** + * PLC-18: the bookings and tours a place is about. A trip place is linked to + * bookings and tours of its own trip, a saved place to tours kept in its own + * list; a booking that names the place itself (its place, a stay at the + * place, a plan entry of the place) and a tour with a station standing for + * the place belong to it without a link, are shown as such and cannot be + * unlinked here. A link changes neither end and gives no + * one access, and unlinking takes only the link: the booking or tour stays. + * + * Trip side: reading takes the trip; linking and unlinking take + * 'place_edit' on it. Tours count only while the trip has the Tours addon on. + * List side: reading takes any role on the list, linking and unlinking any + * role but viewer, and kept tours count only while Tours is on. A trip or + * list out of reach is not found, never hinted at. + */ +@Injectable() +export class PlaceActivitiesService { + constructor( + @InjectRepository(PlaceActivityLinks) private readonly links: PlaceActivityLinksRepository, + private readonly trips: TripAccessService, + private readonly permissions: PermissionsService, + private readonly collections: CollectionsService, + private readonly addons: AddonsService, + private readonly realtime: RealtimeService, + private readonly uow: UnitOfWork, + ) {} + + /** The REST caller of a trip-side write: skips the sender's socket. */ + restWriter(tripId: number, user: User, socketId: string | undefined): TripWriter { + return restTripWriter(this.realtime, tripId, user, socketId); + } + + // ── Trip places ──────────────────────────────────────────────────────── + + /** The activities of the trip place, and whether the reader may link more. */ + async tripPlace(tripId: number, placeId: number, reader: PlaceActivitiesReader): Promise { + const canLink = await this.canLinkOnTrip(tripId, reader); + await this.requireTripPlace(tripId, placeId); + const source = { kind: 'trip', trip_id: tripId, place_id: placeId } as const; + return { + activities: tripPlaceActivities(source, await this.tripRows([placeId], [tripId]), canLink), + can_link: canLink, + }; + } + + /** The bookings and tours of the trip not related to the place yet, the place itself left out. */ + async tripCandidates( + tripId: number, + placeId: number, + reader: PlaceActivitiesReader, + ): Promise { + const { activities } = await this.tripPlace(tripId, placeId, reader); + const tours = (await this.addons.isEnabledForTrip(tripId, ADDON_IDS.TOURS)) + ? (await this.links.tripTours(tripId)).filter((row) => row.tour_id !== placeId) + : []; + const bookings = await this.links.tripBookings(tripId); + return { + candidates: remainingCandidates([...bookings.map(bookingCandidate), ...tours.map(tourCandidate)], activities), + }; + } + + /** + * Links a booking or a tour of the same trip to the place. Linking it again + * changes nothing and sends nothing; a booking that already belongs to the + * place on its own is refused, since its own place, stay or plan entry says so. + */ + async linkTrip( + tripId: number, + placeId: number, + body: TripPlaceActivityLinkRequest, + writer: TripWriter, + ): Promise { + const target = tripActivityTargetOf(body.reservation_id, body.tour_id); + await this.requireLinkWrite(tripId, writer); + const linked = await this.uow.transactional(async () => { + await this.requireTripPlace(tripId, placeId); + if ('reservation_id' in target) { + if (!(await this.links.bookingInTrip(tripId, target.reservation_id))) throw bookingNotFound(); + const own = await this.links.implicitBookings([placeId]); + if (own.some((row) => row.reservation_id === target.reservation_id)) { + throw conflict('This booking already belongs to the place', { code: 'implicit_activity' }); + } + return this.links.link({ place_id: placeId, reservation_id: target.reservation_id }, writer.userId); + } + if (target.tour_id === placeId) throw badRequest('A tour cannot be linked to itself'); + if (!(await this.addons.isEnabledForTrip(tripId, ADDON_IDS.TOURS))) throw tourNotFound(); + if (!(await this.links.tourInTrip(tripId, target.tour_id))) throw tourNotFound(); + const stations = await this.links.implicitTours([placeId]); + if (stations.some((row) => row.tour_id === target.tour_id)) { + throw conflict('This tour already belongs to the place', { code: 'implicit_activity' }); + } + return this.links.link({ place_id: placeId, tour_place_id: target.tour_id }, writer.userId); + }); + if (linked) writer.events.emit('placeActivities:changed', { placeId }); + return this.tripPlace(tripId, placeId, { id: writer.userId, role: writer.role }); + } + + /** Takes the link of the place to a booking or tour off; the booking or tour stays as it is. */ + async unlinkTrip( + tripId: number, + placeId: number, + target: TripActivityTarget, + writer: TripWriter, + ): Promise { + await this.requireLinkWrite(tripId, writer); + await this.requireTripPlace(tripId, placeId); + const removed = await this.links.unlinkTrip( + placeId, + 'reservation_id' in target ? { reservation_id: target.reservation_id } : { tour_place_id: target.tour_id }, + ); + if (!removed) throw notLinked(); + writer.events.emit('placeActivities:changed', { placeId }); + return this.tripPlace(tripId, placeId, { id: writer.userId, role: writer.role }); + } + + /** + * The trip-side activity rows of `placeIds`, read once for all of them; + * the linked tours only of those of the trips `tripIds` that have Tours on. + */ + async tripRows(placeIds: number[], tripIds: number[]): Promise { + const toursOn = new Set(await this.addons.tripsWithAddon(tripIds, ADDON_IDS.TOURS)); + const linkedBookings = await this.links.linkedBookings(placeIds); + const implicitBookings = await this.links.implicitBookings(placeIds); + const linkedTours = toursOn.size > 0 ? await this.links.linkedTours(placeIds) : []; + const stationTours = toursOn.size > 0 ? await this.links.implicitTours(placeIds) : []; + const shown = (row: { trip_id: number }) => toursOn.has(row.trip_id); + return { + linkedBookings, + implicitBookings, + linkedTours: linkedTours.filter(shown), + stationTours: stationTours.filter(shown), + }; + } + + /** Whether the reader may change the links of the trip's places; the trip they cannot reach is not found. */ + private async canLinkOnTrip(tripId: number, reader: PlaceActivitiesReader): Promise { + const trip = await this.trips.findAccessible(tripId, reader.id); + if (!trip) throw tripNotFound(); + return this.permissions.checkPermission( + LINK_PERMISSION, + reader.role, + trip.user_id, + reader.id, + trip.user_id !== reader.id, + ); + } + + private async requireTripPlace(tripId: number, placeId: number): Promise { + if (!(await this.links.tripPlace(tripId, placeId))) throw placeNotFound(); + } + + /** The trip with 'place_edit' (404, 403). */ + private async requireLinkWrite(tripId: number, writer: TripWriter): Promise { + await requireTripWrite({ access: this.trips, permissions: this.permissions }, LINK_PERMISSION, tripId, writer); + } + + // ── Saved places ─────────────────────────────────────────────────────── + + /** The kept tours linked to the saved place, and whether the user may link more. */ + async savedPlace(userId: number, collectionPlaceId: number): Promise { + const { place, role } = await this.readableSavedPlace(userId, collectionPlaceId); + const canLink = role !== 'viewer' && (await this.toursOn()); + return { + activities: await this.savedActivities(place, canLink), + can_link: canLink, + }; + } + + /** The tours kept in the list not linked to the saved place yet; none while Tours is off. */ + async savedCandidates(userId: number, collectionPlaceId: number): Promise { + const { place } = await this.readableSavedPlace(userId, collectionPlaceId); + if (!(await this.toursOn())) return { candidates: [] }; + const linked = await this.savedActivities(place, false); + const kept = await this.links.keptTours(place.collection_id); + return { candidates: remainingCandidates(kept.map(keptTourCandidate), linked) }; + } + + /** Links a tour kept in the same list to the saved place; linking it again changes nothing and sends nothing. */ + async linkSaved( + userId: number, + collectionPlaceId: number, + body: SavedPlaceActivityLinkRequest, + socketId?: string, + ): Promise { + const place = await this.writableSavedPlace(userId, collectionPlaceId); + const linked = await this.uow.transactional(async () => { + if (!(await this.links.keptTourInList(place.collection_id, body.collection_tour_id))) throw tourNotFound(); + return this.links.link( + { collection_place_id: collectionPlaceId, collection_tour_id: body.collection_tour_id }, + userId, + ); + }); + if (linked) await this.collections.notifyCollectionUsers(place.collection_id, socketId); + return this.savedPlace(userId, collectionPlaceId); + } + + /** + * Takes the link of the saved place to a kept tour off; the tour stays in the list. A link the place left + * behind in its old list is no link here, as it reads none. + */ + async unlinkSaved( + userId: number, + collectionPlaceId: number, + collectionTourId: number, + socketId?: string, + ): Promise { + const place = await this.writableSavedPlace(userId, collectionPlaceId); + if (!(await this.links.keptTourInList(place.collection_id, collectionTourId))) throw notLinked(); + if (!(await this.links.unlinkSaved(collectionPlaceId, collectionTourId))) throw notLinked(); + await this.collections.notifyCollectionUsers(place.collection_id, socketId); + return this.savedPlace(userId, collectionPlaceId); + } + + /** The kept tours linked to the saved places of `sources`, none while Tours is off. */ + async savedRows(collectionPlaceIds: number[]) { + return (await this.toursOn()) ? this.links.linkedKeptTours(collectionPlaceIds) : []; + } + + private async savedActivities(place: ActivitySavedPlaceRow, canUnlink: boolean): Promise { + const source: Extract = { + kind: 'list', + collection_id: place.collection_id, + collection_place_id: place.id, + }; + return savedPlaceActivities(source, await this.savedRows([place.id]), canUnlink); + } + + /** The saved place with the user's role on its list; one on a list they cannot see is not found. */ + private async readableSavedPlace(userId: number, collectionPlaceId: number) { + const place = await this.links.savedPlace(collectionPlaceId); + const role = place ? await this.collections.roleOf(userId, place.collection_id) : null; + if (!place || role === null) throw placeNotFound(); + return { place, role }; + } + + /** The saved place on a list the user may change (404, 403), with Tours on (404). */ + private async writableSavedPlace(userId: number, collectionPlaceId: number): Promise { + const { place, role } = await this.readableSavedPlace(userId, collectionPlaceId); + if (role === 'viewer') throw forbidden('You have read-only access to this list'); + if (!(await this.toursOn())) throw tourNotFound(); + return place; + } + + /** Kept tours live behind the Tours addon as well as the Collections addon. */ + private async toursOn(): Promise { + return this.addons.isAddonEnabled(ADDON_IDS.TOURS); + } +} diff --git a/server/src/nest/place-activities/saved-place-activities.controller.ts b/server/src/nest/place-activities/saved-place-activities.controller.ts new file mode 100644 index 000000000..152e56981 --- /dev/null +++ b/server/src/nest/place-activities/saved-place-activities.controller.ts @@ -0,0 +1,61 @@ +import { ADDON_IDS } from '../../addons'; +import type { User } from '../../types'; +import { AddonGuard } from '../addons/addon.guard'; +import { RequireAddon } from '../addons/require-addon.decorator'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ResponseContract } from '../common/response-contract'; +import { rowId } from '../common/row-id.pipe'; +import { SavedPlaceActivityLinkDto } from './place-activities.dto'; +import { PlaceActivitiesService } from './place-activities.service'; +import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common'; +import { placeActivitiesResponseSchema, placeActivityCandidatesResponseSchema } from '@trek/shared'; + +/** + * PLC-18 at /api/addons/collections/places/:placeId/activities: the tours + * kept in a list that one of its saved places is about. Any role on the list + * reads them; linking and unlinking take any role but viewer, and the Tours + * addon (without it a list keeps no tours). Behind the Collections addon. + */ +@Controller('api/addons/collections/places/:placeId/activities') +@UseGuards(AddonGuard, JwtAuthGuard) +@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections') +export class SavedPlaceActivitiesController { + constructor(private readonly activities: PlaceActivitiesService) {} + + @Get() + @ResponseContract(placeActivitiesResponseSchema) + async list(@CurrentUser() user: User, @Param('placeId', rowId('Place not found')) placeId: number) { + return this.activities.savedPlace(user.id, placeId); + } + + @Get('candidates') + @ResponseContract(placeActivityCandidatesResponseSchema) + async candidates(@CurrentUser() user: User, @Param('placeId', rowId('Place not found')) placeId: number) { + return this.activities.savedCandidates(user.id, placeId); + } + + @Post() + @HttpCode(200) + @ResponseContract(placeActivitiesResponseSchema) + async link( + @CurrentUser() user: User, + @Param('placeId', rowId('Place not found')) placeId: number, + @Body() body: SavedPlaceActivityLinkDto, + @Headers('x-socket-id') socketId?: string, + ) { + return this.activities.linkSaved(user.id, placeId, body, socketId); + } + + @Delete('tours/:tourId') + @HttpCode(200) + @ResponseContract(placeActivitiesResponseSchema) + async unlink( + @CurrentUser() user: User, + @Param('placeId', rowId('Place not found')) placeId: number, + @Param('tourId', rowId('This activity is not linked to the place')) tourId: number, + @Headers('x-socket-id') socketId?: string, + ) { + return this.activities.unlinkSaved(user.id, placeId, tourId, socketId); + } +} diff --git a/server/src/nest/place-activities/saved-place-activities.mcp.ts b/server/src/nest/place-activities/saved-place-activities.mcp.ts new file mode 100644 index 000000000..0d255f2c4 --- /dev/null +++ b/server/src/nest/place-activities/saved-place-activities.mcp.ts @@ -0,0 +1,120 @@ +import { ADDON_IDS } from '../../addons'; +import { canRead, canReadTrips, canWrite } from '../../mcp/scopes'; +import { + McpController, + Tool, + TOOL_ANNOTATIONS_DELETE, + TOOL_ANNOTATIONS_READONLY, + TOOL_ANNOTATIONS_WRITE, + ok, + type McpContext, +} from '../../nest-mcp'; +import { addonGate } from '../addons/addon-gate'; +import { AddonsService } from '../addons/addons.service'; +import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; +import { PlaceActivitiesLibraryService } from './place-activities-library.service'; +import { ACTIVITY_FIELDS } from './place-activities.mcp'; +import { PlaceActivitiesService } from './place-activities.service'; +import { + idSchema, + placeLibraryActivitiesRequestSchema, + savedPlaceActivityLinkRequestSchema, + type PlaceLibraryActivitiesRequest, +} from '@trek/shared'; + +/** A saved place's kept tours are the list's. */ +const readsList = (ctx: McpContext) => canRead(ctx.scopes, 'collections'); +const writesList = (ctx: McpContext) => canWrite(ctx.scopes, 'collections'); +/** An entry of All places spans trips (with their bookings) and lists. */ +const readsEntry = (ctx: McpContext) => + canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes) && canRead(ctx.scopes, 'reservations'); + +const savedPlaceInput = { collection_place_id: idSchema }; +const savedLinkInput = { ...savedPlaceInput, ...savedPlaceActivityLinkRequestSchema.shape }; + +/** + * PLC-18 over MCP, the list side: the same services, permissions and addon + * rules as `/api/addons/collections/places/:placeId/activities` and the All + * places reads. The assistant loads these with the collections; the trip + * tools are PlaceActivitiesMcp. + */ +@McpController() +export class SavedPlaceActivitiesMcp { + constructor( + private readonly activities: PlaceActivitiesService, + private readonly library: PlaceActivitiesLibraryService, + private readonly guards: McpToolGuardsService, + // Read by the addon gate of every tool here. + readonly addons: AddonsService, + ) {} + + @Tool({ + name: 'list_saved_place_activities', + description: `The tours kept in a list that one of its saved places is linked to; a place moved in from another list brings none of that list's tours along. ${ACTIVITY_FIELDS} can_link says whether you may link more (any list role but viewer, and Tours on).`, + inputSchema: savedPlaceInput, + annotations: TOOL_ANNOTATIONS_READONLY, + when: addonGate(ADDON_IDS.COLLECTIONS), + access: readsList, + }) + async listSavedPlaceActivities({ collection_place_id }: { collection_place_id: number }, ctx: McpContext) { + return ok(await this.activities.savedPlace(ctx.userId, collection_place_id)); + } + + @Tool({ + name: 'list_saved_place_activity_candidates', + description: + 'The tours kept in the list of a saved place not linked to it yet, which link_saved_place_tour can link. None while Tours is off.', + inputSchema: savedPlaceInput, + annotations: TOOL_ANNOTATIONS_READONLY, + when: addonGate(ADDON_IDS.COLLECTIONS), + access: readsList, + }) + async listSavedPlaceActivityCandidates({ collection_place_id }: { collection_place_id: number }, ctx: McpContext) { + return ok(await this.activities.savedCandidates(ctx.userId, collection_place_id)); + } + + @Tool({ + name: 'link_saved_place_tour', + description: + 'Link a tour kept in the same list to a saved place. Changes neither. Needs a list role other than viewer and the Tours addon.', + inputSchema: savedLinkInput, + annotations: TOOL_ANNOTATIONS_WRITE, + when: addonGate(ADDON_IDS.COLLECTIONS), + access: writesList, + }) + async linkSavedPlaceTour( + { collection_place_id, collection_tour_id }: { collection_place_id: number; collection_tour_id: number }, + ctx: McpContext, + ) { + return ok(await this.activities.linkSaved(ctx.userId, collection_place_id, { collection_tour_id })); + } + + @Tool({ + name: 'unlink_saved_place_tour', + description: + 'Take the link of a saved place to a kept tour off; the tour stays in the list. Needs a list role other than viewer and the Tours addon.', + inputSchema: savedLinkInput, + annotations: TOOL_ANNOTATIONS_DELETE, + when: addonGate(ADDON_IDS.COLLECTIONS), + access: writesList, + }) + async unlinkSavedPlaceTour( + { collection_place_id, collection_tour_id }: { collection_place_id: number; collection_tour_id: number }, + ctx: McpContext, + ) { + return ok(await this.activities.unlinkSaved(ctx.userId, collection_place_id, collection_tour_id)); + } + + @Tool({ + name: 'get_library_place_activities', + description: `The bookings and tours of one entry of All places, opened from a trip place (kind trip, place_id) or a saved place (kind list, collection_place_id), over the trips and lists of the entry you can open; each activity once. ${ACTIVITY_FIELDS} source names the trip place or saved place it belongs to. sources lists the origins of the entry with can_link, to link more with link_place_activity or link_saved_place_tour.`, + inputSchema: placeLibraryActivitiesRequestSchema.shape, + annotations: TOOL_ANNOTATIONS_READONLY, + when: addonGate(ADDON_IDS.COLLECTIONS), + access: readsEntry, + }) + async getLibraryPlaceActivities(input: PlaceLibraryActivitiesRequest, ctx: McpContext) { + const role = (await this.guards.isAdminUser(ctx.userId)) ? 'admin' : 'user'; + return ok(await this.library.entry({ id: ctx.userId, role }, input.kind, input.id)); + } +} diff --git a/server/src/nest/place-changes/place-changes.helpers.ts b/server/src/nest/place-changes/place-changes.helpers.ts new file mode 100644 index 000000000..43e56425e --- /dev/null +++ b/server/src/nest/place-changes/place-changes.helpers.ts @@ -0,0 +1,88 @@ +import type { + PlaceChangeClear, + PlaceChangeWrite, + PlaceDetailsRow, + SavedPlaceDetailsRow, + TripPlaceDetailsRow, +} from '../../db/repositories/PlaceChangeLog.repository'; +import { AUTOMATIC_CHANGE, type ChangeEditor, type ChangeTarget } from './place-changes.types'; +import type { PlaceHistoryField } from '@trek/shared'; + +/** What a place holds of each field its history follows, null where it holds none. */ +export type DetailsSnapshot = Partial>; + +/** A stored value as the history keeps it: text, with an empty or blank one read as none. */ +export function historyValue(value: string | number | null | undefined): string | null { + if (value === null || value === undefined) return null; + const text = String(value); + return text.trim() === '' ? null : text; +} + +/** The coordinates as one value, none unless both are there. */ +export function positionValue(lat: number | null, lng: number | null): string | null { + return lat === null || lng === null ? null : `${lat},${lng}`; +} + +function commonSnapshot(row: PlaceDetailsRow): DetailsSnapshot { + return { + name: historyValue(row.name), + address: historyValue(row.address), + position: positionValue(row.lat, row.lng), + category: historyValue(row.category_name), + description: historyValue(row.description), + notes: historyValue(row.notes), + website: historyValue(row.website), + phone: historyValue(row.phone), + image: historyValue(row.image_url), + }; +} + +export function tripPlaceSnapshot(row: TripPlaceDetailsRow): DetailsSnapshot { + return { ...commonSnapshot(row), opening_hours: historyValue(row.opening_hours) }; +} + +export function savedPlaceSnapshot(row: SavedPlaceDetailsRow): DetailsSnapshot { + return { ...commonSnapshot(row), status: historyValue(row.status) }; +} + +export const targetKey = (target: ChangeTarget): string => `${target.kind}:${target.id}`; + +/** What a write did to one place: the fields it set to a new value, and the ones it cleared. */ +interface DetailsDiff { + changed: Array<{ field: PlaceHistoryField; old_value: string | null; new_value: string }>; + cleared: PlaceHistoryField[]; +} + +export function diffDetails(before: DetailsSnapshot, after: DetailsSnapshot): DetailsDiff { + const diff: DetailsDiff = { changed: [], cleared: [] }; + for (const field of Object.keys(after) as PlaceHistoryField[]) { + const old = before[field] ?? null; + const now = after[field] ?? null; + if (old === now) continue; + if (now === null) diff.cleared.push(field); + else diff.changed.push({ field, old_value: old, new_value: now }); + } + return diff; +} + +/** The rows a diff writes and drops for one place, by who made it. */ +export function changeRowsOf( + target: ChangeTarget, + diff: DetailsDiff, + editor: ChangeEditor, +): { writes: PlaceChangeWrite[]; clear: PlaceChangeClear } { + const owner = { + place_id: target.kind === 'trip' ? target.id : null, + collection_place_id: target.kind === 'list' ? target.id : null, + }; + const automatic = editor === AUTOMATIC_CHANGE; + return { + writes: diff.changed.map((change) => ({ + ...owner, + ...change, + user_id: automatic ? null : editor, + automatic: automatic ? 1 : 0, + })), + clear: { ...owner, fields: diff.cleared }, + }; +} diff --git a/server/src/nest/place-changes/place-changes.module.ts b/server/src/nest/place-changes/place-changes.module.ts new file mode 100644 index 000000000..0b05d5836 --- /dev/null +++ b/server/src/nest/place-changes/place-changes.module.ts @@ -0,0 +1,16 @@ +import { PlaceChangeLog } from '../../db/entities/PlaceChangeLog.entity'; +import { PlaceChangesService } from './place-changes.service'; +import { MikroOrmModule } from '@mikro-orm/nestjs'; +import { Module } from '@nestjs/common'; + +/** + * PLC-14: the history of the details of trip places and saved places. Below + * the places, the collections and the maps, which record through it, and the + * places library, which reads it; it imports no domain itself. + */ +@Module({ + imports: [MikroOrmModule.forFeature([PlaceChangeLog])], + providers: [PlaceChangesService], + exports: [PlaceChangesService], +}) +export class PlaceChangesModule {} diff --git a/server/src/nest/place-changes/place-changes.service.ts b/server/src/nest/place-changes/place-changes.service.ts new file mode 100644 index 000000000..a953db1dd --- /dev/null +++ b/server/src/nest/place-changes/place-changes.service.ts @@ -0,0 +1,120 @@ +import { PlaceChangeLog } from '../../db/entities/PlaceChangeLog.entity'; +import type { + PlaceChangeClear, + PlaceChangeLogRepository, + PlaceChangeRow, + PlaceChangeWrite, +} from '../../db/repositories/PlaceChangeLog.repository'; +import { UnitOfWork } from '../database/unit-of-work'; +import { + changeRowsOf, + diffDetails, + savedPlaceSnapshot, + targetKey, + tripPlaceSnapshot, + type DetailsSnapshot, +} from './place-changes.helpers'; +import type { ChangeEditor, ChangeTarget } from './place-changes.types'; +import { InjectRepository } from '@mikro-orm/nestjs'; +import { Injectable } from '@nestjs/common'; + +// The writers name their targets and editors in the same import as the service. +export { AUTOMATIC_CHANGE, savedPlaceTarget, tripPlaceTarget, type ChangeEditor } from './place-changes.types'; + +/** The places a write may change, or how to find them inside its transaction. */ +type ChangeTargets = ChangeTarget | readonly ChangeTarget[] | (() => Promise); + +/** + * PLC-14: the history of the details of trip places and saved places, kept by + * every path that writes them (REST, MCP, the plugin RPC, the assistant, the + * imports and TREK's own fills) through {@link track}, in the same transaction + * as the write: the details before, the write, the details after, and a row + * for every field that went from one value to another. A field the write + * cleared drops the rows it had instead, so a value deleted on purpose does + * not live on here; a field the write left alone, or set to what it held, + * records nothing. Who may read which history is the reader's question + * (`PlaceHistoryService` in places-library), never this service's. + */ +@Injectable() +export class PlaceChangesService { + constructor( + @InjectRepository(PlaceChangeLog) private readonly log: PlaceChangeLogRepository, + private readonly uow: UnitOfWork, + ) {} + + /** Runs `write` and records what it changed in the details of `targets`; a write that throws records nothing. */ + async track(targets: ChangeTargets, editor: ChangeEditor, write: () => Promise): Promise { + return this.uow.transactional(async () => { + const list = await targetsOf(targets); + if (list.length === 0) return write(); + const before = await this.snapshots(list); + const result = await write(); + await this.record(list, before, await this.snapshots(list), editor); + return result; + }); + } + + /** The changes of these places, newest first, before the change `beforeId` when given. */ + async page( + tripPlaceIds: readonly number[], + savedPlaceIds: readonly number[], + beforeId: number | null, + limit: number, + ): Promise { + return this.log.page(tripPlaceIds, savedPlaceIds, beforeId, limit); + } + + /** The trip places with this Google id and no picture: the ones the photo cache's fill reaches. */ + async tripPlacesWithoutImage(googlePlaceId: string): Promise { + return this.log.tripPlaceIdsWithoutImage(googlePlaceId); + } + + private async snapshots(targets: readonly ChangeTarget[]): Promise> { + const ids = (kind: ChangeTarget['kind']) => targets.filter((target) => target.kind === kind).map((t) => t.id); + const tripIds = ids('trip'); + const savedIds = ids('list'); + const tripRows = tripIds.length > 0 ? await this.log.tripPlaceDetails(tripIds) : []; + const savedRows = savedIds.length > 0 ? await this.log.savedPlaceDetails(savedIds) : []; + return new Map([ + ...tripRows.map((row) => [targetKey({ kind: 'trip', id: row.id }), tripPlaceSnapshot(row)] as const), + ...savedRows.map((row) => [targetKey({ kind: 'list', id: row.id }), savedPlaceSnapshot(row)] as const), + ]); + } + + /** Runs inside {@link track}'s transaction: the cleared fields' rows go, the new values come in. */ + private async record( + targets: readonly ChangeTarget[], + before: Map, + after: Map, + editor: ChangeEditor, + ): Promise { + const writes: PlaceChangeWrite[] = []; + const clears: PlaceChangeClear[] = []; + for (const target of uniqueTargets(targets)) { + const was = before.get(targetKey(target)); + const now = after.get(targetKey(target)); + // A place the write deleted (or one that never was) keeps no history. + if (!was || !now) continue; + const rows = changeRowsOf(target, diffDetails(was, now), editor); + writes.push(...rows.writes); + clears.push(rows.clear); + } + await this.log.deleteCleared(clears); + await this.log.insertChanges(writes); + } +} + +function targetsOf(targets: ChangeTargets): Promise { + if (typeof targets === 'function') return targets(); + return Promise.resolve(isTargetList(targets) ? targets : [targets]); +} + +function isTargetList(targets: ChangeTarget | readonly ChangeTarget[]): targets is readonly ChangeTarget[] { + return Array.isArray(targets); +} + +function uniqueTargets(targets: readonly ChangeTarget[]): ChangeTarget[] { + const seen = new Map(); + for (const target of targets) seen.set(targetKey(target), target); + return [...seen.values()]; +} diff --git a/server/src/nest/place-changes/place-changes.types.ts b/server/src/nest/place-changes/place-changes.types.ts new file mode 100644 index 000000000..33dd7ecf6 --- /dev/null +++ b/server/src/nest/place-changes/place-changes.types.ts @@ -0,0 +1,14 @@ +/** A place whose details a write may change: a trip place or a saved place. */ +export interface ChangeTarget { + kind: 'trip' | 'list'; + id: number; +} + +export const tripPlaceTarget = (id: number): ChangeTarget => ({ kind: 'trip', id }); +export const savedPlaceTarget = (id: number): ChangeTarget => ({ kind: 'list', id }); + +/** A value TREK filled in itself, which nobody typed. */ +export const AUTOMATIC_CHANGE = 'automatic' as const; + +/** Who made a change: a user's id, TREK itself, or nobody known. */ +export type ChangeEditor = number | typeof AUTOMATIC_CHANGE | null; diff --git a/server/src/nest/places-library/place-history.controller.ts b/server/src/nest/places-library/place-history.controller.ts new file mode 100644 index 000000000..09a29ce18 --- /dev/null +++ b/server/src/nest/places-library/place-history.controller.ts @@ -0,0 +1,45 @@ +import { ADDON_IDS } from '../../addons'; +import type { User } from '../../types'; +import { AddonGuard } from '../addons/addon.guard'; +import { RequireAddon } from '../addons/require-addon.decorator'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ResponseContract } from '../common/response-contract'; +import { rowId } from '../common/row-id.pipe'; +import { PlaceHistoryQueryDto } from './place-history.dto'; +import { PlaceHistoryService } from './place-history.service'; +import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common'; +import { placeHistoryPageResponseSchema } from '@trek/shared'; + +/** + * PLC-14 beside the place detail of All places: what changed in the details + * of the entry, when and by whom, over the trips and lists the user reaches. + * Read only; the history is kept by the writes themselves. Behind the + * Collections addon like the rest of the library. + */ +@Controller('api/addons/collections/library/places') +@UseGuards(AddonGuard, JwtAuthGuard) +@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections') +export class PlaceHistoryController { + constructor(private readonly history: PlaceHistoryService) {} + + @Get('trip/:id/history') + @ResponseContract(placeHistoryPageResponseSchema) + async tripPlace( + @CurrentUser() user: User, + @Param('id', rowId('Place not found')) id: number, + @Query() query: PlaceHistoryQueryDto, + ) { + return this.history.history({ id: user.id, role: user.role }, 'trip', id, query); + } + + @Get('list/:id/history') + @ResponseContract(placeHistoryPageResponseSchema) + async savedPlace( + @CurrentUser() user: User, + @Param('id', rowId('Place not found')) id: number, + @Query() query: PlaceHistoryQueryDto, + ) { + return this.history.history({ id: user.id, role: user.role }, 'list', id, query); + } +} diff --git a/server/src/nest/places-library/place-history.dto.ts b/server/src/nest/places-library/place-history.dto.ts new file mode 100644 index 000000000..0062a7b39 --- /dev/null +++ b/server/src/nest/places-library/place-history.dto.ts @@ -0,0 +1,5 @@ +import { placeHistoryQuerySchema } from '@trek/shared'; + +import { createZodDto } from 'nestjs-zod'; + +export class PlaceHistoryQueryDto extends createZodDto(placeHistoryQuerySchema) {} diff --git a/server/src/nest/places-library/place-history.mcp.ts b/server/src/nest/places-library/place-history.mcp.ts new file mode 100644 index 000000000..f7137d9ee --- /dev/null +++ b/server/src/nest/places-library/place-history.mcp.ts @@ -0,0 +1,48 @@ +import { ADDON_IDS } from '../../addons'; +import { canRead, canReadTrips } from '../../mcp/scopes'; +import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp'; +import { addonGate } from '../addons/addon-gate'; +import { AddonsService } from '../addons/addons.service'; +import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; +import { PlaceHistoryService } from './place-history.service'; +import { + PLACE_HISTORY_PAGE_DEFAULT, + PLACE_HISTORY_PAGE_MAX, + placeHistoryRequestSchema, + type PlaceHistoryRequest, +} from '@trek/shared'; + +/** The history spans the entry's trips and lists, so a token needs to read both. */ +const readsTripsAndLists = (ctx: McpContext) => canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes); + +/** + * PLC-14 over MCP: the same service and the same reach as + * `GET /api/addons/collections/library/places/{trip|list}/:id/history`. + */ +@McpController() +export class PlaceHistoryMcp { + constructor( + private readonly history: PlaceHistoryService, + private readonly guards: McpToolGuardsService, + // Read by the addon gate of the tool. + readonly addons: AddonsService, + ) {} + + @Tool({ + name: 'get_library_place_history', + description: `What changed in the details of one entry of All places, opened from a trip place (kind trip, place_id) or a saved place (kind list, collection_place_id): newest first, ${PLACE_HISTORY_PAGE_DEFAULT} at a time unless limit says otherwise (at most ${PLACE_HISTORY_PAGE_MAX}), over the trips and lists of the entry you can open. Each change has its origin (trip with trip_title, or list with collection_name), field (name, address, position as "lat,lng", category by name, description, notes, website, phone, image, opening_hours, status), old_value and new_value, editor (id, username; null when the account is gone or TREK filled the value in itself, then automatic is true) and changed_at (UTC). A value that was cleared leaves no change behind, and its earlier changes are gone too. next_cursor, passed back as cursor, goes on; null on the last page. Changes nothing.`, + inputSchema: placeHistoryRequestSchema.shape, + annotations: TOOL_ANNOTATIONS_READONLY, + when: addonGate(ADDON_IDS.COLLECTIONS), + access: readsTripsAndLists, + }) + async getLibraryPlaceHistory(input: PlaceHistoryRequest, ctx: McpContext) { + const role = (await this.guards.isAdminUser(ctx.userId)) ? 'admin' : 'user'; + return ok( + await this.history.history({ id: ctx.userId, role }, input.kind, input.id, { + cursor: input.cursor, + limit: input.limit, + }), + ); + } +} diff --git a/server/src/nest/places-library/place-history.module.ts b/server/src/nest/places-library/place-history.module.ts new file mode 100644 index 000000000..1e5027199 --- /dev/null +++ b/server/src/nest/places-library/place-history.module.ts @@ -0,0 +1,22 @@ +import { AddonsModule } from '../addons/addons.module'; +import { McpSharedModule } from '../mcp-shared/mcp-shared.module'; +import { PlaceChangesModule } from '../place-changes/place-changes.module'; +import { PlaceHistoryController } from './place-history.controller'; +import { PlaceHistoryMcp } from './place-history.mcp'; +import { PlaceHistoryService } from './place-history.service'; +import { PlacesLibraryModule } from './places-library.module'; +import { Module } from '@nestjs/common'; + +/** + * PLC-14: the history of the details of an entry of All places, read over + * the origins the user reaches. Part of the places-library domain, beside + * PlacesLibraryModule, which resolves every entry; the history itself is + * kept by PlaceChangesModule, which every write of a place's details goes + * through. Read only. + */ +@Module({ + imports: [PlacesLibraryModule, PlaceChangesModule, AddonsModule, McpSharedModule], + controllers: [PlaceHistoryController], + providers: [PlaceHistoryService, PlaceHistoryMcp], +}) +export class PlaceHistoryModule {} diff --git a/server/src/nest/places-library/place-history.service.ts b/server/src/nest/places-library/place-history.service.ts new file mode 100644 index 000000000..d3b94c018 --- /dev/null +++ b/server/src/nest/places-library/place-history.service.ts @@ -0,0 +1,105 @@ +import type { PlaceChangeRow } from '../../db/repositories/PlaceChangeLog.repository'; +import { avatarUrl } from '../common/avatarUrl'; +import { PlaceChangesService } from '../place-changes/place-changes.service'; +import { PlacesLibraryService, placeNotFound, type LibraryUser } from './places-library.service'; +import { Injectable } from '@nestjs/common'; +import { + PLACE_HISTORY_FIELDS, + PLACE_HISTORY_PAGE_DEFAULT, + type PlaceHistoryEntry, + type PlaceHistoryField, + type PlaceHistoryOrigin, + type PlaceHistoryPageResponse, + type PlaceHistoryQuery, + type PlacesLibraryKind, +} from '@trek/shared'; + +const isHistoryField = (field: string): field is PlaceHistoryField => + (PLACE_HISTORY_FIELDS as readonly string[]).includes(field); + +/** + * PLC-14: the history of an entry of All places, newest first, over the + * origins of the entry the user reaches right now, read with the library's + * own reach for every call: a trip place of a trip they own or are a member + * of, a saved place of a list open to them. A change of any other origin is + * left out without a trace (no count, no placeholder, no gap in the cursor), + * so losing access to a trip or a list takes its changes out of the history + * at once, as it takes the origin out of the entry. An entry the user does + * not reach at all is not found. + */ +@Injectable() +export class PlaceHistoryService { + constructor( + private readonly library: PlacesLibraryService, + private readonly changes: PlaceChangesService, + ) {} + + async history( + user: LibraryUser, + kind: PlacesLibraryKind, + id: number, + query: PlaceHistoryQuery, + ): Promise { + const reach = await this.library.reach(user.id); + const anchor = await this.library.anchorOfUse(reach, kind, id); + if (anchor === null) throw placeNotFound(); + const [rows] = await this.library.rows(reach, [anchor]); + if (!rows) throw placeNotFound(); + + const trips = new Map( + rows.trips.map((row): [number, PlaceHistoryOrigin] => [ + row.id, + { kind: 'trip', trip_id: row.trip_id, trip_title: row.trip_title, place_id: row.id }, + ]), + ); + const saved = new Map( + rows.saved.map((row): [number, PlaceHistoryOrigin] => [ + row.id, + { + kind: 'list', + collection_id: row.collection_id, + collection_name: row.collection_name, + collection_place_id: row.id, + }, + ]), + ); + const limit = query.limit ?? PLACE_HISTORY_PAGE_DEFAULT; + const beforeId = query.cursor === undefined ? null : Number(query.cursor); + // One change more than the page holds says whether another page follows. + const found = await this.changes.page([...trips.keys()], [...saved.keys()], beforeId, limit + 1); + const page = found.slice(0, limit); + const last = page[page.length - 1]; + return { + entries: page.flatMap((row) => { + const origin = originOf(row, trips, saved); + return origin && isHistoryField(row.field) ? [entryOf(row, row.field, origin)] : []; + }), + next_cursor: found.length > limit && last ? String(last.id) : null, + }; + } +} + +function originOf( + row: PlaceChangeRow, + trips: Map, + saved: Map, +): PlaceHistoryOrigin | undefined { + if (row.place_id !== null) return trips.get(row.place_id); + return row.collection_place_id === null ? undefined : saved.get(row.collection_place_id); +} + +function entryOf(row: PlaceChangeRow, field: PlaceHistoryField, origin: PlaceHistoryOrigin): PlaceHistoryEntry { + return { + id: row.id, + origin, + field, + old_value: row.old_value, + new_value: row.new_value, + editor: + row.user_id === null || row.username === null + ? null + : { id: row.user_id, username: row.username, avatar_url: avatarUrl({ avatar: row.avatar }) }, + automatic: row.automatic === 1, + changed_at: row.created_at, + }; +} diff --git a/server/src/nest/places-library/place-media.controller.ts b/server/src/nest/places-library/place-media.controller.ts new file mode 100644 index 000000000..b63b7590d --- /dev/null +++ b/server/src/nest/places-library/place-media.controller.ts @@ -0,0 +1,35 @@ +import { ADDON_IDS } from '../../addons'; +import type { User } from '../../types'; +import { AddonGuard } from '../addons/addon.guard'; +import { RequireAddon } from '../addons/require-addon.decorator'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ResponseContract } from '../common/response-contract'; +import { rowId } from '../common/row-id.pipe'; +import { PlaceMediaService } from './place-media.service'; +import { Controller, Get, Param, UseGuards } from '@nestjs/common'; +import { placeMediaResponseSchema } from '@trek/shared'; + +/** + * PLC-19/PLC-20 beside the place detail of All places: its pictures, the + * journey photos and the trip files that hang on it, each with where it comes + * from. Behind the Collections addon like the rest of the library. + */ +@Controller('api/addons/collections/library/places') +@UseGuards(AddonGuard, JwtAuthGuard) +@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections') +export class PlaceMediaController { + constructor(private readonly media: PlaceMediaService) {} + + @Get('trip/:id/media') + @ResponseContract(placeMediaResponseSchema) + async tripPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) { + return this.media.media({ id: user.id, role: user.role }, 'trip', id); + } + + @Get('list/:id/media') + @ResponseContract(placeMediaResponseSchema) + async savedPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) { + return this.media.media({ id: user.id, role: user.role }, 'list', id); + } +} diff --git a/server/src/nest/places-library/place-media.service.ts b/server/src/nest/places-library/place-media.service.ts new file mode 100644 index 000000000..0bc230e70 --- /dev/null +++ b/server/src/nest/places-library/place-media.service.ts @@ -0,0 +1,145 @@ +import { ADDON_IDS } from '../../addons'; +import { PlaceVisitContextRepository } from '../../db/repositories/PlaceVisitContext.repository'; +import { AddonsService } from '../addons/addons.service'; +import { JourneyDomainService } from '../journey/journey-domain.service'; +import { uniqueIds } from './place-visits.helpers'; +import { PlacesLibraryService, placeNotFound, type LibraryUser } from './places-library.service'; +import { Injectable } from '@nestjs/common'; +import type { + PlaceMediaFile, + PlaceMediaImage, + PlaceMediaJourneyPhoto, + PlaceMediaResponse, + PlacesLibraryKind, +} from '@trek/shared'; + +/** + * PLC-19/PLC-20: what an entry of All places shows of its photos and files, + * each with where it comes from, read with the rights of where it lives. + * + * - The general pictures are the ones its trip places and saved places carry + * (`image_url`), with the trip or list each comes from. + * - The journey photos are those of journey entries made from one of its + * trip places, in journeys the user can open (the journey domain's own + * check, asked per journey), while the Journey addon is on; an entry the + * journey set aside (dismissed) or has not filled yet (skeleton) gives none. + * - The files are the trip files not in the trash attached to one of its + * trip places, by a link or as the file's own place, with the trip they + * open in. A file is there exactly as the trip's file manager has it for a + * member: trip access (only trips the user opens contribute places) and + * the Documents addon on for the instance; a file attached to a place + * stays reachable while one trip turns Documents off, as in the trip. + * + * A list gives no photo and no file of its own beyond its pictures: being on + * a list never opens a journey or a trip. + */ +@Injectable() +export class PlaceMediaService { + constructor( + private readonly library: PlacesLibraryService, + private readonly context: PlaceVisitContextRepository, + private readonly journeys: JourneyDomainService, + private readonly addons: AddonsService, + ) {} + + async media(user: LibraryUser, kind: PlacesLibraryKind, id: number): Promise { + const reach = await this.library.reach(user.id); + const anchor = await this.library.anchorOfUse(reach, kind, id); + if (anchor === null) throw placeNotFound(); + const [rows] = await this.library.rows(reach, [anchor]); + if (!rows) throw placeNotFound(); + + const images: PlaceMediaImage[] = [ + ...rows.trips.flatMap((row): PlaceMediaImage[] => + row.image_url + ? [ + { + kind: 'trip', + image_url: row.image_url, + trip_id: row.trip_id, + trip_title: row.trip_title, + place_id: row.id, + }, + ] + : [], + ), + ...rows.saved.flatMap((row): PlaceMediaImage[] => + row.image_url + ? [ + { + kind: 'list', + image_url: row.image_url, + collection_id: row.collection_id, + collection_name: row.collection_name, + collection_place_id: row.id, + }, + ] + : [], + ), + ]; + + const placeIds = rows.trips.map((row) => row.id); + const tripTitles = new Map(rows.trips.map((row) => [row.trip_id, row.trip_title])); + + const journeysOn = placeIds.length > 0 && (await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY)); + const photos = journeysOn ? await this.context.journeyPhotosOfPlaces(placeIds) : []; + const open = await this.openJourneyIds( + user.id, + photos.map((photo) => photo.journey_id), + ); + const journeyPhotos = photos.flatMap((photo): PlaceMediaJourneyPhoto[] => { + if (!open.has(photo.journey_id)) return []; + return [ + { + journey_id: photo.journey_id, + journey_title: photo.journey_title, + entry_id: photo.entry_id, + entry_date: photo.entry_date, + journey_photo_id: photo.journey_photo_id, + photo_id: photo.photo_id, + provider: photo.provider, + asset_id: photo.asset_id, + owner_id: photo.owner_id, + file_path: photo.file_path, + thumbnail_path: photo.thumbnail_path, + width: photo.width, + height: photo.height, + media_type: photo.media_type, + caption: photo.caption, + taken_at: photo.taken_at, + }, + ]; + }); + + const documentsOn = placeIds.length > 0 && (await this.addons.isAddonEnabled(ADDON_IDS.DOCUMENTS)); + const fileRows = documentsOn ? await this.context.filesOfPlaces(placeIds) : []; + const files = fileRows.flatMap((file): PlaceMediaFile[] => { + const tripTitle = tripTitles.get(file.trip_id); + if (tripTitle === undefined) return []; + return [ + { + file_id: file.file_id, + trip_id: file.trip_id, + trip_title: tripTitle, + place_id: file.place_id, + original_name: file.original_name, + mime_type: file.mime_type, + file_size: file.file_size, + created_at: file.created_at, + url: `/api/trips/${file.trip_id}/files/${file.file_id}/download`, + }, + ]; + }); + + return { images, journey_photos: journeyPhotos, files }; + } + + /** Which of the journeys the user can open, asked of the journey domain for each. */ + private async openJourneyIds(userId: number, journeyIds: readonly number[]): Promise> { + const ids = uniqueIds(journeyIds); + const answers = await Promise.all( + ids.map(async (id) => (await this.journeys.canAccessJourney(id, userId)) !== null), + ); + return new Set(ids.filter((_, index) => answers[index])); + } +} diff --git a/server/src/nest/places-library/place-tags.controller.ts b/server/src/nest/places-library/place-tags.controller.ts new file mode 100644 index 000000000..379056e72 --- /dev/null +++ b/server/src/nest/places-library/place-tags.controller.ts @@ -0,0 +1,38 @@ +import { ADDON_IDS } from '../../addons'; +import type { User } from '../../types'; +import { AddonGuard } from '../addons/addon.guard'; +import { RequireAddon } from '../addons/require-addon.decorator'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ResponseContract } from '../common/response-contract'; +import { PlaceTagsService } from './place-tags.service'; +import { PlacesLibraryBulkTagsDto, PlacesLibraryEntryTagsDto } from './places-library.dto'; +import { Body, Controller, HttpCode, Post, Put, UseGuards } from '@nestjs/common'; +import { placesLibraryBulkTagsResponseSchema, placesLibraryEntryTagsResponseSchema } from '@trek/shared'; + +/** + * PLC-21 under /api/addons/collections/library/places/tags: the user's + * personal tags on the entries of "All places", for one entry or for several. + * The tags themselves are created, renamed and deleted under /api/tags. Only + * the user's own rows change, so nothing is broadcast. Behind the Collections + * addon like the rest of the library. + */ +@Controller('api/addons/collections/library/places/tags') +@UseGuards(AddonGuard, JwtAuthGuard) +@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections') +export class PlaceTagsController { + constructor(private readonly tags: PlaceTagsService) {} + + @Put() + @ResponseContract(placesLibraryEntryTagsResponseSchema) + async setForEntry(@CurrentUser() user: User, @Body() body: PlacesLibraryEntryTagsDto) { + return this.tags.setForEntry({ id: user.id, role: user.role }, body); + } + + @Post('bulk') + @HttpCode(200) + @ResponseContract(placesLibraryBulkTagsResponseSchema) + async bulk(@CurrentUser() user: User, @Body() body: PlacesLibraryBulkTagsDto) { + return this.tags.bulk({ id: user.id, role: user.role }, body); + } +} diff --git a/server/src/nest/places-library/place-tags.helpers.ts b/server/src/nest/places-library/place-tags.helpers.ts new file mode 100644 index 000000000..20f6d9291 --- /dev/null +++ b/server/src/nest/places-library/place-tags.helpers.ts @@ -0,0 +1,70 @@ +import type { PersonalTagAssignment } from '../../db/repositories/PersonalPlaceTags.repository'; +import type { LibraryEntryTagRow } from '../../db/repositories/PlacesLibrary.repository'; +import { ANCHOR_LIST, ANCHOR_OWN, ANCHOR_SPAN, ANCHOR_TRIP } from '../../db/repositories/PlacesLibrary.repository'; +import type { EntryRows } from './places-library.helpers'; +import type { PlacesLibraryTag } from '@trek/shared'; + +/** + * PLC-21, the pure half of the personal tags on "All places": where an entry's + * tags are read from, where a new one is put, and which rows belong to which + * entry. + */ + +interface TagTargets { + identityIds: number[]; + placeIds: number[]; + collectionPlaceIds: number[]; +} + +/** + * Everything the entries' tags can sit on: their own places, trip places and + * saved places. Read for showing them and for taking one off, so a tag comes + * off every copy of it on the entry. + */ +export function tagTargetsOf(rows: readonly EntryRows[]): TagTargets { + return { + identityIds: rows.flatMap((row) => (row.identity ? [row.identity.id] : [])), + placeIds: rows.flatMap((row) => row.trips.map((trip) => trip.id)), + collectionPlaceIds: rows.flatMap((row) => row.saved.map((saved) => saved.id)), + }; +} + +/** Whether a tag row sits on the entry: on its own place (or one merged into it), or on one of its uses. */ +function belongsTo(row: LibraryEntryTagRow, entry: EntryRows): boolean { + const identityId = entry.identity?.id; + if (identityId !== undefined && row.user_place_id !== null) { + return row.user_place_id === identityId || row.merged_into_id === identityId; + } + if (row.place_id !== null) return entry.trips.some((trip) => trip.id === row.place_id); + if (row.collection_place_id !== null) return entry.saved.some((saved) => saved.id === row.collection_place_id); + return false; +} + +/** Each entry's tags, once each, in the name order the rows come in. */ +export function tagsByEntry(entries: readonly EntryRows[], rows: readonly LibraryEntryTagRow[]): PlacesLibraryTag[][] { + return entries.map((entry) => { + const seen = new Set(); + return rows.flatMap((row) => { + if (seen.has(row.id) || !belongsTo(row, entry)) return []; + seen.add(row.id); + return [{ id: row.id, name: row.name, color: row.color }]; + }); + }); +} + +/** The target a tag of the entry `anchor` is put on: its own place, else the trip place or saved place it is. */ +export function assignmentOf(anchor: number, tagId: number): PersonalTagAssignment { + const id = Math.floor(anchor / ANCHOR_SPAN); + const kind = anchor % ANCHOR_SPAN; + return { + tag_id: tagId, + user_place_id: kind === ANCHOR_OWN ? id : null, + place_id: kind === ANCHOR_TRIP ? id : null, + collection_place_id: kind === ANCHOR_LIST ? id : null, + }; +} + +/** The ids once each, in their first order. */ +export function uniqueIds(ids: readonly number[]): number[] { + return [...new Set(ids)]; +} diff --git a/server/src/nest/places-library/place-tags.mcp.ts b/server/src/nest/places-library/place-tags.mcp.ts new file mode 100644 index 000000000..c34b03f0f --- /dev/null +++ b/server/src/nest/places-library/place-tags.mcp.ts @@ -0,0 +1,65 @@ +import { ADDON_IDS } from '../../addons'; +import { canReadTrips, canWrite } from '../../mcp/scopes'; +import { McpController, Tool, TOOL_ANNOTATIONS_WRITE, ok, type McpContext } from '../../nest-mcp'; +import { addonGate } from '../addons/addon-gate'; +import { AddonsService } from '../addons/addons.service'; +import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; +import { PlaceTagsService } from './place-tags.service'; +import type { LibraryUser } from './places-library.service'; +import { + PLACES_LIBRARY_TAG_KEYS_MAX, + PLACES_LIBRARY_TAGS_MAX, + placesLibraryBulkTagsRequestSchema, + placesLibraryEntryTagsRequestSchema, + type PlacesLibraryBulkTagsRequest, + type PlacesLibraryEntryTagsRequest, +} from '@trek/shared'; + +/** Tagging writes only the user's own rows, under the lists' write scope, over trips and lists alike. */ +const writesOwnTags = (ctx: McpContext) => canWrite(ctx.scopes, 'collections') && canReadTrips(ctx.scopes); + +const PRIVATE = + 'The tags are your personal tags (list_tags, create_tag) and stay private: no trip place and no saved place changes, and no one else sees them. To share some with a trip, copy the place with copy_collection_places_to_trip and personal_tag_ids.'; + +/** + * PLC-21 over the same service and checks as the REST routes under + * /api/addons/collections/library/places/tags: the user's personal tags on + * the entries of All places. + */ +@McpController() +export class PlaceTagsMcp { + constructor( + private readonly tags: PlaceTagsService, + private readonly guards: McpToolGuardsService, + // Read by the addon gate of every tool here. + readonly addons: AddonsService, + ) {} + + private async user(userId: number): Promise { + return { id: userId, role: (await this.guards.isAdminUser(userId)) ? 'admin' : 'user' }; + } + + @Tool({ + name: 'set_library_place_tags', + description: `Set which of your personal tags an entry of All places carries, by its key from list_all_places (own:, trip: or list:): exactly tag_ids from now on (at most ${PLACES_LIBRARY_TAGS_MAX}), an empty list takes every tag off. Answers the entry with its tags. ${PRIVATE}`, + inputSchema: placesLibraryEntryTagsRequestSchema.shape, + annotations: TOOL_ANNOTATIONS_WRITE, + when: addonGate(ADDON_IDS.COLLECTIONS), + access: writesOwnTags, + }) + async setLibraryPlaceTags(input: PlacesLibraryEntryTagsRequest, ctx: McpContext) { + return ok(await this.tags.setForEntry(await this.user(ctx.userId), input)); + } + + @Tool({ + name: 'tag_library_places', + description: `Put personal tags on several entries of All places at once (add) and take others off them (remove), by their keys from list_all_places (at most ${PLACES_LIBRARY_TAG_KEYS_MAX} keys); a tag already on an entry stays. Every key must name an entry you reach and every id one of your personal tags, else nothing changes. Answers the entries with their tags. ${PRIVATE}`, + inputSchema: placesLibraryBulkTagsRequestSchema.shape, + annotations: TOOL_ANNOTATIONS_WRITE, + when: addonGate(ADDON_IDS.COLLECTIONS), + access: writesOwnTags, + }) + async tagLibraryPlaces(input: PlacesLibraryBulkTagsRequest, ctx: McpContext) { + return ok(await this.tags.bulk(await this.user(ctx.userId), input)); + } +} diff --git a/server/src/nest/places-library/place-tags.service.ts b/server/src/nest/places-library/place-tags.service.ts new file mode 100644 index 000000000..6095fd475 --- /dev/null +++ b/server/src/nest/places-library/place-tags.service.ts @@ -0,0 +1,99 @@ +import { PersonalPlaceTags } from '../../db/entities/PersonalPlaceTags.entity'; +import type { PersonalPlaceTagsRepository } from '../../db/repositories/PersonalPlaceTags.repository'; +import { badRequest, notFound } from '../common/domain-error'; +import { UnitOfWork } from '../database/unit-of-work'; +import { assignmentOf, tagTargetsOf, uniqueIds } from './place-tags.helpers'; +import { anchorOfKey, type EntryRows } from './places-library.helpers'; +import { PlacesLibraryService, placeNotFound, type LibraryReach, type LibraryUser } from './places-library.service'; +import { InjectRepository } from '@mikro-orm/nestjs'; +import { Injectable } from '@nestjs/common'; +import type { + PlacesLibraryBulkTagsRequest, + PlacesLibraryBulkTagsResponse, + PlacesLibraryEntryTagsRequest, + PlacesLibraryEntryTagsResponse, +} from '@trek/shared'; + +const tagNotFound = () => notFound('Tag not found'); + +/** + * PLC-21: the user's personal tags on the entries of "All places", one method + * per use case for REST and MCP alike. The tags are the user's personal ones + * (`tags` with no trip, managed under /api/tags); a tag of a trip or of + * another person names no tag here and is not found. + * + * Every write changes only the user's own rows: no trip place and no saved + * place is written, nobody else sees the tags, so nothing is broadcast. An + * entry must be one the user reaches today (the library's checks), else it is + * not found; the tags and the entries are read in the transaction that + * writes, so a tag or a place deleted in between is not found either. + * + * A new tag goes on the entry itself: its own place, else the trip place or + * saved place it stands for. Taking one off takes it off everything the entry + * reads tags from (its own place, the ones merged into that, its uses), so it + * is gone from the entry wherever it sat. + */ +@Injectable() +export class PlaceTagsService { + constructor( + private readonly library: PlacesLibraryService, + @InjectRepository(PersonalPlaceTags) private readonly assignments: PersonalPlaceTagsRepository, + private readonly uow: UnitOfWork, + ) {} + + /** The entry `key` carries exactly `tag_ids` from now on. */ + async setForEntry( + user: LibraryUser, + request: PlacesLibraryEntryTagsRequest, + ): Promise { + const anchor = anchorOfKey(request.key); + if (anchor === null) throw placeNotFound(); + const tagIds = uniqueIds(request.tag_ids); + const reach = await this.library.reach(user.id); + await this.uow.transactional(async () => { + await this.requireOwnTags(user.id, tagIds); + const rows = await this.requireEntries(reach, [anchor]); + await this.assignments.remove(user.id, tagTargetsOf(rows), null); + await this.assignments.add(tagIds.map((tagId) => assignmentOf(anchor, tagId))); + }); + return { entry: await this.library.entry(user, anchor) }; + } + + /** Puts `add` on every entry of `keys` and takes `remove` off them, in one transaction. */ + async bulk(user: LibraryUser, request: PlacesLibraryBulkTagsRequest): Promise { + const anchors = uniqueIds( + request.keys.map((key) => { + const anchor = anchorOfKey(key); + if (anchor === null) throw placeNotFound(); + return anchor; + }), + ); + const add = uniqueIds(request.add ?? []); + const remove = uniqueIds(request.remove ?? []); + // The contract refuses both, but an MCP call is checked field by field. + if (add.length + remove.length === 0) throw badRequest('Name tags to add or to remove'); + if (add.some((id) => remove.includes(id))) throw badRequest('A tag cannot be added and removed at once'); + const reach = await this.library.reach(user.id); + await this.uow.transactional(async () => { + await this.requireOwnTags(user.id, [...add, ...remove]); + const rows = await this.requireEntries(reach, anchors); + await this.assignments.remove(user.id, tagTargetsOf(rows), remove); + await this.assignments.add(anchors.flatMap((anchor) => add.map((tagId) => assignmentOf(anchor, tagId)))); + }); + return { entries: await this.library.entries(user, reach, anchors) }; + } + + /** Refuses unless every id names a personal tag of the user. */ + private async requireOwnTags(userId: number, tagIds: readonly number[]): Promise { + const wanted = uniqueIds(tagIds); + const own = await this.assignments.ownTags(userId, wanted); + if (own.length !== wanted.length) throw tagNotFound(); + } + + /** The rows of every entry, refusing when one of them is out of the user's reach. */ + private async requireEntries(reach: LibraryReach, anchors: number[]): Promise { + const rows = await this.library.rows(reach, anchors); + if (rows.length !== anchors.length) throw placeNotFound(); + return rows; + } +} diff --git a/server/src/nest/places-library/place-visits-reader.service.ts b/server/src/nest/places-library/place-visits-reader.service.ts new file mode 100644 index 000000000..c710e1d3f --- /dev/null +++ b/server/src/nest/places-library/place-visits-reader.service.ts @@ -0,0 +1,93 @@ +import { PlaceVisitContextRepository, type PlannedVisitRow } from '../../db/repositories/PlaceVisitContext.repository'; +import { PlaceVisitsClock } from './place-visits.clock'; +import { + collapseVisits, + participantsOf, + summaryOf, + uniqueIds, + visitsOfEntry, + wireVisit, + type DerivedVisit, + type VisitSummary, +} from './place-visits.helpers'; +import { groupBy, readInChunks, type EntryRows } from './places-library.helpers'; +import { Injectable } from '@nestjs/common'; +import type { PlaceVisit } from '@trek/shared'; + +/** The trips a reader reaches, as the library resolved them. */ +interface VisitReach { + userId: number; + tripIds: readonly number[]; +} + +/** + * D7: visits are never entered, they are read from the trips. A place counts + * as visited by a reader on a day when a trip the reader owns or is a member + * of has it planned on a day with a date up to today (UTC), and the stop + * names no one or names the reader among who takes part. A day without a + * date counts nothing, a coming day neither. Each place counts once per + * calendar day, however many stops have it that day. Losing access to a + * trip takes its visits with it, since only reached trips are read. + */ +@Injectable() +export class PlaceVisitsReaderService { + constructor( + private readonly context: PlaceVisitContextRepository, + private readonly clock: PlaceVisitsClock, + ) {} + + /** The planned rows that count for the reader at the trip places `placeIds`, of reached trips only. */ + async plannedAt(reach: VisitReach, placeIds: readonly number[]): Promise { + const today = this.clock.today(); + const trips = new Set(reach.tripIds); + const rows = await readInChunks(uniqueIds(placeIds), (chunk) => + this.context.plannedAtPlaces(reach.userId, today, chunk), + ); + return rows.filter((row) => trips.has(row.trip_id)); + } + + /** The planned rows that count for the reader on the trips `tripIds`. */ + async plannedOn(reach: VisitReach, tripIds: readonly number[]): Promise { + const today = this.clock.today(); + const reached = new Set(reach.tripIds); + const wanted = uniqueIds(tripIds).filter((id) => reached.has(id)); + return readInChunks(wanted, (chunk) => this.context.plannedOnTrips(reach.userId, today, chunk)); + } + + /** The visit count and latest visit of each entry, in the entries' order, from one read. */ + async summaries(reach: VisitReach, entries: readonly EntryRows[]): Promise { + const placeIds = entries.flatMap((rows) => rows.trips.map((row) => row.id)); + const planned = placeIds.length > 0 ? await this.plannedAt(reach, placeIds) : []; + return entries.map((rows) => summaryOf(visitsOfEntry(rows, planned))); + } + + /** The visits of one entry of All places, newest first. */ + async ofEntry(reach: VisitReach, rows: EntryRows): Promise { + const placeIds = rows.trips.map((row) => row.id); + if (placeIds.length === 0) return []; + return visitsOfEntry(rows, await this.plannedAt(reach, placeIds)); + } + + /** The visits on the trips, one per group and day, newest first. */ + async onTrips( + reach: VisitReach, + tripIds: readonly number[], + groupOf: (row: PlannedVisitRow) => string, + ): Promise { + return collapseVisits(await this.plannedOn(reach, tripIds), groupOf); + } + + /** The visits as the contract sends them, with who each counts for, read in two blocks of statements. */ + async wire(visits: readonly DerivedVisit[]): Promise { + if (visits.length === 0) return []; + const assignmentIds = uniqueIds(visits.flatMap((visit) => visit.assignment_ids)); + const named = await readInChunks(assignmentIds, (chunk) => this.context.assignmentPeople(chunk)); + const byAssignment = groupBy(named, (row) => row.assignment_id); + const tripIds = uniqueIds( + visits.filter((visit) => visit.assignment_ids.some((id) => !byAssignment.has(id))).map((visit) => visit.trip_id), + ); + const roster = await readInChunks(tripIds, (chunk) => this.context.tripPeople(chunk)); + const byTrip = groupBy(roster, (row) => row.trip_id); + return visits.map((visit) => wireVisit(visit, participantsOf(visit, byAssignment, byTrip))); + } +} diff --git a/server/src/nest/places-library/place-visits-trip.controller.ts b/server/src/nest/places-library/place-visits-trip.controller.ts new file mode 100644 index 000000000..8d8e2fd0a --- /dev/null +++ b/server/src/nest/places-library/place-visits-trip.controller.ts @@ -0,0 +1,27 @@ +import type { TripAccess } from '../../db/repositories/Trips.repository'; +import type { User } from '../../types'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ResponseContract } from '../common/response-contract'; +import { TripAccessGuard } from '../permissions/trip-access.guard'; +import { Trip } from '../permissions/trip.decorator'; +import { PlaceVisitsService } from './place-visits.service'; +import { Controller, Get, UseGuards } from '@nestjs/common'; +import { placeVisitTripVisitedResponseSchema } from '@trek/shared'; + +/** + * PLC-23 at /api/trips/:tripId/place-visits: which of the trip's places the + * user visited, for the "visited" filter of the trip's list and map. Every + * member reads it, each for themselves; nothing here writes. + */ +@Controller('api/trips/:tripId/place-visits') +@UseGuards(JwtAuthGuard, TripAccessGuard) +export class PlaceVisitsTripController { + constructor(private readonly visits: PlaceVisitsService) {} + + @Get('mine') + @ResponseContract(placeVisitTripVisitedResponseSchema) + async mine(@CurrentUser() user: User, @Trip() trip: TripAccess) { + return this.visits.tripVisited(trip.id, { id: user.id, role: user.role }); + } +} diff --git a/server/src/nest/places-library/place-visits.clock.ts b/server/src/nest/places-library/place-visits.clock.ts new file mode 100644 index 000000000..9bf072b8f --- /dev/null +++ b/server/src/nest/places-library/place-visits.clock.ts @@ -0,0 +1,12 @@ +import { Injectable } from '@nestjs/common'; + +/** + * The calendar day visits are counted up to: today in UTC, the server's own + * clock, as YYYY-MM-DD. A provider of its own so a test can name the day. + */ +@Injectable() +export class PlaceVisitsClock { + today(): string { + return new Date().toISOString().slice(0, 10); + } +} diff --git a/server/src/nest/places-library/place-visits.controller.ts b/server/src/nest/places-library/place-visits.controller.ts new file mode 100644 index 000000000..d647721ba --- /dev/null +++ b/server/src/nest/places-library/place-visits.controller.ts @@ -0,0 +1,32 @@ +import type { User } from '../../types'; +import { CurrentUser } from '../auth-core/current-user.decorator'; +import { JwtAuthGuard } from '../auth-core/jwt-auth.guard'; +import { ResponseContract } from '../common/response-contract'; +import { PlaceVisitsForPlaceQueryDto, PlaceVisitsListQueryDto } from './place-visits.dto'; +import { PlaceVisitsService } from './place-visits.service'; +import { Controller, Get, Query, UseGuards } from '@nestjs/common'; +import { placeVisitsForPlaceResponseSchema, placeVisitsListResponseSchema } from '@trek/shared'; + +/** + * D7/PLC-10 at /api/place-visits: the user's visits and the visits at one + * place of All places, read from the trips they reach. Read only: a visit + * comes from the trip's plan, never from here. Not behind an addon: a visit + * belongs to its trip as much as to Places. + */ +@Controller('api/place-visits') +@UseGuards(JwtAuthGuard) +export class PlaceVisitsController { + constructor(private readonly visits: PlaceVisitsService) {} + + @Get() + @ResponseContract(placeVisitsListResponseSchema) + async list(@CurrentUser() user: User, @Query() query: PlaceVisitsListQueryDto) { + return this.visits.list({ id: user.id, role: user.role }, query); + } + + @Get('place') + @ResponseContract(placeVisitsForPlaceResponseSchema) + async forPlace(@CurrentUser() user: User, @Query() query: PlaceVisitsForPlaceQueryDto) { + return this.visits.forPlace({ id: user.id, role: user.role }, query.kind, query.id); + } +} diff --git a/server/src/nest/places-library/place-visits.dto.ts b/server/src/nest/places-library/place-visits.dto.ts new file mode 100644 index 000000000..78a45d959 --- /dev/null +++ b/server/src/nest/places-library/place-visits.dto.ts @@ -0,0 +1,6 @@ +import { placeVisitsForPlaceQuerySchema, placeVisitsListQuerySchema } from '@trek/shared'; + +import { createZodDto } from 'nestjs-zod'; + +export class PlaceVisitsForPlaceQueryDto extends createZodDto(placeVisitsForPlaceQuerySchema) {} +export class PlaceVisitsListQueryDto extends createZodDto(placeVisitsListQuerySchema) {} diff --git a/server/src/nest/places-library/place-visits.helpers.ts b/server/src/nest/places-library/place-visits.helpers.ts new file mode 100644 index 000000000..aa249fe37 --- /dev/null +++ b/server/src/nest/places-library/place-visits.helpers.ts @@ -0,0 +1,163 @@ +import type { PlannedVisitRow, VisitPersonRow } from '../../db/repositories/PlaceVisitContext.repository'; +import { avatarUrl } from '../common/avatarUrl'; +import type { EntryRows } from './places-library.helpers'; +import type { PlaceVisit, PlaceVisitPerson } from '@trek/shared'; + +/** The visit count and latest day of some visits, as "All places" shows them. */ +export interface VisitSummary { + visit_count: number; + last_visit: string | null; +} + +/** + * One visit, derived from the plan: a place on one calendar day, read from + * the first trip day that has it, with every assignment of the place on that + * trip day behind it (their participants are the visit's). + */ +export interface DerivedVisit { + visited_on: string; + visited_time: string | null; + trip_id: number; + trip_title: string; + place_id: number; + day_id: number; + day_number: number; + name: string; + assignment_ids: number[]; +} + +/** The order the plan reads in: day first, then the trip, the day number and the stop order. */ +function planOrder(a: PlannedVisitRow, b: PlannedVisitRow): number { + return ( + (a.date < b.date ? 1 : a.date > b.date ? -1 : 0) || + a.trip_id - b.trip_id || + a.day_number - b.day_number || + (a.order_index ?? 0) - (b.order_index ?? 0) || + a.assignment_id - b.assignment_id + ); +} + +/** The earlier of two clock times, a known one before none. */ +function earlier(a: string | null, b: string | null): string | null { + if (a === null) return b; + if (b === null) return a; + return a <= b ? a : b; +} + +/** Newest day first, the later time first, a visit without a time after the timed ones of its day. */ +function newestFirst(a: DerivedVisit, b: DerivedVisit): number { + if (a.visited_on !== b.visited_on) return a.visited_on < b.visited_on ? 1 : -1; + if (a.visited_time !== b.visited_time) { + if (a.visited_time === null) return 1; + if (b.visited_time === null) return -1; + return a.visited_time < b.visited_time ? 1 : -1; + } + return a.trip_id - b.trip_id || a.day_id - b.day_id || a.place_id - b.place_id; +} + +/** + * The visits of planned rows: one per group (what counts as one place) and + * calendar day, however many assignments, trip places or trips name it that + * day. The first trip day in plan order stands for the visit; the time is the + * earliest set on that day (the stop's own time, else the place's). + */ +export function collapseVisits( + rows: readonly PlannedVisitRow[], + groupOf: (row: PlannedVisitRow) => string, +): DerivedVisit[] { + const visits = new Map(); + for (const row of [...rows].sort(planOrder)) { + const key = `${groupOf(row)}|${row.date}`; + const time = row.assignment_time ?? row.place_time; + const visit = visits.get(key); + if (!visit) { + visits.set(key, { + visited_on: row.date, + visited_time: time, + trip_id: row.trip_id, + trip_title: row.trip_title, + place_id: row.place_id, + day_id: row.day_id, + day_number: row.day_number, + name: row.name, + assignment_ids: [row.assignment_id], + }); + } else if (visit.day_id === row.day_id) { + visit.visited_time = earlier(visit.visited_time, time); + if (!visit.assignment_ids.includes(row.assignment_id)) visit.assignment_ids.push(row.assignment_id); + } + } + return [...visits.values()].sort(newestFirst); +} + +/** + * The visits that belong to one entry of "All places": those at one of its + * trip places, which are only the trip places of trips the user reaches. + * A saved place or an own place adds no visit of its own; an own place + * gathers the trip places it groups, and those count once per day. + */ +export function visitsOfEntry(rows: EntryRows, planned: readonly PlannedVisitRow[]): DerivedVisit[] { + const places = new Set(rows.trips.map((row) => row.id)); + return collapseVisits( + planned.filter((row) => places.has(row.place_id)), + () => 'entry', + ); +} + +/** How many visits there are and the latest day among them. */ +export function summaryOf(visits: readonly DerivedVisit[]): VisitSummary { + const last = visits.reduce( + (latest, visit) => (latest === null || visit.visited_on > latest ? visit.visited_on : latest), + null, + ); + return { visit_count: visits.length, last_visit: last }; +} + +/** People once each, in the order first given. */ +export function uniquePeople(people: readonly T[]): T[] { + const seen = new Set(); + return people.filter((person) => { + if (seen.has(person.id)) return false; + seen.add(person.id); + return true; + }); +} + +/** + * Who a visit counts for: the people its assignments name, or, for an + * assignment naming no one, everyone with an account on the trip. + */ +export function participantsOf( + visit: DerivedVisit, + byAssignment: ReadonlyMap, + byTrip: ReadonlyMap, +): PlaceVisitPerson[] { + const people = visit.assignment_ids.flatMap((id) => { + const named = byAssignment.get(id) ?? []; + return named.length > 0 ? named : (byTrip.get(visit.trip_id) ?? []); + }); + return uniquePeople(people).map((person) => ({ + id: person.id, + username: person.username, + avatar_url: avatarUrl(person), + })); +} + +/** A derived visit as the contract sends it. */ +export function wireVisit(visit: DerivedVisit, participants: PlaceVisitPerson[]): PlaceVisit { + return { + visited_on: visit.visited_on, + visited_time: visit.visited_time, + trip: { id: visit.trip_id, title: visit.trip_title }, + place_id: visit.place_id, + day_id: visit.day_id, + day_number: visit.day_number, + name: visit.name, + participants, + }; +} + +/** The ids once each, in the order first given. */ +export function uniqueIds(ids: readonly number[]): number[] { + return [...new Set(ids)]; +} diff --git a/server/src/nest/places-library/place-visits.mcp.ts b/server/src/nest/places-library/place-visits.mcp.ts new file mode 100644 index 000000000..f579aef52 --- /dev/null +++ b/server/src/nest/places-library/place-visits.mcp.ts @@ -0,0 +1,90 @@ +import { ADDON_IDS } from '../../addons'; +import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp'; +import { addonGate } from '../addons/addon-gate'; +import { AddonsService } from '../addons/addons.service'; +import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service'; +import { PlaceMediaService } from './place-media.service'; +import { PlaceVisitsService } from './place-visits.service'; +import type { LibraryUser } from './places-library.service'; +import { + idSchema, + placesLibraryDetailRequestSchema, + placeVisitsForPlaceQuerySchema, + placeVisitsListQuerySchema, + type PlaceVisitsForPlaceQuery, + type PlaceVisitsListQuery, + type PlacesLibraryDetailRequest, +} from '@trek/shared'; + +const DERIVED = + 'Visits are read from the trips, never entered: a place counts as visited on a dated day up to today it is planned on, in a trip you own or are a member of, when the stop names no one or names you. Each place counts once per day.'; + +const tripInput = { tripId: idSchema }; + +/** + * D7/PLC-10, PLC-19, PLC-20, PLC-23 over the same services and checks as + * /api/place-visits, /api/trips/:tripId/place-visits and the media route of + * All places. Read only, like the routes. The visits answer to the places + * scope; the media of an entry of All places sits behind the Collections + * addon like the rest of the library. + */ +@McpController() +export class PlaceVisitsMcp { + constructor( + private readonly visits: PlaceVisitsService, + private readonly media: PlaceMediaService, + private readonly guards: McpToolGuardsService, + // Read by the addon gate of the media tool. + readonly addons: AddonsService, + ) {} + + private async user(userId: number): Promise { + return { id: userId, role: (await this.guards.isAdminUser(userId)) ? 'admin' : 'user' }; + } + + @Tool({ + name: 'list_place_visits', + description: `Your visits, newest day first, of one trip (trip_id) or of all, paged with limit and offset, each with its day, time, trip, trip place, day and who it counts for. ${DERIVED}`, + inputSchema: placeVisitsListQuerySchema.shape, + annotations: TOOL_ANNOTATIONS_READONLY, + access: { group: 'places', mode: 'read' }, + }) + async listPlaceVisits(input: PlaceVisitsListQuery, ctx: McpContext) { + return ok(await this.visits.list(await this.user(ctx.userId), input)); + } + + @Tool({ + name: 'get_place_visit_history', + description: `Your visits at one place of All places, opened from a trip place (kind trip) or a saved place (kind list), newest first, plus visit_count and last_visit. A day counts once however many trips or lists hold the place. ${DERIVED}`, + inputSchema: placeVisitsForPlaceQuerySchema.shape, + annotations: TOOL_ANNOTATIONS_READONLY, + access: { group: 'places', mode: 'read' }, + }) + async getPlaceVisitHistory(input: PlaceVisitsForPlaceQuery, ctx: McpContext) { + return ok(await this.visits.forPlace(await this.user(ctx.userId), input.kind, input.id)); + } + + @Tool({ + name: 'list_my_visited_trip_places', + description: `The trip's places you visited (place_ids), counting the days at each trip place and at the same place on your other trips, with visit_count and last_visit. ${DERIVED}`, + inputSchema: tripInput, + annotations: TOOL_ANNOTATIONS_READONLY, + access: { group: 'places', mode: 'read' }, + }) + async listMyVisitedTripPlaces({ tripId }: { tripId: number }, ctx: McpContext) { + return ok(await this.visits.tripVisited(tripId, await this.user(ctx.userId))); + } + + @Tool({ + name: 'get_library_place_media', + description: + 'The pictures, journey photos and trip files of one entry of All places, opened from a trip place or a saved place, each with the trip, list or journey it comes from. Only journeys and trips you can open contribute.', + inputSchema: placesLibraryDetailRequestSchema.shape, + annotations: TOOL_ANNOTATIONS_READONLY, + when: addonGate(ADDON_IDS.COLLECTIONS), + access: { group: 'collections', mode: 'read' }, + }) + async getLibraryPlaceMedia(input: PlacesLibraryDetailRequest, ctx: McpContext) { + return ok(await this.media.media(await this.user(ctx.userId), input.kind, input.id)); + } +} diff --git a/server/src/nest/places-library/place-visits.module.ts b/server/src/nest/places-library/place-visits.module.ts new file mode 100644 index 000000000..1c133898a --- /dev/null +++ b/server/src/nest/places-library/place-visits.module.ts @@ -0,0 +1,34 @@ +import { AddonsModule } from '../addons/addons.module'; +import { JourneyDomainModule } from '../journey/journey-domain.module'; +import { McpSharedModule } from '../mcp-shared/mcp-shared.module'; +import { PermissionsModule } from '../permissions/permissions.module'; +import { TripMembershipModule } from '../trip-membership/trip-membership.module'; +import { PlaceMediaController } from './place-media.controller'; +import { PlaceMediaService } from './place-media.service'; +import { PlaceVisitsTripController } from './place-visits-trip.controller'; +import { PlaceVisitsController } from './place-visits.controller'; +import { PlaceVisitsMcp } from './place-visits.mcp'; +import { PlaceVisitsService } from './place-visits.service'; +import { PlacesLibraryModule } from './places-library.module'; +import { Module } from '@nestjs/common'; + +/** + * D7/PLC-10, PLC-19, PLC-20, PLC-23: the visits read from the trips, their + * history at a place of All places, the trip places visited, and the photos + * and files of an entry of All places. Part of the places-library domain, + * beside PlacesLibraryModule, which resolves every place and provides the + * visit reader and its context repository. Read only. + */ +@Module({ + imports: [ + PlacesLibraryModule, + AddonsModule, + PermissionsModule, + JourneyDomainModule, + TripMembershipModule, + McpSharedModule, + ], + controllers: [PlaceVisitsController, PlaceVisitsTripController, PlaceMediaController], + providers: [PlaceVisitsService, PlaceMediaService, PlaceVisitsMcp], +}) +export class PlaceVisitsModule {} diff --git a/server/src/nest/places-library/place-visits.service.ts b/server/src/nest/places-library/place-visits.service.ts new file mode 100644 index 000000000..6ff25c00c --- /dev/null +++ b/server/src/nest/places-library/place-visits.service.ts @@ -0,0 +1,121 @@ +import { PlaceVisitContextRepository } from '../../db/repositories/PlaceVisitContext.repository'; +import { tripNotFound } from '../common/trip-writer'; +import { TripAccessService } from '../trip-membership/trip-access.service'; +import { PlaceVisitsReaderService } from './place-visits-reader.service'; +import { collapseVisits, uniqueIds, visitsOfEntry } from './place-visits.helpers'; +import { entryKey, type EntryRows } from './places-library.helpers'; +import { PlacesLibraryService, placeNotFound, type LibraryReach, type LibraryUser } from './places-library.service'; +import { Injectable } from '@nestjs/common'; +import { + PLACE_VISITS_PAGE_DEFAULT, + type PlaceVisitsForPlaceResponse, + type PlaceVisitsListQuery, + type PlaceVisitsListResponse, + type PlaceVisitTripVisitedResponse, + type PlacesLibraryKind, +} from '@trek/shared'; + +/** + * D7/PLC-10, PLC-23: the visits of a reader, read from the trips they reach + * (`PlaceVisitsReaderService` has the rule). Nothing here writes: a visit + * comes from planning a place on a day and goes with that plan or with the + * access to its trip. What counts as one place is what All places shows as + * one entry, so a place grouped with others or on several trips counts once + * per day. + */ +@Injectable() +export class PlaceVisitsService { + constructor( + private readonly library: PlacesLibraryService, + private readonly reader: PlaceVisitsReaderService, + private readonly context: PlaceVisitContextRepository, + private readonly trips: TripAccessService, + ) {} + + /** + * The reader's visits at one place of All places, opened from a trip place + * or a saved place: every day at one of the entry's trip places, newest + * first, the same ones the entry counts. + */ + async forPlace(user: LibraryUser, kind: PlacesLibraryKind, id: number): Promise { + const reach = await this.library.reach(user.id); + const anchor = await this.library.anchorOfUse(reach, kind, id); + if (anchor === null) throw placeNotFound(); + const [rows] = await this.library.rows(reach, [anchor]); + if (!rows) throw placeNotFound(); + const visits = await this.reader.ofEntry(reach, rows); + return { + visits: await this.reader.wire(visits), + visit_count: visits.length, + last_visit: visits[0]?.visited_on ?? null, + }; + } + + /** The reader's visits, newest day first, of one trip or of all, paged. */ + async list(user: LibraryUser, query: PlaceVisitsListQuery): Promise { + const reach = await this.library.reach(user.id); + const tripIds = query.trip_id === undefined ? reach.tripIds : [query.trip_id]; + const entryOf = await this.entryKeys(reach); + const visits = await this.reader.onTrips( + reach, + tripIds, + (row) => entryOf.get(row.place_id) ?? `trip:${row.place_id}`, + ); + const offset = query.offset ?? 0; + const page = visits.slice(offset, offset + (query.limit ?? PLACE_VISITS_PAGE_DEFAULT)); + return { visits: await this.reader.wire(page), total: visits.length }; + } + + /** + * The trip's places the reader visited, for the filter of the trip's list + * and map: every place with a visit at it or at the same place elsewhere + * (the same entry of All places), with how many days and the latest. + */ + async tripVisited(tripId: number, user: LibraryUser): Promise { + if (!(await this.trips.findAccessible(tripId, user.id))) throw tripNotFound(); + const placeIds = await this.context.tripPlaceIds(tripId); + if (placeIds.length === 0) return { place_ids: [], places: [] }; + const reach = await this.library.reach(user.id); + const entries = await this.entriesOfPlaces(reach, placeIds); + const entryPlaces = uniqueIds([ + ...placeIds, + ...[...entries.values()].flatMap((rows) => rows.trips.map((row) => row.id)), + ]); + const planned = await this.reader.plannedAt(reach, entryPlaces); + if (planned.length === 0) return { place_ids: [], places: [] }; + const places = placeIds.flatMap((placeId) => { + const rows = entries.get(placeId); + const visits = rows + ? visitsOfEntry(rows, planned) + : collapseVisits( + planned.filter((row) => row.place_id === placeId), + () => 'place', + ); + const last = visits[0]?.visited_on; + return last === undefined ? [] : [{ place_id: placeId, visit_count: visits.length, last_visit: last }]; + }); + return { place_ids: places.map((place) => place.place_id), places }; + } + + /** The entry of All places each trip place the reader reaches stands for, by its key. */ + private async entryKeys(reach: LibraryReach): Promise> { + const uses = await this.library.usesOf(reach, null); + return new Map(uses.filter((use) => use.from_list === 0).map((use) => [use.use_id, entryKey(use.anchor_key)])); + } + + /** The entry of All places each trip place stands for, by trip place id. */ + private async entriesOfPlaces(reach: LibraryReach, placeIds: readonly number[]): Promise> { + const wanted = new Set(placeIds); + const uses = (await this.library.usesOf(reach, null)).filter( + (use) => use.from_list === 0 && wanted.has(use.use_id), + ); + const anchors = uniqueIds(uses.map((use) => use.anchor_key)); + const rows = new Map((await this.library.rows(reach, anchors)).map((row) => [row.anchor, row])); + const byPlace = new Map(); + for (const use of uses) { + const row = rows.get(use.anchor_key); + if (row) byPlace.set(use.use_id, row); + } + return byPlace; + } +} diff --git a/server/src/nest/places-library/places-library.dto.ts b/server/src/nest/places-library/places-library.dto.ts index 53e1dc145..60bd93781 100644 --- a/server/src/nest/places-library/places-library.dto.ts +++ b/server/src/nest/places-library/places-library.dto.ts @@ -1,5 +1,7 @@ import { + placesLibraryBulkTagsRequestSchema, placesLibraryDuplicatesQuerySchema, + placesLibraryEntryTagsRequestSchema, placesLibraryQuerySchema, placesLibraryLinkRequestSchema, placesLibraryMergeRequestSchema, @@ -16,3 +18,7 @@ export class PlacesLibraryUnlinkDto extends createZodDto(placesLibraryUnlinkRequ export class PlacesLibraryDuplicatesQueryDto extends createZodDto(placesLibraryDuplicatesQuerySchema) {} export class PlacesLibraryPairDto extends createZodDto(placesLibraryPairRequestSchema) {} export class PlacesLibraryMergeDto extends createZodDto(placesLibraryMergeRequestSchema) {} + +/** PLC-21: the personal tags of one entry, and of several at once. */ +export class PlacesLibraryEntryTagsDto extends createZodDto(placesLibraryEntryTagsRequestSchema) {} +export class PlacesLibraryBulkTagsDto extends createZodDto(placesLibraryBulkTagsRequestSchema) {} diff --git a/server/src/nest/places-library/places-library.helpers.ts b/server/src/nest/places-library/places-library.helpers.ts index 3a6b8e940..a2efb954a 100644 --- a/server/src/nest/places-library/places-library.helpers.ts +++ b/server/src/nest/places-library/places-library.helpers.ts @@ -142,6 +142,7 @@ function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean, linked: boolea trip_title: row.trip_title, trip_start: row.trip_start, trip_end: row.trip_end, + trip_cover: row.trip_cover ?? null, place_id: row.id, can_edit: canEdit, read_only: !canEdit, @@ -154,6 +155,8 @@ function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean, linked: kind: 'list', collection_id: row.collection_id, collection_name: row.collection_name, + collection_color: row.collection_color ?? null, + collection_icon: row.collection_icon ?? null, collection_place_id: row.id, status: collectionStatusSchema.parse(row.status), can_edit: canEdit, diff --git a/server/src/nest/places-library/places-library.mcp.ts b/server/src/nest/places-library/places-library.mcp.ts index 7e6d96a43..76269244a 100644 --- a/server/src/nest/places-library/places-library.mcp.ts +++ b/server/src/nest/places-library/places-library.mcp.ts @@ -43,7 +43,7 @@ export class PlacesLibraryMcp { @Tool({ name: 'list_all_places', - description: `Page through every place the user has: the saved places of every list they can open and the places of every trip they can open, by name (sort: name, the default) or last changed first (sort: updated), ${PLACES_LIBRARY_PAGE_DEFAULT} at a time unless limit says otherwise (at most ${PLACES_LIBRARY_PAGE_MAX}). Tours, tracks and road trip stops of the drive are left out; lodging counts as a place. A saved place and a trip place are one entry only when the saved place came from that trip place and both agree (the same provider id, or the same name at the same spot); otherwise they are separate entries, unless the user put them together as an own place of theirs (link_library_places, merge_library_places). Each entry has a key (trip:, list:, or own: for an own place), identity_id (the own place's id, null for any other entry), name, address, lat, lng, category, image_url and its origins: kind trip (trip_id, trip_title, trip_start, trip_end, place_id, can_edit, read_only) or kind list (collection_id, collection_name, collection_place_id, status, can_edit). No notes; get_library_place reads one entry in full. Filter by q (name or address), category_id, kind, collection_id, trip_id or status (a list status); a list filter and a trip filter do not go together. Next to the page: total (what every filter matches), counts (all, trip, list for q and category_id alone) and next_cursor, passed back as cursor for the next page, null on the last. A page can end before limit, so always go on at next_cursor.`, + description: `Page through every place the user has: the saved places of every list they can open and the places of every trip they can open, by name (sort: name, the default) or last changed first (sort: updated), ${PLACES_LIBRARY_PAGE_DEFAULT} at a time unless limit says otherwise (at most ${PLACES_LIBRARY_PAGE_MAX}). Tours, tracks and road trip stops of the drive are left out; lodging counts as a place. A saved place and a trip place are one entry only when the saved place came from that trip place and both agree (the same provider id, or the same name at the same spot); otherwise they are separate entries, unless the user put them together as an own place of theirs (link_library_places, merge_library_places). Each entry has a key (trip:, list:, or own: for an own place), identity_id (the own place's id, null for any other entry), name, address, lat, lng, category, image_url and its origins: kind trip (trip_id, trip_title, trip_start, trip_end, trip_cover, place_id, can_edit, read_only) or kind list (collection_id, collection_name, collection_color, collection_icon, collection_place_id, status, can_edit). Each entry also carries tags, your own personal tags on it (private, set with set_library_place_tags or tag_library_places). No notes; get_library_place reads one entry in full. Filter by q (name or address), category_id, kind, collection_id, trip_id, status (a list status) or tag_ids (entries with at least one of these personal tags); a list filter and a trip filter do not go together. Next to the page: total (what every filter matches), counts (all, trip, list for q, category_id and tag_ids alone) and next_cursor, passed back as cursor for the next page, null on the last. A page can end before limit, so always go on at next_cursor.`, inputSchema: placesLibraryQuerySchema.shape, annotations: TOOL_ANNOTATIONS_READONLY, when: addonGate(ADDON_IDS.COLLECTIONS), diff --git a/server/src/nest/places-library/places-library.module.ts b/server/src/nest/places-library/places-library.module.ts index 82e073e26..ca1900b5e 100644 --- a/server/src/nest/places-library/places-library.module.ts +++ b/server/src/nest/places-library/places-library.module.ts @@ -1,7 +1,9 @@ +import { PersonalPlaceTags } from '../../db/entities/PersonalPlaceTags.entity'; import { UserPlaceLinks } from '../../db/entities/UserPlaceLinks.entity'; import { UserPlaceMergeDismissals } from '../../db/entities/UserPlaceMergeDismissals.entity'; import { UserPlaceMerges } from '../../db/entities/UserPlaceMerges.entity'; import { UserPlaces } from '../../db/entities/UserPlaces.entity'; +import { PlaceVisitContextRepository } from '../../db/repositories/PlaceVisitContext.repository'; import { PlacesLibraryRepository } from '../../db/repositories/PlacesLibrary.repository'; import { AddonsModule } from '../addons/addons.module'; import { CollectionsModule } from '../collections/collections.module'; @@ -14,6 +16,11 @@ import { PlaceIdentitiesPruneJob } from './place-identities-prune.job'; import { PlaceIdentitiesController } from './place-identities.controller'; import { PlaceIdentitiesMcp } from './place-identities.mcp'; import { PlaceIdentitiesService } from './place-identities.service'; +import { PlaceTagsController } from './place-tags.controller'; +import { PlaceTagsMcp } from './place-tags.mcp'; +import { PlaceTagsService } from './place-tags.service'; +import { PlaceVisitsReaderService } from './place-visits-reader.service'; +import { PlaceVisitsClock } from './place-visits.clock'; import { PlacesLibraryController } from './places-library.controller'; import { PlacesLibraryMcp } from './places-library.mcp'; import { PlacesLibraryService } from './places-library.service'; @@ -25,9 +32,10 @@ import { Module } from '@nestjs/common'; * PLC-07/PLC-08 "All places" under the Collections addon: the saved places of * every list and the places of every trip the user can open, read only, plus * (D5/PLC-13) the user's own places that group them, the duplicate - * suggestions and merges. The library repository reads across trips and - * lists, so it backs no entity and is built here over the context-resolving - * EntityManager, the way MaintenanceModule builds its own. + * suggestions and merges, and (D7) the visits every entry carries, read from + * the trips' day plans, and (PLC-21) the user's personal tags on them. The library repository and the visit context read + * across trips and lists, so they back no entity and are built here over the + * context-resolving EntityManager, the way MaintenanceModule builds its own. */ @Module({ imports: [ @@ -37,21 +45,38 @@ import { Module } from '@nestjs/common'; PermissionsModule, McpSharedModule, SchedulingModule, - MikroOrmModule.forFeature([UserPlaces, UserPlaceLinks, UserPlaceMerges, UserPlaceMergeDismissals]), + MikroOrmModule.forFeature([ + UserPlaces, + UserPlaceLinks, + UserPlaceMerges, + UserPlaceMergeDismissals, + PersonalPlaceTags, + ]), ], - controllers: [PlacesLibraryController, PlaceIdentitiesController], + controllers: [PlacesLibraryController, PlaceIdentitiesController, PlaceTagsController], providers: [ { provide: PlacesLibraryRepository, useFactory: (em: EntityManager) => new PlacesLibraryRepository(em), inject: [EntityManager], }, + { + provide: PlaceVisitContextRepository, + useFactory: (em: EntityManager) => new PlaceVisitContextRepository(em), + inject: [EntityManager], + }, + PlaceVisitsClock, + PlaceVisitsReaderService, PlacesLibraryService, PlacesLibraryMcp, PlaceIdentitiesService, PlaceDuplicatesService, PlaceIdentitiesMcp, PlaceIdentitiesPruneJob, + PlaceTagsService, + PlaceTagsMcp, ], + // The visits and media of All places (PlaceVisitsModule, same domain) read through these. + exports: [PlacesLibraryService, PlaceVisitsReaderService, PlaceVisitContextRepository], }) export class PlacesLibraryModule {} diff --git a/server/src/nest/places-library/places-library.service.ts b/server/src/nest/places-library/places-library.service.ts index bfb0c19c6..38e0586b9 100644 --- a/server/src/nest/places-library/places-library.service.ts +++ b/server/src/nest/places-library/places-library.service.ts @@ -11,6 +11,8 @@ import { CollectionsService } from '../collections/collections.service'; import { badRequest, notFound } from '../common/domain-error'; import { PermissionsService } from '../permissions/permissions.service'; import { TripMembershipService } from '../trip-membership/trip-membership.service'; +import { tagsByEntry, tagTargetsOf } from './place-tags.helpers'; +import { PlaceVisitsReaderService } from './place-visits-reader.service'; import { decodeLibraryCursor, encodeLibraryCursor, @@ -35,6 +37,7 @@ import { type PlacesLibraryKind, type PlacesLibraryPageResponse, type PlacesLibraryQuery, + type PlacesLibraryTag, } from '@trek/shared'; /** Who asks, as the permission check reads them. */ @@ -80,6 +83,10 @@ function armsOfReach(reach: LibraryReach): LibraryArms { * Uses the user put together as one place of their own (D5) are one entry, * named and placed as that own place; only the uses the user reaches today * belong to it. + * + * Every entry carries the user's visits to it (D7/PLC-10), read from the + * plans of the trips they reach (`PlaceVisitsReaderService`): each day once + * per entry, the same ones the visit history of the place lists. */ @Injectable() export class PlacesLibraryService { @@ -88,6 +95,7 @@ export class PlacesLibraryService { private readonly collections: CollectionsService, private readonly membership: TripMembershipService, private readonly permissions: PermissionsService, + private readonly visits: PlaceVisitsReaderService, ) {} async list( @@ -106,6 +114,8 @@ export class PlacesLibraryService { search: query.q ? query.q : null, categoryId: query.category_id ?? null, status: query.status ?? null, + // PLC-21: a tag on any use the user reaches counts, whatever the page's other filters leave out. + tags: query.tag_ids === undefined ? null : { tagIds: query.tag_ids, reach: armsOfReach(reach) }, }; const counts = await this.repo.countEntries(armsOfReach(reach), { ...match, status: null }); @@ -151,7 +161,12 @@ export class PlacesLibraryService { const rows = (await this.rows(reach, [anchor]))[0]; if (!rows) throw placeNotFound(); const entry = entryOf(rows, await this.access(user, rows.trips, rows.saved)); - return { entry, details: await this.details(user.id, rows) }; + const [summary] = await this.visits.summaries(reach, [rows]); + const [tags] = await this.tagsOf(user.id, [rows]); + return { + entry: { ...entry, ...summary, tags: tags ?? [] }, + details: await this.details(user.id, rows), + }; } /** The trips and lists the user reaches right now. */ @@ -205,7 +220,15 @@ export class PlacesLibraryService { rows.flatMap((row) => row.trips), rows.flatMap((row) => row.saved), ); - return rows.map((row) => entryOf(row, access)); + const summaries = await this.visits.summaries(reach, rows); + const tags = await this.tagsOf(user.id, rows); + return rows.map((row, index) => ({ ...entryOf(row, access), ...summaries[index], tags: tags[index] ?? [] })); + } + + /** PLC-21: the user's own personal tags of each entry, in the entries' order. */ + private async tagsOf(userId: number, rows: readonly EntryRows[]): Promise { + const tagRows = await readInChunks(rows, (chunk) => this.repo.entryTags(userId, tagTargetsOf(chunk))); + return tagsByEntry(rows, tagRows); } /** One entry, or null when it has no use the user reaches. */ diff --git a/server/src/nest/places/places.controller.ts b/server/src/nest/places/places.controller.ts index ca1307ecc..f55ed4fa5 100644 --- a/server/src/nest/places/places.controller.ts +++ b/server/src/nest/places/places.controller.ts @@ -426,7 +426,12 @@ export class PlacesController { if (!('category_id' in body)) { throw new HttpException({ error: 'Provide at least one field to update' }, 400); } - const updated = await this.places.updateMany(tripId, ids, { category_id: body.category_id as number | null }); + const updated = await this.places.updateMany( + tripId, + ids, + { category_id: body.category_id as number | null }, + user.id, + ); for (const place of updated) { this.places.broadcast(tripId, 'place:updated', { place }, socketId); await this.places.onUpdated(place.id); @@ -470,7 +475,13 @@ export class PlacesController { await this.storage.put('places', file.filename, { tmpPath: file.path }); // Reuse the existing image_url slot (the top-precedence thumbnail source); the // update path reclaims any previously uploaded file it replaces. - const result = await this.places.update(tripId, id, { image_url: placeImageUrl(file.filename) } as never); + const result = await this.places.update( + tripId, + id, + { image_url: placeImageUrl(file.filename) } as never, + undefined, + user.id, + ); if (!result || isUpdateConflict(result)) { throw new HttpException({ error: 'Place not found' }, 404); } @@ -494,7 +505,7 @@ export class PlacesController { if (isDemoWriteBlocked(this.env, user.email)) { throw new HttpException(DEMO_WRITE_ERROR, 403); } - const result = await this.places.setImageFromFile(tripId, id, body.file_id); + const result = await this.places.setImageFromFile(tripId, id, body.file_id, user.id); if (result === 'not_found') throw new HttpException({ error: 'File not found' }, 404); if (result === 'not_image') throw new HttpException({ error: 'Only jpg, png, gif, webp images allowed' }, 400); if (result === 'too_large') throw new HttpException({ error: 'Image too large' }, 400); @@ -567,7 +578,7 @@ export class PlacesController { validateRouteColor(body); validateUrlFields(body); await this.requireEdit(trip, user); - const result = await this.places.update(tripId, id, body as never, ifMatch); + const result = await this.places.update(tripId, id, body as never, ifMatch, user.id); if (!result) { throw new HttpException({ error: 'Place not found' }, 404); } diff --git a/server/src/nest/places/places.mcp.ts b/server/src/nest/places/places.mcp.ts index 1262d1133..915266d23 100644 --- a/server/src/nest/places/places.mcp.ts +++ b/server/src/nest/places/places.mcp.ts @@ -233,7 +233,7 @@ 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, tags }); + 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, tags }, undefined, ctx.userId); // 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 }); @@ -261,7 +261,7 @@ 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); + const result = await this.places.setImageFromFile(String(tripId), String(placeId), fileId, ctx.userId); 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.'); @@ -561,7 +561,7 @@ export class PlacesMcp { const before = new Map( await Promise.all(placeIds.map(async (id) => [id, await this.origins.valuesBefore(id)] as const)), ); - const updated = await this.places.updateMany(String(tripId), placeIds, fields); + const updated = await this.places.updateMany(String(tripId), placeIds, fields, ctx.userId); // Per place, the event and then the journey hook, in the order POST /places/bulk-update keeps. await inOrder(updated, async (place) => { this.guards.safeBroadcast(tripId, 'place:updated', { place }); diff --git a/server/src/nest/places/places.module.ts b/server/src/nest/places/places.module.ts index 473f35e50..2c7e08010 100644 --- a/server/src/nest/places/places.module.ts +++ b/server/src/nest/places/places.module.ts @@ -17,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 { PlaceChangesModule } from '../place-changes/place-changes.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'; @@ -79,6 +80,8 @@ import { MulterModule } from '@nestjs/platform-express'; // Every place write records where its shareable details came from, and the // user's values go to the community enrichment's queue there. PlaceContribModule, + // PLC-14: every write of a place's details keeps its history, in the write's transaction. + PlaceChangesModule, // Plan 3c Task 4: `PlacesService`'s and `PlacesMcp`'s own `@InjectRepository` // constructor params (`PlacesRepository`, `TagsRepository`, // `PlaceRatingsRepository`, `TripMembersRepository`, diff --git a/server/src/nest/places/places.rpc.ts b/server/src/nest/places/places.rpc.ts index 39d9eea70..35730d394 100644 --- a/server/src/nest/places/places.rpc.ts +++ b/server/src/nest/places/places.rpc.ts @@ -97,7 +97,13 @@ export class PlacesRpc { // 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); + const place = await this.places.update( + String(tripId), + String(placeId), + parsed.data as PlaceUpdateInput, + undefined, + actor, + ); 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); diff --git a/server/src/nest/places/places.service.ts b/server/src/nest/places/places.service.ts index 326a5144e..f1fe5583e 100644 --- a/server/src/nest/places/places.service.ts +++ b/server/src/nest/places/places.service.ts @@ -27,6 +27,7 @@ import { JourneyDomainService } from '../journey/journey-domain.service'; import { StorageService } from '../storage/storage.service'; import { StorageReleaseService } from '../storage/storage-release.service'; import { AccommodationsService } from '../accommodations/accommodations.service'; +import { AUTOMATIC_CHANGE, PlaceChangesService, tripPlaceTarget, type ChangeEditor } from '../place-changes/place-changes.service'; import { Places } from '../../db/entities/Places.entity'; import { Tags } from '../../db/entities/Tags.entity'; import { PlaceRatings } from '../../db/entities/PlaceRatings.entity'; @@ -164,6 +165,7 @@ export class PlacesService { private readonly release: StorageReleaseService, // the images a change or a delete left unnamed (#2924) // Reading files and shared lists; this service only persists what it reads. private readonly placeImport: PlaceImportService, + private readonly changes: PlaceChangesService, // PLC-14: the history of every details write, in its transaction ) {} /** @@ -283,7 +285,7 @@ export class PlacesService { * and the storage reclaim job takes the copy like any other uploaded image. Returns a reason * string when the file cannot serve, the updated place otherwise. */ - async setImageFromFile(tripId: string, placeId: string, fileId: number): Promise<'not_found' | 'not_image' | 'too_large' | Awaited>> { + async setImageFromFile(tripId: string, placeId: string, fileId: number, editor: ChangeEditor = null): Promise<'not_found' | 'not_image' | 'too_large' | Awaited>> { const tid = toRowId(tripId); // PL53 — the trip's own, not-trashed attachment. const file = tid === null ? undefined : await this.placesRepo.findActiveTripFile(fileId, tid); @@ -295,7 +297,7 @@ export class PlacesService { const name = `${randomUUID()}${ext}`; const { stream } = await this.storage.getStream('files', path.basename(file.filename)); await this.storage.put('places', name, stream, { contentType: mime }); - const updated = await this.update(tripId, placeId, { image_url: placeImageUrl(name) } as never); + const updated = await this.update(tripId, placeId, { image_url: placeImageUrl(name) } as never, undefined, editor); // The copy is this request's own until the update names it, so a failed update drops it here. if (!updated || isUpdateConflict(updated)) await this.storage.delete('places', name).catch(() => undefined); return updated; @@ -408,8 +410,9 @@ export class PlacesService { placeId: string, body: PlaceUpdateInput, ifMatch?: string, + editor: ChangeEditor = null, // who the history names (PLC-14) ): Promise { - const { result, previousImage } = await this.uow.transactional(() => this.applyUpdate(tripId, placeId, body, ifMatch)); + const { result, previousImage } = await this.uow.transactional(() => this.applyUpdate(tripId, placeId, body, ifMatch, editor)); await this.release.releaseValues([previousImage]); // after the commit: kept while a copy or a cover names it return result; } @@ -422,7 +425,8 @@ export class PlacesService { tripId: string, placeId: string, body: PlaceUpdateInput, - ifMatch?: string, + ifMatch: string | undefined, + editor: ChangeEditor, ): Promise<{ result: PlaceWithTags | UpdateConflict | null; previousImage?: string | null }> { // PL9 — the pre-image read every `!== undefined` fallback below needs. // `toRowId` first (Task 3 review H1, absorbed here): every write in @@ -468,7 +472,7 @@ export class PlacesService { // `!== undefined ? x : existing.x` pre-image fallbacks are resolved to // their final value HERE, in the service — the repository writes // exactly what it is handed. - await this.placesRepo.updatePlace(id, { + await this.changes.track(tripPlaceTarget(id), editor, () => this.placesRepo.updatePlace(id, { // COALESCE(?, name): the bound value is `name || null` (falsy clears // to null), and `?? existingPlace.name` is the COALESCE half itself — // a `nativeUpdate` writes a literal value, it does not evaluate SQL @@ -509,7 +513,7 @@ export class PlacesService { stop_type: stop_type !== undefined ? stop_type : existingPlace.stop_type, // And how a stop that had its own fill amount goes back to following the setting. fill_percent: fill_percent !== undefined ? fill_percent : existingPlace.fill_percent, - }); + })); if (tags !== undefined) { await this.tagsRepo.deleteForPlace(id); // PL12 @@ -680,7 +684,7 @@ export class PlacesService { * fields change and everything else is preserved. IDs that don't belong to the * trip are skipped. Returns the updated places. */ - async updateMany(tripId: string, ids: number[], body: PlaceUpdateInput): Promise { + async updateMany(tripId: string, ids: number[], body: PlaceUpdateInput, editor: ChangeEditor = null): Promise { if (ids.length === 0) return []; const updated: PlaceWithTags[] = []; const previousImages: (string | null | undefined)[] = []; @@ -688,7 +692,7 @@ export class PlacesService { for (const id of ids) { // Bulk update sends no If-Match, so applyUpdate() never returns a // conflict here; the guard keeps the types honest. - const { result: place, previousImage } = await this.applyUpdate(tripId, String(id), body); + const { result: place, previousImage } = await this.applyUpdate(tripId, String(id), body, undefined, editor); if (place && !isUpdateConflict(place)) updated.push(place); previousImages.push(previousImage); } @@ -1302,14 +1306,8 @@ export class PlacesService { if (place.google_place_id) return; if (typeof place.lat !== 'number' || typeof place.lng !== 'number') return; - // Rule 21 / M1 (Task 9 fix wave): non-null asserted — this whole path - // only ever runs right after this service's own import, downstream of - // the controller's `requireTrip` gate, which already `toRowId`-parsed - // this same `tripId` once. Deliberately NOT applied to - // `this.realtime.broadcast` below: every broadcast call in this domain, - // controller included, keys the room by the raw route string, and - // changing this one call's room shape alone would desync it from what - // the client actually joined. + // Rule 21 / M1: asserted, this only runs after this service's own import behind `requireTrip`, which parsed + // this `tripId`. The broadcast below keeps the raw route string: that is the room the client joined. const tid = toRowId(tripId)!; // Asked for a Google identity rather than for the best answer: the whole @@ -1331,10 +1329,8 @@ export class PlacesService { if (!gpid) return; const gftid = trimOrNull(match.google_ftid); - // PL43 — `fillIfEmpty`, COALESCE-per-column so enrichment only fills - // empty columns — never overwrites data the import already captured - // (e.g. Naver's address) or anything the user edited. - await this.placesRepo.fillIfEmpty(place.id, tid, { + // PL43: only the empty columns, never what the import captured (e.g. Naver's address) or the user edited. + await this.fillTracked(place.id, tid, { google_place_id: gpid, google_ftid: gftid, address: trimOrNull(match.address), @@ -1342,26 +1338,29 @@ export class PlacesService { phone: trimOrNull(match.phone), }); - // Photo is best-effort: Google often has none, in which case getPlacePhoto - // resolves with photoUrl: null. A missing photo (or a provider outage, which - // still throws) must never abort the rest of the enrichment. + // Best-effort: Google often has no photo (photoUrl: null), and a missing one or a provider outage (which still + // throws) must never abort the rest of the enrichment. try { const photo = await this.maps.getPlacePhoto(userId, gpid, place.lat, place.lng, place.name); - if (photo?.photoUrl) { - // PL44 — `fillIfEmpty`, the `image_url`-only shape. - await this.placesRepo.fillIfEmpty(place.id, tid, { image_url: photo.photoUrl }); - } + if (photo?.photoUrl) await this.fillTracked(place.id, tid, { image_url: photo.photoUrl }); // PL44 } catch { /* no photo — leave image_url as-is */ } - // PL45 — push the enriched row to every connected client (no socket - // exclusion: the importer's own client should also receive the late - // update — `socketId: undefined`, no `X-Socket-Id` to exclude). + // PL45: every connected client gets the late enriched row, the importer's own included (`socketId: undefined`, + // no `X-Socket-Id` to exclude). const updated = await this.placesRepo.findWithTagsAndRatings(place.id); if (updated) this.realtime.broadcast(tripId, 'place:updated', { place: updated }, undefined); } + /** + * PL43/PL44/PL46: TREK's own fill of a trip place's empty columns (COALESCE per column), and its + * history (PLC-14), in one transaction. Each fill stands alone: network lookups sit between them. + */ + private fillTracked(id: number, tid: number, fill: Parameters[2]): Promise { + return this.uow.transactional(() => this.changes.track(tripPlaceTarget(id), AUTOMATIC_CHANGE, () => this.placesRepo.fillIfEmpty(id, tid, fill))); + } + /** * Enrich a batch of just-imported places in the background. Never throws — * any per-place failure is swallowed so one bad lookup can't take down the @@ -1438,10 +1437,8 @@ export class PlacesService { timeoutMs: 10000, }); if (!address) continue; - // PL46 — `fillIfEmpty`, the `address`-only shape. - await this.placesRepo.fillIfEmpty(place.id, tid, { address }); - // PL47 — same broadcast shape as PL45: `socketId: undefined`, no - // exclusion. + await this.fillTracked(place.id, tid, { address }); // PL46 + // PL47 — same broadcast shape as PL45: `socketId: undefined`, no exclusion. const updated = await this.placesRepo.findWithTagsAndRatings(place.id); if (updated) this.realtime.broadcast(tripId, 'place:updated', { place: updated }, undefined); } catch (err) { diff --git a/server/src/nest/tags/tag-writes.service.ts b/server/src/nest/tags/tag-writes.service.ts index f5856f52c..bba7d45fb 100644 --- a/server/src/nest/tags/tag-writes.service.ts +++ b/server/src/nest/tags/tag-writes.service.ts @@ -9,7 +9,9 @@ import type { Tag } from '@trek/shared'; * A ping rather than the tag: a delete has nothing left to send. * * `socketId` is REST's requesting tab, which updated its own list and is left - * out; MCP passes none. The callers keep their ownership checks. + * out; MCP passes none. The callers keep their ownership checks. A create that + * answers a tag the user had already (one name per person, PLC-21) changed + * nothing, so it sends nothing. */ @Injectable() export class TagWritesService { @@ -19,8 +21,8 @@ export class TagWritesService { ) {} async create(userId: number, name: string, color: string | undefined, socketId: string | undefined): Promise { - const tag = await this.tags.create(userId, name, color); - this.announce(userId, socketId); + const { tag, created } = await this.tags.ensure(userId, name, color); + if (created) this.announce(userId, socketId); return tag; } diff --git a/server/src/nest/tags/tags.mcp.ts b/server/src/nest/tags/tags.mcp.ts index ae3615b20..95d4e684c 100644 --- a/server/src/nest/tags/tags.mcp.ts +++ b/server/src/nest/tags/tags.mcp.ts @@ -43,7 +43,8 @@ export class TagsMcp { @Tool({ name: 'create_tag', - description: 'Create a new tag (user-scoped label for places).', + description: + 'Create a personal tag (user-scoped label for places). A name stands once per person, whatever its case: when you have a tag of that name already, that tag is returned as it is (its color unchanged) and nothing new is made.', inputSchema: { name: z.string().min(1).max(100), color: z.string().optional().describe('Hex color string e.g. #6366f1'), diff --git a/server/src/nest/tags/tags.service.ts b/server/src/nest/tags/tags.service.ts index e2b6cbd41..4691f4a7c 100644 --- a/server/src/nest/tags/tags.service.ts +++ b/server/src/nest/tags/tags.service.ts @@ -1,6 +1,8 @@ import { Tags } from '../../db/entities/Tags.entity'; -import type { TagsRepository } from '../../db/repositories/Tags.repository'; +import type { TagRow, TagsRepository } from '../../db/repositories/Tags.repository'; +import { conflict } from '../common/domain-error'; import { toRowId } from '../common/row-id'; +import { UnitOfWork } from '../database/unit-of-work'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; import type { Tag } from '@trek/shared'; @@ -20,7 +22,10 @@ import type { Tag } from '@trek/shared'; */ @Injectable() export class TagsService { - constructor(@InjectRepository(Tags) private readonly tags: TagsRepository) {} + constructor( + @InjectRepository(Tags) private readonly tags: TagsRepository, + private readonly uow: UnitOfWork, + ) {} // `TagRow`'s `color`/`created_at` are nullable (the DB columns carry no NOT // NULL constraint); the `@trek/shared` `Tag` contract narrows them to @@ -49,13 +54,35 @@ export class TagsService { return tag as unknown as Tag; } + /** + * A personal tag of that name, the user's own when they have one already + * (PLC-21: a name stands once per person, whatever its case), else a new one. + */ async create(userId: number, name: string, color?: string): Promise { - const tag = await this.tags.createTag({ - user_id: userId, - name, - color: color || '#10b981', + return (await this.ensure(userId, name, color)).tag; + } + + /** + * {@link create}, saying whether the tag is new. An existing one is answered + * as it is: the color asked for is the new tag's, never a recolor of the old. + */ + async ensure(userId: number, name: string, color?: string): Promise<{ tag: Tag; created: boolean }> { + return this.uow.transactional(async () => { + const existing = await this.namesake(userId, name, null); + if (existing) return { tag: existing as unknown as Tag, created: false }; + const tag = await this.tags.createTag({ user_id: userId, name, color: color || '#10b981' }); + return { tag: tag as unknown as Tag, created: true }; }); - return tag as unknown as Tag; + } + + /** The user's other personal tag named `name` (trimmed, case ignored), or undefined. */ + private async namesake(userId: number, name: unknown, exceptId: number | null): Promise { + if (typeof name !== 'string') return undefined; + const key = name.trim().toLowerCase(); + return (await this.tags.listByUser(userId)).find( + // A legacy row can hold a number as its name, so it is read as text. + (tag) => tag.trip_id === null && tag.id !== exceptId && String(tag.name).trim().toLowerCase() === key, + ); } async update(id: string | number, name?: string, color?: string): Promise { @@ -79,7 +106,15 @@ export class TagsService { // fold into the same `?? undefined` parity the legacy re-select had. const rowId = toRowId(id); if (rowId === null) return undefined as unknown as Tag; - return ((await this.tags.patch(rowId, changes)) ?? undefined) as unknown as Tag; + const patched = await this.uow.transactional(async () => { + // PLC-21: a personal tag is not renamed onto another of the same person's names. + const [current] = await this.tags.findByIds([rowId]); + if (changes.name && current?.trip_id === null && (await this.namesake(current.user_id, changes.name, rowId))) { + throw conflict('A tag with this name already exists'); + } + return await this.tags.patch(rowId, changes); + }); + return (patched ?? undefined) as unknown as Tag; } async remove(id: string | number): Promise { diff --git a/server/tests/e2e/place-activities.e2e.test.ts b/server/tests/e2e/place-activities.e2e.test.ts new file mode 100644 index 000000000..ae524e8b9 --- /dev/null +++ b/server/tests/e2e/place-activities.e2e.test.ts @@ -0,0 +1,197 @@ +/** + * The bookings and tours a place is about (PLC-18) through the real + * AddonGuard, JwtAuthGuard and TripAccessGuard against a migrated and seeded + * temp SQLite db, every answer checked against its response contract. + */ +import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; +import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe'; +import { PlaceActivitiesModule } from '../../src/nest/place-activities/place-activities.module'; +import { RealtimeModule } from '../../src/nest/realtime/realtime.module'; +import { RealtimeService } from '../../src/nest/realtime/realtime.service'; +import { createSnapshotTestDb } from '../helpers/db-mock'; +import { setAddonEnabled } from '../helpers/factories/settings'; +import { addTripMember } from '../helpers/factories/trips'; +import { FakeRealtimeService } from '../helpers/fake-realtime'; +import { oneByOne } from '../helpers/one-by-one'; +import { seedPlaceActivities, type PlaceActivitiesFixture } from '../helpers/place-activities-fixture'; +import { resetTestDb } from '../helpers/test-db'; +import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm'; +import { TestUnitOfWorkModule } from '../helpers/test-uow'; +import { sessionCookie } from './harness'; +import type { INestApplication } from '@nestjs/common'; +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 realtime = new FakeRealtimeService(); + +let app: INestApplication; +let server: Server; +let orm: TestOrm; +let f: PlaceActivitiesFixture; + +const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); +const tripBase = (tripId: number, placeId: number) => `/api/trips/${tripId}/places/${placeId}/activities`; +const savedBase = (id: number | string) => `/api/addons/collections/places/${id}/activities`; + +beforeAll(async () => { + const moduleRef = await Test.createTestingModule({ + imports: [ + await TestUnitOfWorkModule.forRoot(db), + await createTestMikroOrmModule(db), + RealtimeModule, + PlaceActivitiesModule, + ], + }) + .overrideProvider(RealtimeService) + .useValue(realtime) + .compile(); + app = moduleRef.createNestApplication(); + app.use(cookieParser()); + app.useGlobalPipes(new ZodValidationPipe()); + app.useGlobalFilters(new TrekExceptionFilter()); + await app.init(); + server = app.getHttpServer() as Server; + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + realtime.reset(); + f = await seedPlaceActivities(orm); + await setAddonEnabled(orm, 'collections', true); + await setAddonEnabled(orm, 'tours', true); +}); +afterAll(async () => { + await app.close(); + await orm.close(); + db.close(); +}); + +describe('Place activities e2e (real guards + temp SQLite)', () => { + it('answers 401 without a session and 404 for a trip out of reach or a place of another trip', async () => { + expect((await request(server).get(tripBase(f.alps.id, f.places.cafe.id))).status).toBe(401); + const hidden = await request(server).get(tripBase(f.elsewhere.id, f.places.hidden.id)).set(as(f.me.id)); + expect(hidden.status).toBe(404); + expect(hidden.body).toEqual({ error: 'Trip not found' }); + const foreign = await request(server).get(tripBase(f.alps.id, f.places.forum.id)).set(as(f.me.id)); + expect(foreign.status).toBe(404); + expect(foreign.body).toEqual({ error: 'Place not found' }); + }); + + it('links a booking and a tour to a trip place, lists them with the candidates, and unlinks them', async () => { + const cafe = f.places.cafe.id; + const candidates = await request(server) + .get(`${tripBase(f.alps.id, cafe)}/candidates`) + .set(as(f.me.id)); + expect(candidates.status).toBe(200); + expect(candidates.body.candidates.map((c: { title: string }) => c.title)).toEqual( + expect.arrayContaining(['Guided tour', 'Old town walk', 'Ridge walk']), + ); + + const link = await request(server) + .post(tripBase(f.alps.id, cafe)) + .set(as(f.me.id)) + .set('X-Socket-Id', '42') + .send({ reservation_id: f.bookings.guided.id }); + expect(link.status).toBe(200); + expect(realtime.broadcastMock).toHaveBeenCalledWith(f.alps.id, 'placeActivities:changed', { placeId: cafe }, '42'); + await request(server).post(tripBase(f.alps.id, cafe)).set(as(f.me.id)).send({ tour_id: f.tours.walk.id }); + + const list = await request(server).get(tripBase(f.alps.id, cafe)).set(as(f.me.id)); + expect(list.status).toBe(200); + expect(list.body.can_link).toBe(true); + expect(list.body.activities.map((a: { key: string; explicit: boolean }) => [a.key, a.explicit])).toEqual([ + [`reservation:${f.bookings.guided.id}`, true], + [`reservation:${f.bookings.dinner.id}`, false], + [`tour:${f.tours.walk.id}`, true], + ]); + + const booking = await request(server) + .delete(`${tripBase(f.alps.id, cafe)}/reservations/${f.bookings.guided.id}`) + .set(as(f.me.id)); + expect(booking.status).toBe(200); + const tour = await request(server) + .delete(`${tripBase(f.alps.id, cafe)}/tours/${f.tours.walk.id}`) + .set(as(f.me.id)); + expect(tour.status).toBe(200); + expect(tour.body.activities.map((a: { title: string }) => a.title)).toEqual(['Dinner']); + }); + + it('refuses a body it does not take, a booking that belongs already and a bad id', async () => { + const cafe = f.places.cafe.id; + const refused = await oneByOne( + [{}, { reservation_id: 1, tour_id: 2 }, { reservation_id: '0x5' }, { tour_id: 1.5 }, { tour_id: 1, x: 1 }], + (body) => request(server).post(tripBase(f.alps.id, cafe)).set(as(f.me.id)).send(body), + ); + expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400, 400]); + const own = await request(server) + .post(tripBase(f.alps.id, cafe)) + .set(as(f.me.id)) + .send({ reservation_id: f.bookings.dinner.id }); + expect(own.status).toBe(409); + expect(own.body).toMatchObject({ error: 'This booking already belongs to the place' }); + const missing = await oneByOne(['abc', '0x5'], (id) => + request(server) + .delete(`${tripBase(f.alps.id, cafe)}/reservations/${id}`) + .set(as(f.me.id)), + ); + for (const res of missing) { + expect(res.status).toBe(404); + expect(res.body).toEqual({ error: 'This activity is not linked to the place' }); + } + }); + + it('lets a member read what a place is about', async () => { + await addTripMember(orm, f.alps.id, f.friend.id); + const res = await request(server).get(tripBase(f.alps.id, f.places.hotel.id)).set(as(f.friend.id)); + expect(res.status).toBe(200); + expect(res.body.activities).toEqual([expect.objectContaining({ title: 'Hotel Sonne', implicit_via: 'place' })]); + }); + + it('links a kept tour to a saved place behind the Collections addon, and reads an entry of All places', async () => { + await setAddonEnabled(orm, 'collections', false); + expect((await request(server).get(savedBase(f.saved.savedCafe.id)).set(as(f.me.id))).status).toBe(404); + await setAddonEnabled(orm, 'collections', true); + + const link = await request(server) + .post(savedBase(f.saved.savedCafe.id)) + .set(as(f.me.id)) + .send({ collection_tour_id: f.kept.keptRidge.id }); + expect(link.status).toBe(200); + expect(link.body.activities).toEqual([expect.objectContaining({ title: 'Kept ridge', can_unlink: true })]); + const candidates = await request(server) + .get(`${savedBase(f.saved.savedCafe.id)}/candidates`) + .set(as(f.me.id)); + expect(candidates.body.candidates.map((c: { title: string }) => c.title)).toEqual(['Kept lake loop']); + + const entry = await request(server) + .get(`/api/addons/collections/library/places/list/${f.saved.savedCafe.id}/activities`) + .set(as(f.me.id)); + expect(entry.status).toBe(200); + expect(entry.body.activities.map((a: { title: string }) => a.title).sort()).toEqual(['Dinner', 'Kept ridge']); + expect(entry.body.sources).toHaveLength(2); + + const unlink = await request(server) + .delete(`${savedBase(f.saved.savedCafe.id)}/tours/${f.kept.keptRidge.id}`) + .set(as(f.me.id)); + expect(unlink.status).toBe(200); + expect(unlink.body).toEqual({ activities: [], can_link: true }); + + const viewer = await request(server) + .post(savedBase(f.saved.pantheon.id)) + .set(as(f.me.id)) + .send({ collection_tour_id: f.kept.keptRome.id }); + expect(viewer.status).toBe(403); + const secret = await request(server).get(savedBase(f.saved.secret.id)).set(as(f.me.id)); + expect(secret.status).toBe(404); + expect(secret.body).toEqual({ error: 'Place not found' }); + const bad = await request(server).get(savedBase('0x5')).set(as(f.me.id)); + expect(bad.status).toBe(404); + expect(bad.body).toEqual({ error: 'Place not found' }); + }); +}); diff --git a/server/tests/e2e/place-history.e2e.test.ts b/server/tests/e2e/place-history.e2e.test.ts new file mode 100644 index 000000000..b1ba85381 --- /dev/null +++ b/server/tests/e2e/place-history.e2e.test.ts @@ -0,0 +1,242 @@ +/** + * PLC-14 end to end on the whole app (buildApp, the real guards, services, + * MCP registry and a migrated temp database): the history of a place's + * details is written by the routes and tools that change them, in their own + * transaction, and read over the origins of an entry of All places the + * reader reaches today. A change of a trip or list the reader cannot open + * leaves no trace, a cleared value takes its earlier changes along, a deleted + * place takes its history along, and the pages go on by their cursor. + */ +import { buildApp } from '../../src/bootstrap'; +import { CollectionMembers } from '../../src/db/entities/CollectionMembers.entity'; +import { PlaceChangeLog } from '../../src/db/entities/PlaceChangeLog.entity'; +import { Places } from '../../src/db/entities/Places.entity'; +import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp'; +import { withRequestContext } from '../../src/nest/database/request-context'; +import { addCollectionMember } from '../helpers/factories/collections'; +import { countRows, deleteRows } from '../helpers/factories/rows'; +import { setAddonEnabled } from '../helpers/factories/settings'; +import { seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture'; +import { resetRateLimits } from '../helpers/test-db'; +import { sessionCookie } from './harness'; +import { MikroORM } from '@mikro-orm/core'; +import { Client } from '@modelcontextprotocol/sdk/client/index'; +import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory'; +import type { INestApplication } from '@nestjs/common'; +import type { PlaceHistoryPageResponse } from '@trek/shared'; + +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const LIBRARY = '/api/addons/collections/library/places'; + +let app: INestApplication; +let orm: MikroORM; +let f: LibraryFixture; + +const http = () => request(app.getHttpServer()); + +async function history(userId: number, kind: 'trip' | 'list', id: number, query: Record = {}) { + return http().get(`${LIBRARY}/${kind}/${id}/history`).query(query).set('Cookie', sessionCookie(userId)); +} + +async function changes(userId: number, kind: 'trip' | 'list', id: number): Promise { + const res = await history(userId, kind, id); + expect(res.status).toBe(200); + return res.body as PlaceHistoryPageResponse; +} + +const fieldsOf = (page: PlaceHistoryPageResponse) => page.entries.map((entry) => entry.field); + +async function editTripPlace(userId: number, tripId: number, placeId: number, body: object) { + const res = await http() + .put(`/api/trips/${tripId}/places/${placeId}`) + .set('Cookie', sessionCookie(userId)) + .send(body); + expect(res.status).toBe(200); +} + +async function editSavedPlace(userId: number, savedId: number, body: object) { + const res = await http() + .patch(`/api/addons/collections/places/${savedId}`) + .set('Cookie', sessionCookie(userId)) + .send(body); + expect(res.status).toBe(200); +} + +/** One tool call through a real MCP session as `userId`: its JSON answer, or its error text. */ +async function callTool(userId: number, name: string, args: Record) { + const server = createLocalMcpServer('TREK place history e2e'); + const around = (_info: unknown, call: () => unknown): unknown => withRequestContext(orm, call); + await withRequestContext(orm, () => + app + .get(McpRegistryService) + .attach(server, { userId, scopes: null, isStaticToken: false }, { include: (kind) => kind === 'tool', around }), + ); + const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair(); + const client = new Client({ name: 'place-history-e2e', version: '1.0.0' }); + await server.connect(serverTransport); + await client.connect(clientTransport); + try { + const result = await client.callTool({ name, arguments: args }); + const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : []; + const text = content[0]?.text ?? ''; + return result.isError === true + ? { error: text, answer: null } + : { error: null, answer: JSON.parse(text) as unknown }; + } finally { + await client.close(); + await server.close(); + } +} + +beforeAll(async () => { + app = await buildApp(); + orm = app.get(MikroORM); + await setAddonEnabled(orm, 'collections', true); +}, 60_000); + +beforeEach(async () => { + await resetRateLimits(app); + f = await seedLibrary(orm); +}); + +afterAll(async () => { + await app?.close(); +}); + +describe('the history of a place', () => { + it('PHIST-E2E-001: records each changed field of a trip place with who changed it, newest first', async () => { + await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { + name: 'Café Central Wien', + address: 'Herrengasse 14, 1010 Wien', + // Unchanged: no row for it. + description: 'A coffee house', + }); + const page = await changes(f.me.id, 'trip', f.places.cafe.id); + expect(page.next_cursor).toBeNull(); + expect(page.entries).toEqual([ + expect.objectContaining({ + field: 'address', + old_value: 'Herrengasse 14, Wien', + new_value: 'Herrengasse 14, 1010 Wien', + automatic: false, + editor: expect.objectContaining({ id: f.me.id }), + origin: { kind: 'trip', trip_id: f.alps.id, trip_title: 'Alps', place_id: f.places.cafe.id }, + }), + expect.objectContaining({ field: 'name', old_value: 'Café Central', new_value: 'Café Central Wien' }), + ]); + expect(page.entries[0]?.changed_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/); + }); + + it('PHIST-E2E-002: one entry reads the changes of all its origins, the list ones with their list', async () => { + await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { phone: '+43 1 533' }); + await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'Try the strudel' }); + const status = await http() + .post(`/api/addons/collections/places/${f.saved.savedCafe.id}/status`) + .set('Cookie', sessionCookie(f.me.id)) + .send({ status: 'visited' }); + expect(status.status).toBe(200); + + const fromTrip = await changes(f.me.id, 'trip', f.places.cafe.id); + expect(fieldsOf(fromTrip)).toEqual(['status', 'notes', 'phone']); + expect(fromTrip.entries[0]).toEqual( + expect.objectContaining({ + old_value: 'want', + new_value: 'visited', + origin: { + kind: 'list', + collection_id: f.lists.food.id, + collection_name: 'Food', + collection_place_id: f.saved.savedCafe.id, + }, + }), + ); + // Opened from the saved place, the same entry reads the same history. + expect(await changes(f.me.id, 'list', f.saved.savedCafe.id)).toEqual(fromTrip); + }); + + it('PHIST-E2E-003: shows only the changes of the origins the reader reaches, and none after access ends', async () => { + await addCollectionMember(orm, f.lists.food.id, f.friend.id, { role: 'viewer' }); + await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { notes: 'Window seat' }); + await editSavedPlace(f.me.id, f.saved.savedCafe.id, { description: 'Viennese coffee house' }); + + // The friend reaches the list but not the trip: the trip's change is not there, nor counted anywhere. + const friendPage = await changes(f.friend.id, 'list', f.saved.savedCafe.id); + expect(fieldsOf(friendPage)).toEqual(['description']); + expect(friendPage.next_cursor).toBeNull(); + expect(JSON.stringify(friendPage)).not.toContain('Window seat'); + expect((await history(f.friend.id, 'trip', f.places.cafe.id)).status).toBe(404); + + // The stranger reaches neither; their own list's copy has a history of its own. + expect((await history(f.stranger.id, 'list', f.saved.savedCafe.id)).status).toBe(404); + await editSavedPlace(f.stranger.id, f.saved.secret.id, { notes: 'Secret note' }); + expect(JSON.stringify(await changes(f.me.id, 'trip', f.places.cafe.id))).not.toContain('Secret note'); + + await deleteRows(orm, CollectionMembers, { collection: f.lists.food.id, user: f.friend.id }); + expect((await history(f.friend.id, 'list', f.saved.savedCafe.id)).status).toBe(404); + }); + + it('PHIST-E2E-004: a cleared value takes the earlier changes of its field along, and is no change itself', async () => { + await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'First' }); + await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'Second', address: 'Herrengasse 14' }); + expect(fieldsOf(await changes(f.me.id, 'list', f.saved.savedCafe.id))).toEqual(['notes', 'address', 'notes']); + + await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: null }); + const page = await changes(f.me.id, 'list', f.saved.savedCafe.id); + expect(fieldsOf(page)).toEqual(['address']); + expect(JSON.stringify(page)).not.toContain('First'); + expect(JSON.stringify(page)).not.toContain('Try the cake'); + + // A trip place's text cleared to empty counts as cleared too. + await editTripPlace(f.me.id, f.alps.id, f.places.museum.id, { address: 'Museumstraße 15' }); + await editTripPlace(f.me.id, f.alps.id, f.places.museum.id, { address: '' }); + expect((await changes(f.me.id, 'trip', f.places.museum.id)).entries).toEqual([]); + }); + + it('PHIST-E2E-005: pages newest first by its cursor and refuses a cursor it never gave', async () => { + await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://a.example' }); + await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://b.example' }); + await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://c.example' }); + + const first = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '2' }); + expect(first.status).toBe(200); + const one = first.body as PlaceHistoryPageResponse; + expect(one.entries.map((entry) => entry.new_value)).toEqual(['https://c.example', 'https://b.example']); + expect(one.next_cursor).not.toBeNull(); + + const second = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '2', cursor: one.next_cursor ?? '' }); + const two = second.body as PlaceHistoryPageResponse; + expect(two.entries.map((entry) => entry.new_value)).toEqual(['https://a.example']); + expect(two.next_cursor).toBeNull(); + + expect((await history(f.me.id, 'trip', f.places.cafe.id, { cursor: 'abc' })).status).toBe(400); + }); + + it('PHIST-E2E-006: a deleted place takes its history along', async () => { + await editTripPlace(f.me.id, f.alps.id, f.places.museum.id, { name: 'Landesmuseum' }); + expect(await countRows(orm, PlaceChangeLog, { place: f.places.museum.id })).toBe(1); + await deleteRows(orm, Places, { id: f.places.museum.id }); + expect(await countRows(orm, PlaceChangeLog, { place: f.places.museum.id })).toBe(0); + }); + + it('PHIST-E2E-007: the MCP tools write and read the same history with the same reach', async () => { + const updated = await callTool(f.me.id, 'update_place', { + tripId: f.alps.id, + placeId: f.places.cafe.id, + address: 'Herrengasse 14, 1010 Wien', + }); + expect(updated.error).toBeNull(); + + const read = await callTool(f.me.id, 'get_library_place_history', { kind: 'trip', id: f.places.cafe.id }); + expect(read.error).toBeNull(); + const page = read.answer as PlaceHistoryPageResponse; + expect(page.entries).toEqual([ + expect.objectContaining({ field: 'address', editor: expect.objectContaining({ id: f.me.id }) }), + ]); + + const refused = await callTool(f.friend.id, 'get_library_place_history', { kind: 'trip', id: f.places.cafe.id }); + expect(refused.answer).toBeNull(); + expect(refused.error).toMatch(/not found/i); + }); +}); diff --git a/server/tests/e2e/place-tags.e2e.test.ts b/server/tests/e2e/place-tags.e2e.test.ts new file mode 100644 index 000000000..3222c6dbe --- /dev/null +++ b/server/tests/e2e/place-tags.e2e.test.ts @@ -0,0 +1,201 @@ +/** + * Personal tags on "All places" (PLC-21) through the real AddonGuard and + * JwtAuthGuard against a migrated and seeded temp SQLite db, every answer + * checked against its response contract: tagging one entry and several, the + * tag filter in the query string, and sharing chosen personal tags with a trip + * when a saved place is copied into it. + */ +import { Places } from '../../src/db/entities/Places.entity'; +import { Tags } from '../../src/db/entities/Tags.entity'; +import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; +import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe'; +import { PlacesLibraryModule } from '../../src/nest/places-library/places-library.module'; +import { RealtimeModule } from '../../src/nest/realtime/realtime.module'; +import { RealtimeService } from '../../src/nest/realtime/realtime.service'; +import { createSnapshotTestDb } from '../helpers/db-mock'; +import { makeTag } from '../helpers/factories/places'; +import { findRow, findRows } from '../helpers/factories/rows'; +import { setAddonEnabled } from '../helpers/factories/settings'; +import { FakeRealtimeService } from '../helpers/fake-realtime'; +import { oneByOne } from '../helpers/one-by-one'; +import { seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture'; +import { resetTestDb } from '../helpers/test-db'; +import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm'; +import { TestUnitOfWorkModule } from '../helpers/test-uow'; +import { sessionCookie } from './harness'; +import type { INestApplication } from '@nestjs/common'; +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, vi } from 'vitest'; + +vi.mock('../../src/nest/audit/audit-log.logger', () => ({ + LOG_LEVEL: 'error', + logInfo: vi.fn(), + logDebug: vi.fn(), + logError: vi.fn(), + logWarn: vi.fn(), +})); + +const db = createSnapshotTestDb(); +const LIBRARY = '/api/addons/collections/library/places'; +const TAGS = `${LIBRARY}/tags`; + +let app: INestApplication; +let server: Server; +let orm: TestOrm; +let f: LibraryFixture; +let wine: number; +let view: number; + +const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); +const keysOf = (body: { entries: { key: string }[] }) => body.entries.map((entry) => entry.key); + +beforeAll(async () => { + const moduleRef = await Test.createTestingModule({ + imports: [ + await TestUnitOfWorkModule.forRoot(db), + await createTestMikroOrmModule(db), + RealtimeModule, + PlacesLibraryModule, + ], + }) + .overrideProvider(RealtimeService) + .useValue(new FakeRealtimeService()) + .compile(); + app = moduleRef.createNestApplication(); + app.use(cookieParser()); + app.useGlobalPipes(new ZodValidationPipe()); + app.useGlobalFilters(new TrekExceptionFilter()); + await app.init(); + server = app.getHttpServer() as Server; + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + f = await seedLibrary(orm); + await setAddonEnabled(orm, 'collections', true); + wine = (await makeTag(orm, f.me.id, { name: 'Wine', color: '#aa0000' })).id; + view = (await makeTag(orm, f.me.id, { name: 'View', color: '#00aa00' })).id; +}); +afterAll(async () => { + await app.close(); + await orm.close(); + db.close(); +}); + +describe('Personal place tags e2e (real guards + temp SQLite)', () => { + it('answers 404 while Collections is off, before any sign-in check, and 401 without a session', async () => { + await setAddonEnabled(orm, 'collections', false); + expect((await request(server).put(TAGS).send({ key: 'trip:1', tag_ids: [] })).status).toBe(404); + await setAddonEnabled(orm, 'collections', true); + expect((await request(server).put(TAGS).send({ key: 'trip:1', tag_ids: [] })).status).toBe(401); + expect( + ( + await request(server) + .post(`${TAGS}/bulk`) + .send({ keys: ['trip:1'], add: [1] }) + ).status, + ).toBe(401); + }); + + it('tags one entry and several, and filters the list by the tags in the query string', async () => { + const cafe = `trip:${f.places.cafe.id}`; + const pantheon = `list:${f.saved.pantheon.id}`; + const set = await request(server) + .put(TAGS) + .set(as(f.me.id)) + .send({ key: cafe, tag_ids: [wine] }); + expect(set.status).toBe(200); + expect(set.body.entry.tags).toEqual([{ id: wine, name: 'Wine', color: '#aa0000' }]); + + const bulk = await request(server) + .post(`${TAGS}/bulk`) + .set(as(f.me.id)) + .send({ keys: [pantheon, cafe], add: [view] }); + expect(bulk.status).toBe(200); + expect(keysOf(bulk.body)).toEqual([pantheon, cafe]); + expect(bulk.body.entries[1].tags.map((tag: { name: string }) => tag.name)).toEqual(['View', 'Wine']); + + const filtered = await request(server) + .get(LIBRARY) + .query({ tag_ids: String(wine) }) + .set(as(f.me.id)); + expect(filtered.status).toBe(200); + expect(keysOf(filtered.body)).toEqual([cafe]); + expect(filtered.body.counts).toEqual({ all: 1, trip: 1, list: 1 }); + const both = await request(server) + .get(LIBRARY) + .query({ tag_ids: `${wine},${view}` }) + .set(as(f.me.id)); + expect(both.body.total).toBe(2); + const detail = await request(server).get(`${LIBRARY}/list/${f.saved.pantheon.id}`).set(as(f.me.id)); + expect(detail.body.entry.tags).toEqual([{ id: view, name: 'View', color: '#00aa00' }]); + const friends = await request(server) + .get(LIBRARY) + .query({ tag_ids: String(wine) }) + .set(as(f.friend.id)); + expect(friends.body.total).toBe(0); + }); + + it('refuses malformed bodies and filters, foreign tags and entries out of reach', async () => { + const theirs = (await makeTag(orm, f.friend.id, { name: 'Theirs' })).id; + const bad = await oneByOne( + [ + { key: 'trip:abc', tag_ids: [] }, + { key: 'trip:1', tag_ids: [1.5] }, + { key: 'trip:1', tag_ids: [], extra: true }, + ], + (body) => request(server).put(TAGS).set(as(f.me.id)).send(body), + ); + expect(bad.map((res) => res.status)).toEqual([400, 400, 400]); + const badBulk = await oneByOne( + [{ keys: ['trip:1'] }, { keys: [], add: [1] }, { keys: ['trip:1'], add: [1], remove: [1] }], + (body) => request(server).post(`${TAGS}/bulk`).set(as(f.me.id)).send(body), + ); + expect(badBulk.map((res) => res.status)).toEqual([400, 400, 400]); + const badQuery = await oneByOne(['0x5', '1,,2', '1.5', ''], (tagIds) => + request(server).get(LIBRARY).query({ tag_ids: tagIds }).set(as(f.me.id)), + ); + expect(badQuery.map((res) => res.status)).toEqual([400, 400, 400, 400]); + + const foreign = await request(server) + .put(TAGS) + .set(as(f.me.id)) + .send({ key: `trip:${f.places.cafe.id}`, tag_ids: [theirs] }); + expect(foreign.status).toBe(404); + expect(foreign.body).toEqual({ error: 'Tag not found' }); + const hidden = await request(server) + .post(`${TAGS}/bulk`) + .set(as(f.me.id)) + .send({ keys: [`list:${f.saved.secret.id}`], add: [wine] }); + expect(hidden.status).toBe(404); + expect(hidden.body).toEqual({ error: 'Place not found' }); + }); + + it('shares only the chosen personal tags with a trip when a saved place is copied into it', async () => { + await makeTag(orm, f.me.id, { name: 'wine', trip: f.alps.id, color: '#111111' }); + const res = await request(server) + .post('/api/addons/collections/copy-to-trip') + .set(as(f.me.id)) + .send({ trip_id: f.alps.id, place_ids: [f.saved.pantheon.id], personal_tag_ids: [wine, view, 999999] }); + expect(res.status).toBe(200); + const placeId = res.body.created[0].id as number; + expect(await findRow(orm, Places, { id: placeId })).not.toBeNull(); + const tripTags = await findRows(orm, Tags, { trip: f.alps.id }, { name: 'asc' }); + // The trip's own "wine" is reused, whatever its case; "View" becomes a new trip tag. + expect(tripTags.map((tag) => tag.name)).toEqual(['View', 'wine']); + const personal = await findRows(orm, Tags, { user: f.me.id, trip: null }); + expect(personal.map((tag) => tag.id).sort((a, b) => a - b)).toEqual([wine, view].sort((a, b) => a - b)); + + const none = await request(server) + .post('/api/addons/collections/copy-to-trip') + .set(as(f.me.id)) + .send({ trip_id: f.alps.id, place_ids: [f.saved.lunch.id], force: true }); + expect(none.status).toBe(200); + expect(await findRows(orm, Tags, { trip: f.alps.id })).toHaveLength(2); + }); +}); diff --git a/server/tests/e2e/place-visits.e2e.test.ts b/server/tests/e2e/place-visits.e2e.test.ts new file mode 100644 index 000000000..00de0bef2 --- /dev/null +++ b/server/tests/e2e/place-visits.e2e.test.ts @@ -0,0 +1,183 @@ +/** + * Visits read from the trips (D7/PLC-10 to PLC-23) through the real + * JwtAuthGuard, TripAccessGuard and AddonGuard against a migrated and seeded + * temp SQLite db, the visit clock pinned on the second day of the fixture's + * trip Alps: the history and the counts on All places, the trip's visited + * places, the list, the stop's participants, losing access, the refused + * queries, that nothing can be written, and the media of an entry. + */ +import { AssignmentParticipants } from '../../src/db/entities/AssignmentParticipants.entity'; +import { DayAssignments } from '../../src/db/entities/DayAssignments.entity'; +import { TripMembers } from '../../src/db/entities/TripMembers.entity'; +import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter'; +import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe'; +import { PlaceVisitsClock } from '../../src/nest/places-library/place-visits.clock'; +import { PlaceVisitsModule } from '../../src/nest/places-library/place-visits.module'; +import { RealtimeModule } from '../../src/nest/realtime/realtime.module'; +import { RealtimeService } from '../../src/nest/realtime/realtime.service'; +import { createSnapshotTestDb } from '../helpers/db-mock'; +import { makeDayAssignment } from '../helpers/factories/itinerary'; +import { createRow, deleteRows, findRow } from '../helpers/factories/rows'; +import { setAddonEnabled } from '../helpers/factories/settings'; +import { addTripMember, makeDay, readTripDays } from '../helpers/factories/trips'; +import { FakeRealtimeService } from '../helpers/fake-realtime'; +import { oneByOne } from '../helpers/one-by-one'; +import { seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture'; +import { resetTestDb } from '../helpers/test-db'; +import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm'; +import { TestUnitOfWorkModule } from '../helpers/test-uow'; +import { sessionCookie } from './harness'; +import type { INestApplication } from '@nestjs/common'; +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, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +const realtime = new FakeRealtimeService(); + +let app: INestApplication; +let server: Server; +let orm: TestOrm; +let f: LibraryFixture; + +const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); +const VISITS = '/api/place-visits'; +const LIBRARY = '/api/addons/collections/library/places'; +const TODAY = '2026-07-02'; + +beforeAll(async () => { + const moduleRef = await Test.createTestingModule({ + imports: [ + await TestUnitOfWorkModule.forRoot(db), + await createTestMikroOrmModule(db), + RealtimeModule, + PlaceVisitsModule, + ], + }) + .overrideProvider(RealtimeService) + .useValue(realtime) + .compile(); + app = moduleRef.createNestApplication(); + app.use(cookieParser()); + app.useGlobalPipes(new ZodValidationPipe()); + app.useGlobalFilters(new TrekExceptionFilter()); + await app.init(); + server = app.getHttpServer() as Server; + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + realtime.reset(); + vi.restoreAllMocks(); + vi.spyOn(app.get(PlaceVisitsClock), 'today').mockReturnValue(TODAY); + f = await seedLibrary(orm); + await setAddonEnabled(orm, 'collections', true); +}); +afterAll(async () => { + await app.close(); + await orm.close(); + db.close(); +}); + +async function entryOf(userId: number, key: string) { + const res = await request(server).get(LIBRARY).set(as(userId)); + expect(res.status).toBe(200); + return res.body.entries.find((row: { key: string }) => row.key === key); +} + +describe('Place visits e2e (real guards + temp SQLite)', () => { + it('answers 401 without a session and refuses queries it does not take', async () => { + expect((await request(server).get(VISITS)).status).toBe(401); + expect((await request(server).get(`/api/trips/${f.alps.id}/place-visits/mine`)).status).toBe(401); + const refused = await oneByOne( + [{ kind: 'own', id: '1' }, { kind: 'trip', id: '0x5' }, { kind: 'trip' }, { kind: 'trip', id: '1', extra: '1' }], + (query) => request(server).get(`${VISITS}/place`).query(query).set(as(f.me.id)), + ); + expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400]); + const list = await oneByOne([{ limit: '0' }, { limit: '201' }, { trip_id: 'abc' }], (query) => + request(server).get(VISITS).query(query).set(as(f.me.id)), + ); + expect(list.map((res) => res.status)).toEqual([400, 400, 400]); + }); + + it('has nothing to write: confirming, correcting and deleting a visit are gone', async () => { + const tries = await oneByOne( + [ + () => + request(server).post(VISITS).set(as(f.me.id)).send({ visited_on: '2026-07-01', place_id: f.places.cafe.id }), + () => request(server).patch(`${VISITS}/1`).set(as(f.me.id)).send({ note: 'x' }), + () => request(server).delete(`${VISITS}/1`).set(as(f.me.id)), + () => request(server).get(`${VISITS}/candidates`).set(as(f.me.id)), + () => request(server).get(`/api/trips/${f.alps.id}/place-visits/suggestions`).set(as(f.me.id)), + ], + (call) => call(), + ); + expect(tries.map((res) => res.status)).toEqual([404, 404, 404, 404, 404]); + }); + + it('reads the history and the counts of All places from the dated days that have come', async () => { + const [, day2, day3] = await readTripDays(orm, f.alps.id); + if (!day2 || !day3) throw new Error('Alps has three days'); + await makeDayAssignment(orm, day2.id, f.places.cafe.id, { assignment_time: '12:00' }); + await makeDayAssignment(orm, day2.id, f.places.cafe.id, { assignment_time: '10:00' }); + await makeDayAssignment(orm, day3.id, f.places.cafe.id); + const undated = await makeDay(orm, f.alps.id, { date: null }); + await makeDayAssignment(orm, undated.id, f.places.museum.id); + + const history = await request(server) + .get(`${VISITS}/place`) + .query({ kind: 'list', id: f.saved.savedCafe.id }) + .set(as(f.me.id)); + expect(history.status).toBe(200); + expect(history.body).toMatchObject({ visit_count: 2, last_visit: TODAY }); + expect( + history.body.visits.map((v: { visited_on: string; visited_time: string }) => [v.visited_on, v.visited_time]), + ).toEqual([ + [TODAY, '10:00'], + ['2026-07-01', '09:00'], + ]); + expect(await entryOf(f.me.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 2, last_visit: TODAY }); + expect(await entryOf(f.me.id, `trip:${f.places.museum.id}`)).toMatchObject({ visit_count: 0, last_visit: null }); + + const mine = await request(server).get(`/api/trips/${f.alps.id}/place-visits/mine`).set(as(f.me.id)); + expect(mine.body).toEqual({ + place_ids: [f.places.cafe.id], + places: [{ place_id: f.places.cafe.id, visit_count: 2, last_visit: TODAY }], + }); + const list = await request(server).get(VISITS).query({ limit: '1' }).set(as(f.me.id)); + expect(list.body).toMatchObject({ total: 2, visits: [{ visited_on: TODAY, trip: { id: f.alps.id } }] }); + }); + + it('counts a stop for its participants only, and nothing once the trip is out of reach', async () => { + await addTripMember(orm, f.alps.id, f.friend.id); + await createRow(orm, AssignmentParticipants, { assignment: (await firstCafeStop()).id, user: f.friend.id }); + expect(await entryOf(f.me.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 0 }); + expect(await entryOf(f.friend.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 1 }); + + await deleteRows(orm, TripMembers, { trip: f.alps.id, user: f.friend.id }); + expect((await request(server).get(VISITS).set(as(f.friend.id))).body).toEqual({ visits: [], total: 0 }); + expect((await request(server).get(`/api/trips/${f.alps.id}/place-visits/mine`).set(as(f.friend.id))).status).toBe( + 404, + ); + }); + + it('reads the media of an entry behind the Collections addon; the visits are no addon’s', async () => { + const media = await request(server).get(`${LIBRARY}/trip/${f.places.cafe.id}/media`).set(as(f.me.id)); + expect(media.status).toBe(200); + expect(media.body).toEqual({ images: [], journey_photos: [], files: [] }); + await setAddonEnabled(orm, 'collections', false); + expect((await request(server).get(`${LIBRARY}/trip/${f.places.cafe.id}/media`).set(as(f.me.id))).status).toBe(404); + expect((await request(server).get(VISITS).set(as(f.me.id))).status).toBe(200); + }); +}); + +/** The stop that plans Café Central on the first day of Alps in the fixture. */ +async function firstCafeStop() { + const stop = await findRow(orm, DayAssignments, { day: f.day1.id, place: f.places.cafe.id }); + if (!stop) throw new Error('the fixture plans Café Central on day 1'); + return stop; +} diff --git a/server/tests/helpers/factories/place-activities.ts b/server/tests/helpers/factories/place-activities.ts new file mode 100644 index 000000000..2d77dfdea --- /dev/null +++ b/server/tests/helpers/factories/place-activities.ts @@ -0,0 +1,46 @@ +/** + * PLC-18: the bookings and tours a place names, and the tours a list keeps + * for a saved place to name, seeded through the ORM like the app writes them. + */ +import { CollectionTours } from '../../../src/db/entities/CollectionTours.entity'; +import { PlaceActivityLinks } from '../../../src/db/entities/PlaceActivityLinks.entity'; +import type { FactoryOrm } from './context'; +import { createRow } from './rows'; +import type { EntityDTO, EntityData } from '@mikro-orm/core'; + +export type KeptTourRow = EntityDTO; +export type PlaceActivityLinkRow = EntityDTO; + +/** A hike kept in the list `collectionId`, with no line and no points. */ +export function makeKeptTour( + orm: FactoryOrm, + collectionId: number, + overrides: EntityData = {}, +): Promise { + return createRow( + orm, + CollectionTours, + { + collection: collectionId, + name: 'Kept ridge', + waypoints: '[]', + tourTypeRef: 'hike', + origin: 'trek', + source_trip_title: 'Alps', + source_tour_name: 'Ridge', + }, + overrides, + ); +} + +/** A link of a trip place to a booking or a tour (its place), or of a saved place to a kept tour. */ +export function linkPlaceActivity( + orm: FactoryOrm, + link: + | { place: number; reservation: number } + | { place: number; tourPlace: number } + | { collectionPlace: number; collectionTour: number }, + linkedBy: number | null = null, +): Promise { + return createRow(orm, PlaceActivityLinks, { ...link, linkedByRef: linkedBy }); +} diff --git a/server/tests/helpers/maps-service.ts b/server/tests/helpers/maps-service.ts index 499567ae4..a07ddc5a7 100644 --- a/server/tests/helpers/maps-service.ts +++ b/server/tests/helpers/maps-service.ts @@ -15,6 +15,7 @@ import { WikimediaClient } from '../../src/nest/maps/providers/wikimedia.client' import type { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-cache.service'; import { noGoogleQuota } from './google-quota'; import { photonOff } from './photon'; +import { passThroughPlaceChanges } from './place-changes'; /** MapsService and the outbound clients it was wired with, for tests that reach a client directly. */ export interface MapsParts { @@ -43,7 +44,7 @@ export function buildMapsParts( const osm = new OsmClient(photonOff()); const wiki = new WikimediaClient(); const selector = new PlacesProviderSelector(appSettings, users, googleQuota); - const photos = new PlacePhotoResolver(photoCache, places, google, wiki, selector); + const photos = new PlacePhotoResolver(photoCache, places, google, wiki, selector, passThroughPlaceChanges()); const links = new MapsUrlResolver(osm); const details = new PlaceDetailsResolver(placeDetailsCache, google, osm, selector); const along = new PoisAlongResolver(osm); diff --git a/server/tests/helpers/place-activities-fixture.ts b/server/tests/helpers/place-activities-fixture.ts new file mode 100644 index 000000000..57236f3dc --- /dev/null +++ b/server/tests/helpers/place-activities-fixture.ts @@ -0,0 +1,52 @@ +/** + * The bookings and tours the place activity suites (PLC-18) read, on top of + * the All places fixture (`seedLibrary`): in Alps, a guided tour booking on + * no place and a dinner booked against Café Central's plan entry; a lake + * cabin booking against the stay at Camp Lake; the tour Ridge walk with a + * station standing for Museum, and a second tour, Old town walk, on no place. + * Food keeps two tours. Hotel Sonne's own booking names the place already. + */ +import { DayAccommodations } from '../../src/db/entities/DayAccommodations.entity'; +import { DayAssignments } from '../../src/db/entities/DayAssignments.entity'; +import type { FactoryOrm } from './factories/context'; +import { makeKeptTour } from './factories/place-activities'; +import { makePlace } from './factories/places'; +import { makeReservation } from './factories/reservations'; +import { findRow } from './factories/rows'; +import { addTourWaypoints, makeTour } from './factories/tours'; +import { seedLibrary } from './places-library-fixture'; + +export async function seedPlaceActivities(orm: FactoryOrm) { + const f = await seedLibrary(orm); + const { alps, places, lists, day1 } = f; + const guided = await makeReservation(orm, alps.id, { + title: 'Guided tour', + type: 'tour', + status: 'confirmed', + reservation_time: '2026-07-01T10:00', + day: day1.id, + }); + const plan = await findRow(orm, DayAssignments, { place: places.cafe.id }); + if (!plan) throw new Error('seedPlaceActivities: Café Central has no plan entry'); + const dinner = await makeReservation(orm, alps.id, { title: 'Dinner', type: 'restaurant', assignment: plan.id }); + const stay = await findRow(orm, DayAccommodations, { place: places.camp.id }); + if (!stay) throw new Error('seedPlaceActivities: Camp Lake has no stay'); + const cabin = await makeReservation(orm, alps.id, { + title: 'Lake cabin', + type: 'hotel', + accommodation_id: `${stay.id}.0`, + }); + await addTourWaypoints(orm, places.ridge.id, [ + { lat: 47.26, lng: 11.39 }, + { lat: 47.2681, lng: 11.3933, linkedPlace: places.museum.id }, + { lat: 47.27, lng: 11.4 }, + ]); + const walk = await makePlace(orm, alps.id, { name: 'Old town walk' }); + await makeTour(orm, walk.id, { tourTypeRef: 'walk' }); + const keptRidge = await makeKeptTour(orm, lists.food.id, { name: 'Kept ridge' }); + const keptLake = await makeKeptTour(orm, lists.food.id, { name: 'Kept lake loop' }); + const keptRome = await makeKeptTour(orm, lists.sights.id, { name: 'Rome by night' }); + return { ...f, bookings: { guided, dinner, cabin }, tours: { walk }, kept: { keptRidge, keptLake, keptRome } }; +} + +export type PlaceActivitiesFixture = Awaited>; diff --git a/server/tests/helpers/place-changes.ts b/server/tests/helpers/place-changes.ts new file mode 100644 index 000000000..0c9697a85 --- /dev/null +++ b/server/tests/helpers/place-changes.ts @@ -0,0 +1,13 @@ +import type { PlaceChangesService } from '../../src/nest/place-changes/place-changes.service'; + +/** + * A PlaceChangesService for the suites that build a places or collections + * service by hand and are about something else: it runs every write and + * records no history. The history itself is tested in + * tests/unit/nest/place-changes/ and tests/e2e/place-history.e2e.test.ts. + */ +export function passThroughPlaceChanges(): PlaceChangesService { + return { + track: (_targets: unknown, _editor: unknown, write: () => Promise) => write(), + } as unknown as PlaceChangesService; +} diff --git a/server/tests/helpers/plugin-host.ts b/server/tests/helpers/plugin-host.ts index d240b26dc..bbcb0eff4 100644 --- a/server/tests/helpers/plugin-host.ts +++ b/server/tests/helpers/plugin-host.ts @@ -134,6 +134,7 @@ import { createTestPackingTemplateCategoriesRepo, createTestPackingTemplateItemsRepo, } from './packing-repos'; +import { passThroughPlaceChanges } from './place-changes'; import { buildPlaceImportService } from './place-import'; import { createTestVacayHolidayCalendarsRepo, createTestSchoolHolidayRegionsRepo } from './school-holidays-repos'; import { createTestShareTokensRepo, createTestPluginsRepo, createTestPluginUserErasureQueueRepo } from './share-repos'; @@ -465,6 +466,7 @@ export async function createPluginRpcHostParts( await createTestBudgetItemsRepo(db), { releaseValues: async () => [] } as never, // StorageReleaseService buildPlaceImportService(), + passThroughPlaceChanges(), ); // After places: copying saved places into a trip runs the places journey hook. const collections = new CollectionsService( @@ -494,6 +496,7 @@ export async function createPluginRpcHostParts( usersRepo, buildPlaceImportService(), places, + passThroughPlaceChanges(), ); // After accommodations: a hotel booking writes the stay's day stop through it. const reservations = new ReservationsService( @@ -576,7 +579,7 @@ export async function createPluginRpcHostParts( const guards = new PluginGuards(await createTestTripsRepo(db), permissions, addons, usersRepo); const controllers: object[] = [ - new TagsRpc(new TagsService(await createTestTagsRepo(db))), + new TagsRpc(new TagsService(await createTestTagsRepo(db), await createTestUnitOfWork(db))), new CategoriesRpc(new CategoriesService(await createTestCategoriesRepo(db))), new WeatherRpc(new WeatherService()), new ExchangeRatesRpc(exchangeRates), diff --git a/server/tests/integration/broadcast-parity/plan.cases.ts b/server/tests/integration/broadcast-parity/plan.cases.ts index d3bf7daed..525c0f881 100644 --- a/server/tests/integration/broadcast-parity/plan.cases.ts +++ b/server/tests/integration/broadcast-parity/plan.cases.ts @@ -5,6 +5,7 @@ import type { ListImportResult } from '../../../src/nest/places/places.helpers'; import { PlacesService } from '../../../src/nest/places/places.service'; import { StorageService } from '../../../src/nest/storage/storage.service'; import { makeDayAssignment } from '../../helpers/factories/itinerary'; +import { linkPlaceActivity } from '../../helpers/factories/place-activities'; import { makeTag } from '../../helpers/factories/places'; import { insertRow, updateRows } from '../../helpers/factories/rows'; import { linkTripCollection } from '../../helpers/factories/user-places'; @@ -403,6 +404,31 @@ export const plan: CaseGroup = { rest: { method: 'delete', path: (s) => `/api/trips/${s.trip.id}/collections/${s.collection.id}` }, expect: ['tripCollections:changed'], }, + { + // PLC-18: the members' place detail reads the place's activities again. + tool: 'link_place_activity', + needs: ['place', 'transport'], + args: (s) => ({ tripId: s.trip.id, placeId: s.place.id, reservation_id: s.transport.id }), + rest: { + method: 'post', + path: (s) => `/api/trips/${s.trip.id}/places/${s.place.id}/activities`, + body: (s) => ({ reservation_id: s.transport.id }), + }, + expect: ['placeActivities:changed'], + }, + { + tool: 'unlink_place_activity', + needs: ['place', 'tour'], + setup: async (s, app) => { + await linkPlaceActivity(app.get(MikroORM), { place: s.place.id, tourPlace: s.tourPlace.id }); + }, + args: (s) => ({ tripId: s.trip.id, placeId: s.place.id, tour_id: s.tourPlace.id }), + rest: { + method: 'delete', + path: (s) => `/api/trips/${s.trip.id}/places/${s.place.id}/activities/tours/${s.tourPlace.id}`, + }, + expect: ['placeActivities:changed'], + }, { tool: 'create_day_note', args: (s) => ({ tripId: s.trip.id, dayId: s.days[0].id, text: 'Bring the museum pass' }), diff --git a/server/tests/integration/broadcast-parity/user.cases.ts b/server/tests/integration/broadcast-parity/user.cases.ts index b83b2aa77..a1dfcab15 100644 --- a/server/tests/integration/broadcast-parity/user.cases.ts +++ b/server/tests/integration/broadcast-parity/user.cases.ts @@ -19,6 +19,8 @@ import { PlaceIdentitiesService } from '../../../src/nest/places-library/place-i import { addCollectionMember } from '../../helpers/factories/collections'; import { inContext } from '../../helpers/factories/context'; import { addJourneyContributor, linkTripToJourney, makeJourneyEntry } from '../../helpers/factories/journeys'; +import { linkPlaceActivity, makeKeptTour } from '../../helpers/factories/place-activities'; +import { makeTag } from '../../helpers/factories/places'; import { createRow, insertRow, updateRows } from '../../helpers/factories/rows'; import { linkUserPlace, makeUserPlace } from '../../helpers/factories/user-places'; import { addVacayPlanMember } from '../../helpers/factories/vacay'; @@ -56,6 +58,13 @@ async function mergedPlaces(s: Scene, app: INestApplication): Promise { ); keep(s, 'merge', merged.merge_id); } +const PERSONAL_TAGS = + "puts the caller's own personal tags on entries of All places (PLC-21): no trip place or saved place is written and nobody else sees them, so there is nothing to send"; + +/** A personal tag of the owner, for tagging the scene's places. */ +async function personalTag(s: Scene, app: INestApplication): Promise { + keep(s, 'tag', (await makeTag(ormOf(app), s.owner.id, { name: `Personal ${s.n}` })).id); +} const TOKEN_ONLY = 'manages a public link token: nothing on any screen follows it live, so there is nothing to send'; const onJourney = (s: Scene) => ({ journeyId: s.journey.id }); const WINTER = { name: 'Winter', startDate: '2027-02-01', endDate: '2027-02-12' }; @@ -1068,6 +1077,36 @@ const collectionCases: ParityCase[] = [ { event: 'collections:removed', user: 'actor' }, ], }, + { + // PLC-18: the list's members read the saved place's kept tours again. + tool: 'link_saved_place_tour', + needs: ['collection'], + setup: async (s, app) => { + keep(s, 'keptTour', (await makeKeptTour(ormOf(app), s.collection.id, { name: `Kept ridge ${s.n}` })).id); + }, + args: (s) => ({ collection_place_id: s.collectionPlace.id, collection_tour_id: kept(s, 'keptTour') }), + rest: { + method: 'post', + path: (s) => `${COLLECTIONS}/places/${s.collectionPlace.id}/activities`, + body: (s) => ({ collection_tour_id: kept(s, 'keptTour') }), + }, + expect: [{ event: 'collections:updated', user: 'actor' }], + }, + { + tool: 'unlink_saved_place_tour', + needs: ['collection'], + setup: async (s, app) => { + const tour = await makeKeptTour(ormOf(app), s.collection.id, { name: `Kept ridge ${s.n}` }); + await linkPlaceActivity(ormOf(app), { collectionPlace: s.collectionPlace.id, collectionTour: tour.id }); + keep(s, 'keptTour', tour.id); + }, + args: (s) => ({ collection_place_id: s.collectionPlace.id, collection_tour_id: kept(s, 'keptTour') }), + rest: { + method: 'delete', + path: (s) => `${COLLECTIONS}/places/${s.collectionPlace.id}/activities/tours/${kept(s, 'keptTour')}`, + }, + expect: [{ event: 'collections:updated', user: 'actor' }], + }, ]; /** The page ids of the scenes' books, in page order, so the tools can name them. */ @@ -1358,6 +1397,20 @@ export const user: CaseGroup = { setup: mergedPlaces, args: (s) => ({ merge_id: kept(s, 'merge') }), }, + { + tool: 'set_library_place_tags', + reason: PERSONAL_TAGS, + needs: ['place'], + setup: personalTag, + args: (s) => ({ key: `trip:${s.place.id}`, tag_ids: [kept(s, 'tag')] }), + }, + { + tool: 'tag_library_places', + reason: PERSONAL_TAGS, + needs: ['place', 'place2'], + setup: personalTag, + args: (s) => ({ keys: [`trip:${s.place.id}`, `trip:${s.place2.id}`], add: [kept(s, 'tag')] }), + }, { tool: 'create_manual_school_holiday_country', reason: HOLIDAY_CATALOG, diff --git a/server/tests/unit/db/entities-index.test.ts b/server/tests/unit/db/entities-index.test.ts index 63da47024..a056b6030 100644 --- a/server/tests/unit/db/entities-index.test.ts +++ b/server/tests/unit/db/entities-index.test.ts @@ -63,14 +63,17 @@ describe('ALL_ENTITIES', () => { * + trip_addon_overrides, the owner's per-trip on or off for a trip addon * + user_places, user_place_links, user_place_merges and user_place_merge_dismissals, * a user's own place identities, the uses they group, the merges and the dismissed pairs - * + trip_collection_links, the lists a trip links) + * + trip_collection_links, the lists a trip links + * + place_change_log, what changed in the details of a trip place or a saved place + * + place_activity_links, the bookings and tours a trip place or a saved place names + * + personal_place_tags, the personal tags a user put on the entries of All places) * is registered, and no two share a class name (a silent duplicate would * shadow one of them in `orm.getMetadata()`, exactly the kind of drift * `entity-schema-parity.test.ts` can't see — it iterates the metadata map, * which de-duplicates by class name). */ - it('ENT-003: exactly 179 entities, every class name unique', () => { - expect(ALL_ENTITIES.length).toBe(179); + it('ENT-003: exactly 182 entities, every class name unique', () => { + expect(ALL_ENTITIES.length).toBe(182); const names = ALL_ENTITIES.map((s) => s.meta.className); expect(new Set(names).size).toBe(names.length); }); diff --git a/server/tests/unit/db/entity-class-fields.test.ts b/server/tests/unit/db/entity-class-fields.test.ts index 068096cf5..3d91bc8f6 100644 --- a/server/tests/unit/db/entity-class-fields.test.ts +++ b/server/tests/unit/db/entity-class-fields.test.ts @@ -70,7 +70,10 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; // + user_places: id, user_id, name; user_place_links: id, user_place_id, user_id; user_place_merges: id, user_id, // leading_id, merged_id, moved_link_ids; user_place_merge_dismissals: id, user_id, key_a, key_b; // trip_collection_links: id, trip_id, collection_id (each row is written whole by the places library or the trip). -const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 653; +// + place_change_log: id, field (a change is only ever written whole, by the history of a place's details). +// + place_activity_links: id (a link is only ever written whole, by the place it names an activity for). +// + personal_place_tags: id, tag_id (a tag on an entry is only ever written whole, by the places library). +const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 658; describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => { it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => { diff --git a/server/tests/unit/db/legacy-baseline.test.ts b/server/tests/unit/db/legacy-baseline.test.ts index f69186e1f..21a4fd568 100644 --- a/server/tests/unit/db/legacy-baseline.test.ts +++ b/server/tests/unit/db/legacy-baseline.test.ts @@ -121,6 +121,9 @@ const UNNUMBERED = [ 'Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to', 'Migration20200101046530_a_user_keeps_their_own_place_identities', 'Migration20200101046540_a_trip_links_its_collections', + 'Migration20200101046550_a_place_keeps_the_history_of_its_details', + 'Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about', + 'Migration20200101046580_a_person_tags_the_places_they_keep', ]; // The last step the positional runner ever had; planLegacyBaseline refuses a // schema_version past it. diff --git a/server/tests/unit/db/repositories/PlaceActivityLinks.repository.test.ts b/server/tests/unit/db/repositories/PlaceActivityLinks.repository.test.ts new file mode 100644 index 000000000..77a10f514 --- /dev/null +++ b/server/tests/unit/db/repositories/PlaceActivityLinks.repository.test.ts @@ -0,0 +1,183 @@ +/** + * PlaceActivityLinksRepository and the table under it (PLC-18): the checks a + * link relies on, the links it writes and takes off, the bookings and tours + * it reads for trip places (linked, by their own place, stay or plan entry, + * by a station), the kept tours of saved places, and the shape the CHECK, + * the UNIQUE pairs and the cascades hold. + */ +import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity'; +import { PlaceActivityLinks } from '../../../../src/db/entities/PlaceActivityLinks.entity'; +import { Places } from '../../../../src/db/entities/Places.entity'; +import { Reservations } from '../../../../src/db/entities/Reservations.entity'; +import { Users } from '../../../../src/db/entities/Users.entity'; +import type { PlaceActivityLinksRepository } from '../../../../src/db/repositories/PlaceActivityLinks.repository'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { linkPlaceActivity } from '../../../helpers/factories/place-activities'; +import { countRows, deleteRows, findRow, updateRows } from '../../../helpers/factories/rows'; +import { makeUser } from '../../../helpers/factories/users'; +import { seedPlaceActivities, type PlaceActivitiesFixture } from '../../../helpers/place-activities-fixture'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const testDb = createSnapshotTestDb(); +let t: TestOrm; +let repo: PlaceActivityLinksRepository; +let f: PlaceActivitiesFixture; + +beforeAll(async () => { + t = await createTestOrm(testDb); + repo = t.repo(PlaceActivityLinks); +}); +beforeEach(async () => { + resetTestDb(testDb); + t.clear(); + f = await seedPlaceActivities(t); +}); +afterAll(async () => { + await t.close(); + testDb.close(); +}); + +describe('PlaceActivityLinksRepository', () => { + it('PAL-REPO-001: finds the places and activities a link names only where they belong', async () => { + const { alps, rome, places, saved, bookings, kept, lists } = f; + expect(await repo.tripPlace(alps.id, places.cafe.id)).toEqual({ id: places.cafe.id, trip_id: alps.id }); + expect(await repo.tripPlace(rome.id, places.cafe.id)).toBeUndefined(); + expect(await repo.savedPlace(saved.savedCafe.id)).toEqual({ id: saved.savedCafe.id, collection_id: lists.food.id }); + expect(await repo.savedPlace(999999)).toBeUndefined(); + expect(await repo.bookingInTrip(alps.id, bookings.guided.id)).toBe(true); + expect(await repo.bookingInTrip(rome.id, bookings.guided.id)).toBe(false); + expect(await repo.tourInTrip(alps.id, places.ridge.id)).toBe(true); + expect(await repo.tourInTrip(alps.id, places.cafe.id)).toBe(false); + expect(await repo.tourInTrip(rome.id, places.ridge.id)).toBe(false); + expect(await repo.keptTourInList(lists.food.id, kept.keptRidge.id)).toBe(true); + expect(await repo.keptTourInList(lists.food.id, kept.keptRome.id)).toBe(false); + }); + + it('PAL-REPO-002: links once, unlinks once, and reads the linked bookings, tours and kept tours', async () => { + const { me, places, saved, bookings, kept } = f; + expect(await repo.link({ place_id: places.cafe.id, reservation_id: bookings.guided.id }, me.id)).toBe(true); + expect(await repo.link({ place_id: places.cafe.id, reservation_id: bookings.guided.id }, me.id)).toBe(false); + expect(await repo.link({ place_id: places.cafe.id, tour_place_id: places.ridge.id }, me.id)).toBe(true); + expect( + await repo.link({ collection_place_id: saved.savedCafe.id, collection_tour_id: kept.keptRidge.id }, me.id), + ).toBe(true); + + const [booking] = await repo.linkedBookings([places.cafe.id]); + expect(booking).toMatchObject({ + source_id: places.cafe.id, + trip_id: f.alps.id, + trip_title: 'Alps', + reservation_id: bookings.guided.id, + title: 'Guided tour', + type: 'tour', + status: 'confirmed', + reservation_time: '2026-07-01T10:00', + date: '2026-07-01', + day_number: 1, + }); + expect(await repo.linkedTours([places.cafe.id])).toEqual([ + expect.objectContaining({ + source_id: places.cafe.id, + tour_id: places.ridge.id, + title: 'Ridge walk', + tour_type: 'hike', + }), + ]); + expect(await repo.linkedKeptTours([saved.savedCafe.id])).toEqual([ + expect.objectContaining({ + source_id: saved.savedCafe.id, + collection_id: f.lists.food.id, + collection_name: 'Food', + collection_tour_id: kept.keptRidge.id, + title: 'Kept ridge', + }), + ]); + expect(await repo.linkedBookings([])).toEqual([]); + + expect(await repo.unlinkTrip(places.cafe.id, { reservation_id: bookings.guided.id })).toBe(true); + expect(await repo.unlinkTrip(places.cafe.id, { reservation_id: bookings.guided.id })).toBe(false); + expect(await repo.unlinkTrip(places.cafe.id, { tour_place_id: places.ridge.id })).toBe(true); + expect(await repo.unlinkSaved(saved.savedCafe.id, kept.keptRidge.id)).toBe(true); + expect(await repo.unlinkSaved(saved.savedCafe.id, kept.keptRidge.id)).toBe(false); + expect(await countRows(t, PlaceActivityLinks, {})).toBe(0); + }); + + it('PAL-REPO-003: reads the bookings that belong to a place by its own place, stay or plan entry, and the station tours', async () => { + const { places, bookings } = f; + const own = await repo.implicitBookings([places.hotel.id, places.camp.id, places.cafe.id]); + expect(own.map((row) => [row.source_id, row.title, row.via]).sort()).toEqual( + [ + [places.hotel.id, 'Hotel Sonne', 'place'], + [places.camp.id, 'Lake cabin', 'stay'], + [places.cafe.id, 'Dinner', 'plan'], + ].sort(), + ); + expect(own.find((row) => row.via === 'stay')?.reservation_id).toBe(bookings.cabin.id); + expect(await repo.implicitTours([places.museum.id])).toEqual([ + expect.objectContaining({ source_id: places.museum.id, tour_id: places.ridge.id }), + ]); + expect(await repo.implicitTours([places.cafe.id])).toEqual([]); + }); + + it('PAL-REPO-004: lists the candidates of a trip and a list', async () => { + const bookings = await repo.tripBookings(f.alps.id); + expect(bookings.map((row) => row.title).sort()).toEqual(['Dinner', 'Guided tour', 'Hotel Sonne', 'Lake cabin']); + expect(bookings.every((row) => row.source_id === 0)).toBe(true); + const tours = await repo.tripTours(f.alps.id); + expect(tours.map((row) => row.title)).toEqual(['Old town walk', 'Ridge walk']); + expect(tours.find((row) => row.title === 'Old town walk')?.tour_type).toBe('walk'); + const kept = await repo.keptTours(f.lists.food.id); + expect(kept.map((row) => row.title)).toEqual(['Kept lake loop', 'Kept ridge']); + }); + + it('PAL-REPO-005: the CHECK refuses a mixed or empty link, the UNIQUE a second one, and an account that goes leaves its links', async () => { + const { me, places, saved, bookings } = f; + await expect( + linkPlaceActivity(t, { + place: places.cafe.id, + reservation: bookings.guided.id, + tourPlace: places.ridge.id, + } as never), + ).rejects.toThrow(); + await expect( + linkPlaceActivity(t, { place: places.cafe.id, collectionTour: f.kept.keptRidge.id } as never), + ).rejects.toThrow(); + await expect(linkPlaceActivity(t, { collectionPlace: saved.savedCafe.id } as never)).rejects.toThrow(); + await linkPlaceActivity(t, { place: places.cafe.id, reservation: bookings.guided.id }, me.id); + await expect(linkPlaceActivity(t, { place: places.cafe.id, reservation: bookings.guided.id })).rejects.toThrow(); + // Who linked it is kept as unknown when that account goes; the link stays. + const { user: helper } = await makeUser(t); + await linkPlaceActivity(t, { place: places.museum.id, reservation: bookings.guided.id }, helper.id); + await deleteRows(t, Users, { id: helper.id }); + const kept = await findRow(t, PlaceActivityLinks, { place: places.museum.id, reservation: bookings.guided.id }); + expect(kept?.linked_by).toBeNull(); + expect(await countRows(t, PlaceActivityLinks, {})).toBe(2); + }); + + it('PAL-REPO-006: deleting the booking, the tour or the place takes only its links', async () => { + const { places, bookings } = f; + await linkPlaceActivity(t, { place: places.cafe.id, reservation: bookings.guided.id }); + await linkPlaceActivity(t, { place: places.museum.id, reservation: bookings.guided.id }); + await linkPlaceActivity(t, { place: places.cafe.id, tourPlace: places.ridge.id }); + await deleteRows(t, Reservations, { id: bookings.guided.id }); + expect(await countRows(t, PlaceActivityLinks, {})).toBe(1); + await deleteRows(t, Places, { id: places.ridge.id }); + expect(await countRows(t, PlaceActivityLinks, {})).toBe(0); + expect(await findRow(t, Places, { id: places.cafe.id })).not.toBeNull(); + }); + + it('PAL-REPO-007: a saved place moved to another list reads none of the tours of its old list, and has them back on its return', async () => { + const { me, saved, kept, lists } = f; + await repo.link({ collection_place_id: saved.savedCafe.id, collection_tour_id: kept.keptRidge.id }, me.id); + await updateRows(t, CollectionPlaces, { id: saved.savedCafe.id }, { collection: lists.sights.id }); + expect(await repo.linkedKeptTours([saved.savedCafe.id])).toEqual([]); + // The link itself stays: it belongs to the old list, which may get the place back. + expect(await countRows(t, PlaceActivityLinks, { collectionPlace: saved.savedCafe.id })).toBe(1); + await updateRows(t, CollectionPlaces, { id: saved.savedCafe.id }, { collection: lists.food.id }); + const back = await repo.linkedKeptTours([saved.savedCafe.id]); + expect(back.map((row) => [row.title, row.collection_id])).toEqual([['Kept ridge', lists.food.id]]); + }); +}); diff --git a/server/tests/unit/db/repositories/PlaceChangeLog.repository.test.ts b/server/tests/unit/db/repositories/PlaceChangeLog.repository.test.ts new file mode 100644 index 000000000..e95d45840 --- /dev/null +++ b/server/tests/unit/db/repositories/PlaceChangeLog.repository.test.ts @@ -0,0 +1,179 @@ +/** + * PlaceChangeLogRepository and the table under it (PLC-14): the details it + * reads of trip places and saved places, the trip places a photo fill + * reaches, the changes it writes and drops, the page it reads with who made + * each change, the list a saved place's change was made in, the CHECK on + * its owner, and the rows that go with their place, list or account. + */ +import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity'; +import { Collections } from '../../../../src/db/entities/Collections.entity'; +import { PlaceChangeLog } from '../../../../src/db/entities/PlaceChangeLog.entity'; +import { Places } from '../../../../src/db/entities/Places.entity'; +import { Users } from '../../../../src/db/entities/Users.entity'; +import type { PlaceChangeLogRepository } from '../../../../src/db/repositories/PlaceChangeLog.repository'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { makeCollection, makeCollectionPlace } from '../../../helpers/factories/collections'; +import { makeCategory, makePlace } from '../../../helpers/factories/places'; +import { countRows, deleteRows, insertRow, updateRows } from '../../../helpers/factories/rows'; +import { makeTour } from '../../../helpers/factories/tours'; +import { makeTrip } from '../../../helpers/factories/trips'; +import { makeUser } from '../../../helpers/factories/users'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const testDb = createSnapshotTestDb(); +let t: TestOrm; +let repo: PlaceChangeLogRepository; + +beforeAll(async () => { + t = await createTestOrm(testDb); + repo = t.repo(PlaceChangeLog); +}); +beforeEach(async () => { + t.clear(); + await deleteRows(t, PlaceChangeLog); +}); +afterAll(async () => { + await t.close(); + testDb.close(); +}); + +const change = (over: Partial[0][number]>) => ({ + place_id: null, + collection_place_id: null, + field: 'name', + old_value: 'A', + new_value: 'B', + user_id: null, + automatic: 0, + ...over, +}); + +async function seed() { + const { user } = await makeUser(t); + const category = await makeCategory(t); + const trip = await makeTrip(t, user.id); + const place = await makePlace(t, trip.id, { + name: 'Café', + address: 'Herrengasse 14', + lat: 48.2, + lng: 16.3, + category: category.id, + opening_hours: 'Mo-Fr 8-18', + google_place_id: 'g-cafe', + }); + const list = await makeCollection(t, user.id); + const saved = await makeCollectionPlace(t, list.id, user.id, { name: 'Saved café', status: 'want', notes: 'Cake' }); + return { user, category, trip, place, list, saved }; +} + +describe('PlaceChangeLogRepository', () => { + it('PCLREPO-001: reads the details of trip places and saved places with their category names', async () => { + const s = await seed(); + expect(await repo.tripPlaceDetails([s.place.id, 999_999])).toEqual([ + expect.objectContaining({ + id: s.place.id, + name: 'Café', + address: 'Herrengasse 14', + lat: 48.2, + lng: 16.3, + category_name: s.category.name, + opening_hours: 'Mo-Fr 8-18', + }), + ]); + expect(await repo.savedPlaceDetails([s.saved.id])).toEqual([ + expect.objectContaining({ id: s.saved.id, name: 'Saved café', status: 'want', notes: 'Cake' }), + ]); + expect(await repo.tripPlaceDetails([])).toEqual([]); + }); + + it('PCLREPO-002: finds the trip places of a Google id that have no picture yet', async () => { + const s = await seed(); + const pictured = await makePlace(t, s.trip.id, { google_place_id: 'g-cafe', image_url: '/uploads/places/a.jpg' }); + const blank = await makePlace(t, s.trip.id, { google_place_id: 'g-cafe', image_url: '' }); + const ids = await repo.tripPlaceIdsWithoutImage('g-cafe'); + expect([...ids].sort((a, b) => a - b)).toEqual([s.place.id, blank.id].sort((a, b) => a - b)); + expect(ids).not.toContain(pictured.id); + }); + + it('PCLREPO-003: writes changes, pages them newest first with their editor, and drops a cleared field', async () => { + const s = await seed(); + await repo.insertChanges([ + change({ place_id: s.place.id, field: 'name', user_id: s.user.id }), + change({ place_id: s.place.id, field: 'notes', old_value: null, new_value: 'x', automatic: 1 }), + change({ collection_place_id: s.saved.id, field: 'status', old_value: 'idea', new_value: 'want' }), + ]); + await repo.insertChanges([]); + + const page = await repo.page([s.place.id], [s.saved.id], null, 10); + expect(page.map((row) => row.field)).toEqual(['status', 'notes', 'name']); + expect(page[2]).toEqual(expect.objectContaining({ user_id: s.user.id, username: s.user.username, automatic: 0 })); + expect(page[1]).toEqual(expect.objectContaining({ user_id: null, username: null, automatic: 1 })); + + const after = page[1]?.id ?? 0; + expect((await repo.page([s.place.id], [s.saved.id], after, 10)).map((row) => row.field)).toEqual(['name']); + expect((await repo.page([s.place.id], [], null, 1)).map((row) => row.field)).toEqual(['notes']); + expect(await repo.page([], [], null, 10)).toEqual([]); + + await repo.deleteCleared([ + { place_id: s.place.id, collection_place_id: null, fields: ['notes'] }, + { place_id: null, collection_place_id: s.saved.id, fields: ['status'] }, + { place_id: s.place.id, collection_place_id: null, fields: [] }, + ]); + await repo.deleteCleared([]); + expect((await repo.page([s.place.id], [s.saved.id], null, 10)).map((row) => row.field)).toEqual(['name']); + }); + + it('PCLREPO-004: the changes go with their place, and name nobody once the account is gone', async () => { + const s = await seed(); + const { user: other } = await makeUser(t); + await repo.insertChanges([ + change({ place_id: s.place.id, user_id: other.id }), + change({ collection_place_id: s.saved.id, user_id: other.id }), + ]); + await deleteRows(t, Users, { id: other.id }); + expect(await countRows(t, PlaceChangeLog, { collectionPlace: s.saved.id, user: null })).toBe(1); + await deleteRows(t, Places, { id: s.place.id }); + expect(await countRows(t, PlaceChangeLog, { place: s.place.id })).toBe(0); + expect(await countRows(t, PlaceChangeLog)).toBe(1); + }); + + it('PCLREPO-005: a saved place moved to another list shows only the changes made there, the old ones again on its return', async () => { + const s = await seed(); + await repo.insertChanges([change({ collection_place_id: s.saved.id, field: 'notes', user_id: s.user.id })]); + expect(await countRows(t, PlaceChangeLog, { collectionPlace: s.saved.id, collection: s.list.id })).toBe(1); + const other = await makeCollection(t, s.user.id); + await updateRows(t, CollectionPlaces, { id: s.saved.id }, { collection: other.id }); + expect(await repo.page([], [s.saved.id], null, 10)).toEqual([]); + await repo.insertChanges([change({ collection_place_id: s.saved.id, field: 'name' })]); + expect((await repo.page([], [s.saved.id], null, 10)).map((row) => row.field)).toEqual(['name']); + await updateRows(t, CollectionPlaces, { id: s.saved.id }, { collection: s.list.id }); + expect((await repo.page([], [s.saved.id], null, 10)).map((row) => row.field)).toEqual(['notes']); + // A deleted list takes the changes made in it; the place lives on in the other one. + await updateRows(t, CollectionPlaces, { id: s.saved.id }, { collection: other.id }); + await deleteRows(t, Collections, { id: s.list.id }); + expect(await countRows(t, PlaceChangeLog, { collectionPlace: s.saved.id })).toBe(1); + }); + + it('PCLREPO-006: the CHECK holds exactly one owner, and a list beside a saved place only', async () => { + const s = await seed(); + const row = { field: 'name', old_value: 'A', new_value: 'B' }; + await expect(insertRow(t, PlaceChangeLog, { ...row })).rejects.toThrow(); + await expect( + insertRow(t, PlaceChangeLog, { ...row, place: s.place.id, collectionPlace: s.saved.id, collection: s.list.id }), + ).rejects.toThrow(); + await expect(insertRow(t, PlaceChangeLog, { ...row, collectionPlace: s.saved.id })).rejects.toThrow(); + await expect(insertRow(t, PlaceChangeLog, { ...row, place: s.place.id, collection: s.list.id })).rejects.toThrow(); + await insertRow(t, PlaceChangeLog, { ...row, place: s.place.id }); + await insertRow(t, PlaceChangeLog, { ...row, collectionPlace: s.saved.id, collection: s.list.id }); + expect(await countRows(t, PlaceChangeLog)).toBe(2); + }); + + it('PCLREPO-007: a tour has no details to follow, so no write records a change of it', async () => { + const s = await seed(); + const tour = await makePlace(t, s.trip.id, { name: 'Ridge loop' }); + await makeTour(t, tour.id); + expect((await repo.tripPlaceDetails([s.place.id, tour.id])).map((row) => row.id)).toEqual([s.place.id]); + }); +}); diff --git a/server/tests/unit/nest/collections.service.test.ts b/server/tests/unit/nest/collections.service.test.ts index cf7ee81d8..90650ad31 100644 --- a/server/tests/unit/nest/collections.service.test.ts +++ b/server/tests/unit/nest/collections.service.test.ts @@ -56,6 +56,7 @@ import { Places } from '../../../src/db/entities/Places.entity'; import { Tags } from '../../../src/db/entities/Tags.entity'; import { Users } from '../../../src/db/entities/Users.entity'; import { FakeRealtimeService } from '../../helpers/fake-realtime'; +import { passThroughPlaceChanges } from '../../helpers/place-changes'; const realtime = new FakeRealtimeService(); const broadcastToUser = realtime.broadcastToUserMock; @@ -132,9 +133,8 @@ beforeAll(async () => { await createTestCollectionPlacesRepo(testDb), await createTestCollectionPlaceRatingsRepo(testDb), tripsRepoForSpy, await createTestTripMembersRepo(testDb), await createTestPlacesRepo(testDb), await createTestPlaceRatingsRepo(testDb), - await createTestTagsRepo(testDb), await createTestUsersRepo(testDb), - buildPlaceImportService(), - placesHooks as never, + await createTestTagsRepo(testDb), await createTestUsersRepo(testDb), buildPlaceImportService(), + placesHooks as never, passThroughPlaceChanges(), ); photoCache = new PlacePhotoCacheService( makeStorageFixture('photos/google/').storage, diff --git a/server/tests/unit/nest/collections.tags-to-carry.test.ts b/server/tests/unit/nest/collections.tags-to-carry.test.ts new file mode 100644 index 000000000..8c49661d2 --- /dev/null +++ b/server/tests/unit/nest/collections.tags-to-carry.test.ts @@ -0,0 +1,55 @@ +/** + * tagsToCarry (D9/PLC-21): which tags a copy into a trip brings along per + * saved place: the list's tags asked for where the place carries them, and + * the copier's personal tags asked for on every copy, nothing unasked. + */ +import { tagsToCarry } from '../../../src/nest/collections/collections.helpers'; + +import { describe, expect, it, vi } from 'vitest'; + +const listTags = [ + { pid: 1, id: 10, name: 'Must', color: '#ff0000' }, + { pid: 2, id: 11, name: 'Later', color: '#00ff00' }, +]; +const personal = [ + { id: 20, name: 'Wine', color: '#aa0000', trip_id: null }, + { id: 21, name: 'Old', color: null, trip_id: null }, + { id: 22, name: 'Trip tag', color: '#000000', trip_id: 5 }, +]; + +describe('tagsToCarry', () => { + it('COLL-CARRY-001: reads and brings nothing when nothing is asked for', async () => { + const lists = { loadTagsByPlaceIds: vi.fn() }; + const mine = vi.fn(); + expect(await tagsToCarry({}, [1, 2], lists, mine)).toBeNull(); + expect(await tagsToCarry({ tag_ids: [], personal_tag_ids: [] }, [1], lists, mine)).toBeNull(); + expect(lists.loadTagsByPlaceIds).not.toHaveBeenCalled(); + expect(mine).not.toHaveBeenCalled(); + }); + + it('COLL-CARRY-002: the list tags asked for where a place carries them, the personal ones on every copy', async () => { + const lists = { loadTagsByPlaceIds: vi.fn().mockResolvedValue(listTags) }; + const mine = vi.fn().mockResolvedValue(personal); + expect(await tagsToCarry({ tag_ids: [10], personal_tag_ids: [20, 21, 22, 99] }, [1, 2], lists, mine)).toEqual({ + 1: [ + { name: 'Must', color: '#ff0000' }, + { name: 'Wine', color: '#aa0000' }, + { name: 'Old', color: '#10b981' }, + ], + 2: [ + { name: 'Wine', color: '#aa0000' }, + { name: 'Old', color: '#10b981' }, + ], + }); + expect(lists.loadTagsByPlaceIds).toHaveBeenCalledWith([1, 2]); + }); + + it('COLL-CARRY-003: personal tags alone read no list tags', async () => { + const lists = { loadTagsByPlaceIds: vi.fn() }; + const mine = vi.fn().mockResolvedValue(personal); + expect(await tagsToCarry({ personal_tag_ids: [20] }, [3], lists, mine)).toEqual({ + 3: [{ name: 'Wine', color: '#aa0000' }], + }); + expect(lists.loadTagsByPlaceIds).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/unit/nest/common/conflictUpdate.test.ts b/server/tests/unit/nest/common/conflictUpdate.test.ts index 8838629b2..72df4e50a 100644 --- a/server/tests/unit/nest/common/conflictUpdate.test.ts +++ b/server/tests/unit/nest/common/conflictUpdate.test.ts @@ -42,6 +42,7 @@ import { createTestPackingTemplateCategoriesRepo, createTestPackingTemplateItemsRepo, } from '../../../helpers/packing-repos'; +import { passThroughPlaceChanges } from '../../../helpers/place-changes'; import { buildPlaceImportService } from '../../../helpers/place-import'; import { makeStorageFixture } from '../../../helpers/storage-fixture'; import { resetTestDb } from '../../../helpers/test-db'; @@ -168,6 +169,7 @@ beforeAll(async () => { await createTestBudgetItemsRepo(testDb), { releaseValues: async () => [] } as never, // StorageReleaseService buildPlaceImportService(), + passThroughPlaceChanges(), ); }); diff --git a/server/tests/unit/nest/maps.place-photo-resolver.test.ts b/server/tests/unit/nest/maps.place-photo-resolver.test.ts index b17bad6e5..540116cb6 100644 --- a/server/tests/unit/nest/maps.place-photo-resolver.test.ts +++ b/server/tests/unit/nest/maps.place-photo-resolver.test.ts @@ -10,6 +10,7 @@ import type { PlacesProviderSelector } from '../../../src/nest/maps/places-provi import type { GooglePlacesClient } from '../../../src/nest/maps/providers/google-places.provider'; import type { WikimediaClient } from '../../../src/nest/maps/providers/wikimedia.client'; import type { PlacePhotoCacheService } from '../../../src/nest/place-photos/place-photo-cache.service'; +import { passThroughPlaceChanges } from '../../helpers/place-changes'; import { describe, expect, it, vi } from 'vitest'; @@ -45,6 +46,7 @@ function resolver( google as unknown as GooglePlacesClient, wiki as unknown as WikimediaClient, selector as unknown as PlacesProviderSelector, + passThroughPlaceChanges(), ); return { r, places, google, wiki }; } diff --git a/server/tests/unit/nest/place-activities/place-activities.controller.test.ts b/server/tests/unit/nest/place-activities/place-activities.controller.test.ts new file mode 100644 index 000000000..78ee0ed1f --- /dev/null +++ b/server/tests/unit/nest/place-activities/place-activities.controller.test.ts @@ -0,0 +1,105 @@ +/** + * The three PLC-18 controllers over stub services: each route hands the trip + * the guard resolved, the user, its ids and input (and the X-Socket-Id on + * writes) to one service method. Guards, pipes and contracts run in the e2e suite. + */ +import type { TripAccess } from '../../../../src/db/repositories/Trips.repository'; +import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract'; +import type { TripWriter } from '../../../../src/nest/common/trip-writer'; +import { TRIP_PERMISSION_KEY } from '../../../../src/nest/permissions/trip-access.guard'; +import { PlaceActivitiesLibraryController } from '../../../../src/nest/place-activities/place-activities-library.controller'; +import type { PlaceActivitiesLibraryService } from '../../../../src/nest/place-activities/place-activities-library.service'; +import { PlaceActivitiesController } from '../../../../src/nest/place-activities/place-activities.controller'; +import type { PlaceActivitiesService } from '../../../../src/nest/place-activities/place-activities.service'; +import { SavedPlaceActivitiesController } from '../../../../src/nest/place-activities/saved-place-activities.controller'; +import type { User } from '../../../../src/types'; +import { + placeActivitiesResponseSchema, + placeActivityCandidatesResponseSchema, + placeLibraryActivitiesResponseSchema, +} from '@trek/shared'; + +import { describe, expect, it, vi } from 'vitest'; + +const user = { id: 7, role: 'user', username: 'ann', email: 'ann@example.test' } as User; +const trip = { id: 4, user_id: 7 } as TripAccess; +const answer = { activities: [], can_link: true }; +const meta = (key: string, handler: unknown) => Reflect.getMetadata(key, handler as object) as unknown; + +describe('PlaceActivitiesController', () => { + it('PAC-001: reads the activities and the candidates of the trip place for the user', async () => { + const tripPlace = vi.fn().mockResolvedValue(answer); + const tripCandidates = vi.fn().mockResolvedValue({ candidates: [] }); + const c = new PlaceActivitiesController({ tripPlace, tripCandidates } as unknown as PlaceActivitiesService); + expect(await c.list(user, trip, 9)).toBe(answer); + expect(await c.candidates(user, trip, 9)).toEqual({ candidates: [] }); + expect(tripPlace).toHaveBeenCalledWith(4, 9, { id: 7, role: 'user' }); + expect(tripCandidates).toHaveBeenCalledWith(4, 9, { id: 7, role: 'user' }); + }); + + it('PAC-002: links and unlinks with a REST writer that carries the socket id', async () => { + const writer = { userId: 7 } as TripWriter; + const restWriter = vi.fn().mockReturnValue(writer); + const linkTrip = vi.fn().mockResolvedValue(answer); + const unlinkTrip = vi.fn().mockResolvedValue(answer); + const c = new PlaceActivitiesController({ restWriter, linkTrip, unlinkTrip } as unknown as PlaceActivitiesService); + await c.link(user, trip, 9, { reservation_id: 3 }, 'sock-2'); + await c.unlinkBooking(user, trip, 9, 3, 'sock-2'); + await c.unlinkTour(user, trip, 9, 5, 'sock-2'); + expect(restWriter).toHaveBeenCalledWith(4, user, 'sock-2'); + expect(linkTrip).toHaveBeenCalledWith(4, 9, { reservation_id: 3 }, writer); + expect(unlinkTrip).toHaveBeenCalledWith(4, 9, { reservation_id: 3 }, writer); + expect(unlinkTrip).toHaveBeenCalledWith(4, 9, { tour_id: 5 }, writer); + }); + + it('PAC-003: the writes take place_edit, and every route declares its contract', () => { + const proto = PlaceActivitiesController.prototype; + for (const handler of [proto.link, proto.unlinkBooking, proto.unlinkTour]) { + expect(meta(TRIP_PERMISSION_KEY, handler)).toBe('place_edit'); + expect(meta(RESPONSE_CONTRACT_KEY, handler)).toBe(placeActivitiesResponseSchema); + } + expect(meta(TRIP_PERMISSION_KEY, proto.list)).toBeUndefined(); + expect(meta(RESPONSE_CONTRACT_KEY, proto.list)).toBe(placeActivitiesResponseSchema); + expect(meta(RESPONSE_CONTRACT_KEY, proto.candidates)).toBe(placeActivityCandidatesResponseSchema); + }); +}); + +describe('SavedPlaceActivitiesController', () => { + it('PAC-101: hands the user, the saved place and the socket id to the service', async () => { + const savedPlace = vi.fn().mockResolvedValue(answer); + const savedCandidates = vi.fn().mockResolvedValue({ candidates: [] }); + const linkSaved = vi.fn().mockResolvedValue(answer); + const unlinkSaved = vi.fn().mockResolvedValue(answer); + const c = new SavedPlaceActivitiesController({ + savedPlace, + savedCandidates, + linkSaved, + unlinkSaved, + } as unknown as PlaceActivitiesService); + expect(await c.list(user, 8)).toBe(answer); + expect(await c.candidates(user, 8)).toEqual({ candidates: [] }); + await c.link(user, 8, { collection_tour_id: 5 }, 'sock-3'); + await c.unlink(user, 8, 5, 'sock-3'); + expect(savedPlace).toHaveBeenCalledWith(7, 8); + expect(savedCandidates).toHaveBeenCalledWith(7, 8); + expect(linkSaved).toHaveBeenCalledWith(7, 8, { collection_tour_id: 5 }, 'sock-3'); + expect(unlinkSaved).toHaveBeenCalledWith(7, 8, 5, 'sock-3'); + const proto = SavedPlaceActivitiesController.prototype; + expect(meta(RESPONSE_CONTRACT_KEY, proto.link)).toBe(placeActivitiesResponseSchema); + expect(meta(RESPONSE_CONTRACT_KEY, proto.candidates)).toBe(placeActivityCandidatesResponseSchema); + }); +}); + +describe('PlaceActivitiesLibraryController', () => { + it('PAC-201: reads an entry from a trip place or a saved place', async () => { + const entry = vi.fn().mockResolvedValue({ activities: [], sources: [] }); + const c = new PlaceActivitiesLibraryController({ entry } as unknown as PlaceActivitiesLibraryService); + await c.tripPlace(user, 9); + await c.savedPlace(user, 8); + expect(entry).toHaveBeenCalledWith({ id: 7, role: 'user' }, 'trip', 9); + expect(entry).toHaveBeenCalledWith({ id: 7, role: 'user' }, 'list', 8); + expect(meta(RESPONSE_CONTRACT_KEY, PlaceActivitiesLibraryController.prototype.tripPlace)).toBe( + placeLibraryActivitiesResponseSchema, + ); + }); +}); diff --git a/server/tests/unit/nest/place-activities/place-activities.helpers.test.ts b/server/tests/unit/nest/place-activities/place-activities.helpers.test.ts new file mode 100644 index 000000000..e08db2646 --- /dev/null +++ b/server/tests/unit/nest/place-activities/place-activities.helpers.test.ts @@ -0,0 +1,145 @@ +/** + * The pure half of the place activities (PLC-18): rows into the wire shape, + * each activity once per place with why it belongs, the candidates left and + * the one target a trip link names. + */ +import type { + ActivityBookingRow, + ActivityKeptTourRow, + ActivityTourRow, +} from '../../../../src/db/repositories/PlaceActivityLinks.repository'; +import { + keptTourCandidate, + oncePerTarget, + remainingCandidates, + savedPlaceActivities, + tripActivityTargetOf, + tripPlaceActivities, +} from '../../../../src/nest/place-activities/place-activities.helpers'; +import { placeActivitySchema } from '@trek/shared'; + +import { describe, expect, it } from 'vitest'; + +const booking = (over: Partial): ActivityBookingRow => ({ + source_id: 7, + trip_id: 1, + trip_title: 'Alps', + reservation_id: 10, + title: 'Guided tour', + type: 'tour', + status: 'confirmed', + reservation_time: null, + reservation_end_time: null, + date: null, + day_number: null, + ...over, +}); +const tour = (over: Partial): ActivityTourRow => ({ + source_id: 7, + trip_id: 1, + trip_title: 'Alps', + tour_id: 20, + title: 'Ridge walk', + tour_type: 'hike', + date: '2026-07-02', + day_number: 2, + ...over, +}); +const kept: ActivityKeptTourRow = { + source_id: 8, + collection_id: 3, + collection_name: 'Food', + collection_tour_id: 30, + title: 'Kept ridge', + tour_type: 'hike', +}; +const source = { kind: 'trip', trip_id: 1, place_id: 7 } as const; + +describe('place activities helpers', () => { + it('PAH-001: a booking linked and belonging by itself is one activity with both flags; only the link can go', () => { + const activities = tripPlaceActivities( + source, + { + linkedBookings: [booking({ reservation_id: 10 }), booking({ reservation_id: 11, source_id: 99 })], + implicitBookings: [ + { ...booking({ reservation_id: 10 }), via: 'plan' }, + { ...booking({ reservation_id: 10 }), via: 'place' }, + { ...booking({ reservation_id: 12, title: 'Dinner', reservation_time: '2026-07-01T19:00' }), via: 'stay' }, + ], + linkedTours: [tour({ tour_id: 20 })], + stationTours: [tour({ tour_id: 20 }), tour({ tour_id: 21, title: 'Old town walk' })], + }, + true, + ); + expect(activities.map((a) => [a.key, a.explicit, a.implicit_via, a.can_unlink])).toEqual([ + ['reservation:12', false, 'stay', false], + ['reservation:10', true, 'place', true], + ['tour:21', false, 'station', false], + ['tour:20', true, 'station', true], + ]); + for (const activity of activities) expect(placeActivitySchema.parse(activity)).toEqual(activity); + expect(activities[1]).toMatchObject({ + type: 'booking', + origin: { kind: 'trip', trip_id: 1, trip_title: 'Alps' }, + target: { kind: 'reservation', trip_id: 1, reservation_id: 10 }, + source, + booking_type: 'tour', + tour_type: null, + }); + expect(activities[3]).toMatchObject({ + type: 'tour', + target: { kind: 'tour', trip_id: 1, tour_id: 20 }, + date: '2026-07-02', + }); + }); + + it('PAH-002: without the right to change links nothing can be unlinked; bookings without a time come last', () => { + const activities = tripPlaceActivities( + source, + { + linkedBookings: [ + booking({ reservation_id: 3 }), + booking({ reservation_id: 2, reservation_time: '2026-07-01' }), + ], + implicitBookings: [], + linkedTours: [], + stationTours: [], + }, + false, + ); + expect(activities.map((a) => [a.key, a.can_unlink])).toEqual([ + ['reservation:2', false], + ['reservation:3', false], + ]); + }); + + it('PAH-003: the kept tours of a saved place, the candidates left and each target once', () => { + const listSource = { kind: 'list', collection_id: 3, collection_place_id: 8 } as const; + const activities = savedPlaceActivities( + listSource, + [kept, { ...kept, source_id: 9, collection_tour_id: 31 }], + true, + ); + expect(activities).toEqual([ + expect.objectContaining({ + key: 'collection_tour:30', + origin: { kind: 'list', collection_id: 3, collection_name: 'Food' }, + target: { kind: 'collection_tour', collection_id: 3, collection_tour_id: 30 }, + source: listSource, + explicit: true, + can_unlink: true, + }), + ]); + const other = keptTourCandidate({ ...kept, collection_tour_id: 31, title: 'Kept lake' }); + expect(remainingCandidates([keptTourCandidate(kept), other], activities)).toEqual([other]); + const twice = [...activities, { ...activities[0], source: { ...listSource, collection_place_id: 9 } }]; + expect(oncePerTarget(twice)).toEqual(activities); + }); + + it('PAH-004: a trip link names exactly one booking or tour', () => { + expect(tripActivityTargetOf(4, undefined)).toEqual({ reservation_id: 4 }); + expect(tripActivityTargetOf(undefined, 5)).toEqual({ tour_id: 5 }); + expect(() => tripActivityTargetOf(4, 5)).toThrow('Give either reservation_id or tour_id'); + expect(() => tripActivityTargetOf(undefined, undefined)).toThrow('Give either reservation_id or tour_id'); + }); +}); diff --git a/server/tests/unit/nest/place-activities/place-activities.mcp.test.ts b/server/tests/unit/nest/place-activities/place-activities.mcp.test.ts new file mode 100644 index 000000000..142252c0c --- /dev/null +++ b/server/tests/unit/nest/place-activities/place-activities.mcp.test.ts @@ -0,0 +1,142 @@ +/** + * PlaceActivitiesMcp and SavedPlaceActivitiesMcp (PLC-18): the same services, + * permissions and checks as REST, the addon gate of the list tools, the scopes + * and the assistant groups they load with. From the container over a snapshot + * db; broadcasts go to the FakeRealtimeService. + */ +import type { McpContext } from '../../../../src/nest-mcp'; +import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata'; +import { AddonsService } from '../../../../src/nest/addons/addons.service'; +import { groupOf } from '../../../../src/nest/assistant/assistant-tool-offer'; +import { PlaceActivitiesMcp } from '../../../../src/nest/place-activities/place-activities.mcp'; +import { PlaceActivitiesModule } from '../../../../src/nest/place-activities/place-activities.module'; +import { SavedPlaceActivitiesMcp } from '../../../../src/nest/place-activities/saved-place-activities.mcp'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { setAddonEnabled } from '../../../helpers/factories/settings'; +import { seedPlaceActivities, type PlaceActivitiesFixture } from '../../../helpers/place-activities-fixture'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let mcp: PlaceActivitiesMcp; +let saved: SavedPlaceActivitiesMcp; +let f: PlaceActivitiesFixture; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [PlaceActivitiesModule] }); + mcp = t.get(PlaceActivitiesMcp); + saved = t.get(SavedPlaceActivitiesMcp); + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + vi.restoreAllMocks(); + t.realtime.reset(); + f = await seedPlaceActivities(orm); + await setAddonEnabled(orm, 'tours', true); + await setAddonEnabled(orm, 'collections', true); +}); +afterAll(async () => { + await orm.close(); + await t.close(); + db.close(); +}); + +const ctx = (userId: number) => ({ userId }) as McpContext; +const read = (result: { content: Array<{ type: string; text: string }> }) => JSON.parse(result.content[0]?.text ?? ''); +const options = (name: string) => { + const entry = + getEntry(PlaceActivitiesMcp as unknown as ClassRef, name) ?? + getEntry(SavedPlaceActivitiesMcp as unknown as ClassRef, name); + if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`); + return entry.options; +}; +const allowed = (name: string, scopes: string[]) => { + const access = options(name).access; + return typeof access === 'function' ? access({ userId: 1, scopes } as McpContext) : access; +}; + +describe('PlaceActivitiesMcp and SavedPlaceActivitiesMcp', () => { + it('PAM-001: links, reads and unlinks a booking of a trip place, with the event marked as MCP', async () => { + const input = { tripId: f.alps.id, placeId: f.places.cafe.id }; + const candidates = read(await mcp.listPlaceActivityCandidates(input, ctx(f.me.id))).candidates; + expect(candidates.map((c: { title: string }) => c.title)).toContain('Guided tour'); + const linked = read(await mcp.linkPlaceActivity({ ...input, reservation_id: f.bookings.guided.id }, ctx(f.me.id))); + expect(linked.activities.map((a: { title: string }) => a.title)).toEqual(['Guided tour', 'Dinner']); + expect(t.realtime.broadcastMock).toHaveBeenCalledWith(f.alps.id, 'placeActivities:changed', { + placeId: f.places.cafe.id, + _source: 'mcp', + }); + expect(read(await mcp.listPlaceActivities(input, ctx(f.me.id))).can_link).toBe(true); + const after = read(await mcp.unlinkPlaceActivity({ ...input, reservation_id: f.bookings.guided.id }, ctx(f.me.id))); + expect(after.activities.map((a: { title: string }) => a.title)).toEqual(['Dinner']); + await expect(mcp.unlinkPlaceActivity(input, ctx(f.me.id))).rejects.toThrow('Give either reservation_id or tour_id'); + }); + + it('PAM-002: refuses a trip out of reach and a booking of another trip', async () => { + await expect( + mcp.listPlaceActivities({ tripId: f.elsewhere.id, placeId: f.places.hidden.id }, ctx(f.me.id)), + ).rejects.toThrow(); + await expect( + mcp.linkPlaceActivity({ tripId: f.alps.id, placeId: f.places.cafe.id, tour_id: f.places.forum.id }, ctx(f.me.id)), + ).rejects.toThrow('Tour not found'); + }); + + it('PAM-003: links and unlinks a kept tour of a saved place and reads an entry of All places', async () => { + const input = { collection_place_id: f.saved.savedCafe.id, collection_tour_id: f.kept.keptLake.id }; + expect(read(await saved.linkSavedPlaceTour(input, ctx(f.me.id))).activities).toHaveLength(1); + expect( + read(await saved.listSavedPlaceActivityCandidates({ collection_place_id: f.saved.savedCafe.id }, ctx(f.me.id))) + .candidates, + ).toHaveLength(1); + expect( + read(await saved.listSavedPlaceActivities({ collection_place_id: f.saved.savedCafe.id }, ctx(f.me.id))).can_link, + ).toBe(true); + const entry = read(await saved.getLibraryPlaceActivities({ kind: 'trip', id: f.places.cafe.id }, ctx(f.me.id))); + expect(entry.activities.map((a: { title: string }) => a.title).sort()).toEqual(['Dinner', 'Kept lake loop']); + expect(entry.sources).toHaveLength(2); + expect(read(await saved.unlinkSavedPlaceTour(input, ctx(f.me.id))).activities).toEqual([]); + }); + + it('PAM-004: the list tools only with Collections on, and every tool for the tokens that may', async () => { + const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false); + expect(await options('linkSavedPlaceTour').when?.(ctx(1), saved)).toBe(false); + expect(await options('getLibraryPlaceActivities').when?.(ctx(1), saved)).toBe(false); + enabled.mockResolvedValue(true); + expect(await options('linkSavedPlaceTour').when?.(ctx(1), saved)).toBe(true); + expect(options('linkPlaceActivity').when).toBeUndefined(); + + for (const name of ['linkPlaceActivity', 'unlinkPlaceActivity']) { + expect(allowed(name, ['places:write', 'reservations:read'])).toBe(true); + expect(allowed(name, ['places:read', 'reservations:read'])).toBe(false); + expect(allowed(name, ['places:write'])).toBe(false); + } + for (const name of ['listPlaceActivities', 'listPlaceActivityCandidates']) { + expect(allowed(name, ['places:read', 'reservations:read'])).toBe(true); + expect(allowed(name, ['places:read'])).toBe(false); + expect(options(name).annotations).toMatchObject({ readOnlyHint: true }); + } + for (const name of ['linkSavedPlaceTour', 'unlinkSavedPlaceTour']) { + expect(allowed(name, ['collections:write'])).toBe(true); + expect(allowed(name, ['collections:read'])).toBe(false); + } + for (const name of ['listSavedPlaceActivities', 'listSavedPlaceActivityCandidates']) { + expect(allowed(name, ['collections:read'])).toBe(true); + expect(allowed(name, ['places:read'])).toBe(false); + } + expect(allowed('getLibraryPlaceActivities', ['collections:read', 'trips:read', 'reservations:read'])).toBe(true); + expect(allowed('getLibraryPlaceActivities', ['collections:read', 'trips:read'])).toBe(false); + }); + + it('PAM-005: the assistant loads the trip tools with the bookings and the list tools with the collections', () => { + expect(groupOf({ className: 'PlaceActivitiesMcp' })).toBe('bookings'); + expect(groupOf({ className: 'SavedPlaceActivitiesMcp' })).toBe('collections'); + expect(groupOf({ className: 'PlaceHistoryMcp' })).toBe('collections'); + }); +}); diff --git a/server/tests/unit/nest/place-activities/place-activities.service.test.ts b/server/tests/unit/nest/place-activities/place-activities.service.test.ts new file mode 100644 index 000000000..c89a70c2a --- /dev/null +++ b/server/tests/unit/nest/place-activities/place-activities.service.test.ts @@ -0,0 +1,339 @@ +/** + * PlaceActivitiesService and PlaceActivitiesLibraryService (PLC-18) over the + * real repository on a migrated test db: what a trip place, a saved place and + * an entry of All places show (linked, by their own place, stay, plan entry + * or station), linking and unlinking with the permission, the same-trip and + * same-list checks, Tours on or off, and the events. Broadcasts go to a + * FakeRealtimeService. + */ +import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity'; +import { PlaceActivityLinks } from '../../../../src/db/entities/PlaceActivityLinks.entity'; +import { Reservations } from '../../../../src/db/entities/Reservations.entity'; +import { DomainError } from '../../../../src/nest/common/domain-error'; +import { restTripWriter } from '../../../../src/nest/common/trip-writer'; +import { PermissionsService } from '../../../../src/nest/permissions/permissions.service'; +import { PlaceActivitiesLibraryService } from '../../../../src/nest/place-activities/place-activities-library.service'; +import { PlaceActivitiesModule } from '../../../../src/nest/place-activities/place-activities.module'; +import { PlaceActivitiesService } from '../../../../src/nest/place-activities/place-activities.service'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { makeCollection } from '../../../helpers/factories/collections'; +import { linkPlaceActivity } from '../../../helpers/factories/place-activities'; +import { makeReservation } from '../../../helpers/factories/reservations'; +import { countRows, findRow, updateRows } from '../../../helpers/factories/rows'; +import { setAddonEnabled, setTripAddon } from '../../../helpers/factories/settings'; +import { seedPlaceActivities, type PlaceActivitiesFixture } from '../../../helpers/place-activities-fixture'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let service: PlaceActivitiesService; +let library: PlaceActivitiesLibraryService; +let f: PlaceActivitiesFixture; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [PlaceActivitiesModule] }); + service = t.get(PlaceActivitiesService); + library = t.get(PlaceActivitiesLibraryService); + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + vi.restoreAllMocks(); + t.realtime.reset(); + f = await seedPlaceActivities(orm); + await setAddonEnabled(orm, 'tours', true); + await setAddonEnabled(orm, 'collections', true); +}); +afterAll(async () => { + await orm.close(); + await t.close(); + db.close(); +}); + +const reader = (id: number) => ({ id, role: 'user' }); +const writer = (id: number, tripId = f.alps.id) => restTripWriter(t.realtime, tripId, reader(id), 'sock-1'); + +async function refusal(promise: Promise): Promise<{ status: number; message: string }> { + try { + await promise; + } catch (err) { + expect(err).toBeInstanceOf(DomainError); + const error = err as DomainError; + return { status: error.getStatus(), message: error.publicMessage }; + } + throw new Error('expected a refusal'); +} + +describe('PlaceActivitiesService, trip places', () => { + it('PAS-001: shows the bookings that belong to a place by themselves, which cannot be unlinked', async () => { + const hotel = await service.tripPlace(f.alps.id, f.places.hotel.id, reader(f.me.id)); + expect(hotel.can_link).toBe(true); + expect(hotel.activities).toEqual([ + expect.objectContaining({ + title: 'Hotel Sonne', + type: 'booking', + explicit: false, + implicit_via: 'place', + can_unlink: false, + }), + ]); + const camp = await service.tripPlace(f.alps.id, f.places.camp.id, reader(f.me.id)); + expect(camp.activities.map((a) => [a.title, a.implicit_via])).toEqual([['Lake cabin', 'stay']]); + const cafe = await service.tripPlace(f.alps.id, f.places.cafe.id, reader(f.me.id)); + expect(cafe.activities.map((a) => [a.title, a.implicit_via])).toEqual([['Dinner', 'plan']]); + const museum = await service.tripPlace(f.alps.id, f.places.museum.id, reader(f.me.id)); + expect(museum.activities).toEqual([ + expect.objectContaining({ + key: `tour:${f.places.ridge.id}`, + type: 'tour', + implicit_via: 'station', + tour_type: 'hike', + }), + ]); + }); + + it('PAS-002: links a booking and a tour of the trip once each, tells the trip, and unlinks them', async () => { + const first = await service.linkTrip( + f.alps.id, + f.places.cafe.id, + { reservation_id: f.bookings.guided.id }, + writer(f.me.id), + ); + expect(first.activities.map((a) => [a.title, a.explicit, a.can_unlink])).toEqual([ + ['Guided tour', true, true], + ['Dinner', false, false], + ]); + expect(t.realtime.broadcastMock).toHaveBeenCalledWith( + f.alps.id, + 'placeActivities:changed', + { placeId: f.places.cafe.id }, + 'sock-1', + ); + t.realtime.reset(); + await service.linkTrip(f.alps.id, f.places.cafe.id, { reservation_id: f.bookings.guided.id }, writer(f.me.id)); + expect(t.realtime.broadcastMock).not.toHaveBeenCalled(); + const withTour = await service.linkTrip(f.alps.id, f.places.cafe.id, { tour_id: f.tours.walk.id }, writer(f.me.id)); + expect(withTour.activities.find((a) => a.type === 'tour')).toMatchObject({ + target: { kind: 'tour', trip_id: f.alps.id, tour_id: f.tours.walk.id }, + tour_type: 'walk', + explicit: true, + }); + const linked = await findRow(orm, PlaceActivityLinks, { + place: f.places.cafe.id, + reservation: f.bookings.guided.id, + }); + expect(linked?.linked_by).toBe(f.me.id); + + await service.unlinkTrip(f.alps.id, f.places.cafe.id, { reservation_id: f.bookings.guided.id }, writer(f.me.id)); + const after = await service.unlinkTrip(f.alps.id, f.places.cafe.id, { tour_id: f.tours.walk.id }, writer(f.me.id)); + expect(after.activities.map((a) => a.title)).toEqual(['Dinner']); + // Unlinking takes the link only: the booking is still there. + expect(await findRow(orm, Reservations, { id: f.bookings.guided.id })).not.toBeNull(); + expect( + await refusal(service.unlinkTrip(f.alps.id, f.places.cafe.id, { tour_id: f.tours.walk.id }, writer(f.me.id))), + ).toEqual({ status: 404, message: 'This activity is not linked to the place' }); + }); + + it('PAS-003: refuses what is not of the same trip, belongs already, is the place itself or names no one target', async () => { + const rome = await makeReservation(orm, f.rome.id, { title: 'Rome dinner' }); + const cafe = f.places.cafe.id; + expect(await refusal(service.linkTrip(f.alps.id, cafe, { reservation_id: rome.id }, writer(f.me.id)))).toEqual({ + status: 404, + message: 'Booking not found', + }); + expect(await refusal(service.linkTrip(f.alps.id, cafe, { tour_id: f.places.forum.id }, writer(f.me.id)))).toEqual({ + status: 404, + message: 'Tour not found', + }); + expect( + await refusal(service.linkTrip(f.alps.id, f.places.forum.id, { tour_id: f.tours.walk.id }, writer(f.me.id))), + ).toEqual({ + status: 404, + message: 'Place not found', + }); + expect( + await refusal(service.linkTrip(f.alps.id, cafe, { reservation_id: f.bookings.dinner.id }, writer(f.me.id))), + ).toEqual({ status: 409, message: 'This booking already belongs to the place' }); + expect( + await refusal(service.linkTrip(f.alps.id, f.places.museum.id, { tour_id: f.places.ridge.id }, writer(f.me.id))), + ).toEqual({ status: 409, message: 'This tour already belongs to the place' }); + expect( + await refusal(service.linkTrip(f.alps.id, f.places.ridge.id, { tour_id: f.places.ridge.id }, writer(f.me.id))), + ).toEqual({ status: 400, message: 'A tour cannot be linked to itself' }); + expect(await refusal(service.linkTrip(f.alps.id, cafe, {}, writer(f.me.id)))).toEqual({ + status: 400, + message: 'Give either reservation_id or tour_id', + }); + expect(await countRows(orm, PlaceActivityLinks, {})).toBe(0); + }); + + it('PAS-004: a trip out of reach is not found, a member without place_edit may read but not link', async () => { + expect((await refusal(service.tripPlace(f.elsewhere.id, f.places.hidden.id, reader(f.me.id)))).status).toBe(404); + expect( + ( + await refusal( + service.linkTrip(f.elsewhere.id, f.places.hidden.id, { tour_id: 1 }, writer(f.me.id, f.elsewhere.id)), + ) + ).status, + ).toBe(404); + vi.spyOn(t.get(PermissionsService), 'checkPermission').mockResolvedValue(false); + const read = await service.tripPlace(f.alps.id, f.places.hotel.id, reader(f.me.id)); + expect(read.can_link).toBe(false); + expect( + await refusal( + service.linkTrip(f.alps.id, f.places.cafe.id, { reservation_id: f.bookings.guided.id }, writer(f.me.id)), + ), + ).toMatchObject({ status: 403 }); + expect( + await refusal( + service.unlinkTrip(f.alps.id, f.places.cafe.id, { reservation_id: f.bookings.guided.id }, writer(f.me.id)), + ), + ).toMatchObject({ status: 403 }); + }); + + it('PAS-005: with Tours off for the trip its tours are left out and cannot be linked', async () => { + await linkPlaceActivity(orm, { place: f.places.cafe.id, tourPlace: f.tours.walk.id }); + await setTripAddon(orm, f.alps.id, 'tours', false); + const cafe = await service.tripPlace(f.alps.id, f.places.cafe.id, reader(f.me.id)); + expect(cafe.activities.every((a) => a.type === 'booking')).toBe(true); + expect((await service.tripPlace(f.alps.id, f.places.museum.id, reader(f.me.id))).activities).toEqual([]); + const candidates = await service.tripCandidates(f.alps.id, f.places.cafe.id, reader(f.me.id)); + expect(candidates.candidates.every((c) => c.type === 'booking')).toBe(true); + expect( + await refusal(service.linkTrip(f.alps.id, f.places.hotel.id, { tour_id: f.places.ridge.id }, writer(f.me.id))), + ).toEqual({ status: 404, message: 'Tour not found' }); + }); + + it('PAS-006: the candidates are what is not related to the place yet, the tour itself left out', async () => { + await linkPlaceActivity(orm, { place: f.places.ridge.id, reservation: f.bookings.guided.id }); + const { candidates } = await service.tripCandidates(f.alps.id, f.places.ridge.id, reader(f.me.id)); + expect(candidates.map((c) => c.key).sort()).toEqual( + [ + `reservation:${f.bookings.dinner.id}`, + `reservation:${f.bookings.cabin.id}`, + `reservation:${(await findRow(orm, Reservations, { title: 'Hotel Sonne' }))?.id ?? 0}`, + `tour:${f.tours.walk.id}`, + ].sort(), + ); + }); +}); + +describe('PlaceActivitiesService, saved places', () => { + it('PAS-101: links a kept tour of the same list, tells the list, and unlinks it', async () => { + const empty = await service.savedPlace(f.me.id, f.saved.savedCafe.id); + expect(empty).toEqual({ activities: [], can_link: true }); + const linked = await service.linkSaved( + f.me.id, + f.saved.savedCafe.id, + { collection_tour_id: f.kept.keptRidge.id }, + 'sock-1', + ); + expect(linked.activities).toEqual([ + expect.objectContaining({ + key: `collection_tour:${f.kept.keptRidge.id}`, + origin: { kind: 'list', collection_id: f.lists.food.id, collection_name: 'Food' }, + source: { kind: 'list', collection_id: f.lists.food.id, collection_place_id: f.saved.savedCafe.id }, + can_unlink: true, + }), + ]); + expect(t.realtime.broadcastToUserMock).toHaveBeenCalledWith( + f.me.id, + { type: 'collections:updated', collectionId: f.lists.food.id }, + 'sock-1', + ); + const { candidates } = await service.savedCandidates(f.me.id, f.saved.savedCafe.id); + expect(candidates.map((c) => c.title)).toEqual(['Kept lake loop']); + t.realtime.reset(); + await service.linkSaved(f.me.id, f.saved.savedCafe.id, { collection_tour_id: f.kept.keptRidge.id }); + expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled(); + const after = await service.unlinkSaved(f.me.id, f.saved.savedCafe.id, f.kept.keptRidge.id); + expect(after.activities).toEqual([]); + expect(await refusal(service.unlinkSaved(f.me.id, f.saved.savedCafe.id, f.kept.keptRidge.id))).toEqual({ + status: 404, + message: 'This activity is not linked to the place', + }); + }); + + it('PAS-102: a list out of reach is not found, a viewer reads but may not link, a tour of another list is not found', async () => { + expect(await refusal(service.savedPlace(f.me.id, f.saved.secret.id))).toEqual({ + status: 404, + message: 'Place not found', + }); + expect(await service.savedPlace(f.me.id, f.saved.pantheon.id)).toEqual({ activities: [], can_link: false }); + expect( + await refusal(service.linkSaved(f.me.id, f.saved.pantheon.id, { collection_tour_id: f.kept.keptRome.id })), + ).toEqual({ status: 403, message: 'You have read-only access to this list' }); + expect( + await refusal(service.linkSaved(f.me.id, f.saved.savedCafe.id, { collection_tour_id: f.kept.keptRome.id })), + ).toEqual({ status: 404, message: 'Tour not found' }); + }); + + it('PAS-103: with Tours off a list shows and takes no kept tours', async () => { + await linkPlaceActivity(orm, { collectionPlace: f.saved.savedCafe.id, collectionTour: f.kept.keptRidge.id }); + await setAddonEnabled(orm, 'tours', false); + expect(await service.savedPlace(f.me.id, f.saved.savedCafe.id)).toEqual({ activities: [], can_link: false }); + expect(await service.savedCandidates(f.me.id, f.saved.savedCafe.id)).toEqual({ candidates: [] }); + expect( + await refusal(service.linkSaved(f.me.id, f.saved.savedCafe.id, { collection_tour_id: f.kept.keptLake.id })), + ).toEqual({ status: 404, message: 'Tour not found' }); + }); +}); + +describe('a saved place moved to another list', () => { + it('PAS-104: reads and takes off none of the tours of its old list, and has them back on its return', async () => { + await linkPlaceActivity(orm, { collectionPlace: f.saved.savedCafe.id, collectionTour: f.kept.keptRidge.id }); + const trips = await makeCollection(orm, f.me.id, { name: 'Trips to come' }); + await updateRows(orm, CollectionPlaces, { id: f.saved.savedCafe.id }, { collection: trips.id }); + expect(await service.savedPlace(f.me.id, f.saved.savedCafe.id)).toEqual({ activities: [], can_link: true }); + const entry = await library.entry(reader(f.me.id), 'list', f.saved.savedCafe.id); + expect(entry.activities.map((a) => a.key)).not.toContain(`collection_tour:${f.kept.keptRidge.id}`); + expect(await refusal(service.unlinkSaved(f.me.id, f.saved.savedCafe.id, f.kept.keptRidge.id))).toEqual({ + status: 404, + message: 'This activity is not linked to the place', + }); + expect(await countRows(orm, PlaceActivityLinks, { collectionPlace: f.saved.savedCafe.id })).toBe(1); + await updateRows(orm, CollectionPlaces, { id: f.saved.savedCafe.id }, { collection: f.lists.food.id }); + const back = await service.savedPlace(f.me.id, f.saved.savedCafe.id); + expect(back.activities.map((a) => a.title)).toEqual(['Kept ridge']); + }); +}); + +describe('PlaceActivitiesLibraryService', () => { + it('PAS-201: an entry shows the activities of every origin it has once, with the origins to link through', async () => { + await linkPlaceActivity(orm, { place: f.places.cafe.id, reservation: f.bookings.guided.id }); + await linkPlaceActivity(orm, { collectionPlace: f.saved.savedCafe.id, collectionTour: f.kept.keptRidge.id }); + const entry = await library.entry(reader(f.me.id), 'trip', f.places.cafe.id); + expect(entry.activities.map((a) => a.title).sort()).toEqual(['Dinner', 'Guided tour', 'Kept ridge']); + expect(entry.sources).toEqual( + expect.arrayContaining([ + { + source: { kind: 'trip', trip_id: f.alps.id, place_id: f.places.cafe.id }, + origin: { kind: 'trip', trip_id: f.alps.id, trip_title: 'Alps' }, + can_link: true, + }, + { + source: { kind: 'list', collection_id: f.lists.food.id, collection_place_id: f.saved.savedCafe.id }, + origin: { kind: 'list', collection_id: f.lists.food.id, collection_name: 'Food' }, + can_link: true, + }, + ]), + ); + expect((await library.entry(reader(f.me.id), 'list', f.saved.savedCafe.id)).activities).toHaveLength(3); + }); + + it('PAS-202: an entry out of reach is not found, and an origin out of reach adds nothing', async () => { + expect(await refusal(library.entry(reader(f.me.id), 'list', f.saved.secret.id))).toEqual({ + status: 404, + message: 'Place not found', + }); + const friend = await library.entry(reader(f.friend.id), 'list', f.saved.pantheon.id); + expect(friend.activities).toEqual([]); + expect(friend.sources).toHaveLength(1); + }); +}); diff --git a/server/tests/unit/nest/place-changes/place-changes.helpers.test.ts b/server/tests/unit/nest/place-changes/place-changes.helpers.test.ts new file mode 100644 index 000000000..ca9c8e17f --- /dev/null +++ b/server/tests/unit/nest/place-changes/place-changes.helpers.test.ts @@ -0,0 +1,109 @@ +/** + * The pure half of the place history (PLC-14): how a stored value reads, what + * a snapshot of a trip place and a saved place holds, which fields a write + * changed or cleared, and the rows that follows. + */ +import { + changeRowsOf, + diffDetails, + historyValue, + positionValue, + savedPlaceSnapshot, + targetKey, + tripPlaceSnapshot, +} from '../../../../src/nest/place-changes/place-changes.helpers'; +import { + AUTOMATIC_CHANGE, + savedPlaceTarget, + tripPlaceTarget, +} from '../../../../src/nest/place-changes/place-changes.types'; + +import { describe, expect, it } from 'vitest'; + +const details = { + id: 3, + name: 'Café', + address: ' ', + lat: 48.2, + lng: 16.3, + category_name: 'Food', + description: null, + notes: 'Book', + website: '', + phone: '+43', + image_url: '/uploads/places/a.jpg', +}; + +describe('place change helpers', () => { + it('PCHG-H-001: a blank or missing value reads as none, a number as its text', () => { + expect(historyValue(null)).toBeNull(); + expect(historyValue(undefined)).toBeNull(); + expect(historyValue(' ')).toBeNull(); + expect(historyValue(' Café ')).toBe(' Café '); + expect(historyValue(0)).toBe('0'); + }); + + it('PCHG-H-002: the position is both coordinates or none', () => { + expect(positionValue(48.2, 16.3)).toBe('48.2,16.3'); + expect(positionValue(0, 0)).toBe('0,0'); + expect(positionValue(null, 16.3)).toBeNull(); + expect(positionValue(48.2, null)).toBeNull(); + }); + + it('PCHG-H-003: a trip place keeps opening hours, a saved place its status', () => { + expect(tripPlaceSnapshot({ ...details, opening_hours: 'Mo-Fr 8-18' })).toEqual({ + name: 'Café', + address: null, + position: '48.2,16.3', + category: 'Food', + description: null, + notes: 'Book', + website: null, + phone: '+43', + image: '/uploads/places/a.jpg', + opening_hours: 'Mo-Fr 8-18', + }); + const saved = savedPlaceSnapshot({ ...details, status: 'want' }); + expect(saved.status).toBe('want'); + expect('opening_hours' in saved).toBe(false); + }); + + it('PCHG-H-004: a write changes the fields it set to another value and clears the ones it emptied', () => { + const diff = diffDetails( + { name: 'Café', notes: 'Book', phone: null, website: 'https://a' }, + { name: 'Café Wien', notes: null, phone: '+43', website: 'https://a' }, + ); + expect(diff).toEqual({ + changed: [ + { field: 'name', old_value: 'Café', new_value: 'Café Wien' }, + { field: 'phone', old_value: null, new_value: '+43' }, + ], + cleared: ['notes'], + }); + }); + + it('PCHG-H-005: the rows name the place, the editor and whether TREK filled the value in', () => { + const diff = { changed: [{ field: 'name' as const, old_value: 'A', new_value: 'B' }], cleared: ['notes' as const] }; + expect(changeRowsOf(tripPlaceTarget(3), diff, 7)).toEqual({ + writes: [ + { + place_id: 3, + collection_place_id: null, + field: 'name', + old_value: 'A', + new_value: 'B', + user_id: 7, + automatic: 0, + }, + ], + clear: { place_id: 3, collection_place_id: null, fields: ['notes'] }, + }); + expect(changeRowsOf(savedPlaceTarget(5), diff, AUTOMATIC_CHANGE).writes[0]).toEqual( + expect.objectContaining({ place_id: null, collection_place_id: 5, user_id: null, automatic: 1 }), + ); + expect(changeRowsOf(savedPlaceTarget(5), diff, null).writes[0]).toEqual( + expect.objectContaining({ user_id: null, automatic: 0 }), + ); + expect(targetKey(tripPlaceTarget(3))).not.toBe(targetKey(savedPlaceTarget(3))); + }); +}); diff --git a/server/tests/unit/nest/place-changes/place-changes.service.test.ts b/server/tests/unit/nest/place-changes/place-changes.service.test.ts new file mode 100644 index 000000000..e0b0aafc7 --- /dev/null +++ b/server/tests/unit/nest/place-changes/place-changes.service.test.ts @@ -0,0 +1,145 @@ +/** + * PlaceChangesService (PLC-14) in its module with a scripted repository: the + * details before and after a write, what it records and drops, who it names, + * and that a write that throws records nothing. The SQL behind it runs in + * tests/unit/db/repositories/PlaceChangeLog.repository.test.ts and the whole + * path in tests/e2e/place-history.e2e.test.ts. + */ +import { PlaceChangeLog } from '../../../../src/db/entities/PlaceChangeLog.entity'; +import type { + SavedPlaceDetailsRow, + TripPlaceDetailsRow, +} from '../../../../src/db/repositories/PlaceChangeLog.repository'; +import { PlaceChangesModule } from '../../../../src/nest/place-changes/place-changes.module'; +import { PlaceChangesService } from '../../../../src/nest/place-changes/place-changes.service'; +import { + AUTOMATIC_CHANGE, + savedPlaceTarget, + tripPlaceTarget, +} from '../../../../src/nest/place-changes/place-changes.types'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; +import { getRepositoryToken } from '@mikro-orm/nestjs'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const trip = (overrides: Partial = {}): TripPlaceDetailsRow => ({ + id: 1, + name: 'Café', + address: 'Herrengasse 14', + lat: 48.2, + lng: 16.3, + category_name: 'Food', + description: null, + notes: 'Book a table', + website: null, + phone: null, + image_url: null, + opening_hours: null, + ...overrides, +}); + +const saved = (overrides: Partial = {}): SavedPlaceDetailsRow => ({ + ...trip(), + id: 2, + status: 'idea', + ...overrides, +}); + +const repo = { + tripPlaceDetails: vi.fn(), + savedPlaceDetails: vi.fn(), + tripPlaceIdsWithoutImage: vi.fn(), + insertChanges: vi.fn(), + deleteCleared: vi.fn(), + page: vi.fn(), +}; + +const db = createSnapshotTestDb(); +let t: TestModule; +let service: PlaceChangesService; + +beforeAll(async () => { + t = await createTestModule({ + db, + imports: [PlaceChangesModule], + overrides: [{ provide: getRepositoryToken(PlaceChangeLog), useValue: repo }], + }); + service = t.get(PlaceChangesService); +}); +beforeEach(() => { + for (const fn of Object.values(repo)) fn.mockReset(); + repo.tripPlaceDetails.mockResolvedValue([]); + repo.savedPlaceDetails.mockResolvedValue([]); +}); +afterAll(async () => { + await t.close(); + db.close(); +}); + +describe('PlaceChangesService', () => { + it('PCHG-S-001: records each field a write changed, by who wrote it, and drops the cleared ones', async () => { + repo.tripPlaceDetails + .mockResolvedValueOnce([trip()]) + .mockResolvedValueOnce([trip({ name: 'Café Central', notes: '', phone: '+43' })]); + const write = vi.fn().mockResolvedValue('written'); + + expect(await service.track(tripPlaceTarget(1), 7, write)).toBe('written'); + expect(write).toHaveBeenCalledTimes(1); + expect(repo.insertChanges).toHaveBeenCalledWith([ + expect.objectContaining({ place_id: 1, field: 'name', old_value: 'Café', new_value: 'Café Central', user_id: 7 }), + expect.objectContaining({ place_id: 1, field: 'phone', old_value: null, new_value: '+43', user_id: 7 }), + ]); + expect(repo.deleteCleared).toHaveBeenCalledWith([{ place_id: 1, collection_place_id: null, fields: ['notes'] }]); + expect(repo.savedPlaceDetails).not.toHaveBeenCalled(); + }); + + it('PCHG-S-002: a write that changes nothing records nothing', async () => { + repo.savedPlaceDetails.mockResolvedValue([saved()]); + await service.track([savedPlaceTarget(2), savedPlaceTarget(2)], 7, () => Promise.resolve(undefined)); + expect(repo.insertChanges).toHaveBeenCalledWith([]); + expect(repo.deleteCleared).toHaveBeenCalledWith([{ place_id: null, collection_place_id: 2, fields: [] }]); + }); + + it('PCHG-S-003: the places can be found inside the transaction, and TREK fills are marked automatic', async () => { + repo.tripPlaceIdsWithoutImage.mockResolvedValue([1]); + repo.tripPlaceDetails + .mockResolvedValueOnce([trip()]) + .mockResolvedValueOnce([trip({ image_url: '/api/maps/place-photo/g/bytes' })]); + const ids = await service.tripPlacesWithoutImage('g'); + await service.track( + () => Promise.resolve(ids.map(tripPlaceTarget)), + AUTOMATIC_CHANGE, + () => Promise.resolve(1), + ); + expect(repo.tripPlaceIdsWithoutImage).toHaveBeenCalledWith('g'); + expect(repo.insertChanges).toHaveBeenCalledWith([ + expect.objectContaining({ field: 'image', user_id: null, automatic: 1 }), + ]); + }); + + it('PCHG-S-004: no places, or a place the write deleted, record nothing; a write that throws neither', async () => { + const write = vi.fn().mockResolvedValue(0); + await service.track(() => Promise.resolve([]), null, write); + expect(write).toHaveBeenCalledTimes(1); + expect(repo.tripPlaceDetails).not.toHaveBeenCalled(); + + repo.tripPlaceDetails.mockResolvedValueOnce([trip()]).mockResolvedValueOnce([]); + await service.track(tripPlaceTarget(1), 7, () => Promise.resolve(undefined)); + expect(repo.insertChanges).toHaveBeenCalledWith([]); + + repo.insertChanges.mockClear(); + repo.tripPlaceDetails.mockResolvedValue([trip()]); + await expect(service.track(tripPlaceTarget(1), 7, () => Promise.reject(new Error('refused')))).rejects.toThrow( + 'refused', + ); + expect(repo.insertChanges).not.toHaveBeenCalled(); + }); + + it('PCHG-S-005: reads a page of changes as the repository answers it', async () => { + const rows = [{ id: 9 }]; + repo.page.mockResolvedValue(rows); + expect(await service.page([1], [2], 10, 5)).toBe(rows); + expect(repo.page).toHaveBeenCalledWith([1], [2], 10, 5); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-history.service.test.ts b/server/tests/unit/nest/places-library/place-history.service.test.ts new file mode 100644 index 000000000..d352f40c8 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-history.service.test.ts @@ -0,0 +1,185 @@ +/** + * PlaceHistoryService, PlaceHistoryController and PlaceHistoryMcp (PLC-14) + * over a scripted library and change log: the entry is resolved with the + * reader's reach, only the changes of the origins in it are asked for, each + * change carries its origin and editor, the page goes on by its cursor, and + * REST and MCP hand the same reader and input to the same method. The real + * reach and SQL run in tests/e2e/place-history.e2e.test.ts. + */ +import type { PlaceChangeRow } from '../../../../src/db/repositories/PlaceChangeLog.repository'; +import type { McpContext } from '../../../../src/nest-mcp'; +import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata'; +import { AddonsService } from '../../../../src/nest/addons/addons.service'; +import { DomainError } from '../../../../src/nest/common/domain-error'; +import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract'; +import { McpToolGuardsService } from '../../../../src/nest/mcp-shared/mcp-tool-guards.service'; +import { PlaceChangesService } from '../../../../src/nest/place-changes/place-changes.service'; +import { PlaceHistoryController } from '../../../../src/nest/places-library/place-history.controller'; +import { PlaceHistoryMcp } from '../../../../src/nest/places-library/place-history.mcp'; +import { PlaceHistoryService } from '../../../../src/nest/places-library/place-history.service'; +import { PlacesLibraryService } from '../../../../src/nest/places-library/places-library.service'; +import type { User } from '../../../../src/types'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; +import { placeHistoryPageResponseSchema } from '@trek/shared'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const reach = { userId: 7, tripIds: [1], collectionIds: [4] }; +const rows = { + trips: [{ id: 10, trip_id: 1, trip_title: 'Alps' }], + saved: [{ id: 20, collection_id: 4, collection_name: 'Food' }], +}; + +const library = { + reach: vi.fn(), + anchorOfUse: vi.fn(), + rows: vi.fn(), +}; +const changes = { page: vi.fn() }; +const guards = { isAdminUser: vi.fn() }; + +const row = (over: Partial): PlaceChangeRow => ({ + id: 1, + place_id: null, + collection_place_id: null, + field: 'name', + old_value: 'A', + new_value: 'B', + user_id: 7, + username: 'ann', + avatar: null, + automatic: 0, + created_at: '2026-11-29 10:00:00', + ...over, +}); + +const db = createSnapshotTestDb(); +let t: TestModule; +let service: PlaceHistoryService; + +beforeAll(async () => { + t = await createTestModule({ + db, + imports: [], + providers: [ + PlaceHistoryService, + PlaceHistoryMcp, + { provide: PlacesLibraryService, useValue: library }, + { provide: PlaceChangesService, useValue: changes }, + { provide: McpToolGuardsService, useValue: guards }, + { provide: AddonsService, useValue: {} }, + ], + }); + service = t.get(PlaceHistoryService); +}); +beforeEach(() => { + vi.resetAllMocks(); + library.reach.mockResolvedValue(reach); + library.anchorOfUse.mockResolvedValue(41); + library.rows.mockResolvedValue([rows]); + changes.page.mockResolvedValue([]); + guards.isAdminUser.mockResolvedValue(false); +}); +afterAll(async () => { + await t.close(); + db.close(); +}); + +const me = { id: 7, role: 'user' }; + +async function status(promise: Promise): Promise { + try { + await promise; + } catch (err) { + expect(err).toBeInstanceOf(DomainError); + return (err as DomainError).getStatus(); + } + return 200; +} + +describe('PlaceHistoryService', () => { + it('PHIST-001: reads the changes of the origins the reader reaches, each with its origin and editor', async () => { + changes.page.mockResolvedValue([ + row({ id: 3, collection_place_id: 20, field: 'status', old_value: 'idea', new_value: 'want' }), + row({ id: 2, place_id: 10, field: 'address', user_id: null, username: null, automatic: 1 }), + row({ id: 1, place_id: 10, avatar: 'a.png' }), + ]); + const page = await service.history(me, 'trip', 10, {}); + expect(library.anchorOfUse).toHaveBeenCalledWith(reach, 'trip', 10); + expect(library.rows).toHaveBeenCalledWith(reach, [41]); + expect(changes.page).toHaveBeenCalledWith([10], [20], null, 51); + expect(placeHistoryPageResponseSchema.parse(page)).toEqual(page); + expect(page.next_cursor).toBeNull(); + expect(page.entries).toEqual([ + expect.objectContaining({ + id: 3, + field: 'status', + origin: { kind: 'list', collection_id: 4, collection_name: 'Food', collection_place_id: 20 }, + editor: { id: 7, username: 'ann', avatar_url: null }, + automatic: false, + }), + expect.objectContaining({ id: 2, editor: null, automatic: true }), + expect.objectContaining({ + id: 1, + origin: { kind: 'trip', trip_id: 1, trip_title: 'Alps', place_id: 10 }, + editor: { id: 7, username: 'ann', avatar_url: '/uploads/avatars/a.png' }, + }), + ]); + }); + + it('PHIST-002: pages by the id of the last change, and leaves out a field it does not follow', async () => { + changes.page.mockResolvedValue([ + row({ id: 9, place_id: 10 }), + row({ id: 8, place_id: 10, field: 'price' }), + row({ id: 7, place_id: 10 }), + ]); + const page = await service.history(me, 'list', 20, { cursor: '12', limit: 2 }); + expect(changes.page).toHaveBeenCalledWith([10], [20], 12, 3); + expect(page.entries.map((entry) => entry.id)).toEqual([9]); + expect(page.next_cursor).toBe('8'); + }); + + it('PHIST-003: an entry the reader does not reach is not found', async () => { + library.anchorOfUse.mockResolvedValueOnce(null); + expect(await status(service.history(me, 'trip', 10, {}))).toBe(404); + library.rows.mockResolvedValueOnce([]); + expect(await status(service.history(me, 'trip', 10, {}))).toBe(404); + expect(changes.page).not.toHaveBeenCalled(); + }); +}); + +describe('PlaceHistoryController and PlaceHistoryMcp', () => { + it('PHIST-004: both routes hand the reader, the origin and the page to the service', async () => { + const answer = { entries: [], next_cursor: null }; + const history = vi.fn().mockResolvedValue(answer); + const controller = new PlaceHistoryController({ history } as unknown as PlaceHistoryService); + const user = { id: 7, role: 'user' } as User; + expect(await controller.tripPlace(user, 10, { limit: 5 })).toBe(answer); + expect(await controller.savedPlace(user, 20, {})).toBe(answer); + expect(history).toHaveBeenNthCalledWith(1, me, 'trip', 10, { limit: 5 }); + expect(history).toHaveBeenNthCalledWith(2, me, 'list', 20, {}); + const contract = (handler: unknown) => Reflect.getMetadata(RESPONSE_CONTRACT_KEY, handler as object) as unknown; + expect(contract(PlaceHistoryController.prototype.tripPlace)).toBe(placeHistoryPageResponseSchema); + expect(contract(PlaceHistoryController.prototype.savedPlace)).toBe(placeHistoryPageResponseSchema); + }); + + it('PHIST-005: the tool reads the same history as an admin or a user, read only and behind the addon', async () => { + const mcp = t.get(PlaceHistoryMcp); + const ctx = { userId: 7, scopes: null } as unknown as McpContext; + guards.isAdminUser.mockResolvedValueOnce(true); + const result = await mcp.getLibraryPlaceHistory({ kind: 'list', id: 20, cursor: '5', limit: 3 }, ctx); + expect(changes.page).toHaveBeenCalledWith([10], [20], 5, 4); + expect(JSON.stringify(result)).toContain('next_cursor'); + expect(library.reach).toHaveBeenCalledWith(7); + + const entry = getEntry(PlaceHistoryMcp as unknown as ClassRef, 'getLibraryPlaceHistory'); + if (entry?.kind !== 'tool') throw new Error('getLibraryPlaceHistory is no tool'); + expect(entry.options.name).toBe('get_library_place_history'); + expect(entry.options.annotations?.readOnlyHint).toBe(true); + expect(typeof entry.options.when).toBe('function'); + const access = entry.options.access as (c: McpContext) => boolean; + expect(access({ scopes: ['collections:read', 'trips:read'] } as unknown as McpContext)).toBe(true); + expect(access({ scopes: ['collections:read'] } as unknown as McpContext)).toBe(false); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-tags.controller.test.ts b/server/tests/unit/nest/places-library/place-tags.controller.test.ts new file mode 100644 index 000000000..ff23ee806 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-tags.controller.test.ts @@ -0,0 +1,33 @@ +/** + * PlaceTagsController (PLC-21) over a stub service: each route hands the user + * and its body to one service method and answers what it returns. Guards, + * pipes and the response contracts run in the e2e suite. + */ +import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract'; +import { PlaceTagsController } from '../../../../src/nest/places-library/place-tags.controller'; +import type { PlaceTagsService } from '../../../../src/nest/places-library/place-tags.service'; +import type { User } from '../../../../src/types'; +import { placesLibraryBulkTagsResponseSchema, placesLibraryEntryTagsResponseSchema } from '@trek/shared'; + +import { describe, expect, it, vi } from 'vitest'; + +const user = { id: 7, role: 'user', username: 'ann', email: 'ann@example.test' } as User; +const me = { id: 7, role: 'user' }; + +describe('PlaceTagsController', () => { + it('PTAGC-001: set and bulk hand the body on with the user', async () => { + const setForEntry = vi.fn().mockResolvedValue({ entry: null }); + const bulk = vi.fn().mockResolvedValue({ entries: [] }); + const c = new PlaceTagsController({ setForEntry, bulk } as unknown as PlaceTagsService); + expect(await c.setForEntry(user, { key: 'trip:3', tag_ids: [1] })).toEqual({ entry: null }); + expect(await c.bulk(user, { keys: ['list:4'], add: [2] })).toEqual({ entries: [] }); + expect(setForEntry).toHaveBeenCalledWith(me, { key: 'trip:3', tag_ids: [1] }); + expect(bulk).toHaveBeenCalledWith(me, { keys: ['list:4'], add: [2] }); + }); + + it('PTAGC-002: declares the shared response contracts', () => { + const proto = PlaceTagsController.prototype; + expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, proto.setForEntry)).toBe(placesLibraryEntryTagsResponseSchema); + expect(Reflect.getMetadata(RESPONSE_CONTRACT_KEY, proto.bulk)).toBe(placesLibraryBulkTagsResponseSchema); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-tags.helpers.test.ts b/server/tests/unit/nest/places-library/place-tags.helpers.test.ts new file mode 100644 index 000000000..8c254a10b --- /dev/null +++ b/server/tests/unit/nest/places-library/place-tags.helpers.test.ts @@ -0,0 +1,90 @@ +/** + * The pure half of the personal tags on "All places" (PLC-21): what an + * entry's tags are read from, which rows belong to which entry, and where a + * new tag is put. + */ +import type { LibraryEntryTagRow } from '../../../../src/db/repositories/PlacesLibrary.repository'; +import { + assignmentOf, + tagsByEntry, + tagTargetsOf, + uniqueIds, +} from '../../../../src/nest/places-library/place-tags.helpers'; +import type { EntryRows } from '../../../../src/nest/places-library/places-library.helpers'; + +import { describe, expect, it } from 'vitest'; + +const entry = (anchor: number, parts: { identity?: number; trips?: number[]; saved?: number[] }): EntryRows => + ({ + anchor, + identity: parts.identity === undefined ? null : { id: parts.identity }, + trips: (parts.trips ?? []).map((id) => ({ id })), + saved: (parts.saved ?? []).map((id) => ({ id })), + linked: new Set(), + }) as unknown as EntryRows; + +const row = (id: number, name: string, on: Partial): LibraryEntryTagRow => ({ + id, + name, + color: null, + user_place_id: null, + merged_into_id: null, + place_id: null, + collection_place_id: null, + ...on, +}); + +describe('place-tags helpers', () => { + it('PTAGH-001: the targets of entries are their own places, trip places and saved places', () => { + expect( + tagTargetsOf([entry(23, { identity: 5, trips: [1], saved: [2] }), entry(9, { trips: [2], saved: [3, 4] })]), + ).toEqual({ + identityIds: [5], + placeIds: [1, 2], + collectionPlaceIds: [2, 3, 4], + }); + }); + + it('PTAGH-002: each entry gets the tags on its own place, a merged one, and its uses, once each', () => { + const own = entry(23, { identity: 5, trips: [1] }); + const trip = entry(9, { trips: [2], saved: [7] }); + const rows = [ + row(1, 'A', { user_place_id: 5 }), + row(1, 'A', { place_id: 1 }), + row(2, 'B', { user_place_id: 6, merged_into_id: 5 }), + row(3, 'C', { collection_place_id: 7 }), + row(4, 'D', { user_place_id: 8 }), + row(5, 'E', { place_id: 99 }), + ]; + expect(tagsByEntry([own, trip], rows)).toEqual([ + [ + { id: 1, name: 'A', color: null }, + { id: 2, name: 'B', color: null }, + ], + [{ id: 3, name: 'C', color: null }], + ]); + expect(tagsByEntry([trip], [row(4, 'D', { user_place_id: 8 })])).toEqual([[]]); + }); + + it('PTAGH-003: a new tag goes on the own place, else the trip place or saved place the entry is', () => { + expect(assignmentOf(5 * 4 + 3, 9)).toEqual({ + tag_id: 9, + user_place_id: 5, + place_id: null, + collection_place_id: null, + }); + expect(assignmentOf(6 * 4 + 1, 9)).toEqual({ + tag_id: 9, + user_place_id: null, + place_id: 6, + collection_place_id: null, + }); + expect(assignmentOf(7 * 4 + 2, 9)).toEqual({ + tag_id: 9, + user_place_id: null, + place_id: null, + collection_place_id: 7, + }); + expect(uniqueIds([3, 1, 3, 2, 1])).toEqual([3, 1, 2]); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-tags.mcp.test.ts b/server/tests/unit/nest/places-library/place-tags.mcp.test.ts new file mode 100644 index 000000000..522c8a2ad --- /dev/null +++ b/server/tests/unit/nest/places-library/place-tags.mcp.test.ts @@ -0,0 +1,106 @@ +/** + * PlaceTagsMcp (PLC-21): the personal tag tools over the same service as + * REST, with the addon gate and the scopes they need, and the tag filter of + * list_all_places. Taken from the container over a snapshot db. + */ +import type { McpContext } from '../../../../src/nest-mcp'; +import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata'; +import { AddonsService } from '../../../../src/nest/addons/addons.service'; +import { PlaceTagsMcp } from '../../../../src/nest/places-library/place-tags.mcp'; +import { PlacesLibraryMcp } from '../../../../src/nest/places-library/places-library.mcp'; +import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-library.module'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { makeTag } from '../../../helpers/factories/places'; +import { seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; +import { placesLibraryQuerySchema } from '@trek/shared'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({ + LOG_LEVEL: 'error', + logInfo: vi.fn(), + logDebug: vi.fn(), + logError: vi.fn(), + logWarn: vi.fn(), +})); + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let mcp: PlaceTagsMcp; +let f: LibraryFixture; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [PlacesLibraryModule] }); + mcp = t.get(PlaceTagsMcp); + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + vi.restoreAllMocks(); + f = await seedLibrary(orm); +}); +afterAll(async () => { + await orm.close(); + await t.close(); + db.close(); +}); + +const ctx = (userId: number) => ({ userId }) as McpContext; + +function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) { + return JSON.parse(result.content[0]?.text ?? ''); +} + +const options = (name: string) => { + const entry = getEntry(PlaceTagsMcp as unknown as ClassRef, name); + if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`); + return entry.options; +}; + +describe('PlaceTagsMcp', () => { + it('PTAG-MCP-001: sets, adds and removes tags as REST does, and list_all_places filters by them', async () => { + const wine = await makeTag(orm, f.me.id, { name: 'Wine' }); + const view = await makeTag(orm, f.me.id, { name: 'View' }); + const cafe = `trip:${f.places.cafe.id}`; + const set = read(await mcp.setLibraryPlaceTags({ key: cafe, tag_ids: [wine.id] }, ctx(f.me.id))); + expect(set.entry.tags.map((tag: { name: string }) => tag.name)).toEqual(['Wine']); + const bulk = read( + await mcp.tagLibraryPlaces( + { keys: [cafe, `list:${f.saved.pantheon.id}`], add: [view.id], remove: [wine.id] }, + ctx(f.me.id), + ), + ); + expect(bulk.entries.map((entry: { tags: { name: string }[] }) => entry.tags.map((tag) => tag.name))).toEqual([ + ['View'], + ['View'], + ]); + const library = t.get(PlacesLibraryMcp); + const page = read( + await library.listAllPlaces(placesLibraryQuerySchema.parse({ tag_ids: String(view.id) }), ctx(f.me.id)), + ); + expect(page.total).toBe(2); + await expect(mcp.tagLibraryPlaces({ keys: [cafe] }, ctx(f.me.id))).rejects.toThrow('Name tags to add or to remove'); + }); + + it('PTAG-MCP-002: the tools are there only with Collections on, and for tokens that may write lists', async () => { + const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false); + expect(await options('setLibraryPlaceTags').when?.(ctx(1), mcp)).toBe(false); + enabled.mockResolvedValue(true); + expect(await options('tagLibraryPlaces').when?.(ctx(1), mcp)).toBe(true); + const allowed = (name: string, scopes: string[]) => { + const access = options(name).access; + return typeof access === 'function' ? access({ userId: 1, scopes } as McpContext) : access; + }; + for (const name of ['setLibraryPlaceTags', 'tagLibraryPlaces']) { + expect(allowed(name, ['collections:write', 'trips:read'])).toBe(true); + expect(allowed(name, ['collections:read', 'trips:read'])).toBe(false); + expect(allowed(name, ['collections:write'])).toBe(false); + expect(options(name).annotations?.readOnlyHint).not.toBe(true); + } + }); +}); diff --git a/server/tests/unit/nest/places-library/place-tags.service.test.ts b/server/tests/unit/nest/places-library/place-tags.service.test.ts new file mode 100644 index 000000000..c1dca07a8 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-tags.service.test.ts @@ -0,0 +1,251 @@ +/** + * PlaceTagsService and the tag side of PlacesLibraryService (PLC-21) over the + * real repositories on a migrated test db: personal tags on the entries of + * "All places", who sees them, the tag filter and its counts, tags that + * follow an entry through linking, merging and unlinking, the bulk change and + * every refusal leaving nothing half written. + */ +import { PersonalPlaceTags } from '../../../../src/db/entities/PersonalPlaceTags.entity'; +import { Tags } from '../../../../src/db/entities/Tags.entity'; +import { DomainError } from '../../../../src/nest/common/domain-error'; +import { PermissionsService } from '../../../../src/nest/permissions/permissions.service'; +import { PlaceIdentitiesService } from '../../../../src/nest/places-library/place-identities.service'; +import { PlaceTagsService } from '../../../../src/nest/places-library/place-tags.service'; +import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-library.module'; +import { PlacesLibraryService, type LibraryUser } from '../../../../src/nest/places-library/places-library.service'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { makeTag } from '../../../helpers/factories/places'; +import { countRows, deleteRows } from '../../../helpers/factories/rows'; +import { seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; +import type { PlacesLibraryEntry, PlacesLibraryPageResponse } from '@trek/shared'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let tags: PlaceTagsService; +let library: PlacesLibraryService; +let identities: PlaceIdentitiesService; +let f: LibraryFixture; +let wine: number; +let view: number; +let theirs: number; +let tripTag: number; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [PlacesLibraryModule] }); + tags = t.get(PlaceTagsService); + library = t.get(PlacesLibraryService); + identities = t.get(PlaceIdentitiesService); + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + vi.restoreAllMocks(); + vi.spyOn(t.get(PermissionsService), 'checkPermission').mockImplementation( + async (_action, _role, tripOwner, userId) => tripOwner === userId, + ); + f = await seedLibrary(orm); + wine = (await makeTag(orm, f.me.id, { name: 'Wine', color: '#aa0000' })).id; + view = (await makeTag(orm, f.me.id, { name: 'View', color: null })).id; + theirs = (await makeTag(orm, f.friend.id, { name: 'Wine' })).id; + tripTag = (await makeTag(orm, f.me.id, { name: 'Trip only', trip: f.alps.id })).id; +}); +afterAll(async () => { + await orm.close(); + await t.close(); + db.close(); +}); + +const as = (id: number): LibraryUser => ({ id, role: 'user' }); +const keys = (page: PlacesLibraryPageResponse) => page.entries.map((entry) => entry.key); +const tagNames = (entry: PlacesLibraryEntry | null | undefined) => (entry?.tags ?? []).map((tag) => tag.name); +const entryOf = (page: PlacesLibraryPageResponse, key: string) => page.entries.find((entry) => entry.key === key); + +async function refusal(promise: Promise): Promise<{ status: number; message: string }> { + try { + await promise; + } catch (err) { + expect(err).toBeInstanceOf(DomainError); + const error = err as DomainError; + return { status: error.getStatus(), message: error.publicMessage }; + } + throw new Error('expected a refusal'); +} + +describe('PlaceTagsService.setForEntry', () => { + it('PTAG-001: tags an entry, shows the tags by name in the list and the detail, and replaces them', async () => { + const cafe = `trip:${f.places.cafe.id}`; + const set = await tags.setForEntry(as(f.me.id), { key: cafe, tag_ids: [wine, view, wine] }); + expect(set.entry?.key).toBe(cafe); + expect(set.entry?.tags).toEqual([ + { id: view, name: 'View', color: null }, + { id: wine, name: 'Wine', color: '#aa0000' }, + ]); + const page = await library.list(as(f.me.id), {}); + expect(tagNames(entryOf(page, cafe))).toEqual(['View', 'Wine']); + expect(tagNames(entryOf(page, `trip:${f.places.museum.id}`))).toEqual([]); + const detail = await library.detail(as(f.me.id), 'list', f.saved.savedCafe.id); + expect(tagNames(detail.entry)).toEqual(['View', 'Wine']); + + const replaced = await tags.setForEntry(as(f.me.id), { key: cafe, tag_ids: [wine] }); + expect(tagNames(replaced.entry)).toEqual(['Wine']); + const cleared = await tags.setForEntry(as(f.me.id), { key: cafe, tag_ids: [] }); + expect(cleared.entry?.tags).toEqual([]); + expect(await countRows(orm, PersonalPlaceTags, {})).toBe(0); + }); + + it('PTAG-002: the tags are private: the trip owner sees none of a member tagging their place', async () => { + const forum = `trip:${f.places.forum.id}`; + await tags.setForEntry(as(f.me.id), { key: forum, tag_ids: [wine] }); + expect(tagNames(entryOf(await library.list(as(f.me.id), {}), forum))).toEqual(['Wine']); + const friendsPage = await library.list(as(f.friend.id), {}); + expect(entryOf(friendsPage, forum)?.tags).toEqual([]); + expect(keys(await library.list(as(f.friend.id), { tag_ids: [wine] }))).toEqual([]); + }); + + it('PTAG-003: refuses tags that are not the user’s personal ones and entries out of reach', async () => { + const cafe = `trip:${f.places.cafe.id}`; + for (const tagId of [theirs, tripTag, 999999]) { + expect(await refusal(tags.setForEntry(as(f.me.id), { key: cafe, tag_ids: [wine, tagId] }))).toEqual({ + status: 404, + message: 'Tag not found', + }); + } + for (const key of [`list:${f.saved.secret.id}`, `trip:${f.places.hidden.id}`, 'own:999', 'nonsense']) { + expect(await refusal(tags.setForEntry(as(f.me.id), { key, tag_ids: [wine] }))).toEqual({ + status: 404, + message: 'Place not found', + }); + } + expect(await countRows(orm, PersonalPlaceTags, {})).toBe(0); + }); +}); + +describe('PlacesLibraryService.list with tag_ids', () => { + it('PTAG-004: matches entries with any of the tags, with every other filter and in the counts', async () => { + await tags.setForEntry(as(f.me.id), { key: `trip:${f.places.cafe.id}`, tag_ids: [wine] }); + await tags.setForEntry(as(f.me.id), { key: `list:${f.saved.pantheon.id}`, tag_ids: [view] }); + + const wineOnly = await library.list(as(f.me.id), { tag_ids: [wine] }); + expect(keys(wineOnly)).toEqual([`trip:${f.places.cafe.id}`]); + expect(wineOnly.counts).toEqual({ all: 1, trip: 1, list: 1 }); + expect(wineOnly.total).toBe(1); + + const either = await library.list(as(f.me.id), { tag_ids: [wine, view] }); + expect(new Set(keys(either))).toEqual(new Set([`trip:${f.places.cafe.id}`, `list:${f.saved.pantheon.id}`])); + expect(either.counts).toEqual({ all: 2, trip: 1, list: 2 }); + + // The café's saved copy stands for the trip place's entry, so a list filter still finds it. + expect(keys(await library.list(as(f.me.id), { tag_ids: [wine], kind: 'list' }))).toEqual([ + `trip:${f.places.cafe.id}`, + ]); + expect(keys(await library.list(as(f.me.id), { tag_ids: [view], kind: 'trip' }))).toEqual([]); + expect(keys(await library.list(as(f.me.id), { tag_ids: [wine, view], q: 'panth' }))).toEqual([ + `list:${f.saved.pantheon.id}`, + ]); + expect(keys(await library.list(as(f.me.id), { tag_ids: [wine], status: 'want' }))).toEqual([ + `trip:${f.places.cafe.id}`, + ]); + const sorted = await library.list(as(f.me.id), { tag_ids: [wine, view], sort: 'updated', limit: 1 }); + expect(sorted.entries).toHaveLength(1); + expect(sorted.next_cursor).not.toBeNull(); + }); + + it('PTAG-005: a tag of someone else or of a trip matches nothing', async () => { + await tags.setForEntry(as(f.me.id), { key: `trip:${f.places.cafe.id}`, tag_ids: [wine] }); + expect(keys(await library.list(as(f.me.id), { tag_ids: [theirs, tripTag] }))).toEqual([]); + expect((await library.list(as(f.me.id), { tag_ids: [theirs] })).counts).toEqual({ all: 0, trip: 0, list: 0 }); + }); +}); + +describe('tags through linking, merging and unlinking', () => { + it('PTAG-006: a tag on a use shows on the own place it joins and comes off it everywhere', async () => { + const pantheon = `list:${f.saved.pantheon.id}`; + await tags.setForEntry(as(f.me.id), { key: pantheon, tag_ids: [view] }); + const linked = await identities.link(as(f.me.id), { + uses: [ + { kind: 'trip', id: f.places.forum.id }, + { kind: 'list', id: f.saved.pantheon.id }, + ], + }); + const own = linked.entry?.key ?? ''; + expect(own).toMatch(/^own:/); + expect(tagNames(linked.entry)).toEqual(['View']); + expect(keys(await library.list(as(f.me.id), { tag_ids: [view] }))).toEqual([own]); + + const set = await tags.setForEntry(as(f.me.id), { key: own, tag_ids: [wine] }); + expect(tagNames(set.entry)).toEqual(['Wine']); + const unlinked = await identities.unlink(as(f.me.id), { kind: 'list', id: f.saved.pantheon.id }); + expect(unlinked.entry?.key).toBe(pantheon); + expect(unlinked.entry?.tags).toEqual([]); + expect(tagNames(entryOf(await library.list(as(f.me.id), {}), own))).toEqual(['Wine']); + }); + + it('PTAG-007: the tags of an own place merged into another show on the merged entry', async () => { + const linked = await identities.link(as(f.me.id), { uses: [{ kind: 'trip', id: f.places.forum.id }] }); + const own = linked.entry?.key ?? ''; + await tags.setForEntry(as(f.me.id), { key: own, tag_ids: [wine] }); + const merged = await identities.merge(as(f.me.id), `list:${f.saved.pantheon.id}`, own); + expect(tagNames(merged.entry)).toEqual(['Wine']); + expect(keys(await library.list(as(f.me.id), { tag_ids: [wine] }))).toEqual([merged.entry?.key]); + const off = await tags.bulk(as(f.me.id), { keys: [merged.entry?.key ?? ''], remove: [wine] }); + expect(off.entries[0]?.tags).toEqual([]); + expect(await countRows(orm, PersonalPlaceTags, {})).toBe(0); + }); +}); + +describe('PlaceTagsService.bulk', () => { + it('PTAG-008: puts tags on several entries and takes others off, answering them in order', async () => { + const cafe = `trip:${f.places.cafe.id}`; + const lunch = `list:${f.saved.lunch.id}`; + await tags.setForEntry(as(f.me.id), { key: cafe, tag_ids: [view] }); + const done = await tags.bulk(as(f.me.id), { keys: [lunch, cafe, lunch], add: [wine], remove: [view] }); + expect(done.entries.map((entry) => entry.key)).toEqual([lunch, cafe]); + expect(done.entries.map(tagNames)).toEqual([['Wine'], ['Wine']]); + const again = await tags.bulk(as(f.me.id), { keys: [cafe], add: [wine] }); + expect(tagNames(again.entries[0])).toEqual(['Wine']); + expect(await countRows(orm, PersonalPlaceTags, {})).toBe(2); + }); + + it('PTAG-009: refuses the whole change for one bad key or tag, and a change that says nothing', async () => { + const cafe = `trip:${f.places.cafe.id}`; + expect(await refusal(tags.bulk(as(f.me.id), { keys: [cafe, `list:${f.saved.secret.id}`], add: [wine] }))).toEqual({ + status: 404, + message: 'Place not found', + }); + expect(await refusal(tags.bulk(as(f.me.id), { keys: [cafe, 'trip:x'], add: [wine] }))).toEqual({ + status: 404, + message: 'Place not found', + }); + expect(await refusal(tags.bulk(as(f.me.id), { keys: [cafe], add: [wine], remove: [theirs] }))).toEqual({ + status: 404, + message: 'Tag not found', + }); + expect(await refusal(tags.bulk(as(f.me.id), { keys: [cafe] }))).toEqual({ + status: 400, + message: 'Name tags to add or to remove', + }); + expect(await refusal(tags.bulk(as(f.me.id), { keys: [cafe], add: [wine], remove: [wine] }))).toEqual({ + status: 400, + message: 'A tag cannot be added and removed at once', + }); + expect(await countRows(orm, PersonalPlaceTags, {})).toBe(0); + }); + + it('PTAG-010: a deleted tag comes off every entry with it', async () => { + await tags.bulk(as(f.me.id), { + keys: [`trip:${f.places.cafe.id}`, `list:${f.saved.pantheon.id}`], + add: [wine, view], + }); + await deleteRows(orm, Tags, { id: wine }); + expect(await countRows(orm, PersonalPlaceTags, {})).toBe(2); + const page = await library.list(as(f.me.id), {}); + expect(tagNames(entryOf(page, `trip:${f.places.cafe.id}`))).toEqual(['View']); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-visits.controller.test.ts b/server/tests/unit/nest/places-library/place-visits.controller.test.ts new file mode 100644 index 000000000..5578c4125 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-visits.controller.test.ts @@ -0,0 +1,66 @@ +/** + * The visit controllers (D7/PLC-10 to PLC-23) over stub services: each route + * hands the user and its input to one service method and answers what it + * returns. Every route reads; none writes. Guards, pipes and the response + * contracts run in the e2e suite. + */ +import type { TripAccess } from '../../../../src/db/repositories/Trips.repository'; +import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract'; +import { PlaceMediaController } from '../../../../src/nest/places-library/place-media.controller'; +import type { PlaceMediaService } from '../../../../src/nest/places-library/place-media.service'; +import { PlaceVisitsTripController } from '../../../../src/nest/places-library/place-visits-trip.controller'; +import { PlaceVisitsController } from '../../../../src/nest/places-library/place-visits.controller'; +import type { PlaceVisitsService } from '../../../../src/nest/places-library/place-visits.service'; +import type { User } from '../../../../src/types'; +import { + placeMediaResponseSchema, + placeVisitsForPlaceResponseSchema, + placeVisitsListResponseSchema, + placeVisitTripVisitedResponseSchema, +} from '@trek/shared'; + +import { describe, expect, it, vi } from 'vitest'; + +const user = { id: 7, role: 'user', username: 'ann', email: 'ann@example.test' } as User; +const me = { id: 7, role: 'user' }; +const trip = { id: 4, user_id: 7 } as TripAccess; +const contract = (handler: unknown) => Reflect.getMetadata(RESPONSE_CONTRACT_KEY, handler as object) as unknown; + +/** The route handlers a controller class declares. */ +const handlers = (proto: object) => Object.getOwnPropertyNames(proto).filter((name) => name !== 'constructor'); + +describe('place visit controllers', () => { + it('PVC-001: every route reaches its service method with the user and the input', async () => { + const service = { + list: vi.fn().mockResolvedValue({ visits: [], total: 0 }), + forPlace: vi.fn().mockResolvedValue({ visits: [], visit_count: 0, last_visit: null }), + tripVisited: vi.fn().mockResolvedValue({ place_ids: [], places: [] }), + }; + const c = new PlaceVisitsController(service as unknown as PlaceVisitsService); + expect(await c.list(user, { trip_id: 4 })).toEqual({ visits: [], total: 0 }); + await c.forPlace(user, { kind: 'list', id: 9 }); + expect(service.list).toHaveBeenCalledWith(me, { trip_id: 4 }); + expect(service.forPlace).toHaveBeenCalledWith(me, 'list', 9); + + const tc = new PlaceVisitsTripController(service as unknown as PlaceVisitsService); + await tc.mine(user, trip); + expect(service.tripVisited).toHaveBeenCalledWith(4, me); + + const mediaService = { media: vi.fn().mockResolvedValue({ images: [], journey_photos: [], files: [] }) }; + const mc = new PlaceMediaController(mediaService as unknown as PlaceMediaService); + await mc.tripPlace(user, 3); + await mc.savedPlace(user, 9); + expect(mediaService.media).toHaveBeenNthCalledWith(1, me, 'trip', 3); + expect(mediaService.media).toHaveBeenNthCalledWith(2, me, 'list', 9); + }); + + it('PVC-002: only reads are left, each with its shared response contract', () => { + expect(handlers(PlaceVisitsController.prototype).sort()).toEqual(['forPlace', 'list']); + expect(handlers(PlaceVisitsTripController.prototype)).toEqual(['mine']); + expect(contract(PlaceVisitsController.prototype.list)).toBe(placeVisitsListResponseSchema); + expect(contract(PlaceVisitsController.prototype.forPlace)).toBe(placeVisitsForPlaceResponseSchema); + expect(contract(PlaceVisitsTripController.prototype.mine)).toBe(placeVisitTripVisitedResponseSchema); + expect(contract(PlaceMediaController.prototype.tripPlace)).toBe(placeMediaResponseSchema); + expect(contract(PlaceMediaController.prototype.savedPlace)).toBe(placeMediaResponseSchema); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-visits.helpers.test.ts b/server/tests/unit/nest/places-library/place-visits.helpers.test.ts new file mode 100644 index 000000000..d626da57d --- /dev/null +++ b/server/tests/unit/nest/places-library/place-visits.helpers.test.ts @@ -0,0 +1,150 @@ +/** + * The pure halves of the visits read from the trips (D7): one visit per place + * and day however many stops name it, the earliest time of that day, newest + * first, the visits of an entry of All places, the counts, and who a visit + * counts for. + */ +import type { PlannedVisitRow } from '../../../../src/db/repositories/PlaceVisitContext.repository'; +import { + collapseVisits, + participantsOf, + summaryOf, + uniqueIds, + uniquePeople, + visitsOfEntry, + wireVisit, +} from '../../../../src/nest/places-library/place-visits.helpers'; +import type { EntryRows } from '../../../../src/nest/places-library/places-library.helpers'; + +import { describe, expect, it } from 'vitest'; + +function row(assignmentId: number, fields: Partial = {}): PlannedVisitRow { + return { + assignment_id: assignmentId, + place_id: 3, + name: 'Café', + trip_id: 1, + trip_title: 'Alps', + day_id: 10, + day_number: 1, + date: '2026-07-01', + order_index: assignmentId, + assignment_time: null, + place_time: null, + ...fields, + }; +} + +const byPlace = (r: PlannedVisitRow) => `p${r.place_id}`; + +describe('collapseVisits', () => { + it('PVH-001: several stops of a place on one trip day are one visit at the earliest time set', () => { + const [visit, ...rest] = collapseVisits( + [ + row(1, { assignment_time: '11:00' }), + row(2, { place_time: '08:15' }), + row(3, { assignment_time: '09:00', place_time: '07:00' }), + ], + byPlace, + ); + expect(rest).toEqual([]); + expect(visit).toMatchObject({ visited_on: '2026-07-01', visited_time: '08:15', assignment_ids: [1, 2, 3] }); + }); + + it('PVH-002: the same day on two trips is one visit, read from the first trip; other days and places stay apart', () => { + const visits = collapseVisits( + [ + row(5, { trip_id: 2, day_id: 20, trip_title: 'Copy' }), + row(1), + row(2, { date: '2026-06-30', day_id: 9 }), + row(3, { place_id: 4, assignment_time: '10:00' }), + ], + byPlace, + ); + expect(visits.map((v) => [v.visited_on, v.place_id, v.trip_id, v.assignment_ids])).toEqual([ + ['2026-07-01', 4, 1, [3]], + ['2026-07-01', 3, 1, [1]], + ['2026-06-30', 3, 1, [2]], + ]); + }); + + it('PVH-003: newest first: by day, then a timed visit before one without, then the later time first', () => { + const visits = collapseVisits( + [ + row(1, { place_id: 1 }), + row(2, { place_id: 2, assignment_time: '09:00' }), + row(3, { place_id: 3, assignment_time: '18:00' }), + row(4, { place_id: 4, date: '2026-07-02' }), + ], + byPlace, + ); + expect(visits.map((v) => v.place_id)).toEqual([4, 3, 2, 1]); + expect(collapseVisits([], byPlace)).toEqual([]); + }); +}); + +describe('visitsOfEntry and summaryOf', () => { + const entry = { + anchor: 1, + identity: null, + trips: [{ id: 3 }, { id: 5 }], + saved: [], + linked: new Set(), + } as unknown as EntryRows; + + it('PVH-010: an entry holds the visits at its trip places, one per day across them', () => { + const visits = visitsOfEntry(entry, [ + row(1), + row(2, { place_id: 5, trip_id: 2, day_id: 20 }), + row(3, { place_id: 7 }), + ]); + expect(visits).toHaveLength(1); + expect(summaryOf(visits)).toEqual({ visit_count: 1, last_visit: '2026-07-01' }); + expect(summaryOf([])).toEqual({ visit_count: 0, last_visit: null }); + const two = visitsOfEntry(entry, [row(1), row(2, { place_id: 5, date: '2026-07-03', day_id: 11 })]); + expect(summaryOf(two)).toEqual({ visit_count: 2, last_visit: '2026-07-03' }); + }); +}); + +describe('participantsOf and wireVisit', () => { + const ana = { id: 1, username: 'ana', avatar: null }; + const ben = { id: 2, username: 'ben', avatar: 'ben.png' }; + const cleo = { id: 3, username: 'cleo', avatar: 'https://example.test/c.png' }; + + it('PVH-020: the people the stops name, or everyone on the trip for a stop naming no one, each once', () => { + const [visit] = collapseVisits([row(1), row(2)], byPlace); + if (!visit) throw new Error('one visit'); + const named = new Map([[1, [ben]]]); + const roster = new Map([[1, [ana, ben, cleo]]]); + expect(participantsOf(visit, named, roster).map((p) => p.id)).toEqual([2, 1, 3]); + expect( + participantsOf( + visit, + new Map([ + [1, [ben]], + [2, [cleo]], + ]), + roster, + ), + ).toEqual([ + { id: 2, username: 'ben', avatar_url: '/uploads/avatars/ben.png' }, + { id: 3, username: 'cleo', avatar_url: 'https://example.test/c.png' }, + ]); + expect(participantsOf(visit, new Map(), new Map())).toEqual([]); + expect(wireVisit(visit, [])).toEqual({ + visited_on: '2026-07-01', + visited_time: null, + trip: { id: 1, title: 'Alps' }, + place_id: 3, + day_id: 10, + day_number: 1, + name: 'Café', + participants: [], + }); + }); + + it('PVH-021: ids and people once each, in first order', () => { + expect(uniqueIds([3, 1, 3, 2, 1])).toEqual([3, 1, 2]); + expect(uniquePeople([ana, ben, ana]).map((p) => p.id)).toEqual([1, 2]); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-visits.mcp.test.ts b/server/tests/unit/nest/places-library/place-visits.mcp.test.ts new file mode 100644 index 000000000..5441fd460 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-visits.mcp.test.ts @@ -0,0 +1,112 @@ +/** + * PlaceVisitsMcp (D7/PLC-10 to PLC-23): the read-only visit tools over the + * same services and checks as REST, with the scopes and the addon gate they + * need. Taken from the container over a snapshot db, the visit clock pinned + * on the second day of the fixture's trip Alps. + */ +import { TripMembers } from '../../../../src/db/entities/TripMembers.entity'; +import type { McpContext } from '../../../../src/nest-mcp'; +import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata'; +import { AddonsService } from '../../../../src/nest/addons/addons.service'; +import { PlaceVisitsClock } from '../../../../src/nest/places-library/place-visits.clock'; +import { PlaceVisitsMcp } from '../../../../src/nest/places-library/place-visits.mcp'; +import { PlaceVisitsModule } from '../../../../src/nest/places-library/place-visits.module'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { makeDayAssignment } from '../../../helpers/factories/itinerary'; +import { deleteRows } from '../../../helpers/factories/rows'; +import { makeDay } from '../../../helpers/factories/trips'; +import { seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let mcp: PlaceVisitsMcp; +let f: LibraryFixture; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [PlaceVisitsModule] }); + mcp = t.get(PlaceVisitsMcp); + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + vi.restoreAllMocks(); + vi.spyOn(t.get(PlaceVisitsClock), 'today').mockReturnValue('2026-07-02'); + f = await seedLibrary(orm); +}); +afterAll(async () => { + await orm.close(); + await t.close(); + db.close(); +}); + +const ctx = (userId: number) => ({ userId }) as McpContext; + +function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) { + return JSON.parse(result.content[0]?.text ?? ''); +} + +const options = (owner: unknown, name: string) => { + const entry = getEntry(owner as ClassRef, name); + if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`); + return entry.options; +}; + +describe('PlaceVisitsMcp', () => { + it('PV-MCP-001: lists the visits, the history of a place and the trip places visited, as REST does', async () => { + const day = await makeDay(orm, f.rome.id, { date: '2026-06-01' }); + await makeDayAssignment(orm, day.id, f.places.forum.id); + + const listed = read(await mcp.listPlaceVisits({}, ctx(f.me.id))); + expect(listed.total).toBe(2); + expect(listed.visits[0]).toMatchObject({ visited_on: '2026-07-01', place_id: f.places.cafe.id }); + expect(read(await mcp.listPlaceVisits({ trip_id: f.rome.id }, ctx(f.me.id))).total).toBe(1); + expect(read(await mcp.getPlaceVisitHistory({ kind: 'trip', id: f.places.cafe.id }, ctx(f.me.id)))).toMatchObject({ + visit_count: 1, + last_visit: '2026-07-01', + }); + expect(read(await mcp.listMyVisitedTripPlaces({ tripId: f.alps.id }, ctx(f.me.id))).place_ids).toEqual([ + f.places.cafe.id, + ]); + expect(read(await mcp.getLibraryPlaceMedia({ kind: 'trip', id: f.places.cafe.id }, ctx(f.me.id)))).toMatchObject({ + journey_photos: [], + }); + }); + + it('PV-MCP-002: the same rights as REST: a trip out of reach is not found, a trip left counts no more', async () => { + await expect(mcp.listMyVisitedTripPlaces({ tripId: f.elsewhere.id }, ctx(f.me.id))).rejects.toThrow( + 'Trip not found', + ); + await expect(mcp.getPlaceVisitHistory({ kind: 'trip', id: f.places.hidden.id }, ctx(f.me.id))).rejects.toThrow( + 'Place not found', + ); + const day = await makeDay(orm, f.rome.id, { date: '2026-06-01' }); + await makeDayAssignment(orm, day.id, f.places.forum.id); + await deleteRows(orm, TripMembers, { trip: f.rome.id, user: f.me.id }); + expect(read(await mcp.listPlaceVisits({ trip_id: f.rome.id }, ctx(f.me.id))).total).toBe(0); + }); + + it('PV-MCP-003: every tool reads; the media tool follows the Collections addon', async () => { + const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false); + expect(await options(PlaceVisitsMcp, 'getLibraryPlaceMedia').when?.(ctx(1), mcp)).toBe(false); + enabled.mockResolvedValue(true); + expect(await options(PlaceVisitsMcp, 'getLibraryPlaceMedia').when?.(ctx(1), mcp)).toBe(true); + for (const name of ['listPlaceVisits', 'getPlaceVisitHistory', 'listMyVisitedTripPlaces']) { + expect(options(PlaceVisitsMcp, name).access).toEqual({ group: 'places', mode: 'read' }); + expect(options(PlaceVisitsMcp, name).annotations).toMatchObject({ readOnlyHint: true }); + } + expect(options(PlaceVisitsMcp, 'getLibraryPlaceMedia').access).toEqual({ group: 'collections', mode: 'read' }); + const tools = Object.getOwnPropertyNames(PlaceVisitsMcp.prototype).filter( + (name) => getEntry(PlaceVisitsMcp as unknown as ClassRef, name)?.kind === 'tool', + ); + expect(tools.sort()).toEqual( + ['getLibraryPlaceMedia', 'getPlaceVisitHistory', 'listMyVisitedTripPlaces', 'listPlaceVisits'].sort(), + ); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-visits.service.test.ts b/server/tests/unit/nest/places-library/place-visits.service.test.ts new file mode 100644 index 000000000..feb784446 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-visits.service.test.ts @@ -0,0 +1,283 @@ +/** + * PlaceVisitsService and the visit counts of All places (D7/PLC-10, PLC-23) + * over the real repositories on a migrated test db. A visit is never entered: + * it is read from the day plans of the trips the reader reaches, up to the + * day the clock names (pinned here). Past, today, coming and undated days, + * the stop's participants, several stops on one day, a place grouped across + * trips, losing access, the counts, the trip's visited places and the list. + */ +import { AssignmentParticipants } from '../../../../src/db/entities/AssignmentParticipants.entity'; +import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity'; +import { Places } from '../../../../src/db/entities/Places.entity'; +import { TripMembers } from '../../../../src/db/entities/TripMembers.entity'; +import { DomainError } from '../../../../src/nest/common/domain-error'; +import { PlaceMediaService } from '../../../../src/nest/places-library/place-media.service'; +import { PlaceVisitsClock } from '../../../../src/nest/places-library/place-visits.clock'; +import { PlaceVisitsModule } from '../../../../src/nest/places-library/place-visits.module'; +import { PlaceVisitsService } from '../../../../src/nest/places-library/place-visits.service'; +import { PlacesLibraryService, type LibraryUser } from '../../../../src/nest/places-library/places-library.service'; +import { createSnapshotTestDb } from '../../../helpers/db-mock'; +import { linkFile, makeTripFile } from '../../../helpers/factories/files'; +import { makeDayAssignment } from '../../../helpers/factories/itinerary'; +import { makePlace } from '../../../helpers/factories/places'; +import { createRow, deleteRows, updateRows } from '../../../helpers/factories/rows'; +import { setAddonEnabled } from '../../../helpers/factories/settings'; +import { addTripMember, makeDay, makeTrip, readTripDays } from '../../../helpers/factories/trips'; +import { linkUserPlace, makeUserPlace } from '../../../helpers/factories/user-places'; +import { makeUser } from '../../../helpers/factories/users'; +import { seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture'; +import { resetTestDb } from '../../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../../helpers/test-module'; +import { createTestOrm, type TestOrm } from '../../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let visits: PlaceVisitsService; +let library: PlacesLibraryService; +let f: LibraryFixture; + +/** Alps runs 2026-07-01 to 2026-07-03; the clock stands on its second day. */ +const TODAY = '2026-07-02'; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [PlaceVisitsModule] }); + visits = t.get(PlaceVisitsService); + library = t.get(PlacesLibraryService); + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + vi.restoreAllMocks(); + vi.spyOn(t.get(PlaceVisitsClock), 'today').mockReturnValue(TODAY); + f = await seedLibrary(orm); +}); +afterAll(async () => { + await orm.close(); + await t.close(); + db.close(); +}); + +const as = (id: number): LibraryUser => ({ id, role: 'user' }); + +async function alpsDays() { + const [day1, day2, day3] = await readTripDays(orm, f.alps.id); + if (!day1 || !day2 || !day3) throw new Error('Alps has three days'); + return { day1, day2, day3 }; +} + +async function refusal(promise: Promise): Promise<{ status: number; message: string }> { + try { + await promise; + } catch (err) { + expect(err).toBeInstanceOf(DomainError); + const error = err as DomainError; + return { status: error.getStatus(), message: error.publicMessage }; + } + throw new Error('expected a refusal'); +} + +async function entryOf(userId: number, key: string) { + return (await library.list(as(userId), { limit: 200 })).entries.find((entry) => entry.key === key); +} + +describe('PlaceVisitsService.forPlace', () => { + it('PVSVC-001: a past and a present dated day count, a coming day and an undated day do not', async () => { + const { day2, day3 } = await alpsDays(); + await makeDayAssignment(orm, day2.id, f.places.museum.id); + await makeDayAssignment(orm, day3.id, f.places.hotel.id); + const undated = await makeDay(orm, f.alps.id, { date: null }); + await makeDayAssignment(orm, undated.id, f.places.hotel.id); + + const cafe = await visits.forPlace(as(f.me.id), 'trip', f.places.cafe.id); + expect(cafe).toEqual({ + visits: [ + { + visited_on: '2026-07-01', + visited_time: '09:00', + trip: { id: f.alps.id, title: 'Alps' }, + place_id: f.places.cafe.id, + day_id: f.day1.id, + day_number: 1, + name: 'Café Central', + participants: [expect.objectContaining({ id: f.me.id, username: f.me.username })], + }, + ], + visit_count: 1, + last_visit: '2026-07-01', + }); + expect((await visits.forPlace(as(f.me.id), 'trip', f.places.museum.id)).last_visit).toBe(TODAY); + expect(await visits.forPlace(as(f.me.id), 'trip', f.places.hotel.id)).toEqual({ + visits: [], + visit_count: 0, + last_visit: null, + }); + }); + + it('PVSVC-002: a stop with participants counts only for them; one without counts for everyone with an account', async () => { + await addTripMember(orm, f.alps.id, f.friend.id); + const { day2 } = await alpsDays(); + const museum = await makeDayAssignment(orm, day2.id, f.places.museum.id); + await createRow(orm, AssignmentParticipants, { assignment: museum.id, user: f.friend.id }); + + expect((await visits.forPlace(as(f.me.id), 'trip', f.places.museum.id)).visit_count).toBe(0); + const forFriend = await visits.forPlace(as(f.friend.id), 'trip', f.places.museum.id); + expect(forFriend.visit_count).toBe(1); + expect(forFriend.visits[0]?.participants.map((p) => p.id)).toEqual([f.friend.id]); + + const cafe = await visits.forPlace(as(f.friend.id), 'trip', f.places.cafe.id); + expect(cafe.visits[0]?.participants.map((p) => p.id)).toEqual([f.me.id, f.friend.id]); + }); + + it('PVSVC-003: several stops of a place on one day are one visit, at the earliest time', async () => { + await makeDayAssignment(orm, f.day1.id, f.places.cafe.id, { assignment_time: '07:30' }); + await makeDayAssignment(orm, f.day1.id, f.places.cafe.id); + const cafe = await visits.forPlace(as(f.me.id), 'trip', f.places.cafe.id); + expect(cafe.visit_count).toBe(1); + expect(cafe.visits[0]?.visited_time).toBe('07:30'); + }); + + it('PVSVC-004: a saved place grouped with the trip place reads the same visits; a list alone gives none', async () => { + expect((await visits.forPlace(as(f.me.id), 'list', f.saved.savedCafe.id)).visit_count).toBe(1); + expect((await visits.forPlace(as(f.me.id), 'list', f.saved.pantheon.id)).visit_count).toBe(0); + expect(await refusal(visits.forPlace(as(f.me.id), 'trip', f.places.hidden.id))).toEqual({ + status: 404, + message: 'Place not found', + }); + }); + + it('PVSVC-005: an own place gathering trip places of two trips counts each day once', async () => { + const again = await makeTrip(orm, f.me.id, { title: 'Alps again' }); + const sameDay = await makeDay(orm, again.id, { date: '2026-07-01' }); + const laterDay = await makeDay(orm, again.id, { date: '2026-06-20' }); + const copy = await makePlace(orm, again.id, { name: 'Café Central (copy)' }); + await makeDayAssignment(orm, sameDay.id, copy.id); + const own = await makeUserPlace(orm, f.me.id, { name: 'My café' }); + await linkUserPlace(orm, f.me.id, own.id, { place: f.places.cafe.id }); + await linkUserPlace(orm, f.me.id, own.id, { place: copy.id }); + + let history = await visits.forPlace(as(f.me.id), 'trip', copy.id); + expect(history.visit_count).toBe(1); + expect(history.visits[0]?.trip.id).toBe(Math.min(f.alps.id, again.id)); + + await makeDayAssignment(orm, laterDay.id, copy.id); + history = await visits.forPlace(as(f.me.id), 'trip', f.places.cafe.id); + expect(history.visits.map((v) => v.visited_on)).toEqual(['2026-07-01', '2026-06-20']); + expect(await entryOf(f.me.id, `own:${own.id}`)).toMatchObject({ visit_count: 2, last_visit: '2026-07-01' }); + }); + + it('PVSVC-006: losing access to a trip takes its visits with it', async () => { + const day = await makeDay(orm, f.rome.id, { date: '2026-06-01' }); + await makeDayAssignment(orm, day.id, f.places.forum.id); + expect((await visits.forPlace(as(f.me.id), 'trip', f.places.forum.id)).visit_count).toBe(1); + expect((await visits.list(as(f.me.id), {})).total).toBe(2); + + await deleteRows(orm, TripMembers, { trip: f.rome.id, user: f.me.id }); + expect(await refusal(visits.forPlace(as(f.me.id), 'trip', f.places.forum.id))).toMatchObject({ status: 404 }); + expect((await visits.list(as(f.me.id), {})).total).toBe(1); + expect((await visits.forPlace(as(f.friend.id), 'trip', f.places.forum.id)).visit_count).toBe(1); + }); +}); + +describe('visit counts of All places', () => { + it('PVSVC-010: every entry carries its visit count and latest visit, read per reader', async () => { + const { day2 } = await alpsDays(); + await makeDayAssignment(orm, day2.id, f.places.cafe.id); + expect(await entryOf(f.me.id, `trip:${f.places.cafe.id}`)).toMatchObject({ + visit_count: 2, + last_visit: TODAY, + }); + expect(await entryOf(f.me.id, `trip:${f.places.hotel.id}`)).toMatchObject({ visit_count: 0, last_visit: null }); + const detail = await library.detail(as(f.me.id), 'list', f.saved.savedCafe.id); + expect(detail.entry).toMatchObject({ visit_count: 2, last_visit: TODAY }); + }); + + it('PVSVC-011: the clock decides what has come: the day before the trip nothing counts', async () => { + vi.spyOn(t.get(PlaceVisitsClock), 'today').mockReturnValue('2026-06-30'); + expect(await entryOf(f.me.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 0, last_visit: null }); + }); +}); + +describe('PlaceVisitsService.tripVisited', () => { + it('PVSVC-020: names the trip places visited there or at the same place on another trip', async () => { + expect(await visits.tripVisited(f.alps.id, as(f.me.id))).toEqual({ + place_ids: [f.places.cafe.id], + places: [{ place_id: f.places.cafe.id, visit_count: 1, last_visit: '2026-07-01' }], + }); + + const next = await makeTrip(orm, f.me.id, { title: 'Next year' }); + const copy = await makePlace(orm, next.id, { name: 'Café again' }); + const own = await makeUserPlace(orm, f.me.id); + await linkUserPlace(orm, f.me.id, own.id, { place: f.places.cafe.id }); + await linkUserPlace(orm, f.me.id, own.id, { place: copy.id }); + expect((await visits.tripVisited(next.id, as(f.me.id))).place_ids).toEqual([copy.id]); + }); + + it('PVSVC-021: empty for a trip without places or visits, not found for a trip out of reach', async () => { + const empty = await makeTrip(orm, f.me.id, { title: 'Empty' }); + expect(await visits.tripVisited(empty.id, as(f.me.id))).toEqual({ place_ids: [], places: [] }); + expect(await visits.tripVisited(f.rome.id, as(f.me.id))).toEqual({ place_ids: [], places: [] }); + expect(await refusal(visits.tripVisited(f.elsewhere.id, as(f.me.id)))).toMatchObject({ status: 404 }); + }); +}); + +describe('PlaceVisitsService.list', () => { + it('PVSVC-030: the reader’s visits newest first, paged, of one trip or of all', async () => { + const { day2 } = await alpsDays(); + await makeDayAssignment(orm, day2.id, f.places.museum.id, { assignment_time: '10:00' }); + await makeDayAssignment(orm, day2.id, f.places.hotel.id); + const all = await visits.list(as(f.me.id), {}); + expect(all.total).toBe(3); + expect(all.visits.map((v) => [v.visited_on, v.place_id])).toEqual([ + [TODAY, f.places.museum.id], + [TODAY, f.places.hotel.id], + ['2026-07-01', f.places.cafe.id], + ]); + const page = await visits.list(as(f.me.id), { limit: 1, offset: 1 }); + expect(page).toMatchObject({ total: 3, visits: [{ place_id: f.places.hotel.id }] }); + expect((await visits.list(as(f.me.id), { trip_id: f.rome.id })).total).toBe(0); + expect((await visits.list(as(f.me.id), { trip_id: f.elsewhere.id })).total).toBe(0); + }); + + it('PVSVC-031: another reader sees only their own trips', async () => { + const { user: other } = await makeUser(orm); + expect(await visits.list(as(other.id), {})).toEqual({ visits: [], total: 0 }); + }); +}); + +describe('PlaceMediaService', () => { + it('PVSVC-040: the pictures of the entry and the trip files of its trip places, without any visit link', async () => { + const media = t.get(PlaceMediaService); + await updateRows(orm, Places, { id: f.places.cafe.id }, { image_url: '/uploads/places/cafe.jpg' }); + await updateRows(orm, CollectionPlaces, { id: f.saved.savedCafe.id }, { image_url: '/uploads/places/saved.jpg' }); + const linked = await makeTripFile(orm, f.alps.id, { original_name: 'Menu.pdf' }); + await linkFile(orm, linked.id, { place: f.places.cafe.id }); + const own = await makeTripFile(orm, f.alps.id, { original_name: 'Voucher.pdf', place: f.places.cafe.id }); + await makeTripFile(orm, f.alps.id, { + original_name: 'Gone.pdf', + place: f.places.cafe.id, + deleted_at: '2026-07-01 10:00:00', + }); + + await setAddonEnabled(orm, 'documents', true); + await setAddonEnabled(orm, 'journey', true); + const shown = await media.media(as(f.me.id), 'list', f.saved.savedCafe.id); + expect(shown.images.map((image) => image.image_url).sort()).toEqual([ + '/uploads/places/cafe.jpg', + '/uploads/places/saved.jpg', + ]); + expect(shown.journey_photos).toEqual([]); + expect(shown.files.map((file) => [file.file_id, file.original_name, file.url])).toEqual([ + [linked.id, 'Menu.pdf', `/api/trips/${f.alps.id}/files/${linked.id}/download`], + [own.id, 'Voucher.pdf', `/api/trips/${f.alps.id}/files/${own.id}/download`], + ]); + for (const file of shown.files) expect(file).not.toHaveProperty('visit_ids'); + + await setAddonEnabled(orm, 'documents', false); + expect((await media.media(as(f.me.id), 'trip', f.places.cafe.id)).files).toEqual([]); + await expect(media.media(as(f.me.id), 'trip', f.places.hidden.id)).rejects.toThrow('Place not found'); + }); +}); diff --git a/server/tests/unit/nest/places-library/places-library.service.test.ts b/server/tests/unit/nest/places-library/places-library.service.test.ts index 5daea637d..6da8c2928 100644 --- a/server/tests/unit/nest/places-library/places-library.service.test.ts +++ b/server/tests/unit/nest/places-library/places-library.service.test.ts @@ -95,7 +95,7 @@ describe('PlacesLibraryService.list', () => { lng: 16.3655, }); expect(cafe.origins).toEqual([ - { + expect.objectContaining({ kind: 'trip', trip_id: f.alps.id, trip_title: 'Alps', @@ -105,8 +105,9 @@ describe('PlacesLibraryService.list', () => { can_edit: true, read_only: false, linked: false, - }, - { + trip_cover: null, + }), + expect.objectContaining({ kind: 'list', collection_id: f.lists.food.id, collection_name: 'Food', @@ -114,8 +115,10 @@ describe('PlacesLibraryService.list', () => { status: 'want', can_edit: true, linked: false, - }, + }), ]); + // A list origin carries the list's own colour and symbol for its card. + expect(cafe.origins[1]).toHaveProperty('collection_icon'); // The provider id alone is enough, whatever the copy is called. expect(entry(page, `trip:${f.places.museum.id}`).origins.map((origin) => origin.kind)).toEqual(['trip', 'list']); // A renamed copy, one with another provider id, one without a source and one from a trip out of reach stay apart. diff --git a/server/tests/unit/nest/places.directions.test.ts b/server/tests/unit/nest/places.directions.test.ts index 8dbfdaab1..b653fc1ed 100644 --- a/server/tests/unit/nest/places.directions.test.ts +++ b/server/tests/unit/nest/places.directions.test.ts @@ -32,6 +32,7 @@ import { createTestJourneyPhotosRepo, createTestJourneyEntryPhotosRepo, } from '../../helpers/journey-repos'; +import { passThroughPlaceChanges } from '../../helpers/place-changes'; import { buildPlaceImportService } from '../../helpers/place-import'; import { makeStorageFixture } from '../../helpers/storage-fixture'; import { @@ -152,6 +153,7 @@ async function svc(searchNominatim: OsmClient['searchNominatim']): Promise [] } as never, // StorageReleaseService buildPlaceImportService(), + passThroughPlaceChanges(), ); } diff --git a/server/tests/unit/nest/places.service.test.ts b/server/tests/unit/nest/places.service.test.ts index cb02192a4..a96376d90 100644 --- a/server/tests/unit/nest/places.service.test.ts +++ b/server/tests/unit/nest/places.service.test.ts @@ -91,6 +91,7 @@ import { import type { AppSettingsRepository } from '../../../src/db/repositories/AppSettings.repository'; import type { UsersRepository } from '../../../src/db/repositories/Users.repository'; import { isUpdateConflict, type UpdateConflict } from '../../../src/nest/common/conflictResult'; +import { passThroughPlaceChanges } from '../../helpers/place-changes'; /** * Narrows `PlacesService.update`'s `PlaceWithTags | UpdateConflict | null` @@ -157,8 +158,7 @@ async function makePlacesService( await createTestCategoriesRepo(testDb), await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), - placesRelease, - buildPlaceImportService(), + placesRelease, buildPlaceImportService(), passThroughPlaceChanges(), ); } diff --git a/server/tests/unit/nest/tag-writes.service.test.ts b/server/tests/unit/nest/tag-writes.service.test.ts new file mode 100644 index 000000000..fd02e3b95 --- /dev/null +++ b/server/tests/unit/nest/tag-writes.service.test.ts @@ -0,0 +1,71 @@ +/** + * TagWritesService and TagsService.ensure (PLC-21): a name stands once per + * person, so a create of a name the user has already answers that tag as it + * is and tells no tab, while a new tag is announced as before. From the + * container over a snapshot db; broadcasts go to the FakeRealtimeService. + */ +import { Tags } from '../../../src/db/entities/Tags.entity'; +import { TagWritesService } from '../../../src/nest/tags/tag-writes.service'; +import { TagsModule } from '../../../src/nest/tags/tags.module'; +import { TagsService } from '../../../src/nest/tags/tags.service'; +import { createSnapshotTestDb } from '../../helpers/db-mock'; +import { countRows } from '../../helpers/factories/rows'; +import { makeUser } from '../../helpers/factories/users'; +import { resetTestDb } from '../../helpers/test-db'; +import { createTestModule, type TestModule } from '../../helpers/test-module'; +import { createTestOrm, type TestOrm } from '../../helpers/test-orm'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let writes: TagWritesService; +let tags: TagsService; + +beforeAll(async () => { + t = await createTestModule({ db, imports: [TagsModule] }); + writes = t.get(TagWritesService); + tags = t.get(TagsService); + orm = await createTestOrm(db); +}); +beforeEach(() => { + resetTestDb(db); + orm.clear(); + t.realtime.reset(); +}); +afterAll(async () => { + await orm.close(); + await t.close(); + db.close(); +}); + +describe('TagWritesService.create', () => { + it('TAGW-001: a new name makes a tag and tells the other tabs', async () => { + const { user } = await makeUser(orm); + const tag = await writes.create(user.id, 'Wine', '#aa0000', 'sock-1'); + expect(tag).toMatchObject({ user_id: user.id, name: 'Wine', color: '#aa0000' }); + expect(t.realtime.broadcastToUserMock).toHaveBeenCalledWith(user.id, { type: 'tags:changed' }, 'sock-1'); + }); + + it('TAGW-002: a name the user has already answers that tag unchanged and sends nothing', async () => { + const { user } = await makeUser(orm); + const first = await writes.create(user.id, 'Wine', '#aa0000', undefined); + t.realtime.reset(); + const again = await writes.create(user.id, ' wINE ', '#00aa00', 'sock-1'); + expect(again).toMatchObject({ id: first.id, name: 'Wine', color: '#aa0000' }); + expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled(); + expect(await countRows(orm, Tags, { user: user.id })).toBe(1); + }); +}); + +describe('TagsService.ensure', () => { + it('TAGW-003: says whether the tag is new, per person', async () => { + const { user } = await makeUser(orm); + const { user: other } = await makeUser(orm); + const made = await tags.ensure(user.id, 'View'); + expect(made.created).toBe(true); + expect(await tags.ensure(user.id, 'view')).toEqual({ tag: made.tag, created: false }); + expect((await tags.ensure(other.id, 'View')).created).toBe(true); + }); +}); diff --git a/server/tests/unit/nest/tags.service.test.ts b/server/tests/unit/nest/tags.service.test.ts index cba2909c3..d68873e29 100644 --- a/server/tests/unit/nest/tags.service.test.ts +++ b/server/tests/unit/nest/tags.service.test.ts @@ -1,7 +1,7 @@ /** * Unit tests for TagsService — TAG-SVC-001 through TAG-SVC-015. * Uses a real in-memory SQLite DB so SQL logic is exercised faithfully. The - * service is constructed directly (new TagsService(repo)) over a + * service is constructed directly (new TagsService(repo, uow)) over a * TagsRepository resolved from the suite's own ORM (Plan 3a Task 3; * `createTestTagsRepo`/`sharedTestOrm` from tests/helpers/test-uow.ts, same * pattern as audit.service.test.ts) — no Nest container needed. @@ -13,7 +13,7 @@ import { createSnapshotTestDb } from '../../helpers/db-mock'; import { createUser } from '../../helpers/factories'; import { resetTestDb } from '../../helpers/test-db'; import type { TestOrm } from '../../helpers/test-orm'; -import { createTestTagsRepo, sharedTestOrm } from '../../helpers/test-uow'; +import { createTestTagsRepo, createTestUnitOfWork, sharedTestOrm } from '../../helpers/test-uow'; import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'; @@ -26,7 +26,7 @@ let svc: TagsService; beforeAll(async () => { t = await sharedTestOrm(testDb); - svc = new TagsService(await createTestTagsRepo(testDb)); + svc = new TagsService(await createTestTagsRepo(testDb), await createTestUnitOfWork(testDb)); }); beforeEach(() => { @@ -186,3 +186,30 @@ describe('remove', () => { expect(await svc.getByIdAndUser(tag.id, user.id)).toBeDefined(); }); }); + +// ── one name per person (PLC-21) ───────────────────────────────────────────── + +describe('names', () => { + it('TAG-SVC-021 — creating a name the user has already, whatever its case, answers that tag', async () => { + const { user } = createUser(testDb); + const { user: other } = createUser(testDb); + const first = await svc.create(user.id, 'Wine', '#aa0000'); + const again = await svc.create(user.id, ' wINE ', '#00aa00'); + expect(again.id).toBe(first.id); + expect(again.color).toBe('#aa0000'); + expect((await svc.create(other.id, 'Wine')).id).not.toBe(first.id); + expect(await svc.list(user.id)).toHaveLength(1); + }); + + it('TAG-SVC-022 — renaming onto another of the user’s names is refused; a new case of its own is not', async () => { + const { user } = createUser(testDb); + const wine = await svc.create(user.id, 'Wine'); + const view = await svc.create(user.id, 'View'); + await expect(svc.update(view.id, 'WINE', undefined)).rejects.toMatchObject({ + publicMessage: 'A tag with this name already exists', + }); + expect((await svc.getByIdAndUser(view.id, user.id))?.name).toBe('View'); + expect((await svc.update(wine.id, 'wine', undefined)).name).toBe('wine'); + expect((await svc.update(view.id, undefined, '#123456')).color).toBe('#123456'); + }); +}); diff --git a/server/tests/unit/nest/tours.gpx.atomic.test.ts b/server/tests/unit/nest/tours.gpx.atomic.test.ts index bd146dd48..a3e5a4928 100644 --- a/server/tests/unit/nest/tours.gpx.atomic.test.ts +++ b/server/tests/unit/nest/tours.gpx.atomic.test.ts @@ -42,6 +42,7 @@ import { createTestJourneyEntryPhotosRepo, } from '../../helpers/journey-repos'; import { buildMapsService } from '../../helpers/maps-service'; +import { passThroughPlaceChanges } from '../../helpers/place-changes'; import { buildPlaceImportService } from '../../helpers/place-import'; import { makeStorageFixture } from '../../helpers/storage-fixture'; import { resetTestDb } from '../../helpers/test-db'; @@ -141,6 +142,7 @@ async function makePlacesService(): Promise { await createTestBudgetItemsRepo(testDb), { releaseValues: async () => [] } as never, // StorageReleaseService buildPlaceImportService(), + passThroughPlaceChanges(), ); } diff --git a/server/tests/unit/nest/trip-read-model.service.test.ts b/server/tests/unit/nest/trip-read-model.service.test.ts index 4a12ab1c3..de426d54a 100644 --- a/server/tests/unit/nest/trip-read-model.service.test.ts +++ b/server/tests/unit/nest/trip-read-model.service.test.ts @@ -77,6 +77,7 @@ import { createTestPackingTemplateCategoriesRepo, createTestPackingTemplateItemsRepo, } from '../../helpers/packing-repos'; +import { passThroughPlaceChanges } from '../../helpers/place-changes'; import { buildPlaceImportService } from '../../helpers/place-import'; import { createTestShareTokensRepo, @@ -238,6 +239,7 @@ beforeAll(async () => { await createTestBudgetItemsRepo(testDb), { releaseValues: async () => [] } as never, // StorageReleaseService buildPlaceImportService(), + passThroughPlaceChanges(), ); membersSvc = new TripMembersService( budgetSvc, diff --git a/server/tests/unit/nest/trips.service.test.ts b/server/tests/unit/nest/trips.service.test.ts index 7697c3cb4..c9a8b7ae7 100644 --- a/server/tests/unit/nest/trips.service.test.ts +++ b/server/tests/unit/nest/trips.service.test.ts @@ -149,6 +149,7 @@ import { TripMembershipModule } from '../../../src/nest/trip-membership/trip-mem import { TripMembershipService } from '../../../src/nest/trip-membership/trip-membership.service'; import { createTestModule, type TestModule } from '../../helpers/test-module'; import { FakeRealtimeService } from '../../helpers/fake-realtime'; +import { passThroughPlaceChanges } from '../../helpers/place-changes'; const realtime = new FakeRealtimeService(); const broadcast = realtime.broadcastMock; @@ -276,10 +277,9 @@ beforeAll(async () => { await createTestTripMembersRepo(testDb), await createTestDayAssignmentsRepo(testDb), await createTestCategoriesRepo(testDb), - await createTestTripsRepo(testDb), - await createTestBudgetItemsRepo(testDb), + await createTestTripsRepo(testDb), await createTestBudgetItemsRepo(testDb), { releaseValues: async () => [] } as never, // StorageReleaseService - buildPlaceImportService(), + buildPlaceImportService(), passThroughPlaceChanges(), ); // SettingsService reads the trips a planner view may keep (#2639) through TripMembershipService, // which comes out of its own module instead of a constructor call here. diff --git a/server/vitest.config.ts b/server/vitest.config.ts index 8441287c8..68dd3aeea 100644 --- a/server/vitest.config.ts +++ b/server/vitest.config.ts @@ -168,6 +168,12 @@ export default defineConfig({ // 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. + // New domain (PLC-14): the history of a place's details. On the floor until a + // full CI run measures it; raise it with scripts/coverage-thresholds.mjs then. + // New domain (PLC-18): the bookings and tours a place names. On the floor until a + // full CI run measures it; raise it with scripts/coverage-thresholds.mjs then. + 'src/nest/place-activities/**/*.ts': { statements: 80, branches: 80, functions: 80, lines: 80 }, + 'src/nest/place-changes/**/*.ts': { statements: 80, branches: 80, functions: 80, lines: 80 }, '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 diff --git a/shared/src/collection/collection.schema.ts b/shared/src/collection/collection.schema.ts index dc3e918a4..57c920fc6 100644 --- a/shared/src/collection/collection.schema.ts +++ b/shared/src/collection/collection.schema.ts @@ -293,6 +293,13 @@ export const collectionCopyToTripRequestSchema = z.object({ .describe( 'Ids of tags the saved places carry that should come along. Each becomes a tag of the trip, reusing a trip tag of the same name; ids a place does not carry are ignored. Left out, no tags are copied', ), + personal_tag_ids: z + .array(z.number().int()) + .max(50) + .optional() + .describe( + "PLC-21: ids of the caller's own personal tags to share with the trip. Each becomes a tag of the trip on every copied place, reusing a trip tag of the same name; ids that are not the caller's personal tags are ignored. Left out, personal tags stay private", + ), }); export type CollectionCopyToTripRequest = z.infer; diff --git a/shared/src/index.ts b/shared/src/index.ts index 7771fcc48..6ecc7e0c5 100644 --- a/shared/src/index.ts +++ b/shared/src/index.ts @@ -124,6 +124,14 @@ export * from './collection/collection-file.schema'; export * from './places-library/places-library.schema'; // D5/PLC-13: the user's own places, duplicate suggestions and merges in All places. export * from './places-library/place-identity.schema'; +// D7/PLC-09 to PLC-12, PLC-19, PLC-20, PLC-23: confirmed visits, their history, photos and files. +export * from './places-library/place-visits.schema'; +// PLC-14: what changed in the details of a place, when and by whom. +export * from './places-library/place-history.schema'; +// PLC-18: the bookings and tours a place is about. +export * from './places-library/place-activities.schema'; +// PLC-21: the user's personal tags on the entries of All places. +export * from './places-library/place-tags.schema'; // PLC-15/PLC-16: the lists a trip draws on and their saved places on the trip map. export * from './trip-collections/trip-collections.schema'; export * from './trip/trip.schema'; diff --git a/shared/src/places-library/place-activities.schema.spec.ts b/shared/src/places-library/place-activities.schema.spec.ts new file mode 100644 index 000000000..410dbb097 --- /dev/null +++ b/shared/src/places-library/place-activities.schema.spec.ts @@ -0,0 +1,123 @@ +import { + placeActivitiesResponseSchema, + placeActivityCandidatesResponseSchema, + placeLibraryActivitiesRequestSchema, + placeLibraryActivitiesResponseSchema, + savedPlaceActivityLinkRequestSchema, + tripPlaceActivityLinkRequestSchema, +} from './place-activities.schema'; + +import { describe, expect, it } from 'vitest'; + +const booking = { + key: 'reservation:4', + type: 'booking', + origin: { kind: 'trip', trip_id: 1, trip_title: 'Rome' }, + target: { kind: 'reservation', trip_id: 1, reservation_id: 4 }, + title: 'Colosseum guided tour', + booking_type: 'tour', + booking_status: 'confirmed', + tour_type: null, + starts_at: '2026-05-02T10:00', + ends_at: null, + date: '2026-05-02', + day_number: 2, +}; + +describe('place activity contracts (PLC-18)', () => { + it('links exactly one booking or tour of the trip', () => { + expect(tripPlaceActivityLinkRequestSchema.parse({ reservation_id: 4 })).toEqual({ reservation_id: 4 }); + expect(tripPlaceActivityLinkRequestSchema.parse({ tour_id: 9 })).toEqual({ tour_id: 9 }); + for (const body of [ + {}, + { reservation_id: 4, tour_id: 9 }, + { reservation_id: '4' }, + { tour_id: 0 }, + { tour_id: 1.5 }, + { reservation_id: 4, x: 1 }, + ]) { + expect(tripPlaceActivityLinkRequestSchema.safeParse(body).success).toBe(false); + } + }); + + it('links one kept tour of the list', () => { + expect(savedPlaceActivityLinkRequestSchema.parse({ collection_tour_id: 3 })).toEqual({ collection_tour_id: 3 }); + for (const body of [{}, { collection_tour_id: '3' }, { collection_tour_id: -1 }, { collection_tour_id: 3, y: 2 }]) { + expect(savedPlaceActivityLinkRequestSchema.safeParse(body).success).toBe(false); + } + }); + + it('describes the activities of a place, linked and implicit', () => { + const response = { + activities: [ + { + ...booking, + source: { kind: 'trip', trip_id: 1, place_id: 7 }, + explicit: false, + implicit_via: 'place', + can_unlink: false, + }, + { + ...booking, + key: 'tour:12', + type: 'tour', + target: { kind: 'tour', trip_id: 1, tour_id: 12 }, + title: 'City walk', + booking_type: null, + booking_status: null, + tour_type: 'walk', + starts_at: null, + source: { kind: 'trip', trip_id: 1, place_id: 7 }, + explicit: true, + implicit_via: null, + can_unlink: true, + }, + ], + can_link: true, + }; + expect(placeActivitiesResponseSchema.parse(response)).toEqual(response); + const wrongVia = { ...response, activities: [{ ...response.activities[0], implicit_via: 'other' }] }; + expect(placeActivitiesResponseSchema.safeParse(wrongVia).success).toBe(false); + }); + + it('describes the candidates and the activities of an entry of All places', () => { + expect(placeActivityCandidatesResponseSchema.parse({ candidates: [booking] })).toEqual({ candidates: [booking] }); + const kept = { + ...booking, + key: 'collection_tour:5', + type: 'tour', + origin: { kind: 'list', collection_id: 2, collection_name: 'Hikes' }, + target: { kind: 'collection_tour', collection_id: 2, collection_tour_id: 5 }, + source: { kind: 'list', collection_id: 2, collection_place_id: 8 }, + explicit: true, + implicit_via: null, + can_unlink: false, + }; + const library = { + activities: [kept], + sources: [ + { + source: { kind: 'list', collection_id: 2, collection_place_id: 8 }, + origin: { kind: 'list', collection_id: 2, collection_name: 'Hikes' }, + can_link: false, + }, + ], + }; + expect(placeLibraryActivitiesResponseSchema.parse(library)).toEqual(library); + expect( + placeLibraryActivitiesResponseSchema.safeParse({ ...library, sources: [{ source: { kind: 'x' } }] }).success, + ).toBe(false); + }); + + it('reads an entry of All places from a trip place or a saved place', () => { + expect(placeLibraryActivitiesRequestSchema.parse({ kind: 'list', id: 8 })).toEqual({ kind: 'list', id: 8 }); + for (const body of [ + { kind: 'own', id: 8 }, + { kind: 'trip' }, + { kind: 'trip', id: '8' }, + { kind: 'trip', id: 8, z: 1 }, + ]) { + expect(placeLibraryActivitiesRequestSchema.safeParse(body).success).toBe(false); + } + }); +}); diff --git a/shared/src/places-library/place-activities.schema.ts b/shared/src/places-library/place-activities.schema.ts new file mode 100644 index 000000000..a46b3e682 --- /dev/null +++ b/shared/src/places-library/place-activities.schema.ts @@ -0,0 +1,160 @@ +import { idSchema } from '../common/primitives.schema'; +import { PLACES_LIBRARY_KINDS } from './places-library.schema'; + +import { z } from 'zod'; + +/** + * PLC-18: the bookings and tours a place is about. A trip place names + * bookings and tours of its own trip, a saved place names tours kept in its + * own list; a booking that names the place itself (its place, its stay at + * the place, its plan entry of the place) and a tour with a station standing + * for the place belong to it without a link and are shown as such. A link changes nothing on either end and gives no one + * access: everyone sees an activity only while they can open it anyway. + * + * Routes: + * - `GET/POST /api/trips/:tripId/places/:placeId/activities`, + * `GET .../activities/candidates`, + * `DELETE .../activities/reservations/:reservationId` and `.../activities/tours/:tourId` + * - `GET/POST /api/addons/collections/places/:placeId/activities`, + * `GET .../activities/candidates`, `DELETE .../activities/tours/:tourId` + * - `GET /api/addons/collections/library/places/{trip|list}/:id/activities` + * for an entry of All places, over every origin of it the user reaches. + */ + +/** What an activity is: a booking (with its booking type) or a tour. */ +export const PLACE_ACTIVITY_TYPES = ['booking', 'tour'] as const; +export type PlaceActivityType = (typeof PLACE_ACTIVITY_TYPES)[number]; + +/** + * Why an activity belongs to a trip place without a link: a booking names the + * place (`place`), is booked against a stay at the place (`stay`) or is tied + * to a plan entry of the place (`plan`); a tour has a station that stands + * for the place (`station`). + */ +export const PLACE_ACTIVITY_IMPLICIT_VIA = ['place', 'stay', 'plan', 'station'] as const; +export type PlaceActivityImplicitVia = (typeof PLACE_ACTIVITY_IMPLICIT_VIA)[number]; + +/** Where the activity opens: a booking or a tour of a trip, or a tour kept in a list. */ +export const placeActivityTargetSchema = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('reservation'), trip_id: z.number().int(), reservation_id: z.number().int() }), + z.object({ kind: z.literal('tour'), trip_id: z.number().int(), tour_id: z.number().int() }), + z.object({ + kind: z.literal('collection_tour'), + collection_id: z.number().int(), + collection_tour_id: z.number().int(), + }), +]); +export type PlaceActivityTarget = z.infer; + +/** Where the activity comes from: the trip or the list it lives in. */ +export const placeActivityOriginSchema = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('trip'), trip_id: z.number().int(), trip_title: z.string() }), + z.object({ kind: z.literal('list'), collection_id: z.number().int(), collection_name: z.string() }), +]); +export type PlaceActivityOrigin = z.infer; + +/** The use of the place the activity belongs to: a trip place or a saved place. */ +export const placeActivitySourceSchema = z.discriminatedUnion('kind', [ + z.object({ kind: z.literal('trip'), trip_id: z.number().int(), place_id: z.number().int() }), + z.object({ kind: z.literal('list'), collection_id: z.number().int(), collection_place_id: z.number().int() }), +]); +export type PlaceActivitySource = z.infer; + +/** What a booking or tour shows of itself, linked or not. */ +const placeActivityFields = { + /** Stable per target: `reservation:`, `tour:` or `collection_tour:`. */ + key: z.string(), + type: z.enum(PLACE_ACTIVITY_TYPES), + origin: placeActivityOriginSchema, + target: placeActivityTargetSchema, + title: z.string(), + /** The booking's own type (`hotel`, `restaurant`, `tour`, ...), null for a tour. */ + booking_type: z.string().nullable(), + booking_status: z.string().nullable(), + /** The tour's type (`hike`, `walk`, ...), null for a booking. */ + tour_type: z.string().nullable(), + /** The booking's start and end as stored (`YYYY-MM-DDTHH:MM` or a time), null for a tour. */ + starts_at: z.string().nullable(), + ends_at: z.string().nullable(), + /** The day it is on: a booking's day, a tour's first planned day. */ + date: z.string().nullable(), + day_number: z.number().int().nullable(), +}; + +export const placeActivityCandidateSchema = z.object(placeActivityFields); +export type PlaceActivityCandidate = z.infer; + +/** + * An activity of a place. `explicit` says someone linked it; `implicit_via` + * says why it belongs to the place on its own (then that cannot be undone + * here, only on the booking or the tour). An activity can be both. + * `can_unlink` is whether the caller may take the link off. + */ +export const placeActivitySchema = z.object({ + ...placeActivityFields, + source: placeActivitySourceSchema, + explicit: z.boolean(), + implicit_via: z.enum(PLACE_ACTIVITY_IMPLICIT_VIA).nullable(), + can_unlink: z.boolean(), +}); +export type PlaceActivity = z.infer; + +/** The activities of one trip place or saved place, and whether the caller may link more. */ +export const placeActivitiesResponseSchema = z.object({ + activities: z.array(placeActivitySchema), + can_link: z.boolean(), +}); +export type PlaceActivitiesResponse = z.infer; + +/** The bookings and tours the caller could link to the place: the ones not related to it yet. */ +export const placeActivityCandidatesResponseSchema = z.object({ + candidates: z.array(placeActivityCandidateSchema), +}); +export type PlaceActivityCandidatesResponse = z.infer; + +/** One origin of an entry of All places, and whether the caller may link activities there. */ +export const placeLibraryActivitySourceSchema = z.object({ + source: placeActivitySourceSchema, + origin: placeActivityOriginSchema, + can_link: z.boolean(), +}); +export type PlaceLibraryActivitySource = z.infer; + +/** + * The activities of an entry of All places over every origin the user + * reaches (each activity once, under the first origin it belongs to), with + * those origins, so a link is made through the trip place or saved place it + * goes to. + */ +export const placeLibraryActivitiesResponseSchema = z.object({ + activities: z.array(placeActivitySchema), + sources: z.array(placeLibraryActivitySourceSchema), +}); +export type PlaceLibraryActivitiesResponse = z.infer; + +/** Link a booking or a tour of the same trip to a trip place: exactly one of the two. */ +export const tripPlaceActivityLinkRequestSchema = z + .object({ + reservation_id: idSchema.optional().describe('A booking of the same trip'), + tour_id: idSchema.optional().describe('A tour of the same trip (the id of its place)'), + }) + .strict() + .refine((body) => (body.reservation_id === undefined) !== (body.tour_id === undefined), { + message: 'Give either reservation_id or tour_id', + }); +export type TripPlaceActivityLinkRequest = z.infer; + +/** Link a tour kept in the same list to a saved place. */ +export const savedPlaceActivityLinkRequestSchema = z + .object({ collection_tour_id: idSchema.describe('A tour kept in the same list') }) + .strict(); +export type SavedPlaceActivityLinkRequest = z.infer; + +/** Read the activities of an entry of All places, opened from one of its origins (the tool's input). */ +export const placeLibraryActivitiesRequestSchema = z + .object({ + kind: z.enum(PLACES_LIBRARY_KINDS).describe('trip for a trip place id, list for a saved place id'), + id: idSchema.describe('The place_id of a trip origin or the collection_place_id of a list origin'), + }) + .strict(); +export type PlaceLibraryActivitiesRequest = z.infer; diff --git a/shared/src/places-library/place-history.schema.spec.ts b/shared/src/places-library/place-history.schema.spec.ts new file mode 100644 index 000000000..5ec4b12ca --- /dev/null +++ b/shared/src/places-library/place-history.schema.spec.ts @@ -0,0 +1,68 @@ +import { + PLACE_HISTORY_FIELDS, + PLACE_HISTORY_PAGE_MAX, + placeHistoryEntrySchema, + placeHistoryPageResponseSchema, + placeHistoryQuerySchema, + placeHistoryRequestSchema, +} from './place-history.schema'; + +import { describe, expect, it } from 'vitest'; + +describe('placeHistoryQuerySchema', () => { + it('PHIST-S-001: reads a cursor and a limit from a query string', () => { + expect(placeHistoryQuerySchema.parse({ cursor: '42', limit: '10' })).toEqual({ cursor: '42', limit: 10 }); + expect(placeHistoryQuerySchema.parse({})).toEqual({}); + }); + + it('PHIST-S-002: refuses a cursor that is no next_cursor, a limit out of range and unknown keys', () => { + expect(placeHistoryQuerySchema.safeParse({ cursor: '0' }).success).toBe(false); + expect(placeHistoryQuerySchema.safeParse({ cursor: 'abc' }).success).toBe(false); + expect(placeHistoryQuerySchema.safeParse({ cursor: '0x5' }).success).toBe(false); + expect(placeHistoryQuerySchema.safeParse({ limit: '0' }).success).toBe(false); + expect(placeHistoryQuerySchema.safeParse({ limit: String(PLACE_HISTORY_PAGE_MAX + 1) }).success).toBe(false); + expect(placeHistoryQuerySchema.safeParse({ sort: 'name' }).success).toBe(false); + }); +}); + +describe('placeHistoryRequestSchema', () => { + it('PHIST-S-003: names an entry by one of its origins, with the page fields', () => { + expect(placeHistoryRequestSchema.parse({ kind: 'list', id: 3, limit: 5 })).toEqual({ + kind: 'list', + id: 3, + limit: 5, + }); + expect(placeHistoryRequestSchema.safeParse({ kind: 'own', id: 3 }).success).toBe(false); + expect(placeHistoryRequestSchema.safeParse({ kind: 'trip' }).success).toBe(false); + }); +}); + +describe('placeHistoryPageResponseSchema', () => { + const entry = { + id: 7, + origin: { kind: 'trip', trip_id: 1, trip_title: 'Rome', place_id: 9 }, + field: 'address', + old_value: null, + new_value: 'Via Roma 1', + editor: { id: 2, username: 'anna', avatar_url: null }, + automatic: false, + changed_at: '2026-11-29 10:00:00', + }; + + it('PHIST-S-004: describes a page of changes of both origin kinds', () => { + const list = { + ...entry, + id: 6, + origin: { kind: 'list', collection_id: 4, collection_name: 'Ideas', collection_place_id: 11 }, + field: 'status', + editor: null, + automatic: true, + }; + expect(placeHistoryPageResponseSchema.parse({ entries: [entry, list], next_cursor: '6' }).entries).toHaveLength(2); + }); + + it('PHIST-S-005: knows only the fields the history follows', () => { + expect(PLACE_HISTORY_FIELDS).toContain('position'); + expect(placeHistoryEntrySchema.safeParse({ ...entry, field: 'price' }).success).toBe(false); + }); +}); diff --git a/shared/src/places-library/place-history.schema.ts b/shared/src/places-library/place-history.schema.ts new file mode 100644 index 000000000..83dec5592 --- /dev/null +++ b/shared/src/places-library/place-history.schema.ts @@ -0,0 +1,119 @@ +import { idSchema } from '../common/primitives.schema'; +import { PLACES_LIBRARY_KINDS } from './places-library.schema'; + +import { z } from 'zod'; + +/** + * PLC-14: what changed in the details of a place of All places, when and by + * whom, newest first, over every origin of the entry the reader reaches today + * (its trip places and its saved places). A change of a trip or list the + * reader cannot open is not there, and nothing hints at it: no count, no gap. + * + * Each change is one field of one origin, from one value to another. A value + * cleared on purpose takes the earlier changes of that field along, so a + * deleted note or address does not live on in the history. + */ + +export const PLACE_HISTORY_PAGE_DEFAULT = 50; +export const PLACE_HISTORY_PAGE_MAX = 200; + +/** + * The details a history follows. `position` is the coordinates as + * `lat,lng`, `category` the category's name as it was then, `image` the + * picture's address, `opening_hours` the hours as the trip place stores + * them (a trip place only), `status` the list status (a saved place only). + */ +export const PLACE_HISTORY_FIELDS = [ + 'name', + 'address', + 'position', + 'category', + 'description', + 'notes', + 'website', + 'phone', + 'image', + 'opening_hours', + 'status', +] as const; +export type PlaceHistoryField = (typeof PLACE_HISTORY_FIELDS)[number]; + +/** A count from a query string: its digits, or a number. */ +const countSchema = z.union([z.number().int(), z.string().regex(/^\d+$/)]).transform(Number); + +/** Where to go on: the next_cursor of the page before. */ +const cursorSchema = z + .string() + .regex(/^[1-9]\d{0,15}$/, 'Invalid cursor: pass the next_cursor of the page before') + .describe('Where to go on: the next_cursor of the page before. Leave it out for the first page.'); + +const pageFields = { + cursor: cursorSchema.optional(), + limit: countSchema + .pipe(z.number().int().min(1).max(PLACE_HISTORY_PAGE_MAX)) + .optional() + .describe(`How many changes at most (default ${PLACE_HISTORY_PAGE_DEFAULT}, at most ${PLACE_HISTORY_PAGE_MAX})`), +}; + +/** The query of `GET .../library/places/{trip|list}/:id/history`. */ +export const placeHistoryQuerySchema = z.object(pageFields).strict(); +export type PlaceHistoryQuery = z.infer; +export type PlaceHistoryQueryInput = z.input; + +/** The history of one entry, named by one of its origins (as the detail of All places is). */ +export const placeHistoryRequestSchema = z + .object({ + kind: z.enum(PLACES_LIBRARY_KINDS).describe('trip for a trip place id, list for a saved place id'), + id: idSchema.describe('The place_id of a trip origin or the collection_place_id of a list origin'), + ...pageFields, + }) + .strict(); +export type PlaceHistoryRequest = z.infer; + +/** The origin a change was made in: a trip place or a saved place. */ +export const placeHistoryOriginSchema = z.discriminatedUnion('kind', [ + z.object({ + kind: z.literal('trip'), + trip_id: z.number().int(), + trip_title: z.string(), + place_id: z.number().int(), + }), + z.object({ + kind: z.literal('list'), + collection_id: z.number().int(), + collection_name: z.string(), + collection_place_id: z.number().int(), + }), +]); +export type PlaceHistoryOrigin = z.infer; + +/** Who made a change; null where the account is gone or nobody did (an automatic fill). */ +export const placeHistoryEditorSchema = z.object({ + id: z.number().int(), + username: z.string(), + avatar_url: z.string().nullable(), +}); +export type PlaceHistoryEditor = z.infer; + +export const placeHistoryEntrySchema = z.object({ + id: z.number().int(), + origin: placeHistoryOriginSchema, + field: z.enum(PLACE_HISTORY_FIELDS), + /** The value before, null where the field was empty. */ + old_value: z.string().nullable(), + /** The value after; never null, since a cleared field leaves no change behind. */ + new_value: z.string().nullable(), + editor: placeHistoryEditorSchema.nullable(), + /** True for a value TREK filled in itself (a lookup after an import, a picture from the photo cache). */ + automatic: z.boolean(), + /** When, as `YYYY-MM-DD HH:MM:SS` UTC. */ + changed_at: z.string().nullable(), +}); +export type PlaceHistoryEntry = z.infer; + +export const placeHistoryPageResponseSchema = z.object({ + entries: z.array(placeHistoryEntrySchema), + /** Passed back as cursor for the next page; null on the last. */ + next_cursor: z.string().nullable(), +}); +export type PlaceHistoryPageResponse = z.infer; diff --git a/shared/src/places-library/place-tags.schema.spec.ts b/shared/src/places-library/place-tags.schema.spec.ts new file mode 100644 index 000000000..da84fb5e5 --- /dev/null +++ b/shared/src/places-library/place-tags.schema.spec.ts @@ -0,0 +1,87 @@ +import { collectionCopyToTripRequestSchema } from '../collection/collection.schema'; +import { + PLACES_LIBRARY_TAG_KEYS_MAX, + placesLibraryBulkTagsRequestSchema, + placesLibraryEntryTagsRequestSchema, +} from './place-tags.schema'; +import { PLACES_LIBRARY_TAGS_MAX, placesLibraryEntrySchema, placesLibraryQuerySchema } from './places-library.schema'; + +import { describe, expect, it } from 'vitest'; + +describe('PLC-21 personal place tags contracts', () => { + it('reads tag_ids from a query string or a list, and refuses what is no id', () => { + expect(placesLibraryQuerySchema.parse({ tag_ids: '3' }).tag_ids).toEqual([3]); + expect(placesLibraryQuerySchema.parse({ tag_ids: '3,7' }).tag_ids).toEqual([3, 7]); + expect(placesLibraryQuerySchema.parse({ tag_ids: [4, 5] }).tag_ids).toEqual([4, 5]); + for (const bad of ['', '0x5', '1,,2', '1.5', ' 1', '+1', '0', '9007199254740993', [], [1.5], [0]]) { + expect(placesLibraryQuerySchema.safeParse({ tag_ids: bad }).success).toBe(false); + } + const many = Array.from({ length: PLACES_LIBRARY_TAGS_MAX + 1 }, (_, index) => index + 1); + expect(placesLibraryQuerySchema.safeParse({ tag_ids: many.join(',') }).success).toBe(false); + }); + + it('sets the tags of one entry by its key, an empty list taking all off', () => { + expect(placesLibraryEntryTagsRequestSchema.parse({ key: 'own:2', tag_ids: [] })).toEqual({ + key: 'own:2', + tag_ids: [], + }); + for (const bad of [ + { key: 'tour:1', tag_ids: [] }, + { key: 'trip:1', tag_ids: [1.5] }, + { key: 'trip:1' }, + { key: 'trip:1', tag_ids: [], extra: 1 }, + ]) { + expect(placesLibraryEntryTagsRequestSchema.safeParse(bad).success).toBe(false); + } + }); + + it('changes several entries at once, with something to add or remove and never both for one tag', () => { + expect(placesLibraryBulkTagsRequestSchema.safeParse({ keys: ['trip:1', 'list:2'], add: [3] }).success).toBe(true); + expect(placesLibraryBulkTagsRequestSchema.safeParse({ keys: ['trip:1'], remove: [3] }).success).toBe(true); + const keys = Array.from({ length: PLACES_LIBRARY_TAG_KEYS_MAX + 1 }, (_, index) => `trip:${index + 1}`); + for (const bad of [ + { keys: ['trip:1'] }, + { keys: ['trip:1'], add: [], remove: [] }, + { keys: [], add: [1] }, + { keys, add: [1] }, + { keys: ['trip:1'], add: [1], remove: [1] }, + ]) { + expect(placesLibraryBulkTagsRequestSchema.safeParse(bad).success).toBe(false); + } + }); + + it('an entry may carry its tags, and a copy may share personal tags', () => { + const entry = { + key: 'trip:1', + name: 'Café', + address: null, + lat: null, + lng: null, + category: null, + image_url: null, + updated_at: null, + origins: [ + { + kind: 'trip', + trip_id: 1, + trip_title: 'Alps', + trip_start: null, + trip_end: null, + place_id: 1, + can_edit: true, + read_only: false, + }, + ], + }; + expect(placesLibraryEntrySchema.safeParse(entry).success).toBe(true); + expect(placesLibraryEntrySchema.safeParse({ ...entry, tags: [{ id: 1, name: 'Wine', color: null }] }).success).toBe( + true, + ); + expect( + collectionCopyToTripRequestSchema.safeParse({ trip_id: 1, place_ids: [2], personal_tag_ids: [3] }).success, + ).toBe(true); + expect( + collectionCopyToTripRequestSchema.safeParse({ trip_id: 1, place_ids: [2], personal_tag_ids: [1.5] }).success, + ).toBe(false); + }); +}); diff --git a/shared/src/places-library/place-tags.schema.ts b/shared/src/places-library/place-tags.schema.ts new file mode 100644 index 000000000..24ba32285 --- /dev/null +++ b/shared/src/places-library/place-tags.schema.ts @@ -0,0 +1,67 @@ +import { PLACES_LIBRARY_TAGS_MAX, placesLibraryEntrySchema, placesLibraryKeySchema } from './places-library.schema'; + +import { z } from 'zod'; + +/** + * PLC-21: a user's personal tags on the entries of "All places". The tags + * themselves are the user's personal tags of /api/tags (`list_tags`, + * `create_tag`, ...); here they are put on entries and taken off again. Every + * assignment is the user's own: nobody else on a trip or a list sees it, and + * it changes no trip place and no saved place. + * + * A tag sits on the entry: on the user's own place where the entry is one + * (`own:`), else on the trip place or saved place it stands for. A tag + * that sits on one of an entry's uses counts for the entry too, so tags + * survive putting places together and taking them apart again. + */ + +/** The most entries one bulk change names. */ +export const PLACES_LIBRARY_TAG_KEYS_MAX = 200; + +const tagIdsSchema = z + .array(z.number().int().positive()) + .max(PLACES_LIBRARY_TAGS_MAX) + .describe('Ids of personal tags of the user (list_tags)'); + +/** The personal tags an entry carries from now on, all of them: an empty list takes every tag off. */ +export const placesLibraryEntryTagsRequestSchema = z + .object({ + key: placesLibraryKeySchema, + tag_ids: tagIdsSchema.describe('Every personal tag the entry carries from now on; an empty list takes all off'), + }) + .strict(); +export type PlacesLibraryEntryTagsRequest = z.infer; + +/** Put tags on several entries and take others off, in one go. */ +export const placesLibraryBulkTagsRequestSchema = z + .object({ + keys: z + .array(placesLibraryKeySchema) + .min(1) + .max(PLACES_LIBRARY_TAG_KEYS_MAX) + .describe('The entries to change, by their key from list_all_places'), + add: tagIdsSchema.optional().describe('Personal tags to put on every one of the entries'), + remove: tagIdsSchema.optional().describe('Personal tags to take off every one of the entries'), + }) + .strict() + .refine((body) => (body.add?.length ?? 0) + (body.remove?.length ?? 0) > 0, { + message: 'Name tags to add or to remove', + path: ['add'], + }) + .refine((body) => !(body.add ?? []).some((id) => (body.remove ?? []).includes(id)), { + message: 'A tag cannot be added and removed at once', + path: ['remove'], + }); +export type PlacesLibraryBulkTagsRequest = z.infer; + +/** The entry after the change, null when the user does not reach it any more. */ +export const placesLibraryEntryTagsResponseSchema = z.object({ + entry: placesLibraryEntrySchema.nullable(), +}); +export type PlacesLibraryEntryTagsResponse = z.infer; + +/** The entries after a bulk change, in the order the request named them. */ +export const placesLibraryBulkTagsResponseSchema = z.object({ + entries: z.array(placesLibraryEntrySchema), +}); +export type PlacesLibraryBulkTagsResponse = z.infer; diff --git a/shared/src/places-library/place-visits.schema.spec.ts b/shared/src/places-library/place-visits.schema.spec.ts new file mode 100644 index 000000000..01c291e95 --- /dev/null +++ b/shared/src/places-library/place-visits.schema.spec.ts @@ -0,0 +1,92 @@ +import { + placeMediaResponseSchema, + placeVisitSchema, + placeVisitsForPlaceQuerySchema, + placeVisitsListQuerySchema, + placeVisitTripVisitedResponseSchema, +} from './place-visits.schema'; +import * as contract from './place-visits.schema'; +import { placesLibraryEntrySchema } from './places-library.schema'; + +import { describe, expect, it } from 'vitest'; + +describe('place visit contracts (D7/PLC-10 to PLC-23)', () => { + it('PVS-001: visits are only read: no request schema to confirm, correct, leave or delete one', () => { + const requests = Object.keys(contract).filter((name) => /RequestSchema$/.test(name)); + expect(requests).toEqual([]); + }); + + it('PVS-002: the query ids read digits and refuse other spellings', () => { + expect(placeVisitsForPlaceQuerySchema.parse({ kind: 'list', id: '9' })).toEqual({ kind: 'list', id: 9 }); + expect(placeVisitsForPlaceQuerySchema.safeParse({ kind: 'own', id: '9' }).success).toBe(false); + expect(placeVisitsForPlaceQuerySchema.safeParse({ kind: 'trip', id: '0x5' }).success).toBe(false); + expect(placeVisitsListQuerySchema.parse({ trip_id: '3', limit: '10', offset: '0' })).toEqual({ + trip_id: 3, + limit: 10, + offset: 0, + }); + expect(placeVisitsListQuerySchema.safeParse({ limit: '0' }).success).toBe(false); + expect(placeVisitsListQuerySchema.safeParse({ limit: '201' }).success).toBe(false); + expect(placeVisitsListQuerySchema.safeParse({ extra: '1' }).success).toBe(false); + }); + + it('PVS-003: a visit is a day at a trip place, with its trip, day and participants', () => { + const visit = { + visited_on: '2026-07-01', + visited_time: '09:30', + trip: { id: 1, title: 'Alps' }, + place_id: 3, + day_id: 7, + day_number: 2, + name: 'Café', + participants: [{ id: 1, username: 'ana', avatar_url: null }], + }; + expect(placeVisitSchema.parse(visit)).toEqual(visit); + expect(placeVisitSchema.safeParse({ ...visit, trip: null }).success).toBe(false); + expect(placeVisitSchema.safeParse({ ...visit, day_id: null }).success).toBe(false); + expect( + placeVisitTripVisitedResponseSchema.safeParse({ + place_ids: [3], + places: [{ place_id: 3, visit_count: 0, last_visit: '2026-07-01' }], + }).success, + ).toBe(false); + }); + + it('PVS-004: the media and the additive entry fields', () => { + expect( + placeMediaResponseSchema.parse({ + images: [ + { kind: 'list', image_url: '/u/1.jpg', collection_id: 1, collection_name: 'Food', collection_place_id: 2 }, + ], + journey_photos: [], + files: [], + }).images, + ).toHaveLength(1); + const entry = { + key: 'trip:1', + name: 'Café', + address: null, + lat: null, + lng: null, + category: null, + image_url: null, + updated_at: null, + origins: [ + { + kind: 'trip', + trip_id: 1, + trip_title: 'Alps', + trip_start: null, + trip_end: null, + place_id: 1, + can_edit: true, + read_only: false, + }, + ], + }; + expect(placesLibraryEntrySchema.safeParse(entry).success).toBe(true); + expect(placesLibraryEntrySchema.safeParse({ ...entry, visit_count: 2, last_visit: '2026-07-01' }).success).toBe( + true, + ); + }); +}); diff --git a/shared/src/places-library/place-visits.schema.ts b/shared/src/places-library/place-visits.schema.ts new file mode 100644 index 000000000..b9a26162d --- /dev/null +++ b/shared/src/places-library/place-visits.schema.ts @@ -0,0 +1,166 @@ +import { idParamSchema } from '../common/primitives.schema'; +import { PLACES_LIBRARY_KINDS } from './places-library.schema'; + +import { z } from 'zod'; + +/** + * D7/PLC-10, PLC-19, PLC-20, PLC-23: the places a person visited. + * + * A visit is never entered: it is read from the trips. A place counts as + * visited by a reader on a day when a trip they own or are a member of has it + * planned on a day with a date up to today (the server's calendar day, UTC), + * and the stop names no one or names the reader among who takes part. A day + * without a date counts nothing. A place counts once per day, however many + * stops have it that day, also where All places groups several trip places + * as one place. Without access to the trip any more, its visits are gone. + */ + +export const PLACE_VISITS_PAGE_DEFAULT = 50; +export const PLACE_VISITS_PAGE_MAX = 200; + +/** The visits at one place of All places, opened from a trip place or a saved place. */ +export const placeVisitsForPlaceQuerySchema = z + .object({ + kind: z.enum(PLACES_LIBRARY_KINDS).describe('trip for a trip place id, list for a saved place id'), + id: idParamSchema.describe('The place_id of a trip place or the collection_place_id of a saved place'), + }) + .strict(); +export type PlaceVisitsForPlaceQuery = z.infer; + +/** A count from a query string: its digits, or a number. */ +const countSchema = z.union([z.number().int(), z.string().regex(/^\d+$/)]).transform(Number); + +/** Your own visits, newest first. */ +export const placeVisitsListQuerySchema = z + .object({ + trip_id: idParamSchema.optional().describe('Only visits of this trip'), + limit: countSchema + .pipe(z.number().int().min(1).max(PLACE_VISITS_PAGE_MAX)) + .optional() + .describe(`How many at most (default ${PLACE_VISITS_PAGE_DEFAULT}, at most ${PLACE_VISITS_PAGE_MAX})`), + offset: countSchema.pipe(z.number().int().min(0)).optional().describe('How many to skip'), + }) + .strict(); +export type PlaceVisitsListQuery = z.infer; + +/** A person as a visit lists them. */ +export const placeVisitPersonSchema = z.object({ + id: z.number().int(), + username: z.string(), + avatar_url: z.string().nullable(), +}); +export type PlaceVisitPerson = z.infer; + +/** + * One visit: the day, the time planned there (the stop's own, else the + * place's), the trip and its trip place and day it is read from, the place's + * name in that trip, and who it counts for: the people the stops name, or, + * where a stop names no one, everyone with an account on the trip. + */ +export const placeVisitSchema = z.object({ + visited_on: z.string(), + visited_time: z.string().nullable(), + trip: z.object({ id: z.number().int(), title: z.string() }), + place_id: z.number().int(), + day_id: z.number().int(), + day_number: z.number().int(), + name: z.string(), + participants: z.array(placeVisitPersonSchema), +}); +export type PlaceVisit = z.infer; + +/** The visits at one place and their sum, the way "All places" counts them. */ +export const placeVisitsForPlaceResponseSchema = z.object({ + visits: z.array(placeVisitSchema), + visit_count: z.number().int().nonnegative(), + last_visit: z.string().nullable(), +}); +export type PlaceVisitsForPlaceResponse = z.infer; + +export const placeVisitsListResponseSchema = z.object({ + visits: z.array(placeVisitSchema), + total: z.number().int().nonnegative(), +}); +export type PlaceVisitsListResponse = z.infer; + +/** PLC-23: the trip's places the reader visited, at this place or at the same place elsewhere. */ +export const placeVisitTripVisitedSchema = z.object({ + place_id: z.number().int(), + visit_count: z.number().int().positive(), + last_visit: z.string(), +}); + +export const placeVisitTripVisitedResponseSchema = z.object({ + place_ids: z.array(z.number().int()), + places: z.array(placeVisitTripVisitedSchema), +}); +export type PlaceVisitTripVisitedResponse = z.infer; + +// ── PLC-19/PLC-20: photos and files of a place ─────────────────────────── + +/** Where a general picture of the place comes from: a trip place or a saved place. */ +export const placeMediaImageSchema = z.discriminatedUnion('kind', [ + z.object({ + kind: z.literal('trip'), + image_url: z.string(), + trip_id: z.number().int(), + trip_title: z.string(), + place_id: z.number().int(), + }), + z.object({ + kind: z.literal('list'), + image_url: z.string(), + collection_id: z.number().int(), + collection_name: z.string(), + collection_place_id: z.number().int(), + }), +]); +export type PlaceMediaImage = z.infer; + +/** + * A photo of a journey entry made from one of the place's trip places, in a + * journey the reader can open. The photo fields are those of a journey photo. + */ +export const placeMediaJourneyPhotoSchema = z.object({ + journey_id: z.number().int(), + journey_title: z.string(), + entry_id: z.number().int(), + entry_date: z.string(), + journey_photo_id: z.number().int(), + photo_id: z.number().int(), + provider: z.string(), + asset_id: z.string().nullable(), + owner_id: z.number().int().nullable(), + file_path: z.string().nullable(), + thumbnail_path: z.string().nullable(), + width: z.number().nullable(), + height: z.number().nullable(), + media_type: z.string(), + caption: z.string().nullable(), + taken_at: z.string().nullable(), +}); +export type PlaceMediaJourneyPhoto = z.infer; + +/** + * A trip file attached to one of the place's trip places, in a trip the + * reader can open. It opens in the trip. + */ +export const placeMediaFileSchema = z.object({ + file_id: z.number().int(), + trip_id: z.number().int(), + trip_title: z.string(), + place_id: z.number().int(), + original_name: z.string(), + mime_type: z.string().nullable(), + file_size: z.number().nullable(), + created_at: z.string().nullable(), + url: z.string(), +}); +export type PlaceMediaFile = z.infer; + +export const placeMediaResponseSchema = z.object({ + images: z.array(placeMediaImageSchema), + journey_photos: z.array(placeMediaJourneyPhotoSchema), + files: z.array(placeMediaFileSchema), +}); +export type PlaceMediaResponse = z.infer; diff --git a/shared/src/places-library/places-library.schema.ts b/shared/src/places-library/places-library.schema.ts index 8a2180856..3ed27c3f1 100644 --- a/shared/src/places-library/places-library.schema.ts +++ b/shared/src/places-library/places-library.schema.ts @@ -23,6 +23,26 @@ export type PlacesLibraryKind = (typeof PLACES_LIBRARY_KINDS)[number]; export const PLACES_LIBRARY_SORTS = ['name', 'updated'] as const; export type PlacesLibrarySort = (typeof PLACES_LIBRARY_SORTS)[number]; +/** PLC-21: the most personal tags one filter or one assignment names. */ +export const PLACES_LIBRARY_TAGS_MAX = 50; + +/** + * Personal tag ids as a filter takes them: a list of ids (MCP, JSON), or the + * ids joined by commas as a query string carries them (`tag_ids=3,7`). Each + * one is decimal digits naming a positive safe integer. + */ +export const placesLibraryTagIdsSchema = z + .union([ + z.array(z.number().int().positive()), + z + .string() + .regex(/^\d+(,\d+)*$/, 'Invalid id') + .transform((joined) => joined.split(',').map(Number)), + ]) + .pipe( + z.array(z.number().int().positive().refine(Number.isSafeInteger, 'Invalid id')).min(1).max(PLACES_LIBRARY_TAGS_MAX), + ); + /** A count from a query string: its digits, or a number from a client that sends one. */ const pageLimitSchema = z .union([z.number().int(), z.string().regex(/^\d+$/)]) @@ -40,6 +60,11 @@ export const placesLibraryQuerySchema = z collection_id: idParamSchema.optional().describe('Only entries in this list'), trip_id: idParamSchema.optional().describe('Only entries in this trip'), status: z.enum(COLLECTION_STATUSES).optional().describe('Only entries with this status in one of the lists'), + tag_ids: placesLibraryTagIdsSchema + .optional() + .describe( + 'Only entries carrying at least one of these personal tags of the user (ids from list_tags; in a query string joined by commas)', + ), sort: z .enum(PLACES_LIBRARY_SORTS) .optional() @@ -69,6 +94,14 @@ export const placesLibraryDetailRequestSchema = z .strict(); export type PlacesLibraryDetailRequest = z.infer; +/** PLC-21: a personal tag of the user on an entry. Nobody else sees it. */ +export const placesLibraryTagSchema = z.object({ + id: z.number().int(), + name: z.string(), + color: z.string().nullable(), +}); +export type PlacesLibraryTag = z.infer; + export const placesLibraryCategorySchema = z.object({ id: z.number().int(), name: z.string(), @@ -82,6 +115,9 @@ export const placesLibraryListOriginSchema = z.object({ kind: z.literal('list'), collection_id: z.number().int(), collection_name: z.string(), + /** The list's own colour and symbol, null for the defaults. */ + collection_color: z.string().nullable().optional(), + collection_icon: z.string().nullable().optional(), collection_place_id: z.number().int(), status: z.enum(COLLECTION_STATUSES), can_edit: z.boolean(), @@ -97,6 +133,8 @@ export const placesLibraryTripOriginSchema = z.object({ trip_title: z.string(), trip_start: z.string().nullable(), trip_end: z.string().nullable(), + /** The trip's cover picture, null without one. */ + trip_cover: z.string().nullable().optional(), place_id: z.number().int(), can_edit: z.boolean(), read_only: z.boolean(), @@ -137,6 +175,20 @@ export const placesLibraryEntrySchema = z.object({ image_url: z.string().nullable(), updated_at: z.string().nullable(), origins: z.array(placesLibraryOriginSchema).min(1), + /** + * D7/PLC-10: how many days the user visited this entry, read from the + * trips they reach (a dated day up to today with the place planned on it, + * the stop naming no one or them), each day once however many of its uses + * name it, and the latest of them; 0 and null for none. + */ + visit_count: z.number().int().nonnegative().optional(), + last_visit: z.string().nullable().optional(), + /** + * PLC-21: the user's own personal tags on this entry, by name: the ones on + * its own place (and on one merged into it) and on any of its uses. Private: + * only ever the asking user's. + */ + tags: z.array(placesLibraryTagSchema).optional(), }); export type PlacesLibraryEntry = z.infer; @@ -152,7 +204,7 @@ export const placesLibraryPageResponseSchema = z.object({ entries: z.array(placesLibraryEntrySchema), /** Entries every filter of the query matches, on every page. */ total: z.number().int().nonnegative(), - /** Entries `q` and `category_id` match, whatever the other filters say, for the kind tabs. */ + /** Entries `q`, `category_id` and `tag_ids` match, whatever the other filters say, for the kind tabs. */ counts: placesLibraryCountsSchema, next_cursor: z.string().nullable(), }); diff --git a/shared/src/realtime/events.schema.spec.ts b/shared/src/realtime/events.schema.spec.ts index 6a65873db..98174c91f 100644 --- a/shared/src/realtime/events.schema.spec.ts +++ b/shared/src/realtime/events.schema.spec.ts @@ -24,6 +24,7 @@ const FIXTURES: Record> = { 'place:deleted': { placeId: 3 }, 'tripTags:changed': {}, 'tripCollections:changed': {}, + 'placeActivities:changed': { placeId: 3 }, 'tours:changed': { placeIds: [3] }, 'tours:visits': { assignmentId: 9, visits: [{ assignment_id: 9, station_key: 'abcdef', status: 'visited' }] }, 'assignment:created': { assignment: { id: 9, day_id: 2 } }, @@ -204,7 +205,7 @@ const DRIFT_VARIANTS: Partial[]> }; describe('@trek/shared realtime event registry', () => { - it('WSEVT-REG-001: pins the authoritative inventory counts (83 trip + 43 user = 126)', () => { + it('WSEVT-REG-001: pins the authoritative inventory counts (84 trip + 43 user = 127)', () => { // 67th to 69th trip event: the three collab:link:* a shared link emits. // 70th and 71st: the road trip's vias and tracks, which used to be written silently. // 74th: docsync:changed, so a sync run that moved documents refreshes the @@ -230,9 +231,11 @@ describe('@trek/shared realtime event registry', () => { // or off for the trip shows or hides for every member at once. // 83rd trip event: tripCollections:changed, so the lists a trip draws on // follow a link or unlink for every member, each with their own rights. - expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(83); + // 84th trip event: placeActivities:changed, so a booking or tour linked to a + // place of the trip or unlinked shows in its place detail for every member. + expect(TREK_WS_TRIP_EVENT_NAMES).toHaveLength(84); expect(TREK_WS_USER_EVENT_NAMES).toHaveLength(43); - expect(TREK_WS_EVENT_NAMES).toHaveLength(126); + expect(TREK_WS_EVENT_NAMES).toHaveLength(127); }); it('WSEVT-REG-002: every name is domain:action shaped and outside the reserved plugin: namespace', () => { diff --git a/shared/src/realtime/events.schema.ts b/shared/src/realtime/events.schema.ts index 6986cd1e8..8b6a45274 100644 --- a/shared/src/realtime/events.schema.ts +++ b/shared/src/realtime/events.schema.ts @@ -302,6 +302,11 @@ export const TREK_WS_EVENTS = { // is per person, so every member asks again with their own rights. 'tripCollections:changed': { scope: 'trip', payload: empty }, + // A booking or tour was linked to a place of the trip or unlinked (PLC-18): the + // place detail reads its activities again. Every member sees the trip's + // bookings and tours, so the place is all it needs. + 'placeActivities:changed': { scope: 'trip', payload: z.object({ placeId: id }) }, + // ── Notifications (user-scoped) ────────────────────────────────────────── 'notification:new': { scope: 'user', payload: z.object({ notification: entity }) }, 'notification:updated': { scope: 'user', payload: z.object({ notification: entity }) },