diff --git a/server/scripts/import-boundaries-baseline.json b/server/scripts/import-boundaries-baseline.json index 045077bd8..934afebbf 100644 --- a/server/scripts/import-boundaries-baseline.json +++ b/server/scripts/import-boundaries-baseline.json @@ -126,7 +126,6 @@ "booking-import -> llm-parse/image-input.ts", "collab -> storage/storage-upload.factory.ts", "collections -> places/place-image.ts", - "collections -> places/places.dto.ts", "collections -> places/places.helpers.ts", "collections -> storage/storage-upload.factory.ts", "days -> accommodations/night-seat.ts", diff --git a/server/scripts/mcp-inline-zod-baseline.json b/server/scripts/mcp-inline-zod-baseline.json index 87afc36bd..d0a9ed338 100644 --- a/server/scripts/mcp-inline-zod-baseline.json +++ b/server/scripts/mcp-inline-zod-baseline.json @@ -6,7 +6,7 @@ "src/nest/atlas/atlas.mcp.ts": 23, "src/nest/budget/budget.mcp.ts": 36, "src/nest/collab/collab.mcp.ts": 20, - "src/nest/collections/collections.mcp.ts": 14, + "src/nest/collections/collections.mcp.ts": 13, "src/nest/day-notes/day-notes.mcp.ts": 6, "src/nest/days/days.mcp.ts": 2, "src/nest/doc-sync/doc-sync.mcp.ts": 1, @@ -19,7 +19,7 @@ "src/nest/memories/memories.mcp.ts": 8, "src/nest/notifications/notifications.mcp.ts": 2, "src/nest/packing/packing.mcp.ts": 15, - "src/nest/places/places.mcp.ts": 68, + "src/nest/places/places.mcp.ts": 67, "src/nest/plugins/contributions/plugin-pois.mcp.ts": 4, "src/nest/plugins/contributions/plugin-search.mcp.ts": 5, "src/nest/reservations/reservations.mcp.ts": 60, diff --git a/server/scripts/repository-owners.json b/server/scripts/repository-owners.json index 26cacd76d..c531b1b01 100644 --- a/server/scripts/repository-owners.json +++ b/server/scripts/repository-owners.json @@ -82,7 +82,6 @@ "PaddleRegions": "paddle-obstacles", "PaddleWaterGraphs": "paddle-routing", "PasswordResetTokens": "auth", - "PersonalPlaceTags": "places-library", "PhotoProviderFields": "addons", "PhotoProviders": "addons", "Photos": "photos", diff --git a/server/scripts/response-contract-baseline.json b/server/scripts/response-contract-baseline.json index 388f7de45..f0999b2a0 100644 --- a/server/scripts/response-contract-baseline.json +++ b/server/scripts/response-contract-baseline.json @@ -15,7 +15,7 @@ "src/nest/backup/backup.controller.ts": 8, "src/nest/budget/budget.controller.ts": 16, "src/nest/categories/categories.controller.ts": 4, - "src/nest/collections/collections.controller.ts": 40, + "src/nest/collections/collections.controller.ts": 38, "src/nest/config/config.controller.ts": 1, "src/nest/day-notes/day-notes.controller.ts": 4, "src/nest/days/days.controller.ts": 6, @@ -46,7 +46,7 @@ "src/nest/photos/photos.controller.ts": 3, "src/nest/place-enrichment/place-enrichment.controller.ts": 2, "src/nest/place-shadow/place-shadow.controller.ts": 4, - "src/nest/places/places.controller.ts": 17, + "src/nest/places/places.controller.ts": 15, "src/nest/platform/discovery.controller.ts": 9, "src/nest/plugins/contributions/atlas-layers.controller.ts": 1, "src/nest/plugins/contributions/day-schedule.controller.ts": 1, diff --git a/server/scripts/size-baseline.json b/server/scripts/size-baseline.json index c421476d6..bca35b502 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": 1397, + "src/nest/collections/collections.service.ts": 1396, "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/CollectionPlaceRatings.entity.ts b/server/src/db/entities/CollectionPlaceRatings.entity.ts index 7713f023f..653441790 100644 --- a/server/src/db/entities/CollectionPlaceRatings.entity.ts +++ b/server/src/db/entities/CollectionPlaceRatings.entity.ts @@ -13,6 +13,7 @@ export class CollectionPlaceRatings { user_id!: number; rating!: number; created_at?: string | null; + updated_at?: string | null; } export const CollectionPlaceRatingsSchema = defineEntity({ @@ -27,5 +28,6 @@ export const CollectionPlaceRatingsSchema = defineEntity({ user_id: p.integer().persist(false).index('idx_collection_place_ratings_user_id'), rating: p.integer(), created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), + updated_at: p.type(DbTimestampType).nullable(), }, }); diff --git a/server/src/db/entities/CollectionPlaces.entity.ts b/server/src/db/entities/CollectionPlaces.entity.ts index 88cdeae31..0f08b4c33 100644 --- a/server/src/db/entities/CollectionPlaces.entity.ts +++ b/server/src/db/entities/CollectionPlaces.entity.ts @@ -5,7 +5,6 @@ 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'; @@ -47,7 +46,6 @@ 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); @@ -90,7 +88,6 @@ 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/PersonalPlaceTags.entity.ts b/server/src/db/entities/PersonalPlaceTags.entity.ts deleted file mode 100644 index 17569a53f..000000000 --- a/server/src/db/entities/PersonalPlaceTags.entity.ts +++ /dev/null @@ -1,49 +0,0 @@ -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/PlaceRatings.entity.ts b/server/src/db/entities/PlaceRatings.entity.ts index 5bc3488e0..8ad47accf 100644 --- a/server/src/db/entities/PlaceRatings.entity.ts +++ b/server/src/db/entities/PlaceRatings.entity.ts @@ -13,6 +13,7 @@ export class PlaceRatings { user_id!: number; rating!: number; created_at?: string | null; + updated_at?: string | null; } export const PlaceRatingsSchema = defineEntity({ @@ -27,5 +28,6 @@ export const PlaceRatingsSchema = defineEntity({ user_id: p.integer().persist(false).index('idx_place_ratings_user_id'), rating: p.integer(), created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`), + updated_at: p.type(DbTimestampType).nullable(), }, }); diff --git a/server/src/db/entities/Places.entity.ts b/server/src/db/entities/Places.entity.ts index e034019f7..97c2a1bb1 100644 --- a/server/src/db/entities/Places.entity.ts +++ b/server/src/db/entities/Places.entity.ts @@ -8,7 +8,6 @@ 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'; @@ -70,7 +69,6 @@ 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); @@ -134,7 +132,6 @@ 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(), diff --git a/server/src/db/entities/Tags.entity.ts b/server/src/db/entities/Tags.entity.ts index 2a8a94827..efadd8919 100644 --- a/server/src/db/entities/Tags.entity.ts +++ b/server/src/db/entities/Tags.entity.ts @@ -2,7 +2,6 @@ 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'; @@ -18,7 +17,6 @@ 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); } @@ -35,7 +33,6 @@ 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/UserPlaces.entity.ts b/server/src/db/entities/UserPlaces.entity.ts index 3dadab874..f4028e96b 100644 --- a/server/src/db/entities/UserPlaces.entity.ts +++ b/server/src/db/entities/UserPlaces.entity.ts @@ -2,7 +2,6 @@ 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'; @@ -25,7 +24,6 @@ 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); @@ -52,7 +50,6 @@ 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/index.ts b/server/src/db/entities/index.ts index ba059a1cf..2a046a680 100644 --- a/server/src/db/entities/index.ts +++ b/server/src/db/entities/index.ts @@ -83,7 +83,6 @@ 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'; @@ -267,7 +266,6 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [ PaddleRegionsSchema, PaddleWaterGraphsSchema, PasswordResetTokensSchema, - PersonalPlaceTagsSchema, PhotoProviderFieldsSchema, PhotoProvidersSchema, PhotosSchema, diff --git a/server/src/db/kysely/CollectionPlaceRatings.table.ts b/server/src/db/kysely/CollectionPlaceRatings.table.ts index 0e054bd66..56bb1b1c0 100644 --- a/server/src/db/kysely/CollectionPlaceRatings.table.ts +++ b/server/src/db/kysely/CollectionPlaceRatings.table.ts @@ -8,4 +8,5 @@ export interface CollectionPlaceRatingsTable { user_id: number; rating: number; created_at: InsertOptional; + updated_at: InsertOptional; } diff --git a/server/src/db/kysely/PersonalPlaceTags.table.ts b/server/src/db/kysely/PersonalPlaceTags.table.ts deleted file mode 100644 index 8409d9bf1..000000000 --- a/server/src/db/kysely/PersonalPlaceTags.table.ts +++ /dev/null @@ -1,12 +0,0 @@ -// 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/PlaceRatings.table.ts b/server/src/db/kysely/PlaceRatings.table.ts index 5ea1af428..4288d89ec 100644 --- a/server/src/db/kysely/PlaceRatings.table.ts +++ b/server/src/db/kysely/PlaceRatings.table.ts @@ -8,4 +8,5 @@ export interface PlaceRatingsTable { user_id: number; rating: number; created_at: InsertOptional; + updated_at: InsertOptional; } diff --git a/server/src/db/kysely/db.ts b/server/src/db/kysely/db.ts index 450e5f2b3..f2cf657bc 100644 --- a/server/src/db/kysely/db.ts +++ b/server/src/db/kysely/db.ts @@ -88,7 +88,6 @@ 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'; @@ -278,7 +277,6 @@ 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; diff --git a/server/src/db/migrations/Migration20200101046590_a_place_carries_the_tags_of_its_lists_and_trips.ts b/server/src/db/migrations/Migration20200101046590_a_place_carries_the_tags_of_its_lists_and_trips.ts new file mode 100644 index 000000000..bab686999 --- /dev/null +++ b/server/src/db/migrations/Migration20200101046590_a_place_carries_the_tags_of_its_lists_and_trips.ts @@ -0,0 +1,25 @@ +import { engineDdl } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * PLC-21 takes back the tags a person kept on the entries of "All places" for + * themselves alone (`Migration20200101046580_a_person_tags_the_places_they_keep`). + * A place carries the tags of the lists and the trips it is in instead, which + * every member of the list or the trip sees: a list's labels and a trip's + * tags, both stored where they always were and left as they are. + * + * `personal_place_tags` goes, with its indexes and keys. It never shipped in a + * release, and nothing else points at it. The personal tags themselves are + * rows of `tags` (`trip_id` null) and stay, as do the list labels, the trip + * tags and every assignment of them. + */ +export class Migration20200101046590_a_place_carries_the_tags_of_its_lists_and_trips extends Migration { + override name = 'Migration20200101046590_a_place_carries_the_tags_of_its_lists_and_trips'; + + override up(): void { + engineDdl(this, { + sqlite: ['DROP TABLE personal_place_tags'], + postgres: ['drop table "personal_place_tags"'], + }); + } +} diff --git a/server/src/db/migrations/Migration20200101046600_a_list_tour_link_keeps_its_full_unique_name.ts b/server/src/db/migrations/Migration20200101046600_a_list_tour_link_keeps_its_full_unique_name.ts new file mode 100644 index 000000000..2863d8faa --- /dev/null +++ b/server/src/db/migrations/Migration20200101046600_a_list_tour_link_keeps_its_full_unique_name.ts @@ -0,0 +1,26 @@ +import { engineDdl } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * `Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about` + * named the unique key of a saved place and a list tour with 66 characters. + * Postgres keeps the first 63 of them, so the key landed as + * `..._collection_tour_id_uni`, while MikroORM names one that long by a hash + * of the full name, which is what the entities describe. + * + * The key is renamed on Postgres. Every Postgres database that ran 046570 + * holds the truncated name, so the rename cannot miss. SQLite keeps the key + * as an unnamed table constraint and has nothing to change. + */ +export class Migration20200101046600_a_list_tour_link_keeps_its_full_unique_name extends Migration { + override name = 'Migration20200101046600_a_list_tour_link_keeps_its_full_unique_name'; + + override up(): void { + engineDdl(this, { + sqlite: [], + postgres: [ + 'alter table "place_activity_links" rename constraint "place_activity_links_collection_place_id_collection_tour_id_uni" to "place_activity_links_collection_place_id_collecti_252bd_unique"', + ], + }); + } +} diff --git a/server/src/db/migrations/Migration20200101046610_a_vote_remembers_when_it_last_changed.ts b/server/src/db/migrations/Migration20200101046610_a_vote_remembers_when_it_last_changed.ts new file mode 100644 index 000000000..fe5d1ec76 --- /dev/null +++ b/server/src/db/migrations/Migration20200101046610_a_vote_remembers_when_it_last_changed.ts @@ -0,0 +1,30 @@ +import { engineDdl } from '../migration-utils'; +import { Migration } from '@mikro-orm/migrations'; + +/** + * A vote belongs to its person and is the same on every copy of a place they + * have (All places), so where two copies still disagree, the one the person + * changed last is their vote. `created_at` only says when a vote was first + * cast, because changing a vote updates its row in place. + * + * `updated_at` on `place_ratings` and `collection_place_ratings` is set on + * every write of a vote from now on. It stays empty on every existing row, + * which then reads as changed when it was cast, exactly what TREK could tell + * about it before this step. + */ +export class Migration20200101046610_a_vote_remembers_when_it_last_changed extends Migration { + override name = 'Migration20200101046610_a_vote_remembers_when_it_last_changed'; + + override up(): void { + engineDdl(this, { + sqlite: [ + 'ALTER TABLE place_ratings ADD COLUMN updated_at DATETIME', + 'ALTER TABLE collection_place_ratings ADD COLUMN updated_at DATETIME', + ], + postgres: [ + 'alter table "place_ratings" add "updated_at" text null', + 'alter table "collection_place_ratings" add "updated_at" text null', + ], + }); + } +} diff --git a/server/src/db/repositories/CollectionPlaceRatings.repository.ts b/server/src/db/repositories/CollectionPlaceRatings.repository.ts index 05c1ad973..aac04b52e 100644 --- a/server/src/db/repositories/CollectionPlaceRatings.repository.ts +++ b/server/src/db/repositories/CollectionPlaceRatings.repository.ts @@ -1,5 +1,6 @@ import type { CollectionPlaceRatings } from '../entities/CollectionPlaceRatings.entity'; import type { DB } from '../kysely/db'; +import { dbNow } from '../types'; import { TrekRepository } from './_shared/trek-repository'; /** @@ -34,12 +35,17 @@ export class CollectionPlaceRatingsRepository extends TrekRepository { await this.upsert( - { collectionPlace: collectionPlaceId, user: userId, rating }, - { onConflictFields: ['collectionPlace', 'user'], onConflictAction: 'merge', onConflictMergeFields: ['rating'] }, + { collectionPlace: collectionPlaceId, user: userId, rating, updated_at: dbNow() }, + { + onConflictFields: ['collectionPlace', 'user'], + onConflictAction: 'merge', + onConflictMergeFields: ['rating', 'updated_at'], + }, ); } @@ -49,10 +55,16 @@ export class CollectionPlaceRatingsRepository extends TrekRepository { + async insertIgnoreRating( + collectionPlaceId: number, + userId: number, + rating: number, + changedAt?: string | null, + ): Promise { await this.upsert( - { collectionPlace: collectionPlaceId, user: userId, rating }, + { collectionPlace: collectionPlaceId, user: userId, rating, updated_at: changedAt ?? null }, { onConflictFields: ['collectionPlace', 'user'], onConflictAction: 'ignore' }, ); } diff --git a/server/src/db/repositories/Collections.repository.ts b/server/src/db/repositories/Collections.repository.ts index d86a074f0..e5443e611 100644 --- a/server/src/db/repositories/Collections.repository.ts +++ b/server/src/db/repositories/Collections.repository.ts @@ -544,6 +544,25 @@ export class CollectionsRepository extends TrekRepository { .execute(); } + /** + * PLC-21: the list's tags (its labels) on each saved place, with their name + * and colour, for a copy into a trip that brings them along. Empty input + * sends nothing. + */ + async loadLabelsByPlaceIds( + placeIds: number[], + ): Promise<{ pid: number; id: number; name: string; color: string | null }[]> { + if (placeIds.length === 0) return []; + return await this.kysely>() + .selectFrom('collection_place_labels as cpl') + .innerJoin('collection_labels as l', 'l.id', 'cpl.label_id') + .select(['cpl.collection_place_id as pid', 'l.id', 'l.name', 'l.color']) + .where('cpl.collection_place_id', 'in', placeIds) + .orderBy('l.sort_order') + .orderBy('l.id') + .execute(); + } + /** CL8 (`loadLabelIdsByPlaceIds`) — `SELECT collection_place_id AS pid, label_id FROM collection_place_labels WHERE collection_place_id IN (...)`. */ async loadLabelIdsByPlaceIds(placeIds: number[]): Promise<{ pid: number; label_id: number }[]> { if (placeIds.length === 0) return []; diff --git a/server/src/db/repositories/PersonalPlaceTags.repository.ts b/server/src/db/repositories/PersonalPlaceTags.repository.ts deleted file mode 100644 index a12bd974e..000000000 --- a/server/src/db/repositories/PersonalPlaceTags.repository.ts +++ /dev/null @@ -1,119 +0,0 @@ -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/PlaceRatings.repository.ts b/server/src/db/repositories/PlaceRatings.repository.ts index 14c2b006f..5b1013253 100644 --- a/server/src/db/repositories/PlaceRatings.repository.ts +++ b/server/src/db/repositories/PlaceRatings.repository.ts @@ -1,5 +1,6 @@ import type { PlaceRatings } from '../entities/PlaceRatings.entity'; import type { DB } from '../kysely/db'; +import { dbNow } from '../types'; import { TrekRepository } from './_shared/trek-repository'; /** One rated place, from `QueryHelpersService.loadRatingsByPlaceIds` (QH2). */ @@ -64,9 +65,14 @@ export class PlaceRatingsRepository extends TrekRepository { * unchanged across a rating write. */ async upsertRating(place_id: number, user_id: number, rating: number): Promise { + // updated_at says when the person last changed the vote; created_at keeps when they first cast it. await this.upsert( - { place: place_id, user: user_id, rating }, - { onConflictFields: ['place', 'user'], onConflictAction: 'merge', onConflictMergeFields: ['rating'] }, + { place: place_id, user: user_id, rating, updated_at: dbNow() }, + { + onConflictFields: ['place', 'user'], + onConflictAction: 'merge', + onConflictMergeFields: ['rating', 'updated_at'], + }, ); } @@ -104,11 +110,13 @@ export class PlaceRatingsRepository extends TrekRepository { * existing vote on the destination place (unlikely on a freshly copied * row, but not impossible if the place already existed) is left alone, * `onConflictAction: 'ignore'` on the same `['place', 'user']` composite - * unique {@link upsertRating} documents. + * unique {@link upsertRating} documents. `changedAt` is the time the + * vote it carries was last changed, so a carried copy never reads as newer + * than the vote it came from; empty, the new row reads as cast now. */ - async insertIgnore(place_id: number, user_id: number, rating: number): Promise { + async insertIgnore(place_id: number, user_id: number, rating: number, changedAt?: string | null): Promise { await this.upsert( - { place: place_id, user: user_id, rating }, + { place: place_id, user: user_id, rating, updated_at: changedAt ?? null }, { onConflictFields: ['place', 'user'], onConflictAction: 'ignore' }, ); } diff --git a/server/src/db/repositories/PlacesLibrary.repository.ts b/server/src/db/repositories/PlacesLibrary.repository.ts index 3a5fe22fb..371e5eb94 100644 --- a/server/src/db/repositories/PlacesLibrary.repository.ts +++ b/server/src/db/repositories/PlacesLibrary.repository.ts @@ -1,4 +1,4 @@ -import { containsIgnoringCaseKysely } from '../dialect/kysely-functions'; +import { castIntegerKysely, containsIgnoringCaseKysely } from '../dialect/kysely-functions'; import type { DB } from '../kysely/db'; import { memberRoleOf } from './_shared/collection-role'; import type { EntityManager } from '@mikro-orm/core'; @@ -28,7 +28,8 @@ type LibraryDB = Pick< | 'user_places' | 'user_place_links' | 'tags' - | 'personal_place_tags' + | 'place_tags' + | 'users' >; /** @@ -40,7 +41,18 @@ 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, tags: null }; +const NO_MATCH: LibraryMatch = { search: null, categoryId: null, status: null, tags: null, rating: null }; + +/** + * An entry's average vote as one integer that orders like it: the sum of the + * votes times this, divided by how many, truncated. Integers, so the order and + * a cursor read the same on both engines; ties a millionth of a star apart + * fall back to the key. + */ +export const RATING_SCORE_SCALE = 1_000_000; + +/** The sort value of an entry nobody voted on: below every average, so it comes last. */ +export const UNRATED_SCORE = -1; /** * The road trip stops that belong to the drive rather than to the places of @@ -81,29 +93,49 @@ 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. */ + /** PLC-21: only entries carrying a tag of one of these names, a list's label or a trip's tag. */ tags: LibraryTagMatch | null; + /** The votes of the entries: only those whose average reaches `min` stars, and what the rating sort reads. */ + rating: LibraryRatingMatch | 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. + * How the votes of an entry are read for the rating filter and sort: over + * every copy of it the user reaches (`reach`, every trip and list they can + * open), each person once with the vote they changed last, as the entry's + * rating counts them. `min` keeps the entries whose average is at least that + * many stars (an entry without votes has none); null keeps every entry. */ -interface LibraryTagMatch { - tagIds: number[]; +export interface LibraryRatingMatch { + min: number | null; reach: LibraryArms; } -/** One personal tag on one target, with the own place a merged one went into. */ -export interface LibraryEntryTagRow { +/** + * The tag names an entry must carry one of (PLC-21), each as the engines fold + * a name (`lower(trim(name))`), so a name matches whatever its case. `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 { + foldedNames: string[]; + reach: LibraryArms; +} + +/** A tag of a trip on one of its places (`place_tags`). */ +export interface LibraryTripTagRow { + place_id: number; + id: number; + name: string; + color: string | null; +} + +/** A tag a trip or a list owns, with the trip or list it belongs to. */ +export interface LibraryOwnedTagRow { + owner_id: number; 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. */ @@ -112,13 +144,15 @@ export interface LibraryPosition { key: number; } -export type LibrarySort = 'name' | 'updated'; +export type LibrarySort = 'name' | 'updated' | 'rating'; /** One entry of a page, named by its anchor (see `ANCHOR_SPAN`). */ export interface LibraryAnchorRow { anchor_key: number; sort_name: string; sort_time: string; + /** The rating sort's value (see `RATING_SCORE_SCALE`), `UNRATED_SCORE` without votes; 0 under the other sorts. */ + sort_rating: number; } interface UnionRow extends LibraryAnchorRow { @@ -222,6 +256,22 @@ export interface LibraryRatingRow { target_id: number; user_id: number; rating: number; + /** Who voted, as the list's votes name them, and their stored picture. */ + username?: string; + avatar?: string | null; + /** When the vote was last changed (cast, when never changed since), and its row, to tell which of a person's votes came last. */ + changed_at?: string | null; + id?: number; +} + +/** One of a person's votes: on a trip place (from_list 0) or a saved place. */ +export interface LibraryOwnVoteRow { + from_list: number; + use_id: number; + rating: number; + /** When the person last changed the vote, or cast it when they never changed it. */ + changed_at: string | null; + id: number; } interface LibraryDayRow { @@ -454,62 +504,140 @@ 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. + * The entries that carry a tag of one of the names (PLC-21): a trip tag on + * one of their trip places or a list label on one of their saved places. */ private taggedAnchors(db: Kysely, tags: LibraryTagMatch) { - const onUses = db + const names = tags.foldedNames.length > 0 ? tags.foldedNames : ['']; + return 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'))]), - ]), + eb.or([ + eb.and([ + eb('u.from_list', '=', 0), + eb.exists( + eb + .selectFrom('place_tags as pt') + .innerJoin('tags as tg', 'tg.id', 'pt.tag_id') + .select('pt.tag_id') + .whereRef('pt.place_id', '=', 'u.use_id') + .where((inner) => + inner(inner.fn('lower', [inner.fn('trim', ['tg.name'])]), 'in', names), + ), ), - ), - ) - .$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'); + ]), + eb.and([ + eb('u.from_list', '=', 1), + eb.exists( + eb + .selectFrom('collection_place_labels as cpl') + .innerJoin('collection_labels as lb', 'lb.id', 'cpl.label_id') + .select('cpl.label_id') + .whereRef('cpl.collection_place_id', '=', 'u.use_id') + .where((inner) => + inner(inner.fn('lower', [inner.fn('trim', ['lb.name'])]), 'in', names), + ), + ), + ]), + ]), + ); } - /** The union of the entries, narrowed to the ones carrying a tag when the match names tags. */ + /** + * Every person's last vote on each entry, over the copies `reach` holds: the + * votes on its trip places and on its saved places, each person once with + * the vote they changed last (a later row breaks a tie, then a trip place + * before a saved place), the way `unifiedRatingOf` reads them. + */ + private lastVotes(db: Kysely, reach: LibraryArms) { + const onTrips = db + .selectFrom(this.entries(db, reach, NO_MATCH)) + .innerJoin('place_ratings as pr', 'pr.place_id', 'u.use_id') + .where('u.from_list', '=', 0) + .select((eb) => [ + 'u.anchor_key', + 'u.from_list', + 'pr.user_id', + 'pr.rating', + 'pr.id', + eb.fn.coalesce('pr.updated_at', 'pr.created_at', eb.val('')).$castTo().as('changed_at'), + ]); + const onLists = db + .selectFrom(this.entries(db, reach, NO_MATCH)) + .innerJoin('collection_place_ratings as cr', 'cr.collection_place_id', 'u.use_id') + .where('u.from_list', '=', 1) + .select((eb) => [ + 'u.anchor_key', + 'u.from_list', + 'cr.user_id', + 'cr.rating', + 'cr.id', + eb.fn.coalesce('cr.updated_at', 'cr.created_at', eb.val('')).$castTo().as('changed_at'), + ]); + return db.selectFrom(onTrips.unionAll(onLists).as('v')).select((eb) => [ + 'v.anchor_key', + 'v.rating', + eb.fn + .agg('row_number') + .over((ob) => + ob + .partitionBy(['v.anchor_key', 'v.user_id']) + .orderBy('v.changed_at', 'desc') + .orderBy('v.id', 'desc') + .orderBy('v.from_list', 'asc'), + ) + .as('nth'), + ]); + } + + /** + * Each entry with votes on the copies `reach` holds: the sum of every + * person's last vote, how many people voted, and the score the rating sort + * orders by (see `RATING_SCORE_SCALE`). + */ + private entryScores(db: Kysely, reach: LibraryArms) { + const platform = this.em.getPlatform(); + return db + .selectFrom(this.lastVotes(db, reach).as('lv')) + .where('lv.nth', '=', 1) + .groupBy('lv.anchor_key') + .select((eb) => { + const total = eb.fn.sum('lv.rating'); + const voters = eb.fn.countAll(); + const scaled = eb(eb(total, '*', eb.lit(RATING_SCORE_SCALE)), '/', voters); + return [ + 'lv.anchor_key', + total.as('total'), + voters.as('voters'), + castIntegerKysely(platform, eb, scaled).as('score'), + ]; + }); + } + + /** + * The union of the entries, narrowed to the ones carrying a tag when the + * match names tags, and to the ones whose average reaches the fewest stars + * when it names those. + */ 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)); + const { tags, rating } = match; + let all = db.selectFrom(this.entries(db, arms, match)); + if (tags !== null) all = all.where('u.anchor_key', 'in', this.taggedAnchors(db, tags)); + if (rating !== null && rating.min !== null) { + const min = rating.min; + // The average reaches `min` exactly when the sum reaches `min` times the number of voters. + all = all.where( + 'u.anchor_key', + 'in', + db + .selectFrom(this.entryScores(db, rating.reach).as('rs')) + .select('rs.anchor_key') + .where((eb) => eb('rs.total', '>=', eb('rs.voters', '*', eb.val(min)))), + ); + } + return all; } /** How many entries match: all of them, those with a trip place, those with a saved place. */ @@ -539,6 +667,7 @@ export class PlacesLibraryRepository { after: LibraryPosition | null, limit: number, ): Promise { + if (sort === 'rating') return this.pageByRating(arms, match, after, limit); const db = this.db(); const value = after?.value ?? ''; const key = after?.key ?? 0; @@ -563,6 +692,48 @@ export class PlacesLibraryRepository { anchor_key: Number(row.anchor_key), sort_name: row.sort_name, sort_time: row.sort_time, + sort_rating: 0, + })); + } + + /** + * Up to `limit` entries by their votes, the highest average first and the + * entries without votes last, after `after` when given. The votes are read + * over `match.rating.reach` (every copy the user reaches), else over `arms`. + */ + private async pageByRating( + arms: LibraryArms, + match: LibraryMatch, + after: LibraryPosition | null, + limit: number, + ): Promise { + const db = this.db(); + const value = after === null ? 0 : Number(after.value); + const key = after?.key ?? 0; + const rows = await this.matching(db, arms, match) + .leftJoin(this.entryScores(db, match.rating?.reach ?? arms).as('sc'), 'sc.anchor_key', 'u.anchor_key') + .select((eb) => [ + 'u.anchor_key', + 'u.sort_name', + 'u.sort_time', + eb.fn.coalesce('sc.score', eb.val(UNRATED_SCORE)).$castTo().as('sort_rating'), + ]) + .distinct() + .$if(after !== null, (qb) => + qb.where((eb) => { + const score = eb.fn.coalesce('sc.score', eb.val(UNRATED_SCORE)); + return eb.or([eb(score, '<', value), eb.and([eb(score, '=', value), eb('u.anchor_key', '>', key)])]); + }), + ) + .orderBy('sort_rating', 'desc') + .orderBy('u.anchor_key', 'asc') + .limit(limit) + .execute(); + return rows.map((row) => ({ + anchor_key: Number(row.anchor_key), + sort_name: row.sort_name, + sort_time: row.sort_time, + sort_rating: Number(row.sort_rating), })); } @@ -611,45 +782,41 @@ 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') + /** The tags on the trip places (PLC-21), by name. */ + async tripPlaceTags(placeIds: number[]): Promise { + const rows = await this.db() + .selectFrom('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)), - ]), - ) + .select(['pt.place_id', 'tg.id', 'tg.name', 'tg.color']) + .where('pt.place_id', 'in', idsOrNone(placeIds)) .orderBy('tg.name') .orderBy('tg.id') .execute(); + // A legacy row can hold a number as its name, so it is read as text. + return rows.map((row) => ({ ...row, name: String(row.name) })); + } + + /** Every tag the trips own (PLC-21), by name. */ + async tripTags(tripIds: number[]): Promise { + const rows = await this.db() + .selectFrom('tags as tg') + .select(['tg.trip_id as owner_id', 'tg.id', 'tg.name', 'tg.color']) + .where('tg.trip_id', 'in', idsOrNone(tripIds)) + .orderBy('tg.name') + .orderBy('tg.id') + .execute(); + return rows.map((row) => ({ ...row, owner_id: Number(row.owner_id), name: String(row.name) })); + } + + /** Every label of the lists (PLC-21: a list's tags), in each list's label order. */ + async listLabels(collectionIds: number[]): Promise { + return await this.db() + .selectFrom('collection_labels as lb') + .select(['lb.collection_id as owner_id', 'lb.id', 'lb.name', 'lb.color']) + .where('lb.collection_id', 'in', idsOrNone(collectionIds)) + .orderBy('lb.sort_order') + .orderBy('lb.id') + .execute(); } /** The trip places with their trip and category, for the entries of a page. */ @@ -803,22 +970,93 @@ export class PlacesLibraryRepository { .execute(); } + /** The votes on the saved places, each with who cast it (their name and stored picture). */ async savedPlaceRatings(collectionPlaceIds: number[]): Promise { return await this.db() - .selectFrom('collection_place_ratings') - .select(['collection_place_id as target_id', 'user_id', 'rating']) - .where('collection_place_id', 'in', idsOrNone(collectionPlaceIds)) + .selectFrom('collection_place_ratings as cr') + .innerJoin('users as vu', 'vu.id', 'cr.user_id') + .select([ + 'cr.collection_place_id as target_id', + 'cr.user_id', + 'cr.rating', + (eb) => eb.fn.coalesce('cr.updated_at', 'cr.created_at').as('changed_at'), + 'cr.id', + 'vu.username', + 'vu.avatar', + ]) + .where('cr.collection_place_id', 'in', idsOrNone(collectionPlaceIds)) .execute(); } + /** The votes on the trip places, each with who cast it (their name and stored picture). */ async tripPlaceRatings(placeIds: number[]): Promise { return await this.db() - .selectFrom('place_ratings') - .select(['place_id as target_id', 'user_id', 'rating']) - .where('place_id', 'in', idsOrNone(placeIds)) + .selectFrom('place_ratings as pr') + .innerJoin('users as vu', 'vu.id', 'pr.user_id') + .select([ + 'pr.place_id as target_id', + 'pr.user_id', + 'pr.rating', + (eb) => eb.fn.coalesce('pr.updated_at', 'pr.created_at').as('changed_at'), + 'pr.id', + 'vu.username', + 'vu.avatar', + ]) + .where('pr.place_id', 'in', idsOrNone(placeIds)) .execute(); } + /** Every vote of the user, on trip places and on saved places, in row order. */ + async votesOfUser(userId: number): Promise { + const db = this.db(); + const trips = await db + .selectFrom('place_ratings') + .select([ + 'place_id as use_id', + 'rating', + (eb) => eb.fn.coalesce('updated_at', 'created_at').as('changed_at'), + 'id', + ]) + .where('user_id', '=', userId) + .orderBy('id') + .execute(); + const saved = await db + .selectFrom('collection_place_ratings') + .select([ + 'collection_place_id as use_id', + 'rating', + (eb) => eb.fn.coalesce('updated_at', 'created_at').as('changed_at'), + 'id', + ]) + .where('user_id', '=', userId) + .orderBy('id') + .execute(); + return [...trips.map((row) => ({ ...row, from_list: 0 })), ...saved.map((row) => ({ ...row, from_list: 1 }))]; + } + + /** Up to `limit` of the people with a vote anywhere, by id, after the id `after`. */ + async voterIds(after: number, limit: number): Promise { + const db = this.db(); + const trips = await db + .selectFrom('place_ratings') + .select('user_id') + .distinct() + .where('user_id', '>', after) + .orderBy('user_id') + .limit(limit) + .execute(); + const saved = await db + .selectFrom('collection_place_ratings') + .select('user_id') + .distinct() + .where('user_id', '>', after) + .orderBy('user_id') + .limit(limit) + .execute(); + const ids = new Set([...trips, ...saved].map((row) => Number(row.user_id))); + return [...ids].sort((a, b) => a - b).slice(0, limit); + } + /** The days each place is planned on, in day order, with the time set there. */ async plannedDays(placeIds: number[]): Promise { return await this.db() diff --git a/server/src/mcp/scopes.ts b/server/src/mcp/scopes.ts index 8cda41bfd..36324a161 100644 --- a/server/src/mcp/scopes.ts +++ b/server/src/mcp/scopes.ts @@ -275,6 +275,15 @@ export function canWrite(scopes: string[] | null, group: ScopeGroup): boolean { return scopes.includes(`${group}:write`); } +/** + * The kinds of a person's copies of a place an edit or a vote through this + * token may reach: trip places with `places:write`, saved places with + * `collections:write` (place-copies.port.ts). + */ +export function placeCopyReach(scopes: string[] | null): { trips: boolean; lists: boolean } { + return { trips: canWrite(scopes, 'places'), lists: canWrite(scopes, 'collections') }; +} + /** group:read OR group:write grant read access */ export function canRead(scopes: string[] | null, group: ScopeGroup): boolean { if (!scopes) return true; diff --git a/server/src/nest/app.module.ts b/server/src/nest/app.module.ts index b3441c4eb..4e2e3bf2a 100644 --- a/server/src/nest/app.module.ts +++ b/server/src/nest/app.module.ts @@ -83,6 +83,7 @@ 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 { PlaceVotesModule } from './places-library/place-votes.module'; import { PlacesLibraryModule } from './places-library/places-library.module'; import { PlacesModule } from './places/places.module'; import { PlatformModule } from './platform/platform.module'; @@ -209,6 +210,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core'; CollectionsModule, PlacesLibraryModule, PlaceVisitsModule, + PlaceVotesModule, PlaceHistoryModule, PlaceActivitiesModule, TripCollectionsModule, diff --git a/server/src/nest/assistant/assistant-tool-offer.ts b/server/src/nest/assistant/assistant-tool-offer.ts index c11b4e620..d45775fdf 100644 --- a/server/src/nest/assistant/assistant-tool-offer.ts +++ b/server/src/nest/assistant/assistant-tool-offer.ts @@ -407,14 +407,14 @@ const CORE_TOOL_GROUPS: ToolGroups = { 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), ' + - 'your personal tags on them, the lists linked to this trip and the places visited on past trip days, with ' + + 'the tags of their lists and trips, 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', + 'PlaceVotesLibraryMcp', 'PlacesLibraryMcp', 'PlaceIdentitiesMcp', - 'PlaceTagsMcp', 'TripCollectionsMcp', 'PlaceVisitsMcp', 'PlaceHistoryMcp', diff --git a/server/src/nest/collections/collections.controller.ts b/server/src/nest/collections/collections.controller.ts index 10cf043e7..ae03ab9f7 100644 --- a/server/src/nest/collections/collections.controller.ts +++ b/server/src/nest/collections/collections.controller.ts @@ -12,7 +12,6 @@ import { rowId } from '../common/row-id.pipe'; import { SpoolCleanupInterceptor } from '../common/spool-cleanup.interceptor'; import { CollectionGpxError, CollectionMapError } from '../place-import/place-import.types'; import { placeImageUrl } from '../places/place-image'; -import { PlaceRatingDto } from '../places/places.dto'; import { StorageService } from '../storage/storage.service'; import { CollectionCreateDto, @@ -207,7 +206,7 @@ export class CollectionsController { @Body() body: CollectionPlaceUpdateDto, @Headers('x-socket-id') socketId?: string, ) { - return this.collections.updatePlace(user.id, pid, body, socketId); + return this.collections.updatePlace(user.id, pid, body, socketId, { editor: user }); } @Post('places/:pid/status') @@ -221,25 +220,6 @@ export class CollectionsController { return this.collections.setStatus(user.id, pid, body.status, socketId); } - @Put('places/:pid/rating') - setRating( - @CurrentUser() user: User, - @Param('pid', rowId('Place not found')) pid: number, - @Body() body: PlaceRatingDto, - @Headers('x-socket-id') socketId?: string, - ) { - return this.collections.setRating(user.id, pid, body.rating, socketId); - } - - @Delete('places/:pid/rating') - clearRating( - @CurrentUser() user: User, - @Param('pid', rowId('Place not found')) pid: number, - @Headers('x-socket-id') socketId?: string, - ) { - return this.collections.setRating(user.id, pid, null, socketId); - } - @Post('places/:pid/image') @HttpCode(200) @UseInterceptors(FileInterceptor('image', { fileFilter: PLACE_IMAGE_FILE_FILTER }), SpoolCleanupInterceptor) @@ -256,7 +236,7 @@ export class CollectionsController { // Commit the spooled upload to its final storage location (atomic // same-volume rename) before the DB row references the final path. await this.storage.put('places', file.filename, { tmpPath: file.path }); - return this.collections.setPlaceImage(user.id, pid, placeImageUrl(file.filename), socketId); + return this.collections.setPlaceImage(user.id, pid, placeImageUrl(file.filename), socketId, { editor: user }); } @Delete('places/:pid') diff --git a/server/src/nest/collections/collections.helpers.ts b/server/src/nest/collections/collections.helpers.ts index 594a1d0c0..dee9e90d9 100644 --- a/server/src/nest/collections/collections.helpers.ts +++ b/server/src/nest/collections/collections.helpers.ts @@ -1,10 +1,15 @@ +import type { CollectionPlacesRepository } from '../../db/repositories/CollectionPlaces.repository'; import type { CollectionPlacePosition, CollectionPlaceRow } from '../../db/repositories/Collections.repository'; import type { PlaceRow } from '../../db/repositories/Places.repository'; import type { DedupSet } from '../places/places.helpers'; -import { externalIdsOf } from '@trek/shared'; +import { COLLECTION_FILE_FORMAT, COLLECTION_FILE_VERSION, externalIdsOf } from '@trek/shared'; import type { + Collection, + CollectionFile, + CollectionLabel, CollectionFilePlace, CollectionLink, + CollectionPlace, CollectionPlaceUpdateRequest, CollectionStatus, PlaceMatchCandidate, @@ -91,6 +96,65 @@ export function listingWriteOf(body: CollectionPlaceUpdateRequest): ListingWrite return write; } +/** A list as its file carries it: its own facts, its labels by name and its places (#2198). */ +export function collectionFileOf( + collection: Pick, + labels: readonly CollectionLabel[], + places: CollectionFilePlace[], +): Omit & { places: CollectionFilePlace[] } { + return { + format: COLLECTION_FILE_FORMAT, + version: COLLECTION_FILE_VERSION, + name: collection.name, + description: collection.description ?? null, + color: collection.color ?? null, + icon: collection.icon ?? null, + exported_at: new Date().toISOString(), + labels: labels.map((l) => ({ name: l.name, color: l.color ?? null })), + places, + }; +} + +/** What an update of a saved place writes: each field the body names, null clearing it, the rest left as stored. */ +export function placeWriteOf( + body: CollectionPlaceUpdateRequest, +): Parameters[1] { + const write: Parameters[1] = listingWriteOf(body); + if (body.name !== undefined) write.name = body.name; + if (body.description !== undefined) write.description = body.description ?? null; + if (body.notes !== undefined) write.notes = body.notes ?? null; + if (body.lat !== undefined) write.lat = body.lat ?? null; + if (body.lng !== undefined) write.lng = body.lng ?? null; + if (body.address !== undefined) write.address = body.address ?? null; + if (body.status !== undefined) write.status = body.status; + if (body.category_id !== undefined) write.category_id = body.category_id ?? null; + if (body.image_url !== undefined) write.image_url = body.image_url ?? null; + if (body.links !== undefined) write.links = serializeLinks(body.links); + return write; +} + +/** A saved place as the routes answer it: its row with the category, tags, labels and the members' votes. */ +export function hydratedPlaceOf( + r: CollectionPlaceRow, + tags: { id: number; name: string; color: string }[], + labelIds: number[], + ratings: { user_id: number; username: string; avatar: string | null; rating: number }[], +): CollectionPlace { + const { category_name, category_color, category_icon, ...rest } = r; + return { + ...rest, + links: parseLinks((r as { links?: unknown }).links), + category: r.category_id + ? { id: r.category_id, name: category_name ?? '', color: category_color ?? null, icon: category_icon ?? null } + : undefined, + tags, + label_ids: labelIds, + ratings, + rating_avg: ratings.length > 0 ? ratings.reduce((s, x) => s + x.rating, 0) / ratings.length : null, + rating_count: ratings.length, + } as CollectionPlace; +} + /** A cursor as list_collection_places hands it out: the position of the last place of a page. */ const placesCursorSchema = z.tuple([z.number().int(), z.string().max(40), z.number().int().positive()]); @@ -200,35 +264,41 @@ interface CarriedTag { color: string; } -/** The colour a personal tag stored without one comes along with, the tags' own default. */ +/** The colour a list tag stored without one comes along with, the trip tags' own default. */ const DEFAULT_TAG_COLOR = '#10b981'; +/** A tag of a saved place as a copy reads it: the saved place, the tag's id, name and colour. */ +interface PlaceTagRow { + pid: number; + id: number; + name: string; + color: string | null; +} + /** * 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. + * place id. A saved place's tags stay in the list unless asked for, and then + * only where the place carries them: `tag_ids` names its tags (`tags` rows on + * the saved place), `label_ids` the list's own tags (its labels). 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[] }, + body: { tag_ids?: number[]; label_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 }[]>, + lists: { + loadTagsByPlaceIds(ids: number[]): Promise; + loadLabelsByPlaceIds(ids: number[]): Promise; + }, ): 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]])); + const labels = new Set(body.label_ids ?? []); + if (asked.size === 0 && labels.size === 0) return null; + const tagged = asked.size ? (await lists.loadTagsByPlaceIds(placeIds)).filter((tag) => asked.has(tag.id)) : []; + const labelled = labels.size ? (await lists.loadLabelsByPlaceIds(placeIds)).filter((tag) => labels.has(tag.id)) : []; + // A legacy row can hold a number as its name, so it is read as text. + const carried = (tag: PlaceTagRow): CarriedTag => ({ name: String(tag.name), color: tag.color ?? DEFAULT_TAG_COLOR }); + const byTag = groupByPid(tagged, carried); + const byLabel = groupByPid(labelled, carried); + return Object.fromEntries(placeIds.map((id) => [id, [...(byTag[id] ?? []), ...(byLabel[id] ?? [])]])); } diff --git a/server/src/nest/collections/collections.mcp.ts b/server/src/nest/collections/collections.mcp.ts index bd2232c55..f49e38c2e 100644 --- a/server/src/nest/collections/collections.mcp.ts +++ b/server/src/nest/collections/collections.mcp.ts @@ -1,6 +1,7 @@ import { ADDON_IDS } from '../../addons'; import { Users } from '../../db/entities/Users.entity'; import type { UsersRepository } from '../../db/repositories/Users.repository'; +import { placeCopyReach } from '../../mcp/scopes'; import { McpController, Tool, @@ -353,7 +354,7 @@ export class CollectionsMcp { @Tool({ name: 'update_collection_place', description: - "Update a saved place's name, address, coordinates (lat/lng), description, notes, status, category, links, tags, labels, image, provider ids (google_place_id, google_ftid, osm_id), website, phone, price and currency, or move it to another collection (set collection_id). Only the fields you pass change; null clears one. A bare domain as website gets https://, any other scheme is refused. Moving a place out of a list needs the same role there as deleting it (owner or admin).", + "Update a saved place's name, address, coordinates (lat/lng), description, notes, status, category, links, tags, labels, image, provider ids (google_place_id, google_ftid, osm_id), website, phone, price and currency, or move it to another collection (set collection_id). Only the fields you pass change; null clears one. A bare domain as website gets https://, any other scheme is refused. Moving a place out of a list needs the same role there as deleting it (owner or admin). A change of the name, description, address, position, category, image, website or phone is made on your other copies of the place too (the copies list_all_places shows as one entry), in the lists and trips where you may edit them and of the kinds this token may write (trip places with places:write, saved places with collections:write); notes, tags, status and votes stay with each copy.", inputSchema: { placeId: idSchema, ...collectionPlaceUpdateRequestSchema.shape, links: linksInput }, annotations: TOOL_ANNOTATIONS_WRITE, when: collectionsAddonOn, @@ -364,7 +365,15 @@ export class CollectionsMcp { ctx: McpContext, ) { try { - return ok({ place: await this.collections.updatePlace(ctx.userId, placeId, body) }); + return ok({ + place: await this.collections.updatePlace( + ctx.userId, + placeId, + body, + undefined, + await this.guards.copyFollow(ctx.userId, placeCopyReach(ctx.scopes)), + ), + }); } catch (err) { return fail(err); } @@ -407,26 +416,6 @@ export class CollectionsMcp { } } - @Tool({ - name: 'rate_collection_place', - description: - "Set or clear the current user's 1-5 star rating on a saved collection place (#1435). Every member rates independently; the place shows the average. Pass null (or omit rating) to remove the user's vote. Ratings a member casts here follow the place into any trip it is later copied to. Use the ratings to capture the user's preferences.", - inputSchema: { - placeId: idSchema, - rating: z.number().int().min(1).max(5).nullable().optional().describe('1-5 stars; null/omitted clears the vote'), - }, - annotations: TOOL_ANNOTATIONS_WRITE, - when: collectionsAddonOn, - access: { group: 'collections', mode: 'write' }, - }) - async rateCollectionPlace({ placeId, rating }: { placeId: number; rating?: number | null }, ctx: McpContext) { - try { - return ok({ place: await this.collections.setRating(ctx.userId, placeId, rating ?? null) }); - } catch (err) { - return fail(err); - } - } - @Tool({ name: 'delete_collection_place', description: 'Remove a saved place from its collection. Requires delete permission on the list.', @@ -447,7 +436,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. 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.", + "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. The list's own tags (its labels) come along the same way: label_ids names the ones to bring, where the places carry them, each as a tag of the trip; the trip tag and the list 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.service.ts b/server/src/nest/collections/collections.service.ts index aeca9a375..e306dd531 100644 --- a/server/src/nest/collections/collections.service.ts +++ b/server/src/nest/collections/collections.service.ts @@ -35,8 +35,6 @@ import { COORD_DEDUP_TOLERANCE, isPlaceDuplicate, trackInsertedInDedupSet } from import { placeMatchStrategies, collectionFilePlaceSchema, - COLLECTION_FILE_FORMAT, - COLLECTION_FILE_VERSION, MAX_COLLECTION_FILE_LABELS, type PlaceMatchCandidate, type CollectionFileLabel, @@ -72,8 +70,10 @@ 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 { PlaceCopiesSlot, type FollowCopies, type PlaceCopyChanges } from '../common/place-copies.port'; +import { JoinListeners } from '../common/join-listeners'; import { - filePlaceOf, groupByPid, listingWriteOf, parseLinks, placeOrderOf, serializeLinks, tagKeyOf, tripDedupSet, + collectionFileOf, filePlaceOf, groupByPid, hydratedPlaceOf, parseLinks, placeWriteOf, placeOrderOf, serializeLinks, tagKeyOf, tripDedupSet, tagsToCarry, tripPlaceFields, tripTagIdsOf, } from './collections.helpers'; @@ -126,6 +126,18 @@ export class CollectionsService { private readonly changes: PlaceChangesService, // PLC-14: the history of every details write, in its transaction ) {} + /** The other copies of a place follow an edit (the places library registers here), and who joined a list hears of. */ + readonly copies = new PlaceCopiesSlot(); + readonly joins = new JoinListeners(); + + /** Another copy's edit on this saved place (place-copies.port.ts), in its transaction; no event. Its list, its old picture. */ + async writeCopy(placeId: number, changes: PlaceCopyChanges, editorId: number) { + const collectionId = await this.collectionIdOfPlace(placeId); + const previousImage = changes.image_url !== undefined ? (await this.collectionPlaces.imageUrl(placeId)) ?? null : null; + await this.changes.track(savedPlaceTarget(placeId), editorId, () => this.collectionPlaces.updateFields(placeId, changes)); + return { collectionId, previousImage }; + } + // ------------------------------------------------------------------------- // Visibility — a user may see/edit a collection if they own it OR are an // accepted member. Every read/write goes through assertAccess. @@ -213,25 +225,10 @@ export class CollectionsService { const tagsByPlace = await this.loadTagsByCollectionPlaceIds(ids); const labelsByPlace = await this.loadLabelIdsByPlaceIds(ids); const ratingsByPlace = await this.loadRatingsByCollectionPlaceIds(ids); - return rows.map(r => { - const { category_name, category_color, category_icon, ...rest } = r; - const ratings = ratingsByPlace[r.id] || []; - return { - ...rest, - links: parseLinks((r as { links?: unknown }).links), - category: r.category_id - ? { id: r.category_id, name: category_name ?? '', color: category_color ?? null, icon: category_icon ?? null } - : undefined, - tags: tagsByPlace[r.id] || [], - label_ids: labelsByPlace[r.id] || [], - ratings, - rating_avg: ratings.length > 0 ? ratings.reduce((s, x) => s + x.rating, 0) / ratings.length : null, - rating_count: ratings.length, - } as CollectionPlace; - }); + return rows.map(r => hydratedPlaceOf(r, tagsByPlace[r.id] || [], labelsByPlace[r.id] || [], ratingsByPlace[r.id] || [])); } - private async getPlaceById(placeId: number): Promise { + async getPlaceById(placeId: number): Promise { const row = await this.collectionsRepo.findPlaceRowById(placeId); if (!row) httpError(404, 'Place not found'); return (await this.hydratePlaces([row]))[0]; @@ -318,17 +315,7 @@ export class CollectionsService { filePlaceOf(row, (labelIdsByPlace[row.id] || []).map(lid => labelNameById.get(lid)).filter((n): n is string => !!n)), ); - return { - format: COLLECTION_FILE_FORMAT, - version: COLLECTION_FILE_VERSION, - name: collection.name, - description: collection.description ?? null, - color: collection.color ?? null, - icon: collection.icon ?? null, - exported_at: new Date().toISOString(), - labels: labels.map(l => ({ name: l.name, color: l.color ?? null })), - places, - }; + return collectionFileOf(collection, labels, places); } /** @@ -834,22 +821,12 @@ export class CollectionsService { return { copied, skipped }; } - async updatePlace(userId: number, placeId: number, body: CollectionPlaceUpdateRequest, socketId?: string): Promise { + async updatePlace(userId: number, placeId: number, body: CollectionPlaceUpdateRequest, socketId?: string, follow: FollowCopies | null = null): Promise { const currentCollection = await this.collectionIdOfPlace(placeId); await this.assertCanEdit(userId, currentCollection); const prevImage = body.image_url !== undefined ? (await this.collectionPlaces.imageUrl(placeId)) ?? null : null; - const write: Parameters[1] = listingWriteOf(body); - if (body.name !== undefined) write.name = body.name; - if (body.description !== undefined) write.description = body.description ?? null; - if (body.notes !== undefined) write.notes = body.notes ?? null; - if (body.lat !== undefined) write.lat = body.lat ?? null; - if (body.lng !== undefined) write.lng = body.lng ?? null; - if (body.address !== undefined) write.address = body.address ?? null; - if (body.status !== undefined) write.status = body.status; - if (body.category_id !== undefined) write.category_id = body.category_id ?? null; - if (body.image_url !== undefined) write.image_url = body.image_url ?? null; - if (body.links !== undefined) write.links = serializeLinks(body.links); + const write = placeWriteOf(body); let movedTo: number | null = null; if (body.collection_id !== undefined && body.collection_id !== currentCollection) { @@ -860,8 +837,9 @@ export class CollectionsService { movedTo = body.collection_id; } - // Field update + tag rewrite + label rewrite are one logical write, so one transaction. - await this.uow.transactional(async () => { + // Field update + tag rewrite + label rewrite (+ the copies that follow) are one logical write, so one transaction. + const followed = await this.uow.transactional(async () => { + const follows = await this.copies.plan(follow, { kind: 'list', id: placeId }); // before the write, see the port if (movedTo) write.sort_order = await this.nextPlaceOrder(movedTo); // a moved place joins the end of its new list await this.changes.track(savedPlaceTarget(placeId), userId, () => this.collectionPlaces.updateFields(placeId, write)); @@ -874,11 +852,14 @@ export class CollectionsService { // a provided label_ids set replaces them against the (target) collection. if (movedTo) await this.collectionPlaces.deleteLabelAssignments(placeId); if (body.label_ids !== undefined) await this.setPlaceLabels(placeId, movedTo ?? currentCollection, body.label_ids); + return follows ? follows() : null; }); - await this.release.releaseValues([prevImage]); // a replaced custom thumbnail (#1136), unless a copy names it + // A replaced custom thumbnail (#1136), and the copies' ones, unless a copy names it. + await this.release.releaseValues([prevImage, ...(followed?.previousImages ?? [])]); await this.notifyCollectionUsers(currentCollection, socketId, 'collections:updated'); if (movedTo) await this.notifyCollectionUsers(movedTo, socketId, 'collections:updated'); + await this.copies.announce(followed); return this.getPlaceById(placeId); } @@ -891,20 +872,17 @@ export class CollectionsService { } /** - * Set (1-5) or clear (null) the user's own star vote on a saved place (#1435). - * Gated on assertAccess, not assertCanEdit — a vote is the member's personal - * opinion, so read-only viewers get to cast one too. + * The user's vote on a saved place (#1435) under the list's check (any member, viewers too), null taking it back; + * no event, PlaceVotesService announces each list after the commit. With `carry` (the carry-over) it only adds a + * vote where the user has none, as changed at `carry.at`, never overwriting one. Answers the list. */ - async setRating(userId: number, placeId: number, rating: number | null, socketId?: string): Promise { + async writeRating(userId: number, placeId: number, rating: number | null, carry?: { at: string | null }) { const collectionId = await this.collectionIdOfPlace(placeId); await this.assertAccess(userId, collectionId); - if (rating === null) { - await this.collectionPlaceRatings.deleteRating(placeId, userId); - } else { - await this.collectionPlaceRatings.upsertRating(placeId, userId, rating); - } - await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated'); - return this.getPlaceById(placeId); + if (rating === null) await this.collectionPlaceRatings.deleteRating(placeId, userId); + else if (carry) await this.collectionPlaceRatings.insertIgnoreRating(placeId, userId, rating, carry.at); + else await this.collectionPlaceRatings.upsertRating(placeId, userId, rating); + return collectionId; } // A saved place's image goes with it unless a trip place it was copied to (or from) still names it (#2924). @@ -1025,13 +1003,18 @@ export class CollectionsService { } /** Set (or clear) a saved place's custom thumbnail; the replaced upload goes unless another row names it. */ - async setPlaceImage(userId: number, placeId: number, imageUrl: string | null, socketId?: string): Promise { + async setPlaceImage(userId: number, placeId: number, imageUrl: string | null, socketId?: string, follow: FollowCopies | null = null): Promise { const collectionId = await this.collectionIdOfPlace(placeId); await this.assertCanEdit(userId, collectionId); const prev = (await this.collectionPlaces.imageUrl(placeId)) ?? null; - await this.uow.transactional(() => this.changes.track(savedPlaceTarget(placeId), userId, () => this.collectionPlaces.setImageUrl(placeId, imageUrl))); - await this.release.releaseValues([prev]); + const followed = await this.uow.transactional(async () => { + const follows = await this.copies.plan(follow, { kind: 'list', id: placeId }); + await this.changes.track(savedPlaceTarget(placeId), userId, () => this.collectionPlaces.setImageUrl(placeId, imageUrl)); + return follows ? follows() : null; + }); + await this.release.releaseValues([prev, ...(followed?.previousImages ?? [])]); await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated'); + await this.copies.announce(followed); return this.getPlaceById(placeId); } @@ -1066,9 +1049,8 @@ export class CollectionsService { } const dedup = tripDedupSet(await this.tripPlaces.dedupCandidatesForTrip(body.trip_id)); - // 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); + // D9/PLC-21: only the tags asked for (the place's tags, the list's labels), as tags of the trip. + const carried = await tagsToCarry(body, sources.map(s => s.id), this.collectionsRepo); const tripTags = new Map(); // by name, read in the transaction that adds to them let tagsBefore = 0; @@ -1298,6 +1280,7 @@ export class CollectionsService { const inviteId = await this.members.findPendingInvite(collectionId, userId); if (inviteId === undefined) throw new DomainError(404, 'No pending invite'); await this.members.accept(inviteId); + await this.joins.joined(collectionId, userId); // before the list hears of it: the votes they bring along (PlaceVotesService) await this.notifyCollectionUsers(collectionId, socketId, 'collections:accepted'); } diff --git a/server/src/nest/common/app-settings.registry.ts b/server/src/nest/common/app-settings.registry.ts index 99b037941..b2a188757 100644 --- a/server/src/nest/common/app-settings.registry.ts +++ b/server/src/nest/common/app-settings.registry.ts @@ -141,6 +141,10 @@ export const APP_SETTINGS = { dawarich_poll_interval_minutes: { schema: intText, default: null }, /** The release the admins were last notified about (the version-check job's memory). */ last_notified_version: { schema: text, default: null }, + /** When the one pass that carried every person's place votes onto their other copies of the place finished. */ + place_votes_carried_over: { schema: text, default: null }, + /** How many starts that pass has run on; past its limit it is marked finished even with people it could not carry. */ + place_votes_carry_runs: { schema: intText, default: null }, // The trip assistant: whose connection it runs on, how many turns a day a // user may take on the instance's, and how long chats are kept (the JSON of // aiRetentionSchema). The admin sets them through /api/admin/ai/settings. diff --git a/server/src/nest/common/join-listeners.ts b/server/src/nest/common/join-listeners.ts new file mode 100644 index 000000000..3295c41f9 --- /dev/null +++ b/server/src/nest/common/join-listeners.ts @@ -0,0 +1,21 @@ +/** Told that somebody joined a list or a trip: its id and theirs. */ +export type JoinListener = (containerId: number, userId: number) => Promise; + +/** + * Who wants to hear that somebody joined a list or a trip, kept by the service + * that makes the join and filled once at boot by a domain above it (the + * places library carries the joiner's votes in, PlaceVotesService), so the + * join does not depend on that domain. A listener contains its own failures: + * the join never fails for one. + */ +export class JoinListeners { + private readonly listeners: JoinListener[] = []; + + add(listener: JoinListener): void { + this.listeners.push(listener); + } + + async joined(containerId: number, userId: number): Promise { + for (const listener of this.listeners) await listener(containerId, userId); + } +} diff --git a/server/src/nest/common/place-copies.port.ts b/server/src/nest/common/place-copies.port.ts new file mode 100644 index 000000000..a982b7bc0 --- /dev/null +++ b/server/src/nest/common/place-copies.port.ts @@ -0,0 +1,136 @@ +/** + * Copies of a place stay in step: an edit of the general facts of a place in + * one list or trip (its name, description, address, position, category, + * picture, website and phone) is made on every other copy of that place the + * editor may edit, in the same transaction. Which copies are one place is the + * places library's grouping (All places), which sits above the lists and the + * trips; this port is how their services hand an edit up to it without + * depending on it. The library registers the one follower at boot + * (`PlaceCopiesService`); a service without one, or an edit that names no + * follow, changes its own copy only. + */ + +/** Who edits, as the permission checks read them. */ +export interface CopyEditor { + id: number; + role: string; +} + +/** + * The kinds of the editor's other copies an edit may reach: REST reaches both, + * an MCP token only the kinds it holds write scope for (`places:write` the + * trip places, `collections:write` the saved places). + */ +export interface CopyReach { + trips: boolean; + lists: boolean; +} + +/** An edit that the other copies follow, and who makes it. */ +export interface FollowCopies { + editor: CopyEditor; + reach?: CopyReach; +} + +/** The copy an edit starts from: a trip place or a saved place. */ +export interface CopyOrigin { + kind: 'trip' | 'list'; + id: number; +} + +/** The facts of a place that follow from one copy to the others; any other field stays each copy's own. */ +export interface PlaceCopyFacts { + name: string; + description: string | null; + address: string | null; + lat: number | null; + lng: number | null; + category_id: number | null; + image_url: string | null; + website: string | null; + phone: string | null; +} + +/** The facts an edit changed, to write on a copy. */ +export type PlaceCopyChanges = Partial; + +/** One other copy as the edit found it, before it changed anything. */ +export interface CopyTarget { + kind: 'trip' | 'list'; + /** The trip of a trip place, the list of a saved place. */ + containerId: number; + placeId: number; + facts: PlaceCopyFacts; +} + +/** + * What following an edit needs, read before the edit writes anything: the + * grouping decides by name and position too, so it is read while the copies + * still agree. The copies are the ones the editor may edit, of the kinds the + * edit may reach. + */ +export interface CopiesPlan { + origin: CopyOrigin; + editorId: number; + before: PlaceCopyFacts; + targets: CopyTarget[]; + /** The trips and lists the editor reached when the plan was read, to read the origin again in. */ + tripIds: number[]; + collectionIds: number[]; +} + +/** The copies an edit changed, for the announcements after the commit, and the pictures it replaced on them. */ +export interface FollowedCopies { + trips: { tripId: number; placeId: number }[]; + lists: { collectionId: number; placeId: number }[]; + previousImages: (string | null | undefined)[]; +} + +/** No copy changed. */ +export const NO_FOLLOWED_COPIES: FollowedCopies = { trips: [], lists: [], previousImages: [] }; + +/** Two edits' changed copies as one, for a write that edits several places in one transaction. */ +export function mergeFollowed(a: FollowedCopies, b: FollowedCopies): FollowedCopies { + return { + trips: [...a.trips, ...b.trips], + lists: [...a.lists, ...b.lists], + previousImages: [...a.previousImages, ...b.previousImages], + }; +} + +/** + * The library's side of the port. `plan` and `apply` run inside the edit's + * transaction (`plan` before the edit writes, `apply` after it), `announce` + * after the commit. + */ +export interface PlaceCopiesFollower { + plan(follow: FollowCopies, origin: CopyOrigin): Promise; + apply(plan: CopiesPlan): Promise; + announce(followed: FollowedCopies): Promise; +} + +/** + * Where the lists' and the trips' services keep the follower the library + * registered, and how an edit asks it: `plan` inside the edit's transaction + * before it writes, which answers the step to run after the write (null when + * no copy follows), and `announce` after the commit. + */ +export class PlaceCopiesSlot { + private follower: PlaceCopiesFollower | null = null; + + /** Registered once at boot by the places library (PlaceCopiesService). */ + register(follower: PlaceCopiesFollower): void { + this.follower = follower; + } + + async plan(follow: FollowCopies | null, origin: CopyOrigin): Promise<(() => Promise) | null> { + const follower = this.follower; + if (follow === null || follower === null) return null; + const plan = await follower.plan(follow, origin); + return plan === null ? null : () => follower.apply(plan); + } + + async announce(followed: FollowedCopies | null | undefined): Promise { + if (followed && this.follower) await this.follower.announce(followed); + } +} diff --git a/server/src/nest/mcp-shared/mcp-tool-guards.service.ts b/server/src/nest/mcp-shared/mcp-tool-guards.service.ts index 933ec01f1..7c21a2a44 100644 --- a/server/src/nest/mcp-shared/mcp-tool-guards.service.ts +++ b/server/src/nest/mcp-shared/mcp-tool-guards.service.ts @@ -2,6 +2,7 @@ import { Trips } from '../../db/entities/Trips.entity'; import { Users } from '../../db/entities/Users.entity'; import type { TripsRepository } from '../../db/repositories/Trips.repository'; import type { UsersRepository } from '../../db/repositories/Users.repository'; +import type { CopyReach, FollowCopies } from '../common/place-copies.port'; import type { TripEventSink, TripWriter } from '../common/trip-writer'; import { PermissionsService } from '../permissions/permissions.service'; import { RealtimeService } from '../realtime/realtime.service'; @@ -115,4 +116,14 @@ export class McpToolGuardsService { async isAdminUser(userId: number): Promise { return (await this.users.getRole(userId)) === 'admin'; } + + /** + * How an edit by the tool caller reaches their other copies of the place + * (place-copies.port.ts): with their role for the checks, onto the kinds + * `reach` names (the token's write scopes, `placeCopyReach`). + */ + async copyFollow(userId: number, reach: CopyReach): Promise { + const role = (await this.users.getRole(userId)) ?? 'user'; + return { editor: { id: userId, role }, reach }; + } } diff --git a/server/src/nest/places-library/library-tags.helpers.ts b/server/src/nest/places-library/library-tags.helpers.ts new file mode 100644 index 000000000..39d2e4140 --- /dev/null +++ b/server/src/nest/places-library/library-tags.helpers.ts @@ -0,0 +1,96 @@ +import type { LibraryOwnedTagRow, LibraryTripTagRow } from '../../db/repositories/PlacesLibrary.repository'; +import type { EntryRows } from './places-library.helpers'; +import type { PlacesLibraryEntryTag, PlacesLibraryTag } from '@trek/shared'; + +/** + * PLC-21, the pure half of the tags on "All places". A place carries the tags + * of the lists and trips it is in: a list's labels on its saved place, a trip's + * tags on its trip place. Every member of the list or the trip sees them, and + * they are changed there; All places only gathers them. + */ + +/** A label of a list on one of its saved places, as the detail reads them. */ +interface LibraryLabelTagRow { + collection_place_id: number; + id: number; + name: string; + color: string | null; +} + +/** Two names are one tag when they read the same, whatever their case. */ +function nameKey(name: string): string { + return name.trim().toLowerCase(); +} + +/** Lower case for ASCII letters only, the way SQLite's `lower()` reads a name. */ +function asciiLower(name: string): string { + return name.replace(/[A-Z]/g, (char) => char.toLowerCase()); +} + +/** + * The names a filter asks for, each in every spelling an engine folds a stored + * name to (`lower(trim(name))`): SQLite lowers ASCII letters only, Postgres + * every letter, so a name typed as stored matches on both, whatever its case. + */ +export function foldTagNames(names: readonly string[]): string[] { + const folded = new Set(); + for (const name of names) { + const trimmed = name.trim(); + folded.add(trimmed.toLowerCase()); + folded.add(asciiLower(trimmed)); + } + return [...folded]; +} + +/** A tag row as a detail names it. */ +export function tagOf(row: { id: number; name: string; color: string | null }): PlacesLibraryTag { + return { id: row.id, name: row.name, color: row.color }; +} + +/** + * Each entry's tags in the entries' order: the tags on its trip places, then + * the labels on its saved places, a name once whatever its case (the colour of + * the first one read), sorted by name. + */ +export function entryTagsOf( + entries: readonly EntryRows[], + tripTags: readonly LibraryTripTagRow[], + labels: readonly LibraryLabelTagRow[], +): PlacesLibraryEntryTag[][] { + return entries.map((entry) => { + const placeIds = new Set(entry.trips.map((trip) => trip.id)); + const savedIds = new Set(entry.saved.map((saved) => saved.id)); + const byName = new Map(); + const add = (row: { name: string; color: string | null }) => { + const key = nameKey(row.name); + if (key !== '' && !byName.has(key)) byName.set(key, { name: row.name, color: row.color }); + }; + for (const row of tripTags) if (placeIds.has(row.place_id)) add(row); + for (const row of labels) if (savedIds.has(row.collection_place_id)) add(row); + return [...byName.entries()].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)).map(([, tag]) => tag); + }); +} + +/** The tags each trip or list owns, by its id. */ +export function tagsByOwner(rows: readonly LibraryOwnedTagRow[]): Map { + const owned = new Map(); + for (const row of rows) { + const list = owned.get(row.owner_id) ?? []; + list.push(tagOf(row)); + owned.set(row.owner_id, list); + } + return owned; +} + +/** + * The tags an origin can put on its place: every tag its trip or list owns, then + * any tag the place already carries that is not one of them (an older personal + * tag of someone on the trip), so taking it off can be undone from the same list. + */ +export function offeredTags( + owned: readonly PlacesLibraryTag[], + assigned: readonly PlacesLibraryTag[], +): PlacesLibraryTag[] { + const ids = new Set(owned.map((tag) => tag.id)); + return [...owned, ...assigned.filter((tag) => !ids.has(tag.id))]; +} diff --git a/server/src/nest/places-library/place-copies.helpers.ts b/server/src/nest/places-library/place-copies.helpers.ts new file mode 100644 index 000000000..3561a7685 --- /dev/null +++ b/server/src/nest/places-library/place-copies.helpers.ts @@ -0,0 +1,85 @@ +import type { LibraryCollectionPlaceRow, LibraryTripPlaceRow } from '../../db/repositories/PlacesLibrary.repository'; +import type { CopyTarget, PlaceCopyChanges, PlaceCopyFacts } from '../common/place-copies.port'; +import type { EntryRows } from './places-library.helpers'; + +/** The facts that follow from one copy to the others, in the order the port names them. */ +const FACT_KEYS = [ + 'name', + 'description', + 'address', + 'lat', + 'lng', + 'category_id', + 'image_url', + 'website', + 'phone', +] as const satisfies readonly (keyof PlaceCopyFacts)[]; + +/** The general facts of a trip place or a saved place. */ +export function factsOf(row: LibraryTripPlaceRow | LibraryCollectionPlaceRow): PlaceCopyFacts { + return { + name: row.name, + description: row.description ?? null, + address: row.address ?? null, + lat: row.lat ?? null, + lng: row.lng ?? null, + category_id: row.category_id ?? null, + image_url: row.image_url ?? null, + website: row.website ?? null, + phone: row.phone ?? null, + }; +} + +/** The facts that differ between `before` and `after`, with their value after. */ +export function changesOf(before: PlaceCopyFacts, after: PlaceCopyFacts): PlaceCopyChanges { + const changes: Record = {}; + for (const key of FACT_KEYS) { + if (before[key] !== after[key]) changes[key] = after[key]; + } + return changes as PlaceCopyChanges; +} + +/** Of `changes`, the ones a copy does not hold already; an existing difference elsewhere stays as it is. */ +export function ownChangesOf(changes: PlaceCopyChanges, facts: PlaceCopyFacts): PlaceCopyChanges { + const own: Record = {}; + for (const key of FACT_KEYS) { + if (key in changes && changes[key] !== facts[key]) own[key] = changes[key]; + } + return own as PlaceCopyChanges; +} + +/** Which copies an edit may reach, and the editor's checks on each. */ +interface CopyReachOf { + trips: boolean; + lists: boolean; + canEditTrip: (row: LibraryTripPlaceRow) => boolean; + canEditList: (row: LibraryCollectionPlaceRow) => boolean; +} + +/** + * The copies of one entry an edit follows onto: every one but the use the edit + * started from (from_list 0: a trip place, 1: a saved place), of the kinds it + * reaches, that the editor may edit. Any other copy is skipped, never refused. + */ +export function copyTargetsOf( + rows: EntryRows, + origin: { fromList: number; id: number }, + reach: CopyReachOf, +): CopyTarget[] { + const trips = reach.trips + ? rows.trips + .filter((row) => !(origin.fromList === 0 && origin.id === row.id) && reach.canEditTrip(row)) + .map((row): CopyTarget => ({ kind: 'trip', containerId: row.trip_id, placeId: row.id, facts: factsOf(row) })) + : []; + const lists = reach.lists + ? rows.saved + .filter((row) => !(origin.fromList === 1 && origin.id === row.id) && reach.canEditList(row)) + .map((row): CopyTarget => ({ + kind: 'list', + containerId: row.collection_id, + placeId: row.id, + facts: factsOf(row), + })) + : []; + return [...trips, ...lists]; +} diff --git a/server/src/nest/places-library/place-copies.service.ts b/server/src/nest/places-library/place-copies.service.ts new file mode 100644 index 000000000..3402480d6 --- /dev/null +++ b/server/src/nest/places-library/place-copies.service.ts @@ -0,0 +1,132 @@ +import { ADDON_IDS } from '../../addons'; +import { PlacesLibraryRepository } from '../../db/repositories/PlacesLibrary.repository'; +import { AddonsService } from '../addons/addons.service'; +import { CollectionsService } from '../collections/collections.service'; +import { inOrder } from '../common/in-order'; +import { + NO_FOLLOWED_COPIES, + type CopiesPlan, + type CopyOrigin, + type FollowCopies, + type FollowedCopies, + type PlaceCopiesFollower, +} from '../common/place-copies.port'; +import { UnitOfWork } from '../database/unit-of-work'; +import { PlacesService } from '../places/places.service'; +import { changesOf, copyTargetsOf, factsOf, ownChangesOf } from './place-copies.helpers'; +import { fromListOf } from './places-library.helpers'; +import { PlacesLibraryService } from './places-library.service'; +import { Injectable, type OnModuleInit } from '@nestjs/common'; + +/** + * The follower of place-copies.port.ts: an edit of the general facts of a + * place on one copy is made on every other copy of it the editor may edit. + * Which copies are one place is the grouping of All places + * (PlacesLibraryService, the one the votes use); which ones the editor may + * edit is the library's own reading of the checks: a list role but viewer for + * a saved place, the trip's place_edit for a trip place. A copy outside that, + * of a kind the edit may not reach (an MCP token's write scopes), or a saved + * place while the Collections addon is off, is left as it is. Each copy is + * written through its owner's service, with its history entry (PLC-14). + * + * The category needs no mapping: the trip places and the saved places name + * the same categories (copying a saved place to a trip carries its + * category_id as it is), so the id goes across unchanged. + */ +@Injectable() +export class PlaceCopiesService implements PlaceCopiesFollower, OnModuleInit { + constructor( + private readonly library: PlacesLibraryService, + private readonly repo: PlacesLibraryRepository, + private readonly collections: CollectionsService, + private readonly places: PlacesService, + private readonly addons: AddonsService, + private readonly uow: UnitOfWork, + ) {} + + onModuleInit(): void { + this.collections.copies.register(this); + this.places.copies.register(this); + } + + /** The editor's other copies of the place, as they read before the edit; null when there are none. */ + async plan(follow: FollowCopies, origin: CopyOrigin): Promise { + const reach = await this.library.reach(follow.editor.id); + const anchor = await this.library.anchorOfUse(reach, origin.kind, origin.id); + if (anchor === null) return null; + const rows = (await this.library.rows(reach, [anchor]))[0]; + if (!rows) return null; + const self = (origin.kind === 'trip' ? rows.trips : rows.saved).find((row) => row.id === origin.id); + if (!self) return null; + const access = await this.library.access(follow.editor, rows.trips, rows.saved); + const lists = (follow.reach?.lists ?? true) && (await this.addons.isAddonEnabled(ADDON_IDS.COLLECTIONS)); + const targets = copyTargetsOf( + rows, + { fromList: fromListOf(origin.kind), id: origin.id }, + { + trips: follow.reach?.trips ?? true, + lists, + canEditTrip: access.canEditTrip, + canEditList: access.canEditList, + }, + ); + if (targets.length === 0) return null; + return { + origin, + editorId: follow.editor.id, + before: factsOf(self), + targets, + tripIds: reach.tripIds, + collectionIds: reach.collectionIds, + }; + } + + /** + * After the edit wrote its own copy: what it changed there, onto each other + * copy that does not hold it yet. Inside the edit's transaction (a savepoint + * of it), so the copies change with the edit or not at all. + */ + async apply(plan: CopiesPlan): Promise { + return this.uow.transactional(() => this.follow(plan)); + } + + private async follow(plan: CopiesPlan): Promise { + const after = + plan.origin.kind === 'trip' + ? (await this.repo.tripPlaces([plan.origin.id], plan.tripIds))[0] + : (await this.repo.savedPlaces(plan.collectionIds, [plan.origin.id]))[0]; + if (!after) return NO_FOLLOWED_COPIES; + const changes = changesOf(plan.before, factsOf(after)); + if (Object.keys(changes).length === 0) return NO_FOLLOWED_COPIES; + const followed: FollowedCopies = { trips: [], lists: [], previousImages: [] }; + await inOrder(plan.targets, async (target) => { + const own = ownChangesOf(changes, target.facts); + if (Object.keys(own).length === 0) return; + if (target.kind === 'trip') { + const written = await this.places.writeCopy(target.containerId, target.placeId, own, plan.editorId); + if (!written) return; + followed.trips.push({ tripId: target.containerId, placeId: target.placeId }); + followed.previousImages.push(written.previousImage); + return; + } + const written = await this.collections.writeCopy(target.placeId, own, plan.editorId); + followed.lists.push({ collectionId: written.collectionId, placeId: target.placeId }); + followed.previousImages.push(written.previousImage); + }); + return followed; + } + + /** After the commit: each changed trip place to its trip's room, each touched list once to its members. */ + async announce(followed: FollowedCopies): Promise { + await inOrder(followed.trips, async ({ tripId, placeId }) => { + const place = await this.places.get(String(tripId), String(placeId)); + if (!place) return; + this.places.broadcast(String(tripId), 'place:updated', { place }, undefined); + await this.places.onUpdated(placeId); + }); + const lists = [...new Set(followed.lists.map((list) => list.collectionId))]; + await inOrder(lists, (collectionId) => + this.collections.notifyCollectionUsers(collectionId, undefined, 'collections:updated'), + ); + } +} diff --git a/server/src/nest/places-library/place-tags.controller.ts b/server/src/nest/places-library/place-tags.controller.ts deleted file mode 100644 index 379056e72..000000000 --- a/server/src/nest/places-library/place-tags.controller.ts +++ /dev/null @@ -1,38 +0,0 @@ -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 deleted file mode 100644 index 20f6d9291..000000000 --- a/server/src/nest/places-library/place-tags.helpers.ts +++ /dev/null @@ -1,70 +0,0 @@ -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 deleted file mode 100644 index c34b03f0f..000000000 --- a/server/src/nest/places-library/place-tags.mcp.ts +++ /dev/null @@ -1,65 +0,0 @@ -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 deleted file mode 100644 index 6095fd475..000000000 --- a/server/src/nest/places-library/place-tags.service.ts +++ /dev/null @@ -1,99 +0,0 @@ -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-votes-carry.job.ts b/server/src/nest/places-library/place-votes-carry.job.ts new file mode 100644 index 000000000..54b303027 --- /dev/null +++ b/server/src/nest/places-library/place-votes-carry.job.ts @@ -0,0 +1,122 @@ +import { logError, logInfo, logWarn } from '../audit/audit-log.logger'; +import { inOrder } from '../common/in-order'; +import { CronRegistrarService } from '../scheduling/cron-registrar.service'; +import { SettingsService } from '../settings/settings.service'; +import { PlaceVotesService } from './place-votes.service'; +import { Injectable, type OnApplicationBootstrap } from '@nestjs/common'; + +/** How many people one page of the pass reads; each page runs in a request context of its own. */ +const CARRY_PAGE = 100; + +/** + * How many starts the pass runs on at most. A pass that could not carry + * somebody runs again on the next start, but a failure that stays (a row the + * checks keep refusing) must not repeat the whole pass forever; that person's + * next vote writes all their copies anyway. + */ +export const CARRY_MAX_RUNS = 3; + +/** Where the pass stands: whether it ran before, the last person read, what it added and how many people failed. */ +interface CarryPass { + finished: boolean; + after: number; + added: number; + failed: number; +} + +/** + * One pass, on the first start of the version where a vote belongs to its + * person, that carries every person's existing votes onto their other copies + * of the same place (PlaceVotesService.carryOver): adds only, never changes or + * removes a vote, and leaves a person's differing votes on two copies as they + * are. + * + * Not a migration: which copies are one place is the library's grouping + * (PlacesLibraryService over PlacesLibraryRepository: a saved place and the + * trip place it came from when they agree, the person's own places and their + * links), read per person against the lists and trips they reach today. A + * frozen SQL copy of that would drift from the code that decides it, and each + * copy is written through its owner's service under its own check. + * + * Safe on a large install: in the background, a page of people at a time, one + * transaction per person, and a person whose pass fails is logged and skipped. + * app_settings remembers that the pass finished; one cut short by a restart + * or left with a failure runs again (on at most CARRY_MAX_RUNS starts), and a + * second run adds nothing the first one added: every carried vote is an + * insert that leaves a vote already there alone. + */ +@Injectable() +export class PlaceVotesCarryJob implements OnApplicationBootstrap { + constructor( + private readonly votes: PlaceVotesService, + private readonly settings: SettingsService, + private readonly registrar: CronRegistrarService, + ) {} + + onApplicationBootstrap(): void { + if (!this.registrar.isEnabled()) return; + void this.run().catch((err: unknown) => { + logError(`Place votes carry-over: ${err instanceof Error ? err.message : String(err)}`); + }); + } + + /** + * The pass when it has not finished before. + * @txIndependent a page of people after another, each person in a transaction of their own, then the mark. + */ + async run(): Promise { + const pass: CarryPass = { finished: false, after: 0, added: 0, failed: 0 }; + await this.registrar.runOnBoot('place-votes-carry-check', async () => { + pass.finished = (await this.settings.getAppSetting('place_votes_carried_over')) !== null; + }); + if (pass.finished) return; + const run = { count: 0 }; + await this.registrar.runOnBoot('place-votes-carry-start', async () => { + run.count = Number((await this.settings.getAppSetting('place_votes_carry_runs')) ?? '0') + 1; + await this.settings.setAppSettings({ place_votes_carry_runs: String(run.count) }); + }); + await this.pages(pass); + if (pass.added > 0) logInfo(`Place votes: carried ${pass.added} vote(s) onto other copies of the same place`); + // A pass with a failure runs again on the next start, for the people it could not finish, up to CARRY_MAX_RUNS starts. + if (pass.failed > 0 && run.count < CARRY_MAX_RUNS) return; + if (pass.failed > 0) { + logWarn( + `Place votes: ${pass.failed} person(s) still failed after ${run.count} runs of the carry-over; it stops here, their next vote writes all their copies`, + ); + } + await this.registrar.runOnBoot('place-votes-carry-done', () => + this.settings.insertAppSettingIfAbsent('place_votes_carried_over', new Date().toISOString()), + ); + } + + /** The pages of people from `pass.after` on, one after another, each in a request context of its own. */ + private async pages(pass: CarryPass): Promise { + const read = { page: [] as number[] }; + await this.registrar.runOnBoot('place-votes-carry', async () => { + read.page = await this.votes.voters(pass.after, CARRY_PAGE); + const counts = await this.carryPage(read.page); + pass.added += counts.added; + pass.failed += counts.failed; + }); + if (read.page.length < CARRY_PAGE) return; + pass.after = read.page[read.page.length - 1] ?? pass.after; + await this.pages(pass); + } + + /** + * One page of people, each in a transaction of their own. + * @txIndependent one transaction per person of the pass, so one person's failure keeps the others' votes. + */ + async carryPage(userIds: readonly number[]): Promise<{ added: number; failed: number }> { + const counts = { added: 0, failed: 0 }; + await inOrder(userIds, async (userId) => { + try { + counts.added += await this.votes.carryOver(userId); + } catch (err: unknown) { + counts.failed++; + logError(`Place votes carry-over for user ${userId}: ${err instanceof Error ? err.message : String(err)}`); + } + }); + return counts; + } +} diff --git a/server/src/nest/places-library/place-votes.controller.ts b/server/src/nest/places-library/place-votes.controller.ts new file mode 100644 index 000000000..5a4592eeb --- /dev/null +++ b/server/src/nest/places-library/place-votes.controller.ts @@ -0,0 +1,129 @@ +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 { notFound } from '../common/domain-error'; +import { ResponseContract } from '../common/response-contract'; +import { rowId } from '../common/row-id.pipe'; +import { TripAccessGuard } from '../permissions/trip-access.guard'; +import { PlacesService } from '../places/places.service'; +import type { VoteEvents } from './place-votes.service'; +import { PlaceVotesService } from './place-votes.service'; +import { PlaceRatingDto, PlacesLibraryRateDto, PlacesLibraryUnrateQueryDto } from './places-library.dto'; +import { Body, Controller, Delete, Headers, Param, Put, Query, UseGuards } from '@nestjs/common'; +import { + collectionPlaceRateResponseSchema, + placeRateResponseSchema, + placesLibraryRateResponseSchema, +} from '@trek/shared'; + +/** REST's way out for a vote: each trip place to its trip's room, the caller's socket skipped on the copy voted on. */ +function restEvents(places: PlacesService, socketId: string | undefined): VoteEvents { + return { + trip: (tripId, place, voted) => + places.broadcast(String(tripId), 'place:updated', { place }, voted ? socketId : undefined), + socketId, + }; +} + +/** + * The vote on a saved place (#1435) and on an entry of All places, under the + * Collections addon like every list route. A vote on one copy of a place is + * the person's vote on all of its copies (PlaceVotesService); the route, its + * check and its answer are the ones the list route always had. + */ +@Controller('api/addons/collections') +@UseGuards(AddonGuard, JwtAuthGuard) +@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections') +export class PlaceVotesListController { + constructor( + private readonly votes: PlaceVotesService, + private readonly places: PlacesService, + ) {} + + @Put('places/:pid/rating') + @ResponseContract(collectionPlaceRateResponseSchema) + setRating( + @CurrentUser() user: User, + @Param('pid', rowId('Place not found')) pid: number, + @Body() body: PlaceRatingDto, + @Headers('x-socket-id') socketId?: string, + ) { + return this.votes.voteOnSavedPlace(user.id, pid, body.rating, restEvents(this.places, socketId)); + } + + @Delete('places/:pid/rating') + @ResponseContract(collectionPlaceRateResponseSchema) + clearRating( + @CurrentUser() user: User, + @Param('pid', rowId('Place not found')) pid: number, + @Headers('x-socket-id') socketId?: string, + ) { + return this.votes.voteOnSavedPlace(user.id, pid, null, restEvents(this.places, socketId)); + } + + /** The user's vote on an entry of All places, by its key, on every copy of it they may vote on. */ + @Put('library/places/rating') + @ResponseContract(placesLibraryRateResponseSchema) + rateEntry(@CurrentUser() user: User, @Body() body: PlacesLibraryRateDto, @Headers('x-socket-id') socketId?: string) { + return this.votes.voteOnEntry(user.id, body.key, body.rating, restEvents(this.places, socketId)); + } + + @Delete('library/places/rating') + @ResponseContract(placesLibraryRateResponseSchema) + unrateEntry( + @CurrentUser() user: User, + @Query() query: PlacesLibraryUnrateQueryDto, + @Headers('x-socket-id') socketId?: string, + ) { + return this.votes.voteOnEntry(user.id, query.key, null, restEvents(this.places, socketId)); + } +} + +/** + * The vote on a trip place (#1435), the routes and answers the trip's place + * routes always had: every member may vote, place_edit is not asked, and the + * vote lands on the person's other copies of the place too. + */ +@Controller('api/trips/:tripId/places') +@UseGuards(JwtAuthGuard) +export class PlaceVotesTripController { + constructor( + private readonly votes: PlaceVotesService, + private readonly places: PlacesService, + ) {} + + @Put(':id/rating') + @ResponseContract(placeRateResponseSchema) + async rate( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Body() body: PlaceRatingDto, + @Headers('x-socket-id') socketId?: string, + ) { + // In the handler, not a guard: the body's 400 has always come before the trip's 404 here. + if (!(await this.places.verifyTripAccess(tripId, user.id))) throw notFound('Trip not found'); + return this.vote(user, tripId, id, body.rating, socketId); + } + + @Delete(':id/rating') + @UseGuards(TripAccessGuard) + @ResponseContract(placeRateResponseSchema) + async unrate( + @CurrentUser() user: User, + @Param('tripId') tripId: string, + @Param('id') id: string, + @Headers('x-socket-id') socketId?: string, + ) { + return this.vote(user, tripId, id, null, socketId); + } + + private async vote(user: User, tripId: string, id: string, rating: number | null, socketId: string | undefined) { + const place = await this.votes.voteOnTripPlace(user.id, tripId, id, rating, restEvents(this.places, socketId)); + if (!place) throw notFound('Place not found'); + return { place }; + } +} diff --git a/server/src/nest/places-library/place-votes.helpers.ts b/server/src/nest/places-library/place-votes.helpers.ts new file mode 100644 index 000000000..acc280775 --- /dev/null +++ b/server/src/nest/places-library/place-votes.helpers.ts @@ -0,0 +1,53 @@ +import type { LibraryOwnVoteRow, LibraryUseRow } from '../../db/repositories/PlacesLibrary.repository'; +import { castAfter, type EntryRows } from './places-library.helpers'; + +/** The copies of a place a vote lands on: trip places with their trip, and saved places. */ +export interface VoteCopies { + trips: { tripId: number; placeId: number }[]; + lists: { placeId: number }[]; +} + +/** The copies of one entry, but the use `except` (from_list 0: a trip place, 1: a saved place). */ +export function voteTargetsOf(rows: EntryRows, except: { fromList: number; id: number } | null): VoteCopies { + const skip = (fromList: number, id: number) => except !== null && except.fromList === fromList && except.id === id; + return { + trips: rows.trips.filter((row) => !skip(0, row.id)).map((row) => ({ tripId: row.trip_id, placeId: row.id })), + lists: rows.saved.filter((row) => !skip(1, row.id)).map((row) => ({ placeId: row.id })), + }; +} + +/** A vote to carry onto a copy that has none: the use, by kind and id, its stars and when it was last changed. */ +export interface CarriedVote { + fromList: number; + useId: number; + rating: number; + changedAt: string | null; +} + +/** + * What carrying a person's votes over adds: for each place they have a vote + * on at least one copy of, the vote they changed last, on each copy of it where + * they have none. A copy with a vote keeps it, also one that differs from the + * person's vote elsewhere. Run again, it adds nothing it added before. + */ +export function votesToCarry(uses: readonly LibraryUseRow[], votes: readonly LibraryOwnVoteRow[]): CarriedVote[] { + const voteOf = new Map(votes.map((vote) => [`${vote.from_list}:${vote.use_id}`, vote])); + const byAnchor = new Map(); + for (const use of uses) byAnchor.set(use.anchor_key, [...(byAnchor.get(use.anchor_key) ?? []), use]); + const carried: CarriedVote[] = []; + for (const copies of byAnchor.values()) { + if (copies.length < 2) continue; + let last: LibraryOwnVoteRow | undefined; + for (const copy of copies) { + const vote = voteOf.get(`${copy.from_list}:${copy.use_id}`); + if (vote && (last === undefined || castAfter(vote, last))) last = vote; + } + if (last === undefined) continue; + for (const copy of copies) { + if (!voteOf.has(`${copy.from_list}:${copy.use_id}`)) { + carried.push({ fromList: copy.from_list, useId: copy.use_id, rating: last.rating, changedAt: last.changed_at }); + } + } + } + return carried; +} diff --git a/server/src/nest/places-library/place-votes.mcp.ts b/server/src/nest/places-library/place-votes.mcp.ts new file mode 100644 index 000000000..a86a76550 --- /dev/null +++ b/server/src/nest/places-library/place-votes.mcp.ts @@ -0,0 +1,121 @@ +import { ADDON_IDS } from '../../addons'; +import { canWrite, placeCopyReach } 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 { TripAccessService } from '../trip-membership/trip-access.service'; +import { PlaceVotesService, type VoteEvents } from './place-votes.service'; +import { + collectionPlaceRateToolInputSchema, + placeRateToolInputSchema, + placesLibraryRateToolInputSchema, + type CollectionPlaceRateToolInput, + type PlaceRateToolInput, + type PlacesLibraryRateToolInput, +} from '@trek/shared'; + +const collectionsAddonOn = addonGate(ADDON_IDS.COLLECTIONS); + +/** A vote on an entry lands in lists and trips alike, so a token needs to write both. */ +const votesInListsAndTrips = (ctx: McpContext) => canWrite(ctx.scopes, 'collections') && canWrite(ctx.scopes, 'places'); + +const ONE_VOTE = + 'A vote belongs to the person: it is the same on every copy of the place they have (the copies list_all_places shows as one entry, in the lists they belong to and the trips they are on), so it is set or cleared on all of them at once, on the trip copies with the places:write scope and on the list copies with collections:write. Each list and trip shows only its own members their votes.'; + +/** A refusal as the tool answers it: the text alone, marked as an error. */ +function refusal(text: string) { + return { content: [{ type: 'text' as const, text }], isError: true }; +} + +/** + * MCP's way out for a vote: each trip place to its trip's room, no socket to + * skip, and onto the person's other copies only of the kinds the token may + * write: trip places with `places:write`, saved places with `collections:write`. + */ +function mcpEvents(guards: McpToolGuardsService, ctx: McpContext): VoteEvents { + return { + trip: (tripId, place) => guards.safeBroadcast(tripId, 'place:updated', { place }), + reach: placeCopyReach(ctx.scopes), + }; +} + +/** + * The vote on a trip place over PlaceVotesService and the check of its route: + * any member of the trip, place_edit not asked. With the trip's place tools + * in the assistant's core. + */ +@McpController() +export class PlaceVotesMcp { + constructor( + private readonly votes: PlaceVotesService, + private readonly trips: TripAccessService, + private readonly guards: McpToolGuardsService, + ) {} + + @Tool({ + name: 'rate_place', + description: `Set or clear the current user's 1-5 star rating on a trip place (#1435). Every trip member rates independently; the place shows the average. Omit rating (or pass null) to remove the user's vote. ${ONE_VOTE} Use the ratings to capture the user's preferences and shape the itinerary around highly-rated places.`, + inputSchema: placeRateToolInputSchema.shape, + annotations: TOOL_ANNOTATIONS_WRITE, + access: { group: 'places', mode: 'write' }, + }) + async ratePlace({ tripId, placeId, rating }: PlaceRateToolInput, ctx: McpContext) { + // Rating is a personal vote: any trip member may cast one, place_edit not required. + if (!(await this.trips.findAccessible(tripId, ctx.userId))) return refusal('Trip not found or access denied.'); + const place = await this.votes.voteOnTripPlace( + ctx.userId, + String(tripId), + String(placeId), + rating ?? null, + mcpEvents(this.guards, ctx), + ); + if (!place) return refusal('Place not found.'); + return ok({ place }); + } +} + +/** + * The votes on a saved place (any member of the list, viewers too) and on an + * entry of All places, over PlaceVotesService and the checks of their routes, + * behind the Collections addon like the rest of the lists. + */ +@McpController() +export class PlaceVotesLibraryMcp { + constructor( + private readonly votes: PlaceVotesService, + private readonly guards: McpToolGuardsService, + // Read by the addon gate of every tool here. + readonly addons: AddonsService, + ) {} + + @Tool({ + name: 'rate_collection_place', + description: `Set or clear the current user's 1-5 star rating on a saved collection place (#1435). Every member rates independently; the place shows the average. Pass null (or omit rating) to remove the user's vote. ${ONE_VOTE} Ratings a member casts here follow the place into any trip it is later copied to. Use the ratings to capture the user's preferences.`, + inputSchema: collectionPlaceRateToolInputSchema.shape, + annotations: TOOL_ANNOTATIONS_WRITE, + when: collectionsAddonOn, + access: { group: 'collections', mode: 'write' }, + }) + async rateCollectionPlace({ placeId, rating }: CollectionPlaceRateToolInput, ctx: McpContext) { + try { + return ok({ + place: await this.votes.voteOnSavedPlace(ctx.userId, placeId, rating ?? null, mcpEvents(this.guards, ctx)), + }); + } catch (err) { + return refusal(err instanceof Error ? err.message : 'Operation failed'); + } + } + + @Tool({ + name: 'rate_library_place', + description: `Set or clear the current user's 1-5 star rating on an entry of All places, named by its key from list_all_places (own:, trip: or list:). Pass null (or omit rating) to remove the vote. ${ONE_VOTE} Answers the entry's rating: average and count over every person's one vote on the copies the user can see, and mine.`, + inputSchema: placesLibraryRateToolInputSchema.shape, + annotations: TOOL_ANNOTATIONS_WRITE, + when: collectionsAddonOn, + access: votesInListsAndTrips, + }) + async rateLibraryPlace({ key, rating }: PlacesLibraryRateToolInput, ctx: McpContext) { + return ok(await this.votes.voteOnEntry(ctx.userId, key, rating ?? null, mcpEvents(this.guards, ctx))); + } +} diff --git a/server/src/nest/places-library/place-votes.module.ts b/server/src/nest/places-library/place-votes.module.ts new file mode 100644 index 000000000..7fbd1aa6b --- /dev/null +++ b/server/src/nest/places-library/place-votes.module.ts @@ -0,0 +1,41 @@ +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 { PlacesModule } from '../places/places.module'; +import { SchedulingModule } from '../scheduling/scheduling.module'; +import { SettingsModule } from '../settings/settings.module'; +import { TripMembershipModule } from '../trip-membership/trip-membership.module'; +import { PlaceCopiesService } from './place-copies.service'; +import { PlaceVotesCarryJob } from './place-votes-carry.job'; +import { PlaceVotesListController, PlaceVotesTripController } from './place-votes.controller'; +import { PlaceVotesLibraryMcp, PlaceVotesMcp } from './place-votes.mcp'; +import { PlaceVotesService } from './place-votes.service'; +import { PlacesLibraryModule } from './places-library.module'; +import { Module } from '@nestjs/common'; + +/** + * A person's one vote on a place, the same in all their lists and trips: the + * vote routes and tools of a saved place, of a trip place and of an entry of + * All places, and the one pass that carried the votes cast before onto the + * other copies, and the follower that keeps the copies' general facts in + * step when one of them is edited (PlaceCopiesService). Part of the + * places-library domain, above the lists and the trips it writes into through their own services (CollectionsService, + * PlacesService), with the grouping of PlacesLibraryModule. + */ +@Module({ + imports: [ + PlacesLibraryModule, + CollectionsModule, + PlacesModule, + AddonsModule, + McpSharedModule, + PermissionsModule, + SchedulingModule, + SettingsModule, + TripMembershipModule, + ], + controllers: [PlaceVotesListController, PlaceVotesTripController], + providers: [PlaceCopiesService, PlaceVotesService, PlaceVotesMcp, PlaceVotesLibraryMcp, PlaceVotesCarryJob], +}) +export class PlaceVotesModule {} diff --git a/server/src/nest/places-library/place-votes.service.ts b/server/src/nest/places-library/place-votes.service.ts new file mode 100644 index 000000000..b23adcf2a --- /dev/null +++ b/server/src/nest/places-library/place-votes.service.ts @@ -0,0 +1,299 @@ +import { ADDON_IDS } from '../../addons'; +import type { PlaceWithTagsRow } from '../../db/repositories/Places.repository'; +import { PlacesLibraryRepository } from '../../db/repositories/PlacesLibrary.repository'; +import { AddonsService } from '../addons/addons.service'; +import { logError } from '../audit/audit-log.logger'; +import { CollectionsService } from '../collections/collections.service'; +import { DomainError } from '../common/domain-error'; +import { inOrder } from '../common/in-order'; +import { UnitOfWork } from '../database/unit-of-work'; +import { PlacesService } from '../places/places.service'; +import { TripMembershipService } from '../trip-membership/trip-membership.service'; +import { votesToCarry, voteTargetsOf, type CarriedVote, type VoteCopies } from './place-votes.helpers'; +import { anchorOfKey, fromListOf } from './places-library.helpers'; +import { PlacesLibraryService, placeNotFound } from './places-library.service'; +import { Injectable, type OnModuleInit } from '@nestjs/common'; +import type { CollectionPlace, PlacesLibraryKind, PlacesLibraryRateResponse } from '@trek/shared'; + +/** + * How the changes of a vote go out after the commit, and how far the vote + * reaches. `trip` sends a trip place's `place:updated` the way the surface + * does (REST skips the caller's socket, MCP none); `socketId` is the caller's + * socket, skipped only on the copy the vote was cast on, so the caller's other + * open lists and trips still hear about theirs. `reach` names the kinds of the + * person's other copies the vote may land on: MCP narrows it to what the + * token may write (a token holding `places:write` alone never writes a list + * vote), REST leaves it out (both kinds). + */ +export interface VoteEvents { + trip: (tripId: number, place: PlaceWithTagsRow, voted: boolean) => void; + socketId?: string; + reach?: { trips: boolean; lists: boolean }; +} + +/** The list or trip somebody joined. */ +interface CarryInto { + kind: 'trip' | 'list'; + id: number; +} + +/** What one vote changed: the trip places as they read now and the lists whose saved places it touched. */ +interface VoteWrites { + trips: { tripId: number; place: PlaceWithTagsRow; voted: boolean }[]; + lists: { collectionId: number; voted: boolean }[]; +} + +/** + * One vote of a person on a place, the same wherever the place is: a vote + * belongs to its person and counts alike in all their lists and trips. The + * copies of a place are the uses All places shows the person as one entry + * (PlacesLibraryService: a saved place grouped with the trip place it came + * from, and the person's own places with their links). A vote cast or taken + * back on one copy is cast or taken back on each of its other copies the + * person may vote on, in one transaction: every list they belong to (any + * role, as a vote on a saved place asks today) and every trip they can open + * (owner or member, as a vote on a trip place asks today). Each copy is + * written under its own check, through its owner's service. Each list and + * trip keeps showing its own members' votes only, so a vote never reaches a + * list or trip its person is not on. + */ +@Injectable() +export class PlaceVotesService implements OnModuleInit { + constructor( + private readonly library: PlacesLibraryService, + private readonly collections: CollectionsService, + private readonly places: PlacesService, + private readonly uow: UnitOfWork, + private readonly repo: PlacesLibraryRepository, + private readonly addons: AddonsService, + private readonly membership: TripMembershipService, + ) {} + + /** + * The vote on the trip place `placeId` of `tripId` and on the other copies of + * it. Null when the trip holds no such place (the caller answers 404); the + * caller has checked that the user reaches the trip. + */ + async voteOnTripPlace( + userId: number, + tripId: string, + placeId: string, + rating: number | null, + events: VoteEvents, + ): Promise { + const writes = await this.uow.transactional(async () => { + const place = await this.places.rate(tripId, placeId, userId, rating); + if (!place) return null; + const others = await this.otherCopies(userId, 'trip', place.id, events); + const rest = await this.write(userId, rating, others); + return { place, rest: { ...rest, trips: [{ tripId: place.trip_id, place, voted: true }, ...rest.trips] } }; + }); + if (!writes) return null; + await this.announce(writes.rest, events); + return writes.place; + } + + /** The vote on the saved place `placeId` and on the other copies of it; refuses as the list's own vote route does. */ + async voteOnSavedPlace( + userId: number, + placeId: number, + rating: number | null, + events: VoteEvents, + ): Promise { + const writes = await this.uow.transactional(async () => { + const collectionId = await this.collections.writeRating(userId, placeId, rating); + const rest = await this.write(userId, rating, await this.otherCopies(userId, 'list', placeId, events)); + return { ...rest, lists: [{ collectionId, voted: true }, ...rest.lists] }; + }); + await this.announce(writes, events); + return this.collections.getPlaceById(placeId); + } + + /** + * The vote on every copy of the entry `key` of All places the user may vote + * on. 404 'Place not found' for a key that names no entry the user reaches. + * Answers the entry's votes as one after the change. + */ + async voteOnEntry( + userId: number, + key: string, + rating: number | null, + events: VoteEvents, + ): Promise { + const anchor = anchorOfKey(key); + if (anchor === null) throw placeNotFound(); + const { writes, rows } = await this.uow.transactional(async () => { + const reach = await this.library.reach(userId); + const entry = (await this.library.rows(reach, [anchor]))[0]; + if (!entry) throw placeNotFound(); + const copies = await this.within(voteTargetsOf(entry, null), events); + return { writes: await this.write(userId, rating, copies), rows: entry }; + }); + await this.announce(writes, events); + const [after] = await this.library.ratingsOf(userId, [rows]); + return { key, rating: after ?? { average: null, count: 0, mine: null, votes: [] } }; + } + + /** + * The copies of the place the use stands for, the use itself left out, as + * far as the vote reaches (see within); none outside All places. + */ + async otherCopies(userId: number, kind: PlacesLibraryKind, id: number, events: VoteEvents): Promise { + const reach = await this.library.reach(userId); + const anchor = await this.library.anchorOfUse(reach, kind, id); + if (anchor === null) return { trips: [], lists: [] }; + const rows = (await this.library.rows(reach, [anchor]))[0]; + if (!rows) return { trips: [], lists: [] }; + return this.within(voteTargetsOf(rows, { fromList: fromListOf(kind), id }), events); + } + + /** + * The copies a vote may land on: the kinds `events.reach` allows, and the + * saved places only while the Collections addon is on, since every list + * vote route and tool sits behind it. + */ + private async within(copies: VoteCopies, events: VoteEvents): Promise { + const trips = events.reach?.trips ?? true; + const lists = (events.reach?.lists ?? true) && (await this.addons.isAddonEnabled(ADDON_IDS.COLLECTIONS)); + return { trips: trips ? copies.trips : [], lists: lists ? copies.lists : [] }; + } + + /** + * The vote on each copy, under the copy's own check: a trip place through + * PlacesService.rate, a saved place through CollectionsService.writeRating. + * A copy whose check refuses (the person left that list a moment ago) is + * skipped rather than failing the vote on the others. Inside the caller's + * transaction. + */ + async write(userId: number, rating: number | null, copies: VoteCopies): Promise { + const writes: VoteWrites = { trips: [], lists: [] }; + await inOrder(copies.trips, async (copy) => { + const place = await this.places.rate(String(copy.tripId), String(copy.placeId), userId, rating); + if (place) writes.trips.push({ tripId: copy.tripId, place, voted: false }); + }); + await inOrder(copies.lists, async (copy) => { + const collectionId = await refusedAsNull(() => this.collections.writeRating(userId, copy.placeId, rating)); + if (collectionId !== null) writes.lists.push({ collectionId, voted: false }); + }); + return writes; + } + + /** Up to `limit` people with a vote anywhere, by id, after `after`: the pages of carryOver's pass. */ + async voters(after: number, limit: number): Promise { + return this.repo.voterIds(after, limit); + } + + /** + * Carries the person's votes over (see votesToCarry): onto each copy of a + * place they voted on elsewhere and may vote on here, where they have no vote + * yet. Every carried vote is an insert that leaves a vote already there alone + * (PlacesService.carryRating, CollectionsService.writeRating with `carry`), so a vote the + * person casts while the pass runs is never overwritten, and a second run + * adds nothing the first one added. Each copy keeps its own check, and one + * that refuses is skipped. Answers how many votes it carried (at most: a vote + * the person cast on that copy in the same moment counts too, though the + * insert left it as it was). Nothing is announced: it runs at boot. + */ + async carryOver(userId: number): Promise { + return (await this.carry(userId, null)).length; + } + + /** + * Somebody joined a list or a trip: their votes come along onto its copies + * of the places they voted on elsewhere, where they have none yet, as the + * carry-over at boot does. A trip's room hears of each trip place that got + * a vote; a list announces the join itself (CollectionsService.acceptInvite), + * which reads its places anew. A failure is logged, never the join's. + */ + async joined(into: CarryInto, userId: number): Promise { + try { + const carried = await this.carry(userId, into); + if (into.kind !== 'trip') return; + await inOrder(carried, async (copy) => { + const place = await this.places.get(String(into.id), String(copy.useId)); + if (place) this.places.broadcast(String(into.id), 'place:updated', { place }, undefined); + }); + } catch (err: unknown) { + logError( + `Place votes for user ${userId} joining ${into.kind} ${into.id}: ${err instanceof Error ? err.message : String(err)}`, + ); + } + } + + /** Registers the joins of lists and trips (join-listeners.ts). */ + onModuleInit(): void { + this.collections.joins.add((collectionId, userId) => this.joined({ kind: 'list', id: collectionId }, userId)); + this.membership.joins.add((tripId, userId) => this.joined({ kind: 'trip', id: tripId }, userId)); + } + + /** The carry-over of one person, onto every copy or onto the copies in `into` alone; answers the votes it carried. */ + private async carry(userId: number, into: CarryInto | null): Promise { + return this.uow.transactional(async () => { + const reach = await this.library.reach(userId); + const uses = await this.library.usesOf(reach, null); + const carried = votesToCarry(uses, await this.repo.votesOfUser(userId)); + if (carried.length === 0) return []; + const anchorOf = new Map(uses.map((use) => [`${use.from_list}:${use.use_id}`, use.anchor_key])); + const anchors = new Set(carried.map((vote) => anchorOf.get(`${vote.fromList}:${vote.useId}`) ?? 0)); + const touched = uses.filter((use) => anchors.has(use.anchor_key)); + const rows = await this.library.rows(reach, [...anchors], touched); + const tripOf = new Map(rows.flatMap((row) => row.trips.map((trip) => [trip.id, trip.trip_id] as const))); + const listOf = new Map(rows.flatMap((row) => row.saved.map((saved) => [saved.id, saved.collection_id] as const))); + const added: CarriedVote[] = []; + await inOrder( + carried.filter((vote) => into === null || isIn(vote, into, tripOf, listOf)), + async (vote) => { + if ((await refusedAsNull(() => this.carryOne(userId, vote, tripOf))) === true) added.push(vote); + }, + ); + return added; + }); + } + + /** One carried vote onto its copy; false when the copy is no longer where the pass found it. */ + private async carryOne(userId: number, vote: CarriedVote, tripOf: ReadonlyMap): Promise { + if (vote.fromList === 1) { + await this.collections.writeRating(userId, vote.useId, vote.rating, { at: vote.changedAt }); + return true; + } + const tripId = tripOf.get(vote.useId); + if (tripId === undefined) return false; + return this.places.carryRating(tripId, vote.useId, userId, vote.rating, vote.changedAt); + } + + /** After the commit: each trip place once, each list once (the copy voted on first, so it keeps its socket rule). */ + private async announce(writes: VoteWrites, events: VoteEvents): Promise { + for (const { tripId, place, voted } of writes.trips) events.trip(tripId, place, voted); + const lists = new Map(); + for (const { collectionId, voted } of writes.lists) + lists.set(collectionId, voted || lists.get(collectionId) === true); + await inOrder([...lists], ([collectionId, voted]) => + this.collections.notifyCollectionUsers(collectionId, voted ? events.socketId : undefined), + ); + } +} + +/** Whether a carried vote lands in the list or trip `into`. */ +function isIn( + vote: CarriedVote, + into: CarryInto, + tripOf: ReadonlyMap, + listOf: ReadonlyMap, +): boolean { + if (into.kind === 'trip') return vote.fromList === 0 && tripOf.get(vote.useId) === into.id; + return vote.fromList === 1 && listOf.get(vote.useId) === into.id; +} + +/** + * The write, or null when its check refuses it with a DomainError, which is + * thrown before the write sends any SQL, so the transaction it runs in stays + * usable on Postgres too. Any other failure is the vote's own and goes up. + */ +async function refusedAsNull(write: () => Promise): Promise { + try { + return await write(); + } catch (err: unknown) { + if (err instanceof DomainError) return null; + throw err; + } +} diff --git a/server/src/nest/places-library/places-library.dto.ts b/server/src/nest/places-library/places-library.dto.ts index 60bd93781..38de72d04 100644 --- a/server/src/nest/places-library/places-library.dto.ts +++ b/server/src/nest/places-library/places-library.dto.ts @@ -1,12 +1,13 @@ import { - placesLibraryBulkTagsRequestSchema, + placeRatingRequestSchema, placesLibraryDuplicatesQuerySchema, - placesLibraryEntryTagsRequestSchema, placesLibraryQuerySchema, placesLibraryLinkRequestSchema, placesLibraryMergeRequestSchema, placesLibraryPairRequestSchema, + placesLibraryRateRequestSchema, placesLibraryUnlinkRequestSchema, + placesLibraryUnrateQuerySchema, } from '@trek/shared'; import { createZodDto } from 'nestjs-zod'; @@ -19,6 +20,7 @@ export class PlacesLibraryDuplicatesQueryDto extends createZodDto(placesLibraryD 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) {} +/** A vote on one copy of a place, cast where it lives (a saved place, a trip place): 1 to 5 stars. */ +export class PlaceRatingDto extends createZodDto(placeRatingRequestSchema) {} +export class PlacesLibraryRateDto extends createZodDto(placesLibraryRateRequestSchema) {} +export class PlacesLibraryUnrateQueryDto extends createZodDto(placesLibraryUnrateQuerySchema) {} diff --git a/server/src/nest/places-library/places-library.helpers.ts b/server/src/nest/places-library/places-library.helpers.ts index a2efb954a..5f8ac0882 100644 --- a/server/src/nest/places-library/places-library.helpers.ts +++ b/server/src/nest/places-library/places-library.helpers.ts @@ -12,6 +12,7 @@ import { type LibraryTripPlaceRow, type LibraryUseRow, } from '../../db/repositories/PlacesLibrary.repository'; +import { avatarUrl } from '../common/avatarUrl'; import { collectionStatusSchema, PLACES_LIBRARY_KEY_PATTERN, @@ -23,6 +24,7 @@ import { type PlacesLibraryListOrigin, type PlacesLibraryRating, type PlacesLibraryTripOrigin, + type PlacesLibraryVote, } from '@trek/shared'; import { z } from 'zod'; @@ -82,10 +84,16 @@ export function fromListOf(kind: PlacesLibraryKind): number { return kind === 'trip' ? 0 : 1; } +/** The value an entry stands at in the order of `sort`, as a cursor carries it. */ +function sortValueOf(sort: LibrarySort, anchor: LibraryAnchorRow): string { + if (sort === 'name') return anchor.sort_name; + if (sort === 'updated') return anchor.sort_time; + return String(anchor.sort_rating); +} + /** The position after which the next page starts, opaque to the client. */ export function encodeLibraryCursor(sort: LibrarySort, anchor: LibraryAnchorRow): string { - const value = sort === 'name' ? anchor.sort_name : anchor.sort_time; - return Buffer.from(JSON.stringify([sort, value, anchor.anchor_key])).toString('base64url'); + return Buffer.from(JSON.stringify([sort, sortValueOf(sort, anchor), anchor.anchor_key])).toString('base64url'); } /** The position a cursor names, or null for one this sort did not hand out. */ @@ -98,20 +106,65 @@ export function decodeLibraryCursor(sort: LibrarySort, cursor: string): LibraryP } const result = cursorSchema.safeParse(parsed); if (!result.success || result.data[0] !== sort) return null; + // The rating sort's value is a whole score (see RATING_SCORE_SCALE). + if (sort === 'rating' && !/^-?\d{1,10}$/.test(result.data[1])) return null; return { value: result.data[1], key: result.data[2] }; } -/** The votes of one place: their mean, how many there are, and the user's own. */ +/** One vote as the place shows it beside its stars: who cast it, their picture and the stars. */ +function voteOf(row: LibraryRatingRow): PlacesLibraryVote { + return { + user_id: row.user_id, + username: row.username ?? '', + avatar_url: avatarUrl({ avatar: row.avatar ?? null }), + rating: row.rating, + }; +} + +/** + * The votes of one place: their mean, how many there are, the user's own and + * who cast them, in the order they were cast (changed, then row). + */ export function ratingOf(rows: readonly LibraryRatingRow[], userId: number): PlacesLibraryRating { - if (rows.length === 0) return { average: null, count: 0, mine: null }; + if (rows.length === 0) return { average: null, count: 0, mine: null, votes: [] }; const sum = rows.reduce((total, row) => total + row.rating, 0); + const cast = [...rows].sort((a, b) => (castAfter(a, b) ? 1 : castAfter(b, a) ? -1 : 0)); return { average: sum / rows.length, count: rows.length, mine: rows.find((row) => row.user_id === userId)?.rating ?? null, + votes: cast.map(voteOf), }; } +/** + * Whether vote `a` came after vote `b`: changed later, or on the same second + * in a later row (only a tiebreak that keeps the answer stable: two votes + * changed in one second carry the same stars when one vote wrote both). + */ +export function castAfter( + a: { changed_at?: string | null; id?: number }, + b: { changed_at?: string | null; id?: number }, +): boolean { + const at = a.changed_at ?? ''; + const bt = b.changed_at ?? ''; + return at !== bt ? at > bt : (a.id ?? 0) > (b.id ?? 0); +} + +/** + * The votes on the copies of one place as one: each person once, with the + * vote they changed last where they voted differently on two copies, then their + * mean, how many and the user's own. + */ +export function unifiedRatingOf(rows: readonly LibraryRatingRow[], userId: number): PlacesLibraryRating { + const last = new Map(); + for (const row of rows) { + const seen = last.get(row.user_id); + if (seen === undefined || castAfter(row, seen)) last.set(row.user_id, row); + } + return ratingOf([...last.values()], userId); +} + type FactsRow = LibraryTripPlaceRow | LibraryCollectionPlaceRow; type LeadRow = FactsRow | LibraryIdentityRow; diff --git a/server/src/nest/places-library/places-library.mcp.ts b/server/src/nest/places-library/places-library.mcp.ts index 76269244a..c5c680937 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, 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.`, + 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), last changed first (sort: updated) or by votes (sort: rating: the highest average first, entries without votes last), ${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 (name, color): the tags of the lists and trips it is in, a list's labels on its saved place and a trip's tags on its trip place, which everyone on that list or trip sees; a name stands once, whatever its case. They are changed in the list (update_collection_place label_ids) or the trip (update_place tags). Each entry carries rating too: average, count and mine over every person's one vote on the copies the user reaches, and votes (user_id, username, avatar_url, rating) naming each person counted. 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 tags (tag names, case ignored: entries carrying a tag of one of them in any of their lists or trips), and min_rating (1 to 5: only entries whose average vote is at least that, entries without votes left out); 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, tags and min_rating 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), @@ -56,7 +56,7 @@ export class PlacesLibraryMcp { @Tool({ name: 'get_library_place', description: - 'One entry of list_all_places in full, named by one of its origins: kind trip with a trip place_id, or kind list with a collection_place_id. Answers the entry with every origin, and for each origin what it keeps on its own, in the same order: info (name, address, lat, lng, description, website, phone, image_url and category as that origin stores them, so two origins may differ), notes, rating (average, count, mine), for a list its labels, for a trip the days the place is planned on (day number, date, title, time, end time) and whether a stay or a booking uses it. Changes nothing.', + 'One entry of list_all_places in full, named by one of its origins: kind trip with a trip place_id, or kind list with a collection_place_id. Answers the entry with every origin, and for each origin what it keeps on its own, in the same order: info (name, address, lat, lng, description, website, phone, image_url and category as that origin stores them, so two origins may differ), notes, rating (average, count, mine), tags (the labels of the list on the saved place, or the tags of the trip on the trip place, with id, name and color), available_tags (every tag of that list or trip) and can_edit_tags (whether you may put them on, take them off and add one there), for a list also labels (the same as its tags), for a trip the days the place is planned on (day number, date, title, time, end time) and whether a stay or a booking uses it. Changes nothing.', inputSchema: placesLibraryDetailRequestSchema.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 ca1900b5e..c3c9eaedf 100644 --- a/server/src/nest/places-library/places-library.module.ts +++ b/server/src/nest/places-library/places-library.module.ts @@ -1,4 +1,3 @@ -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'; @@ -16,9 +15,6 @@ 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'; @@ -33,8 +29,9 @@ import { Module } from '@nestjs/common'; * 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, 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 + * the trips' day plans, and (PLC-21) the tags of the lists and trips an + * entry is in. 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({ @@ -45,15 +42,9 @@ import { Module } from '@nestjs/common'; PermissionsModule, McpSharedModule, SchedulingModule, - MikroOrmModule.forFeature([ - UserPlaces, - UserPlaceLinks, - UserPlaceMerges, - UserPlaceMergeDismissals, - PersonalPlaceTags, - ]), + MikroOrmModule.forFeature([UserPlaces, UserPlaceLinks, UserPlaceMerges, UserPlaceMergeDismissals]), ], - controllers: [PlacesLibraryController, PlaceIdentitiesController, PlaceTagsController], + controllers: [PlacesLibraryController, PlaceIdentitiesController], providers: [ { provide: PlacesLibraryRepository, @@ -73,10 +64,8 @@ import { Module } from '@nestjs/common'; PlaceDuplicatesService, PlaceIdentitiesMcp, PlaceIdentitiesPruneJob, - PlaceTagsService, - PlaceTagsMcp, ], - // The visits and media of All places (PlaceVisitsModule, same domain) read through these. - exports: [PlacesLibraryService, PlaceVisitsReaderService, PlaceVisitContextRepository], + // The visits and media (PlaceVisitsModule) and the votes (PlaceVotesModule) of All places, same domain, read through these. + exports: [PlacesLibraryService, PlaceVisitsReaderService, PlaceVisitContextRepository, PlacesLibraryRepository], }) 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 38e0586b9..39006f7e5 100644 --- a/server/src/nest/places-library/places-library.service.ts +++ b/server/src/nest/places-library/places-library.service.ts @@ -11,7 +11,7 @@ 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 { entryTagsOf, foldTagNames, offeredTags, tagOf, tagsByOwner } from './library-tags.helpers'; import { PlaceVisitsReaderService } from './place-visits-reader.service'; import { decodeLibraryCursor, @@ -25,6 +25,7 @@ import { infoOf, ratingOf, rowsByAnchor, + unifiedRatingOf, type EntryRows, type OriginAccess, } from './places-library.helpers'; @@ -37,7 +38,8 @@ import { type PlacesLibraryKind, type PlacesLibraryPageResponse, type PlacesLibraryQuery, - type PlacesLibraryTag, + type PlacesLibraryEntryTag, + type PlacesLibraryRating, } from '@trek/shared'; /** Who asks, as the permission check reads them. */ @@ -87,6 +89,13 @@ function armsOfReach(reach: LibraryReach): LibraryArms { * 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. + * + * And the tags of the lists and trips it is in (PLC-21): each list's labels on + * its saved place and each trip's tags on its trip place, shared with everyone + * on the list or the trip. The detail names them per origin, with every tag of + * that list or trip and whether the user may change them there; the writes + * are the list's and the trip's own (the saved place's label_ids, the trip + * place's tags), under their own permission checks. */ @Injectable() export class PlacesLibraryService { @@ -115,7 +124,12 @@ export class PlacesLibraryService { 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) }, + tags: query.tags === undefined ? null : { foldedNames: foldTagNames(query.tags), reach: armsOfReach(reach) }, + // The votes of every copy the user reaches count, as in the entry's rating, whatever the page's other filters leave out. + rating: + query.min_rating === undefined && sort !== 'rating' + ? null + : { min: query.min_rating ?? null, reach: armsOfReach(reach) }, }; const counts = await this.repo.countEntries(armsOfReach(reach), { ...match, status: null }); @@ -160,12 +174,14 @@ export class PlacesLibraryService { if (anchor === null) throw placeNotFound(); const rows = (await this.rows(reach, [anchor]))[0]; if (!rows) throw placeNotFound(); - const entry = entryOf(rows, await this.access(user, rows.trips, rows.saved)); + const access = await this.access(user, rows.trips, rows.saved); + const entry = entryOf(rows, access); const [summary] = await this.visits.summaries(reach, [rows]); - const [tags] = await this.tagsOf(user.id, [rows]); + const [tags] = await this.tagsOf([rows]); + const [rating] = await this.ratingsOf(user.id, [rows]); return { - entry: { ...entry, ...summary, tags: tags ?? [] }, - details: await this.details(user.id, rows), + entry: { ...entry, ...summary, tags: tags ?? [], rating }, + details: await this.details(user.id, rows, access), }; } @@ -221,14 +237,50 @@ export class PlacesLibraryService { rows.flatMap((row) => row.saved), ); 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] ?? [] })); + const tags = await this.tagsOf(rows); + const ratings = await this.ratingsOf(user.id, rows); + return rows.map((row, index) => ({ + ...entryOf(row, access), + ...summaries[index], + tags: tags[index] ?? [], + rating: ratings[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); + /** + * The votes on each entry as one, in the entries' order: the votes on all of + * its copies the user reaches (each list and trip holds its own members' + * votes), every person once with the vote they cast last. + */ + async ratingsOf(userId: number, rows: readonly EntryRows[]): Promise { + const placeIds = rows.flatMap((row) => row.trips.map((trip) => trip.id)); + const savedIds = rows.flatMap((row) => row.saved.map((saved) => saved.id)); + const onTrips = groupBy( + await readInChunks(placeIds, (chunk) => this.repo.tripPlaceRatings(chunk)), + (vote) => vote.target_id, + ); + const onLists = groupBy( + await readInChunks(savedIds, (chunk) => this.repo.savedPlaceRatings(chunk)), + (vote) => vote.target_id, + ); + return rows.map((row) => + unifiedRatingOf( + [ + ...row.trips.flatMap((trip) => onTrips.get(trip.id) ?? []), + ...row.saved.flatMap((saved) => onLists.get(saved.id) ?? []), + ], + userId, + ), + ); + } + + /** PLC-21: the tags of the lists and trips of each entry, in the entries' order. */ + private async tagsOf(rows: readonly EntryRows[]): Promise { + const placeIds = rows.flatMap((row) => row.trips.map((trip) => trip.id)); + const savedIds = rows.flatMap((row) => row.saved.map((saved) => saved.id)); + const tripTags = await readInChunks(placeIds, (chunk) => this.repo.tripPlaceTags(chunk)); + const labels = await readInChunks(savedIds, (chunk) => this.repo.savedPlaceLabels(chunk)); + return entryTagsOf(rows, tripTags, labels); } /** One entry, or null when it has no use the user reaches. */ @@ -263,8 +315,13 @@ export class PlacesLibraryService { }; } - /** What each origin keeps, in the entry's origin order: the trip places first, then the saved places. */ - private async details(userId: number, rows: EntryRows): Promise { + /** + * What each origin keeps, in the entry's origin order: the trip places first, + * then the saved places. Who may change an origin's tags is who may change + * the origin: the trip's place_edit, a list role but viewer. A trip offers its + * own tags plus any older personal tag the place still carries. + */ + private async details(userId: number, rows: EntryRows, access: OriginAccess): Promise { const details: PlacesLibraryDetail[] = []; if (rows.trips.length > 0) { const placeIds = rows.trips.map((row) => row.id); @@ -272,12 +329,18 @@ export class PlacesLibraryService { const ratings = groupBy(await this.repo.tripPlaceRatings(placeIds), (row) => row.target_id); const days = groupBy(await this.repo.plannedDays(placeIds), (row) => row.place_id); const booked = await this.repo.bookedPlaces(placeIds); + const tags = groupBy(await this.repo.tripPlaceTags(placeIds), (row) => row.place_id); + const tripTags = tagsByOwner(await this.repo.tripTags([...new Set(rows.trips.map((row) => row.trip_id))])); for (const row of rows.trips) { + const assigned = (tags.get(row.id) ?? []).map(tagOf); details.push({ kind: 'trip', place_id: row.id, info: infoOf(row), notes: notes.get(row.id) ?? null, + tags: assigned, + available_tags: offeredTags(tripTags.get(row.trip_id) ?? [], assigned), + can_edit_tags: access.canEditTrip(row), rating: ratingOf(ratings.get(row.id) ?? [], userId), days: (days.get(row.id) ?? []).map((day) => ({ day_id: day.day_id, @@ -297,13 +360,20 @@ export class PlacesLibraryService { const notes = new Map((await this.repo.savedPlaceNotes(savedIds)).map((row) => [row.id, row.notes])); const labels = groupBy(await this.repo.savedPlaceLabels(savedIds), (row) => row.collection_place_id); const ratings = groupBy(await this.repo.savedPlaceRatings(savedIds), (row) => row.target_id); + const listTags = tagsByOwner( + await this.repo.listLabels([...new Set(rows.saved.map((row) => row.collection_id))]), + ); for (const row of rows.saved) { + const assigned = (labels.get(row.id) ?? []).map(tagOf); details.push({ kind: 'list', collection_place_id: row.id, info: infoOf(row), notes: notes.get(row.id) ?? null, - labels: (labels.get(row.id) ?? []).map(({ id, name, color }) => ({ id, name, color })), + labels: assigned, + tags: assigned, + available_tags: listTags.get(row.collection_id) ?? [], + can_edit_tags: access.canEditList(row), rating: ratingOf(ratings.get(row.id) ?? [], userId), }); } diff --git a/server/src/nest/places/places.controller.ts b/server/src/nest/places/places.controller.ts index f55ed4fa5..06bbb6c6f 100644 --- a/server/src/nest/places/places.controller.ts +++ b/server/src/nest/places/places.controller.ts @@ -20,7 +20,6 @@ import { PlaceImportGpxDto, PlaceImportListDto, PlaceImportMapDto, - PlaceRatingDto, PlaceImageFromFileDto, PlaceUpdateDto, } from './places.dto'; @@ -431,6 +430,7 @@ export class PlacesController { ids, { category_id: body.category_id as number | null }, user.id, + { editor: user }, ); for (const place of updated) { this.places.broadcast(tripId, 'place:updated', { place }, socketId); @@ -481,6 +481,7 @@ export class PlacesController { { image_url: placeImageUrl(file.filename) } as never, undefined, user.id, + { editor: user }, ); if (!result || isUpdateConflict(result)) { throw new HttpException({ error: 'Place not found' }, 404); @@ -505,7 +506,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, user.id); + const result = await this.places.setImageFromFile(tripId, id, body.file_id, user.id, { editor: user }); 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); @@ -515,41 +516,6 @@ export class PlacesController { return { place: result }; } - @Put(':id/rating') - async rate( - @CurrentUser() user: User, - @Param('tripId') tripId: string, - @Param('id') id: string, - @Body() body: PlaceRatingDto, - @Headers('x-socket-id') socketId?: string, - ) { - // Deliberately no place_edit check: every trip member may cast their own - // vote (#1435), even when an admin restricts place editing. - await this.requireTrip(tripId, user); - const place = await this.places.rate(tripId, id, user.id, body.rating); - if (!place) { - throw new HttpException({ error: 'Place not found' }, 404); - } - this.places.broadcast(tripId, 'place:updated', { place }, socketId); - return { place }; - } - - @Delete(':id/rating') - @UseGuards(TripAccessGuard) - async unrate( - @CurrentUser() user: User, - @Param('tripId') tripId: string, - @Param('id') id: string, - @Headers('x-socket-id') socketId?: string, - ) { - const place = await this.places.rate(tripId, id, user.id, null); - if (!place) { - throw new HttpException({ error: 'Place not found' }, 404); - } - this.places.broadcast(tripId, 'place:updated', { place }, socketId); - return { place }; - } - @Get(':id/image') @UseGuards(TripAccessGuard) async image(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) { @@ -578,7 +544,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, user.id); + const result = await this.places.update(tripId, id, body as never, ifMatch, user.id, { editor: user }); if (!result) { throw new HttpException({ error: 'Place not found' }, 404); } diff --git a/server/src/nest/places/places.dto.ts b/server/src/nest/places/places.dto.ts index ddb7d29ad..82917bd27 100644 --- a/server/src/nest/places/places.dto.ts +++ b/server/src/nest/places/places.dto.ts @@ -6,7 +6,6 @@ import { placeImportListRequestSchema, placeImportMapRequestSchema, placeExportGpxRequestSchema, - placeRatingRequestSchema, placeUpdateRequestSchema, placeImageFromFileRequestSchema, } from '@trek/shared'; @@ -29,7 +28,6 @@ import { createZodDto } from 'nestjs-zod'; export class PlaceCreateDto extends createZodDto(placeCreateRequestSchema) {} export class PlaceUpdateDto extends createZodDto(placeUpdateRequestSchema) {} -export class PlaceRatingDto extends createZodDto(placeRatingRequestSchema) {} export class PlaceImageFromFileDto extends createZodDto(placeImageFromFileRequestSchema) {} export class PlaceBulkDeleteDto extends createZodDto(placeBulkDeleteRequestSchema) {} export class PlaceBulkUpdateDto extends createZodDto(placeBulkUpdateRequestSchema) {} diff --git a/server/src/nest/places/places.helpers.ts b/server/src/nest/places/places.helpers.ts index 5b011a61d..8138ee112 100644 --- a/server/src/nest/places/places.helpers.ts +++ b/server/src/nest/places/places.helpers.ts @@ -1,8 +1,9 @@ -import type { PlaceWithTagsRow as PlaceWithTags } from '../../db/repositories/Places.repository'; +import type { PlacesRepository, PlaceWithTagsRow as PlaceWithTags } from '../../db/repositories/Places.repository'; import { haversineMetres } from '../common/geo'; import { toRowId } from '../common/row-id'; import type { KmlImportSummary } from '../place-import/place-import.types'; import type { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service'; +import type { PlaceUpdateInput } from './places.service'; import { externalIdsOf, normalizePlaceName, placeMatchStrategies, type PlaceMatchCandidate } from '@trek/shared'; /** @@ -338,3 +339,89 @@ export function resolveCategoryIdForFolder(folderName: string | null, lookup: Ma if (!normalizedFolder) return null; return lookup.get(normalizedFolder) ?? null; } + +/** + * What an update writes on a trip place: every column resolved to its final + * value from the body and the row as it stood (`existingPlace`), so the + * repository writes exactly what it is handed. + */ +export function placeWriteOf( + body: PlaceUpdateInput, + existingPlace: NonNullable>>, +): Parameters[1] { + const { + name, + description, + lat, + lng, + address, + category_id, + price, + currency, + place_time, + end_time, + duration_minutes, + notes, + image_url, + google_place_id, + google_ftid, + osm_id, + amap_poi_id, + website, + phone, + email, + opening_hours, + transport_mode, + route_color, + stop_type, + fill_percent, + } = body; + // PL11 — ONE `nativeUpdate` with a typed full partial (the ruling): the + // SQL `COALESCE(?, col)` keep-if-null semantics (name/currency/ + // transport_mode, all three bound `x || null`) and the twenty + // `!== undefined ? x : existing.x` pre-image fallbacks are resolved to + // their final value HERE, before the repository — which writes + // exactly what it is handed. + return { + // 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 + // COALESCE, so the keep-if-null fold has to be resolved here. + name: (name || null) ?? existingPlace.name, + description: description !== undefined ? description : existingPlace.description, + lat: lat !== undefined ? lat : existingPlace.lat, + lng: lng !== undefined ? lng : existingPlace.lng, + address: address !== undefined ? address : existingPlace.address, + category_id: category_id !== undefined ? category_id : existingPlace.category_id, + price: price !== undefined ? price : existingPlace.price, + // COALESCE(?, currency) — same fold as `name` above. + currency: (currency || null) ?? existingPlace.currency, + place_time: place_time !== undefined ? place_time : existingPlace.place_time, + end_time: end_time !== undefined ? end_time : existingPlace.end_time, + // Not COALESCE, like its neighbours: the contract says an explicit null + // clears the planned stay length, and COALESCE made null and absent the + // same thing, so the field advertised a reset it never performed. 0 keeps + // working, which a `|| null` bind would have swallowed. + duration_minutes: duration_minutes !== undefined ? duration_minutes : existingPlace.duration_minutes, + notes: notes !== undefined ? notes : existingPlace.notes, + image_url: image_url !== undefined ? image_url : existingPlace.image_url, + google_place_id: google_place_id !== undefined ? google_place_id : existingPlace.google_place_id, + google_ftid: google_ftid !== undefined ? google_ftid : existingPlace.google_ftid, + osm_id: osm_id !== undefined ? osm_id : existingPlace.osm_id, + amap_poi_id: amap_poi_id !== undefined ? amap_poi_id : existingPlace.amap_poi_id, + website: website !== undefined ? website : existingPlace.website, + phone: phone !== undefined ? phone : existingPlace.phone, + // Empty clears, like null: the form sends what its field holds (#2472). + email: email !== undefined ? email?.trim() || null : existingPlace.email, + opening_hours: opening_hours !== undefined ? opening_hours || null : existingPlace.opening_hours, + // COALESCE(?, transport_mode) — same fold as `name`/`currency` above. + transport_mode: (transport_mode || null) ?? existingPlace.transport_mode, + // Deliberately not COALESCE: an explicit null is how the picker resets a + // track back to its category colour (#776). + route_color: route_color !== undefined ? route_color : existingPlace.route_color, + // Same shape: an explicit null is how a fuel stop becomes an ordinary place again. + 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, + }; +} diff --git a/server/src/nest/places/places.mcp.ts b/server/src/nest/places/places.mcp.ts index 915266d23..2445042ed 100644 --- a/server/src/nest/places/places.mcp.ts +++ b/server/src/nest/places/places.mcp.ts @@ -1,3 +1,4 @@ +import { placeCopyReach } from '../../mcp/scopes'; import { McpController, Tool, ResourceTemplate, type McpContext, TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, @@ -184,7 +185,7 @@ export class PlacesMcp { @Tool({ name: 'update_place', - description: 'Update an existing place in a trip.', + description: 'Update an existing place in a trip. A change of the name, description, address, position, category, image, website or phone is made on your other copies of the place too (the copies list_all_places shows as one entry), in the lists and trips where you may edit them and of the kinds this token may write (trip places with places:write, saved places with collections:write); notes, tags, status and votes stay with each copy.', inputSchema: { tripId: idSchema, placeId: idSchema, @@ -233,7 +234,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 }, undefined, ctx.userId); + 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, await this.guards.copyFollow(ctx.userId, placeCopyReach(ctx.scopes))); // 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 +262,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, ctx.userId); + const result = await this.places.setImageFromFile(String(tripId), String(placeId), fileId, ctx.userId, await this.guards.copyFollow(ctx.userId, placeCopyReach(ctx.scopes))); 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.'); @@ -272,29 +273,6 @@ export class PlacesMcp { return ok({ place: result }); } - @Tool({ - name: 'rate_place', - description: "Set or clear the current user's 1-5 star rating on a trip place (#1435). Every trip member rates independently; the place shows the average. Omit rating (or pass null) to remove the user's vote. Use the ratings to capture the user's preferences and shape the itinerary around highly-rated places.", - inputSchema: { - tripId: idSchema, - placeId: idSchema, - rating: z.number().int().min(1).max(5).nullable().optional().describe('1-5 stars; null/omitted clears the vote'), - }, - annotations: TOOL_ANNOTATIONS_WRITE, - access: { group: 'places', mode: 'write' }, - }) - async ratePlace( - { tripId, placeId, rating }: { tripId: number; placeId: number; rating?: number | null }, - ctx: McpContext, - ) { - // Rating is a personal vote — any trip member may cast one, place_edit not required. - if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess(); - const place = await this.places.rate(String(tripId), String(placeId), ctx.userId, rating ?? null); - if (!place) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true }; - this.guards.safeBroadcast(tripId, 'place:updated', { place }); - return ok({ place }); - } - @Tool({ name: 'delete_place', description: 'Permanently delete a place from a trip. Removes its day assignments, its linked expenses and any nights booked at it, including each night\'s reservation and that reservation\'s expense. If the place is a Tour, its route and editable waypoints are also permanently deleted. A city walk takes all its stations with it, protected ones included: name those to the traveller and ask first. Warn the user before calling: this cannot be undone.', @@ -518,7 +496,7 @@ export class PlacesMcp { @Tool({ name: 'bulk_update_places', - description: 'Update many places in a trip at once, applying the SAME field values to every listed place. Use this for sweeping edits — e.g. re-categorising a batch of POIs (set category_id for 80 places) — in a single call instead of one update_place per place. Only the fields you set are changed; everything else on each place is preserved. Use list_categories for category_id.', + description: 'Update many places in a trip at once, applying the SAME field values to every listed place. Use this for sweeping edits — e.g. re-categorising a batch of POIs (set category_id for 80 places) — in a single call instead of one update_place per place. Only the fields you set are changed; everything else on each place is preserved. Use list_categories for category_id. A change of the name, description, address, position, category, image, website or phone is made on your other copies of the place too (the copies list_all_places shows as one entry), in the lists and trips where you may edit them and of the kinds this token may write (trip places with places:write, saved places with collections:write); notes, tags, status and votes stay with each copy.', inputSchema: { tripId: idSchema, placeIds: z.array(idSchema).min(1).max(500).describe('IDs of the places to update (from list_places)'), @@ -561,7 +539,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, ctx.userId); + const updated = await this.places.updateMany(String(tripId), placeIds, fields, ctx.userId, await this.guards.copyFollow(ctx.userId, placeCopyReach(ctx.scopes))); // 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.service.ts b/server/src/nest/places/places.service.ts index f1fe5583e..7de0474d0 100644 --- a/server/src/nest/places/places.service.ts +++ b/server/src/nest/places/places.service.ts @@ -28,6 +28,7 @@ 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 { NO_FOLLOWED_COPIES, PlaceCopiesSlot, mergeFollowed, type FollowCopies, type FollowedCopies, type PlaceCopyChanges } from '../common/place-copies.port'; import { Places } from '../../db/entities/Places.entity'; import { Tags } from '../../db/entities/Tags.entity'; import { PlaceRatings } from '../../db/entities/PlaceRatings.entity'; @@ -75,6 +76,7 @@ import { type ListImportResult, type PlaceImportResult, placeListIdFilters, + placeWriteOf, } from './places.helpers'; type Trip = TripAccess; @@ -98,13 +100,14 @@ export interface PlaceCreateInput { transport_mode?: string; route_geometry?: string; route_color?: string; tags?: number[]; } -/** Fields accepted when patching a place. */ +/** Fields accepted when patching a place; null clears the facts a copy of the place in a list can clear too. */ export interface PlaceUpdateInput { - name?: string; description?: string; lat?: number; lng?: number; address?: string; - category_id?: number; price?: number; currency?: string; + name?: string; description?: string | null; lat?: number | null; lng?: number | null; address?: string | null; + category_id?: number | null; price?: number; currency?: string; place_time?: string; end_time?: string; - duration_minutes?: number; notes?: string; image_url?: string; - google_place_id?: string; google_ftid?: string; osm_id?: string; amap_poi_id?: string; website?: string; phone?: string; + duration_minutes?: number; notes?: string; image_url?: string | null; + google_place_id?: string; google_ftid?: string; osm_id?: string; amap_poi_id?: string; + website?: string | null; phone?: string | null; email?: string | null; opening_hours?: string | null; /** What kind of stop this is on a drive (fuel, charging, rest_area, campsite); null for an ordinary place. */ stop_type?: string | null; @@ -168,6 +171,15 @@ export class PlacesService { private readonly changes: PlaceChangesService, // PLC-14: the history of every details write, in its transaction ) {} + /** The other copies of a place follow an edit: the places library registers its follower here (place-copies.port.ts). */ + readonly copies = new PlaceCopiesSlot(); + + /** Another copy's edit on this trip place, as an update writes it, in its transaction; no event. Null: no such place. */ + async writeCopy(tripId: number, placeId: number, changes: PlaceCopyChanges, editor: ChangeEditor) { + const { result, previousImage } = await this.applyUpdate(String(tripId), String(placeId), changes, undefined, editor, null); + return result ? { previousImage } : null; + } + /** * The `requireTrip` gate for 13 of the 16 routes on this controller (the * other 3 use `TripAccessGuard` directly). `toRowId`, not `Number()` — @@ -285,7 +297,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, editor: ChangeEditor = null): Promise<'not_found' | 'not_image' | 'too_large' | Awaited>> { + async setImageFromFile(tripId: string, placeId: string, fileId: number, editor: ChangeEditor = null, follow: FollowCopies | null = 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); @@ -297,7 +309,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, undefined, editor); + const updated = await this.update(tripId, placeId, { image_url: placeImageUrl(name) }, undefined, editor, follow); // 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; @@ -411,9 +423,11 @@ export class PlacesService { body: PlaceUpdateInput, ifMatch?: string, editor: ChangeEditor = null, // who the history names (PLC-14) + follow: FollowCopies | null = null, // the editor's other copies of the place follow the edit (place-copies.port.ts) ): Promise { - 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 + const { result, previousImage, followed } = await this.uow.transactional(() => this.applyUpdate(tripId, placeId, body, ifMatch, editor, follow)); + await this.release.releaseValues([previousImage, ...(followed?.previousImages ?? [])]); // after the commit: kept while a copy or a cover names it + await this.copies.announce(followed); return result; } @@ -427,7 +441,8 @@ export class PlacesService { body: PlaceUpdateInput, ifMatch: string | undefined, editor: ChangeEditor, - ): Promise<{ result: PlaceWithTags | UpdateConflict | null; previousImage?: string | null }> { + follow: FollowCopies | null, + ): Promise<{ result: PlaceWithTags | UpdateConflict | null; previousImage?: string | null; followed?: FollowedCopies }> { // PL9 — the pre-image read every `!== undefined` fallback below needs. // `toRowId` first (Task 3 review H1, absorbed here): every write in // this method (`updatePlace`, `tagsRepo.deleteForPlace`/`insertIgnore`) @@ -458,70 +473,19 @@ export class PlacesService { return { result: { conflict: true, server: await this.placesRepo.findWithTagsAndRatings(id) } }; } - const { - name, description, lat, lng, address, category_id, price, currency, - place_time, end_time, - duration_minutes, notes, image_url, google_place_id, google_ftid, osm_id, amap_poi_id, website, phone, - email, opening_hours, - transport_mode, route_color, stop_type, fill_percent, tags, - } = body; + const follows = await this.copies.plan(follow, { kind: 'trip', id }); // the other copies, read before the write - // PL11 — ONE `nativeUpdate` with a typed full partial (the ruling): the - // SQL `COALESCE(?, col)` keep-if-null semantics (name/currency/ - // transport_mode, all three bound `x || null`) and the twenty - // `!== 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.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 - // COALESCE, so the keep-if-null fold has to be resolved here. - name: (name || null) ?? existingPlace.name, - description: description !== undefined ? description : existingPlace.description, - lat: lat !== undefined ? lat : existingPlace.lat, - lng: lng !== undefined ? lng : existingPlace.lng, - address: address !== undefined ? address : existingPlace.address, - category_id: category_id !== undefined ? category_id : existingPlace.category_id, - price: price !== undefined ? price : existingPlace.price, - // COALESCE(?, currency) — same fold as `name` above. - currency: (currency || null) ?? existingPlace.currency, - place_time: place_time !== undefined ? place_time : existingPlace.place_time, - end_time: end_time !== undefined ? end_time : existingPlace.end_time, - // Not COALESCE, like its neighbours: the contract says an explicit null - // clears the planned stay length, and COALESCE made null and absent the - // same thing, so the field advertised a reset it never performed. 0 keeps - // working, which a `|| null` bind would have swallowed. - duration_minutes: duration_minutes !== undefined ? duration_minutes : existingPlace.duration_minutes, - notes: notes !== undefined ? notes : existingPlace.notes, - image_url: image_url !== undefined ? image_url : existingPlace.image_url, - google_place_id: google_place_id !== undefined ? google_place_id : existingPlace.google_place_id, - google_ftid: google_ftid !== undefined ? google_ftid : existingPlace.google_ftid, - osm_id: osm_id !== undefined ? osm_id : existingPlace.osm_id, - amap_poi_id: amap_poi_id !== undefined ? amap_poi_id : existingPlace.amap_poi_id, - website: website !== undefined ? website : existingPlace.website, - phone: phone !== undefined ? phone : existingPlace.phone, - // Empty clears, like null: the form sends what its field holds (#2472). - email: email !== undefined ? (email?.trim() || null) : existingPlace.email, - opening_hours: opening_hours !== undefined ? (opening_hours || null) : existingPlace.opening_hours, - // COALESCE(?, transport_mode) — same fold as `name`/`currency` above. - transport_mode: (transport_mode || null) ?? existingPlace.transport_mode, - // Deliberately not COALESCE: an explicit null is how the picker resets a - // track back to its category colour (#776). - route_color: route_color !== undefined ? route_color : existingPlace.route_color, - // Same shape: an explicit null is how a fuel stop becomes an ordinary place again. - 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, - })); + const { image_url, tags } = body; + await this.changes.track(tripPlaceTarget(id), editor, () => this.placesRepo.updatePlace(id, placeWriteOf(body, existingPlace))); if (tags !== undefined) { await this.tagsRepo.deleteForPlace(id); // PL12 if (tags.length > 0) await this.tagsRepo.insertIgnore(id, await this.tagsOnTrip(tid, tags)); // PL13 } + const followed = follows ? await follows() : undefined; // PL14; the image this write replaced (#1136), for the caller to release once the transaction committed. - return { result: await this.placesRepo.findWithTagsAndRatings(id), previousImage: image_url !== undefined ? existingPlace.image_url : null }; + return { result: await this.placesRepo.findWithTagsAndRatings(id), previousImage: image_url !== undefined ? existingPlace.image_url : null, followed }; } // ------------------------------------------------------------------------- @@ -684,20 +648,23 @@ 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, editor: ChangeEditor = null): Promise { + async updateMany(tripId: string, ids: number[], body: PlaceUpdateInput, editor: ChangeEditor = null, follow: FollowCopies | null = null): Promise { if (ids.length === 0) return []; const updated: PlaceWithTags[] = []; const previousImages: (string | null | undefined)[] = []; + let followed = NO_FOLLOWED_COPIES; await this.uow.transactional(async () => { 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, undefined, editor); - if (place && !isUpdateConflict(place)) updated.push(place); - previousImages.push(previousImage); + const step = await this.applyUpdate(tripId, String(id), body, undefined, editor, follow); + if (step.result && !isUpdateConflict(step.result)) updated.push(step.result); + previousImages.push(step.previousImage); + if (step.followed) followed = mergeFollowed(followed, step.followed); } }); - await this.release.releaseValues(previousImages); // one bulk value may have replaced many uploads + await this.release.releaseValues([...previousImages, ...followed.previousImages]); // one bulk value, many uploads + await this.copies.announce(followed); return updated; } @@ -1483,30 +1450,28 @@ export class PlacesService { * place (with the new aggregate) or null when the place isn't in the trip. */ async rate(tripId: string, placeId: string, userId: number, rating: number | null): Promise { - // `toRowId` first (Task 3 review H1, absorbed here): PL50/PL51 write - // with this SAME id — a non-canonical `placeId` must resolve to "not - // found" here rather than pass a loose affinity match and then write a - // rating against an id `place_ratings`'s own FK never actually named. + // Both ids through toRowId (H1, rule 21): a non-canonical spelling names no place, nor another trip's. const id = toRowId(placeId); - if (id === null) return null; - // Rule 21 (H1): the trip id gets the same `toRowId` treatment as the - // place id above, parsed once and used for the existence gate below — - // `Number(tripId)` used to disagree with it and let a hex trip id rate - // a different trip's place. const tid = toRowId(tripId); - if (tid === null) return null; + if (id === null || tid === null) return null; // PL49 — the existence gate. if (!(await this.placesRepo.existsInTrip(id, tid))) return null; - if (rating === null) { - // PL50 — `DELETE FROM place_ratings WHERE place_id = ? AND user_id = ?`. - await this.placeRatingsRepo.deleteRating(id, userId); - } else { - // PL51 — the only explicit `ON CONFLICT … DO UPDATE` in the cluster; never touches `places.updated_at`. - await this.placeRatingsRepo.upsertRating(id, userId, rating); - } + // PL50 deletes the vote, PL51 upserts it (ON CONFLICT DO UPDATE); neither touches places.updated_at. + if (rating === null) await this.placeRatingsRepo.deleteRating(id, userId); + else await this.placeRatingsRepo.upsertRating(id, userId, rating); return await this.placesRepo.findWithTagsAndRatings(id); // PL52 } + /** + * The carry-over's vote (PlaceVotesService) on the place `id` of `tripId`: added only where the user has none, as + * changed at `at`, never overwriting one. False when the trip holds no such place; nothing is read back. + */ + async carryRating(tripId: number, id: number, userId: number, rating: number, at: string | null): Promise { + if (!(await this.placesRepo.existsInTrip(id, tripId))) return false; + await this.placeRatingsRepo.insertIgnore(id, userId, rating, at); + return true; + } + /** @txStandalone a journey hook: a non-fatal sync after the place write, like the route's try/catch. */ async onCreated(tripId: string, placeId: number): Promise { try { diff --git a/server/src/nest/tags/tag-writes.service.ts b/server/src/nest/tags/tag-writes.service.ts index bba7d45fb..f5856f52c 100644 --- a/server/src/nest/tags/tag-writes.service.ts +++ b/server/src/nest/tags/tag-writes.service.ts @@ -9,9 +9,7 @@ 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. A create that - * answers a tag the user had already (one name per person, PLC-21) changed - * nothing, so it sends nothing. + * out; MCP passes none. The callers keep their ownership checks. */ @Injectable() export class TagWritesService { @@ -21,8 +19,8 @@ export class TagWritesService { ) {} async create(userId: number, name: string, color: string | undefined, socketId: string | undefined): Promise { - const { tag, created } = await this.tags.ensure(userId, name, color); - if (created) this.announce(userId, socketId); + const tag = await this.tags.create(userId, name, color); + 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 95d4e684c..ae3615b20 100644 --- a/server/src/nest/tags/tags.mcp.ts +++ b/server/src/nest/tags/tags.mcp.ts @@ -43,8 +43,7 @@ export class TagsMcp { @Tool({ name: 'create_tag', - 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.', + description: 'Create a new tag (user-scoped label for places).', 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 4691f4a7c..e2b6cbd41 100644 --- a/server/src/nest/tags/tags.service.ts +++ b/server/src/nest/tags/tags.service.ts @@ -1,8 +1,6 @@ import { Tags } from '../../db/entities/Tags.entity'; -import type { TagRow, TagsRepository } from '../../db/repositories/Tags.repository'; -import { conflict } from '../common/domain-error'; +import type { TagsRepository } from '../../db/repositories/Tags.repository'; 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'; @@ -22,10 +20,7 @@ import type { Tag } from '@trek/shared'; */ @Injectable() export class TagsService { - constructor( - @InjectRepository(Tags) private readonly tags: TagsRepository, - private readonly uow: UnitOfWork, - ) {} + constructor(@InjectRepository(Tags) private readonly tags: TagsRepository) {} // `TagRow`'s `color`/`created_at` are nullable (the DB columns carry no NOT // NULL constraint); the `@trek/shared` `Tag` contract narrows them to @@ -54,35 +49,13 @@ 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 { - 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 }; + const tag = await this.tags.createTag({ + user_id: userId, + name, + color: color || '#10b981', }); - } - - /** 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, - ); + return tag as unknown as Tag; } async update(id: string | number, name?: string, color?: string): Promise { @@ -106,15 +79,7 @@ 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; - 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; + return ((await this.tags.patch(rowId, changes)) ?? undefined) as unknown as Tag; } async remove(id: string | number): Promise { diff --git a/server/src/nest/trip-members/trip-member-writes.service.ts b/server/src/nest/trip-members/trip-member-writes.service.ts index 15c926645..a8ac8759d 100644 --- a/server/src/nest/trip-members/trip-member-writes.service.ts +++ b/server/src/nest/trip-members/trip-member-writes.service.ts @@ -7,6 +7,7 @@ import { TripAddonsService } from '../addons/trip-addons.service'; import { BudgetService } from '../budget/budget.service'; import { restTripWriter, type TripWriter } from '../common/trip-writer'; import { RealtimeService } from '../realtime/realtime.service'; +import { TripMembershipService } from '../trip-membership/trip-membership.service'; import { TripMembersService } from './trip-members.service'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; @@ -32,6 +33,7 @@ export class TripMemberWritesService { @InjectRepository(Users) private readonly users: UsersRepository, private readonly addons: AddonsService, private readonly tripAddons: TripAddonsService, + private readonly membership: TripMembershipService, ) {} /** REST's writer for a roster change: the room minus the tab that sent the request. */ @@ -44,6 +46,7 @@ export class TripMemberWritesService { const result = await this.roster.addMember(tripId, identifier, tripOwnerId, writer.userId); writer.events.emit('member:added', { member: result.member }); await this.tripAddons.reattachJoinedMember(Number(tripId), result.targetUserId); + await this.membership.joins.joined(Number(tripId), result.targetUserId); // the votes they bring along (PlaceVotesService) // The invitation names who sent it by name, as the route does with its session user. const actor = { id: writer.userId, username: (await this.users.findById(writer.userId))?.username ?? '' }; this.roster.notifyInvite(String(tripId), actor, result.targetUserId, result.tripTitle, result.member.email); diff --git a/server/src/nest/trip-members/trip-members.module.ts b/server/src/nest/trip-members/trip-members.module.ts index d09c91ab9..83b324397 100644 --- a/server/src/nest/trip-members/trip-members.module.ts +++ b/server/src/nest/trip-members/trip-members.module.ts @@ -8,6 +8,7 @@ import { BudgetModule } from '../budget/budget.module'; import { NotificationsModule } from '../notifications/notifications.module'; import { PermissionsModule } from '../permissions/permissions.module'; import { RealtimeModule } from '../realtime/realtime.module'; +import { TripMembershipModule } from '../trip-membership/trip-membership.module'; import { TripMemberWritesService } from './trip-member-writes.service'; import { TripMembersController } from './trip-members.controller'; import { TripMembersService } from './trip-members.service'; @@ -37,6 +38,7 @@ import { Module } from '@nestjs/common'; AuthModule, BudgetModule, AddonsModule, + TripMembershipModule, MikroOrmModule.forFeature([Trips, TripMembers, Users]), ], controllers: [TripMembersController], diff --git a/server/src/nest/trip-membership/trip-membership.service.ts b/server/src/nest/trip-membership/trip-membership.service.ts index 9c4508889..90e62ef64 100644 --- a/server/src/nest/trip-membership/trip-membership.service.ts +++ b/server/src/nest/trip-membership/trip-membership.service.ts @@ -2,6 +2,7 @@ import { TripMembers } from '../../db/entities/TripMembers.entity'; import { Trips } from '../../db/entities/Trips.entity'; import type { TripMembersRepository } from '../../db/repositories/TripMembers.repository'; import type { TripsRepository } from '../../db/repositories/Trips.repository'; +import { JoinListeners } from '../common/join-listeners'; import { InjectRepository } from '@mikro-orm/nestjs'; import { Injectable } from '@nestjs/common'; @@ -27,6 +28,9 @@ export class TripMembershipService { @InjectRepository(TripMembers) private readonly tripMembers: TripMembersRepository, ) {} + /** Who hears that somebody joined a trip (join-listeners.ts): the places library carries their votes in. */ + readonly joins = new JoinListeners(); + /** The trip owner's user id, or null when the trip does not exist. */ async getOwnerId(tripId: string | number): Promise { return this.trips.getOwnerId(tripId); @@ -75,6 +79,7 @@ export class TripMembershipService { // Added by a person (a trip-bound invite, a plugin acting for a member // manager): the removal note from GHSA-wr4c-964p-39jg no longer applies. if (invitedBy !== null) await this.tripMembers.clearRemoval(tripId, userId); + await this.joins.joined(tripId, userId); // the votes they bring along (PlaceVotesService) return { joined: true, tripId }; } diff --git a/server/tests/e2e/place-copies.e2e.test.ts b/server/tests/e2e/place-copies.e2e.test.ts new file mode 100644 index 000000000..60b7ceedb --- /dev/null +++ b/server/tests/e2e/place-copies.e2e.test.ts @@ -0,0 +1,229 @@ +/** + * The copies of a place stay in step, end to end on the whole app (buildApp, + * the real guards and a migrated temp database; in the Postgres lane on + * Postgres too): an edit of the general facts of a place on a trip place or a + * saved place is made on the editor's other copies of it they may edit, with + * a history entry per copy and an announcement per trip and list, while + * notes, status and the response stay each copy's own. A copy the editor may + * not edit is skipped, and an MCP token reaches only the kinds it may write. + */ +import { buildApp } from '../../src/bootstrap'; +import { Categories } from '../../src/db/entities/Categories.entity'; +import { CollectionPlaces } from '../../src/db/entities/CollectionPlaces.entity'; +import { PlaceChangeLog } from '../../src/db/entities/PlaceChangeLog.entity'; +import { Places } from '../../src/db/entities/Places.entity'; +import type { McpContext } from '../../src/nest-mcp'; +import { CollectionsMcp } from '../../src/nest/collections/collections.mcp'; +import { withRequestContext } from '../../src/nest/database/request-context'; +import { PlacesMcp } from '../../src/nest/places/places.mcp'; +import { addCollectionMember, makeCollection, makeCollectionPlace } from '../helpers/factories/collections'; +import { makePlace } from '../helpers/factories/places'; +import { countRows, findRow, findRows } from '../helpers/factories/rows'; +import { setAddonEnabled } from '../helpers/factories/settings'; +import { makeTrip } from '../helpers/factories/trips'; +import { makeUser } from '../helpers/factories/users'; +import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime'; +import { resetRateLimits } from '../helpers/test-db'; +import { sessionCookie } from './harness'; +import { MikroORM } from '@mikro-orm/core'; +import type { INestApplication } from '@nestjs/common'; + +import type { Server } from 'http'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +let app: INestApplication; +let server: Server; +let orm: MikroORM; +let realtime: RealtimeSpies; + +const COLLECTIONS = '/api/addons/collections'; +const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); + +async function tripPlace(id: number) { + return findRow(orm, Places, { id }); +} +async function savedPlace(id: number) { + return findRow(orm, CollectionPlaces, { id }); +} + +/** + * `me` owns the trip Alps with the place Café and the list Food with a saved + * copy of Café that came from it, so All places shows `me` the two as one + * place. `other` owns the list Theirs with a copy of the same Café, on which + * `me` is a viewer. + */ +async function seed() { + const { user: me } = await makeUser(orm); + const { user: other } = await makeUser(orm); + const alps = await makeTrip(orm, me.id, { title: 'Alps' }); + const cafe = await makePlace(orm, alps.id, { + name: 'Café', + lat: 48.2, + lng: 16.3, + google_place_id: 'g-cafe', + notes: 'trip note', + }); + const food = await makeCollection(orm, me.id, { name: 'Food' }); + const saved = await makeCollectionPlace(orm, food.id, me.id, { + name: 'Café', + lat: 48.2, + lng: 16.3, + google_place_id: 'g-cafe', + source_trip_id: alps.id, + source_place_id: cafe.id, + notes: 'list note', + }); + const theirs = await makeCollection(orm, other.id, { name: 'Theirs' }); + await addCollectionMember(orm, theirs.id, me.id, { role: 'viewer' }); + const foreign = await makeCollectionPlace(orm, theirs.id, other.id, { + name: 'Café', + lat: 48.2, + lng: 16.3, + google_place_id: 'g-cafe', + source_trip_id: alps.id, + source_place_id: cafe.id, + }); + return { me, other, alps, cafe, food, saved, theirs, foreign }; +} + +beforeAll(async () => { + app = await buildApp(); + server = app.getHttpServer() as Server; + orm = app.get(MikroORM); + await setAddonEnabled(orm, 'collections', true); +}, 60_000); + +beforeEach(async () => { + await resetRateLimits(app); + realtime = spyOnRealtime(app); +}); + +afterAll(async () => { + await app?.close(); +}); + +describe('an edit on one copy is made on the other copies the editor may edit', () => { + it('a trip place edit reaches the saved copy, with its own history entry and the list told', async () => { + const s = await seed(); + const res = await request(server) + .put(`/api/trips/${s.alps.id}/places/${s.cafe.id}`) + .set(as(s.me.id)) + .set('X-Socket-Id', '7') + .send({ name: 'Café Central', address: 'Herrengasse 14', notes: 'new trip note' }); + expect(res.status).toBe(200); + expect(res.body.place).toMatchObject({ id: s.cafe.id, name: 'Café Central', address: 'Herrengasse 14' }); + + const saved = await savedPlace(s.saved.id); + expect(saved).toMatchObject({ name: 'Café Central', address: 'Herrengasse 14', notes: 'list note' }); + // A copy the editor may only view keeps what it had. + expect(await savedPlace(s.foreign.id)).toMatchObject({ name: 'Café', address: null }); + + const history = await findRows(orm, PlaceChangeLog, { collectionPlace: s.saved.id }); + expect(history.map((row) => row.field).sort()).toEqual(['address', 'name']); + expect(history.every((row) => row.user_id === s.me.id)).toBe(true); + expect(realtime.broadcastToUser).toHaveBeenCalledWith( + s.me.id, + { type: 'collections:updated', collectionId: s.food.id }, + undefined, + ); + }); + + it('a saved place edit reaches the trip place, whose room hears of it; status and notes stay apart', async () => { + const s = await seed(); + const res = await request(server) + .patch(`${COLLECTIONS}/places/${s.saved.id}`) + .set(as(s.me.id)) + .send({ description: 'Viennese coffee house', website: 'https://cafecentral.wien', notes: 'only here' }); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ id: s.saved.id, description: 'Viennese coffee house' }); + + expect(await tripPlace(s.cafe.id)).toMatchObject({ + description: 'Viennese coffee house', + website: 'https://cafecentral.wien', + notes: 'trip note', + }); + expect(await countRows(orm, PlaceChangeLog, { place: s.cafe.id })).toBe(2); + expect(realtime.broadcast).toHaveBeenCalledWith( + String(s.alps.id), + 'place:updated', + { place: expect.objectContaining({ id: s.cafe.id, description: 'Viennese coffee house' }) }, + undefined, + ); + }); + + it('a field the edit leaves alone is not carried, and an old difference is not filled in', async () => { + const s = await seed(); + await request(server).patch(`${COLLECTIONS}/places/${s.saved.id}`).set(as(s.me.id)).send({ phone: '+43 1 533' }); + expect((await tripPlace(s.cafe.id))?.phone).toBe('+43 1 533'); + // The trip place differs in its notes from the start; renaming the saved copy leaves them. + await request(server).patch(`${COLLECTIONS}/places/${s.saved.id}`).set(as(s.me.id)).send({ name: 'Central' }); + expect(await tripPlace(s.cafe.id)).toMatchObject({ name: 'Central', notes: 'trip note', phone: '+43 1 533' }); + }); + + it('a bulk category change of trip places reaches their saved copies', async () => { + const s = await seed(); + // Another category than the one the trip place starts with, so the edit changes it. + const category = (await findRows(orm, Categories, {})).find((row) => row.id !== s.cafe.category_id); + expect(category).toBeDefined(); + const res = await request(server) + .post(`/api/trips/${s.alps.id}/places/bulk-update`) + .set(as(s.me.id)) + .send({ ids: [s.cafe.id], category_id: category?.id }); + expect(res.body).toEqual({ updated: [s.cafe.id], count: 1 }); + expect((await savedPlace(s.saved.id))?.category_id).toBe(category?.id); + }); + + it('answers as before when no other copy exists, and keeps every refusal of the copy edited', async () => { + const { user } = await makeUser(orm); + const trip = await makeTrip(orm, user.id); + const lone = await makePlace(orm, trip.id, { name: 'Lone' }); + const res = await request(server) + .put(`/api/trips/${trip.id}/places/${lone.id}`) + .set(as(user.id)) + .send({ name: 'Still lone' }); + expect(res.status).toBe(200); + expect(res.body.place.name).toBe('Still lone'); + + const s = await seed(); + const viewer = await request(server) + .patch(`${COLLECTIONS}/places/${s.foreign.id}`) + .set(as(s.me.id)) + .send({ name: 'X' }); + expect(viewer.status).toBe(403); + expect(viewer.body).toEqual({ error: 'You have read-only access to this list' }); + expect((await tripPlace(s.cafe.id))?.name).toBe('Café'); + }); +}); + +describe('over MCP, a token reaches the copies of the kinds it may write', () => { + it('places:write alone leaves the saved copy, collections:write alone the trip place', async () => { + const s = await seed(); + const places = app.get(PlacesMcp); + const collections = app.get(CollectionsMcp); + const placesOnly: McpContext = { userId: s.me.id, scopes: ['places:write'], isStaticToken: false }; + await withRequestContext(orm, () => + places.updatePlace({ tripId: s.alps.id, placeId: s.cafe.id, name: 'Trip name' }, placesOnly), + ); + expect((await tripPlace(s.cafe.id))?.name).toBe('Trip name'); + expect((await savedPlace(s.saved.id))?.name).toBe('Café'); + + const listsOnly: McpContext = { userId: s.me.id, scopes: ['collections:write'], isStaticToken: false }; + await withRequestContext(orm, () => + collections.updateCollectionPlace({ placeId: s.saved.id, address: 'Herrengasse 14' }, listsOnly), + ); + expect((await savedPlace(s.saved.id))?.address).toBe('Herrengasse 14'); + expect((await tripPlace(s.cafe.id))?.address).toBeNull(); + }); + + it('a token with both scopes keeps every copy in step', async () => { + const s = await seed(); + const places = app.get(PlacesMcp); + const both: McpContext = { userId: s.me.id, scopes: null, isStaticToken: false }; + await withRequestContext(orm, () => + places.bulkUpdatePlaces({ tripId: s.alps.id, placeIds: [s.cafe.id], description: 'From the assistant' }, both), + ); + expect((await savedPlace(s.saved.id))?.description).toBe('From the assistant'); + expect((await savedPlace(s.foreign.id))?.description).toBeNull(); + }); +}); diff --git a/server/tests/e2e/place-tags.e2e.test.ts b/server/tests/e2e/place-tags.e2e.test.ts deleted file mode 100644 index 3222c6dbe..000000000 --- a/server/tests/e2e/place-tags.e2e.test.ts +++ /dev/null @@ -1,201 +0,0 @@ -/** - * 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-votes-join.e2e.test.ts b/server/tests/e2e/place-votes-join.e2e.test.ts new file mode 100644 index 000000000..02cc83500 --- /dev/null +++ b/server/tests/e2e/place-votes-join.e2e.test.ts @@ -0,0 +1,144 @@ +/** + * Late joiners bring their votes, end to end on the whole app (buildApp, the + * real guards and a migrated temp database; in the Postgres lane on Postgres + * too): who accepts an invitation to a list or is added to a trip gets their + * latest vote on the copies there of a place they voted on elsewhere, where + * they have none, as an insert that never overwrites, and the list or the + * trip's room hears of it. + */ +import { buildApp } from '../../src/bootstrap'; +import { CollectionPlaceRatings } from '../../src/db/entities/CollectionPlaceRatings.entity'; +import { PlaceRatings } from '../../src/db/entities/PlaceRatings.entity'; +import { addCollectionMember, makeCollection, makeCollectionPlace } from '../helpers/factories/collections'; +import { makePlace } from '../helpers/factories/places'; +import { findRows, insertRow } from '../helpers/factories/rows'; +import { setAddonEnabled } from '../helpers/factories/settings'; +import { makeTrip } from '../helpers/factories/trips'; +import { makeUser } from '../helpers/factories/users'; +import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime'; +import { resetRateLimits } from '../helpers/test-db'; +import { sessionCookie } from './harness'; +import { MikroORM } from '@mikro-orm/core'; +import type { INestApplication } from '@nestjs/common'; + +import type { Server } from 'http'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +let app: INestApplication; +let server: Server; +let orm: MikroORM; +let realtime: RealtimeSpies; + +const COLLECTIONS = '/api/addons/collections'; +const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); + +async function tripVotes(placeId: number): Promise> { + const rows = await findRows(orm, PlaceRatings, { place: placeId }); + return Object.fromEntries(rows.map((row) => [row.user_id, row.rating])); +} +async function listVotes(collectionPlaceId: number): Promise> { + const rows = await findRows(orm, CollectionPlaceRatings, { collectionPlace: collectionPlaceId }); + return Object.fromEntries(rows.map((row) => [row.user_id, row.rating])); +} + +/** + * `owner` has the trip Alps with Café and the list Food with a copy of it + * that came from the trip place. `joiner` has a list Mine with a copy of the + * same Café and voted on it; once on Food or Alps, those copies are the same + * place for them. + */ +async function seed() { + const { user: owner } = await makeUser(orm); + const { user: joiner } = await makeUser(orm); + const alps = await makeTrip(orm, owner.id, { title: 'Alps' }); + const cafe = await makePlace(orm, alps.id, { name: 'Café', lat: 48.2, lng: 16.3, google_place_id: 'g-cafe' }); + const copyOf = { + name: 'Café', + lat: 48.2, + lng: 16.3, + google_place_id: 'g-cafe', + source_trip_id: alps.id, + source_place_id: cafe.id, + }; + const food = await makeCollection(orm, owner.id, { name: 'Food' }); + const shared = await makeCollectionPlace(orm, food.id, owner.id, copyOf); + const mine = await makeCollection(orm, joiner.id, { name: 'Mine' }); + const own = await makeCollectionPlace(orm, mine.id, joiner.id, copyOf); + await insertRow(orm, CollectionPlaceRatings, { collectionPlace: own.id, user: joiner.id, rating: 4 }); + return { owner, joiner, alps, cafe, food, shared, mine, own }; +} + +beforeAll(async () => { + app = await buildApp(); + server = app.getHttpServer() as Server; + orm = app.get(MikroORM); + await setAddonEnabled(orm, 'collections', true); +}, 60_000); + +beforeEach(async () => { + await resetRateLimits(app); + realtime = spyOnRealtime(app); +}); + +afterAll(async () => { + await app?.close(); +}); + +describe('who joins brings their votes', () => { + it('accepting a list invitation carries the vote onto its copy and the list hears of it', async () => { + const s = await seed(); + // The joiner's own trip place, voted on, that the shared list's copy came from. + const home = await makeTrip(orm, s.joiner.id, { title: 'Home' }); + const visited = await makePlace(orm, home.id, { name: 'Bar', lat: 47.1, lng: 15.4, google_place_id: 'g-bar' }); + await insertRow(orm, PlaceRatings, { place: visited.id, user: s.joiner.id, rating: 4 }); + const barCopy = await makeCollectionPlace(orm, s.food.id, s.owner.id, { + name: 'Bar', + lat: 47.1, + lng: 15.4, + google_place_id: 'g-bar', + source_trip_id: home.id, + source_place_id: visited.id, + }); + await addCollectionMember(orm, s.food.id, s.joiner.id, { status: 'pending', role: 'viewer' }); + const res = await request(server) + .post(`${COLLECTIONS}/invite/accept`) + .set(as(s.joiner.id)) + .send({ collection_id: s.food.id }); + expect(res.status).toBe(200); + expect(await listVotes(barCopy.id)).toEqual({ [s.joiner.id]: 4 }); + // Only into the list joined: the trip they are not on keeps none. + expect(await tripVotes(s.cafe.id)).toEqual({}); + expect(realtime.broadcastToUser).toHaveBeenCalledWith( + s.owner.id, + expect.objectContaining({ type: 'collections:accepted', collectionId: s.food.id }), + undefined, + ); + }); + + it('being added to a trip carries the vote onto its copy and tells the trip room', async () => { + const s = await seed(); + const res = await request(server) + .post(`/api/trips/${s.alps.id}/members`) + .set(as(s.owner.id)) + .send({ identifier: s.joiner.email }); + expect(res.status).toBe(201); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.joiner.id]: 4 }); + expect(realtime.broadcast).toHaveBeenCalledWith( + String(s.alps.id), + 'place:updated', + { place: expect.objectContaining({ id: s.cafe.id }) }, + undefined, + ); + }); + + it('never overwrites a vote already on the copy', async () => { + const s = await seed(); + await insertRow(orm, PlaceRatings, { place: s.cafe.id, user: s.joiner.id, rating: 1 }); + await request(server) + .post(`/api/trips/${s.alps.id}/members`) + .set(as(s.owner.id)) + .send({ identifier: s.joiner.email }); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.joiner.id]: 1 }); + }); +}); diff --git a/server/tests/e2e/place-votes.e2e.test.ts b/server/tests/e2e/place-votes.e2e.test.ts new file mode 100644 index 000000000..524485085 --- /dev/null +++ b/server/tests/e2e/place-votes.e2e.test.ts @@ -0,0 +1,471 @@ +/** + * One vote per person on a place, end to end on the whole app (buildApp, the + * real guards and a migrated temp database; in the Postgres lane on Postgres + * too): a vote cast or taken back on one copy of a place lands on the person's + * other copies of it, a list never shows the vote of someone who is not on it, + * the entry of All places counts every person once, the vote by entry key, the + * carry-over of the votes cast before (and that it adds nothing when it runs + * again), the votes a copy into a trip or a list brings along, and the vote + * tools over MCP. + */ +import { buildApp } from '../../src/bootstrap'; +import { AppSettings } from '../../src/db/entities/AppSettings.entity'; +import { CollectionPlaceRatings } from '../../src/db/entities/CollectionPlaceRatings.entity'; +import { PlaceRatings } from '../../src/db/entities/PlaceRatings.entity'; +import type { McpContext } from '../../src/nest-mcp'; +import { withRequestContext } from '../../src/nest/database/request-context'; +import { PlaceVotesCarryJob } from '../../src/nest/places-library/place-votes-carry.job'; +import { PlaceVotesLibraryMcp, PlaceVotesMcp } from '../../src/nest/places-library/place-votes.mcp'; +import { PlaceVotesService } from '../../src/nest/places-library/place-votes.service'; +import { addCollectionMember, makeCollection, makeCollectionPlace } from '../helpers/factories/collections'; +import { makePlace } from '../helpers/factories/places'; +import { deleteRows, findRows, insertRow, updateRows } from '../helpers/factories/rows'; +import { readAppSetting, setAddonEnabled } from '../helpers/factories/settings'; +import { addTripMember, makeTrip } from '../helpers/factories/trips'; +import { makeUser } from '../helpers/factories/users'; +import { spyOnRealtime, type RealtimeSpies } from '../helpers/fake-realtime'; +import { resetRateLimits } from '../helpers/test-db'; +import { sessionCookie } from './harness'; +import { MikroORM } from '@mikro-orm/core'; +import type { INestApplication } from '@nestjs/common'; + +import type { Server } from 'http'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; + +let app: INestApplication; +let server: Server; +let orm: MikroORM; +let realtime: RealtimeSpies; + +const COLLECTIONS = '/api/addons/collections'; +const LIBRARY_RATING = `${COLLECTIONS}/library/places/rating`; +const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); + +/** A voter as the entry rating names them. */ +const voter = (user: { id: number; username: string }, rating: number) => ({ + user_id: user.id, + username: user.username, + avatar_url: null, + rating, +}); +/** An entry rating with its voters in id order, so a comparison does not hang on the order they were read in. */ +function sortedRating(rating: { votes?: { user_id: number }[] } | undefined) { + return rating && { ...rating, votes: [...(rating.votes ?? [])].sort((a, b) => a.user_id - b.user_id) }; +} + +/** The votes on a trip place and on a saved place, by person. */ +async function tripVotes(placeId: number): Promise> { + const rows = await findRows(orm, PlaceRatings, { place: placeId }); + return Object.fromEntries(rows.map((row) => [row.user_id, row.rating])); +} +async function listVotes(collectionPlaceId: number): Promise> { + const rows = await findRows(orm, CollectionPlaceRatings, { collectionPlace: collectionPlaceId }); + return Object.fromEntries(rows.map((row) => [row.user_id, row.rating])); +} + +/** + * `me` owns the trip Alps with the place Café (on it is `friend`) and the list + * Food with a saved copy of Café that came from the trip place (the same + * provider id), so All places shows `me` the two as one entry. `friend` is + * not on Food; `listmate` is on Food and not on Alps. + */ +async function seed() { + const { user: me } = await makeUser(orm); + const { user: friend } = await makeUser(orm); + const { user: listmate } = await makeUser(orm); + const alps = await makeTrip(orm, me.id, { title: 'Alps' }); + await addTripMember(orm, alps.id, friend.id); + const cafe = await makePlace(orm, alps.id, { name: 'Café', lat: 48.2, lng: 16.3, google_place_id: 'g-cafe' }); + const food = await makeCollection(orm, me.id, { name: 'Food' }); + await addCollectionMember(orm, food.id, listmate.id, { role: 'viewer' }); + const saved = await makeCollectionPlace(orm, food.id, me.id, { + name: 'Café', + lat: 48.2, + lng: 16.3, + google_place_id: 'g-cafe', + source_trip_id: alps.id, + source_place_id: cafe.id, + }); + return { me, friend, listmate, alps, cafe, food, saved }; +} + +beforeAll(async () => { + app = await buildApp(); + server = app.getHttpServer() as Server; + orm = app.get(MikroORM); + await setAddonEnabled(orm, 'collections', true); +}, 60_000); + +beforeEach(async () => { + await resetRateLimits(app); + realtime = spyOnRealtime(app); +}); + +afterAll(async () => { + await app?.close(); +}); + +describe('a vote on one copy lands on every copy of the person', () => { + it('a vote on the trip place is the vote on the saved copy, and each trip and list hears of it', async () => { + const s = await seed(); + const res = await request(server) + .put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`) + .set(as(s.me.id)) + .set('X-Socket-Id', '7') + .send({ rating: 4 }); + expect(res.status).toBe(200); + expect(res.body.place).toMatchObject({ id: s.cafe.id, rating_avg: 4, rating_count: 1 }); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 4 }); + expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 4 }); + // The trip place voted on skips the caller's socket; the list it reached does not. + expect(realtime.broadcast).toHaveBeenCalledWith(String(s.alps.id), 'place:updated', expect.anything(), '7'); + expect(realtime.broadcastToUser).toHaveBeenCalledWith( + s.me.id, + { type: 'collections:updated', collectionId: s.food.id }, + undefined, + ); + }); + + it('taking the vote back on the saved copy takes it off the trip place too', async () => { + const s = await seed(); + await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 5 }); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 5 }); + const res = await request(server).delete(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)); + expect(res.status).toBe(200); + expect(res.body).toMatchObject({ id: s.saved.id, rating_avg: null, rating_count: 0 }); + expect(await tripVotes(s.cafe.id)).toEqual({}); + expect(await listVotes(s.saved.id)).toEqual({}); + }); + + it('keeps every check of the copy voted on: an unknown place, a trip out of reach, a bad body', async () => { + const s = await seed(); + const { user: stranger } = await makeUser(orm); + expect( + (await request(server).put(`/api/trips/${s.alps.id}/places/999999/rating`).set(as(s.me.id)).send({ rating: 3 })) + .body, + ).toEqual({ error: 'Place not found' }); + const outside = await request(server) + .put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`) + .set(as(stranger.id)) + .send({ rating: 3 }); + expect(outside.status).toBe(404); + expect(outside.body).toEqual({ error: 'Trip not found' }); + expect( + (await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(stranger.id)).send({ rating: 3 })) + .status, + ).toBe(404); + expect( + (await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 9 })) + .status, + ).toBe(400); + expect(await tripVotes(s.cafe.id)).toEqual({}); + }); +}); + +describe('a list or trip shows only its own members their votes', () => { + it("a trip member's vote never reaches a list they are not on; the entry counts each person once", async () => { + const s = await seed(); + await request(server) + .put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`) + .set(as(s.friend.id)) + .send({ rating: 2 }); + await request(server) + .put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`) + .set(as(s.me.id)) + .send({ rating: 4 }); + expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 4 }); + const list = await request(server).get(`${COLLECTIONS}/${s.food.id}`).set(as(s.listmate.id)); + expect(list.status).toBe(200); + const place = (list.body.places as { id: number; ratings: { user_id: number }[] }[]).find( + (p) => p.id === s.saved.id, + ); + expect(place?.ratings.map((vote) => vote.user_id)).toEqual([s.me.id]); + + // me has a vote on both copies and counts once; friend's vote comes from the trip me is on. + const detail = await request(server).get(`${COLLECTIONS}/library/places/list/${s.saved.id}`).set(as(s.me.id)); + expect(detail.status).toBe(200); + expect(sortedRating(detail.body.entry.rating)).toEqual({ + average: 3, + count: 2, + mine: 4, + votes: [voter(s.me, 4), voter(s.friend, 2)].sort((a, b) => a.user_id - b.user_id), + }); + // The list member sees the list's votes only. + const theirs = await request(server).get(`${COLLECTIONS}/library/places/list/${s.saved.id}`).set(as(s.listmate.id)); + // Nor do they see friend among the voters. + expect(theirs.body.entry.rating).toEqual({ average: 4, count: 1, mine: null, votes: [voter(s.me, 4)] }); + const page = await request(server).get(`${COLLECTIONS}/library/places`).query({ limit: 200 }).set(as(s.me.id)); + const entry = (page.body.entries as { key: string; rating: { votes?: { user_id: number }[] } }[]).find( + (e) => e.key === `trip:${s.cafe.id}`, + ); + expect(sortedRating(entry?.rating)).toEqual({ + average: 3, + count: 2, + mine: 4, + votes: [voter(s.me, 4), voter(s.friend, 2)].sort((a, b) => a.user_id - b.user_id), + }); + }); + + it("counts a person's differing votes on two copies once, with the one changed last", async () => { + const s = await seed(); + // Cast on the trip in January and changed there in March; cast on the list in February. + await insertRow(orm, PlaceRatings, { + place: s.cafe.id, + user: s.me.id, + rating: 5, + created_at: '2026-01-01 10:00:00', + updated_at: '2026-03-01 10:00:00', + }); + await insertRow(orm, CollectionPlaceRatings, { + collectionPlace: s.saved.id, + user: s.me.id, + rating: 1, + created_at: '2026-02-01 10:00:00', + }); + const detail = await request(server).get(`${COLLECTIONS}/library/places/trip/${s.cafe.id}`).set(as(s.me.id)); + expect(detail.body.entry.rating).toEqual({ average: 5, count: 1, mine: 5, votes: [voter(s.me, 5)] }); + // Each copy keeps its own vote where it lives. + expect(detail.body.details.map((d: { rating: { mine: number } }) => d.rating.mine)).toEqual([5, 1]); + + // Never changed, a vote reads as changed when it was cast: then the February list vote is the later one. + await deleteRows(orm, PlaceRatings, { place: s.cafe.id, user: s.me.id }); + await insertRow(orm, PlaceRatings, { + place: s.cafe.id, + user: s.me.id, + rating: 5, + created_at: '2026-01-01 10:00:00', + }); + const again = await request(server).get(`${COLLECTIONS}/library/places/trip/${s.cafe.id}`).set(as(s.me.id)); + expect(again.body.entry.rating).toEqual({ average: 1, count: 1, mine: 1, votes: [voter(s.me, 1)] }); + }); + + it('a vote records when it was changed, on every copy it lands on', async () => { + const s = await seed(); + await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 2 }); + await updateRows( + orm, + CollectionPlaceRatings, + { collectionPlace: s.saved.id }, + { updated_at: '2026-01-01 00:00:00' }, + ); + await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 4 }); + const [listVote] = await findRows(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id }); + const [tripVote] = await findRows(orm, PlaceRatings, { place: s.cafe.id }); + expect(listVote?.rating).toBe(4); + expect(listVote?.updated_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/); + expect(listVote?.updated_at).not.toBe('2026-01-01 00:00:00'); + expect(tripVote?.rating).toBe(4); + expect(tripVote?.updated_at).not.toBeNull(); + }); +}); + +describe('the vote by entry key', () => { + it('sets and takes back the vote on every copy and answers the entry rating', async () => { + const s = await seed(); + const put = await request(server) + .put(LIBRARY_RATING) + .set(as(s.me.id)) + .send({ key: `trip:${s.cafe.id}`, rating: 5 }); + expect(put.status).toBe(200); + expect(put.body).toEqual({ + key: `trip:${s.cafe.id}`, + rating: { average: 5, count: 1, mine: 5, votes: [voter(s.me, 5)] }, + }); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 5 }); + expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 5 }); + expect(realtime.broadcast).toHaveBeenCalledWith(String(s.alps.id), 'place:updated', expect.anything(), undefined); + + const del = await request(server) + .delete(LIBRARY_RATING) + .query({ key: `trip:${s.cafe.id}` }) + .set(as(s.me.id)); + expect(del.status).toBe(200); + expect(del.body.rating).toEqual({ average: null, count: 0, mine: null, votes: [] }); + expect(await tripVotes(s.cafe.id)).toEqual({}); + expect(await listVotes(s.saved.id)).toEqual({}); + }); + + it('a list member votes on the copies they reach only', async () => { + const s = await seed(); + const res = await request(server) + .put(LIBRARY_RATING) + .set(as(s.listmate.id)) + .send({ key: `list:${s.saved.id}`, rating: 3 }); + expect(res.status).toBe(200); + expect(await listVotes(s.saved.id)).toEqual({ [s.listmate.id]: 3 }); + expect(await tripVotes(s.cafe.id)).toEqual({}); + }); + + it('answers 404 for a key out of reach, 400 for a malformed one, 401 without a session', async () => { + const s = await seed(); + const { user: stranger } = await makeUser(orm); + const far = await request(server) + .put(LIBRARY_RATING) + .set(as(stranger.id)) + .send({ key: `trip:${s.cafe.id}`, rating: 3 }); + expect(far.status).toBe(404); + expect(far.body).toEqual({ error: 'Place not found' }); + expect( + (await request(server).put(LIBRARY_RATING).set(as(s.me.id)).send({ key: 'trip:abc', rating: 3 })).status, + ).toBe(400); + expect((await request(server).delete(LIBRARY_RATING).set(as(s.me.id))).status).toBe(400); + expect( + ( + await request(server) + .put(LIBRARY_RATING) + .send({ key: `trip:${s.cafe.id}`, rating: 3 }) + ).status, + ).toBe(401); + expect(await tripVotes(s.cafe.id)).toEqual({}); + }); +}); + +describe('the votes cast before are carried over', () => { + it('adds the last vote where a copy has none, leaves differing votes alone and adds nothing a second time', async () => { + const s = await seed(); + // me voted on the saved copy only; friend on the trip place only and is not on the list. + await insertRow(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id, user: s.me.id, rating: 3 }); + await insertRow(orm, PlaceRatings, { place: s.cafe.id, user: s.friend.id, rating: 4 }); + const votes = app.get(PlaceVotesService); + expect(await withRequestContext(orm, () => votes.carryOver(s.me.id))).toBe(1); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 3, [s.friend.id]: 4 }); + // The carried copy keeps the time of the vote it came from, so it never reads as the newer one. + const [source] = await findRows(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id, user: s.me.id }); + const [carried] = await findRows(orm, PlaceRatings, { place: s.cafe.id, user: s.me.id }); + expect(carried?.updated_at ?? null).toBe(source?.updated_at ?? source?.created_at ?? null); + expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 3 }); + expect(await withRequestContext(orm, () => votes.carryOver(s.me.id))).toBe(0); + expect(await withRequestContext(orm, () => votes.carryOver(s.friend.id))).toBe(0); + + // Differing votes on the two copies stay as they are. + await request(server) + .put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`) + .set(as(s.me.id)) + .send({ rating: 3 }); + await deleteRows(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id, user: s.me.id }); + await insertRow(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id, user: s.me.id, rating: 2 }); + expect(await withRequestContext(orm, () => votes.carryOver(s.me.id))).toBe(0); + expect(await tripVotes(s.cafe.id)).toMatchObject({ [s.me.id]: 3 }); + expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 2 }); + }); + + it('the boot pass carries every voter once, remembers it and then stays put', async () => { + const s = await seed(); + await insertRow(orm, PlaceRatings, { place: s.cafe.id, user: s.me.id, rating: 5 }); + await deleteRows(orm, AppSettings, { key: { $in: ['place_votes_carried_over', 'place_votes_carry_runs'] } }); + const job = app.get(PlaceVotesCarryJob); + await job.run(); + expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 5 }); + expect(await readAppSetting(orm, 'place_votes_carried_over')).not.toBeNull(); + expect(await readAppSetting(orm, 'place_votes_carry_runs')).toBe('1'); + + // Finished: a later start reads the mark and adds nothing, also where a copy lost its vote. + await deleteRows(orm, CollectionPlaceRatings, { collectionPlace: s.saved.id }); + await job.run(); + expect(await listVotes(s.saved.id)).toEqual({}); + }); +}); + +describe('a copy brings the votes of the members of its target along', () => { + it('copying a saved place into a trip carries the votes of the trip members only', async () => { + const s = await seed(); + await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.me.id)).send({ rating: 5 }); + await request(server).put(`${COLLECTIONS}/places/${s.saved.id}/rating`).set(as(s.listmate.id)).send({ rating: 2 }); + const res = await request(server) + .post(`${COLLECTIONS}/copy-to-trip`) + .set(as(s.me.id)) + .send({ trip_id: s.alps.id, place_ids: [s.saved.id], force: true }); + expect(res.status).toBeLessThan(300); + const created = (res.body.created as { id: number }[])[0]; + expect(created).toBeDefined(); + expect(await tripVotes(created?.id ?? 0)).toEqual({ [s.me.id]: 5 }); + }); + + it('saving a trip place into a list carries the votes of the list members only', async () => { + const s = await seed(); + await request(server) + .put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`) + .set(as(s.me.id)) + .send({ rating: 4 }); + await request(server) + .put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`) + .set(as(s.friend.id)) + .send({ rating: 1 }); + const other = await makeCollection(orm, s.me.id, { name: 'Other' }); + const res = await request(server) + .post(`${COLLECTIONS}/places/from-trip`) + .set(as(s.me.id)) + .send({ collection_id: other.id, source_trip_id: s.alps.id, source_place_id: s.cafe.id, force: true }); + expect(res.status).toBe(200); + const copies = await findRows(orm, CollectionPlaceRatings, { user: s.friend.id }); + expect(copies).toEqual([]); + const mine = await findRows(orm, CollectionPlaceRatings, { user: s.me.id }); + expect(mine.map((vote) => vote.rating).sort()).toEqual([4, 4]); + }); +}); + +describe('the vote tools', () => { + it('rate_library_place, rate_place and rate_collection_place write through like the routes', async () => { + const s = await seed(); + const tools = app.get(PlaceVotesMcp); + const libraryTools = app.get(PlaceVotesLibraryMcp); + const ctx: McpContext = { userId: s.me.id, scopes: null, isStaticToken: false }; + const entry = await withRequestContext(orm, () => + libraryTools.rateLibraryPlace({ key: `trip:${s.cafe.id}`, rating: 4 }, ctx), + ); + const text = (entry as { content: { text: string }[] }).content[0]?.text ?? ''; + expect(JSON.parse(text)).toMatchObject({ rating: { mine: 4 } }); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 4 }); + + await withRequestContext(orm, () => tools.ratePlace({ tripId: s.alps.id, placeId: s.cafe.id }, ctx)); + expect(await listVotes(s.saved.id)).toEqual({}); + expect(realtime.broadcast).toHaveBeenCalledWith(s.alps.id, 'place:updated', expect.anything()); + + await withRequestContext(orm, () => libraryTools.rateCollectionPlace({ placeId: s.saved.id, rating: 2 }, ctx)); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 2 }); + + const { user: stranger } = await makeUser(orm); + const refused = await withRequestContext(orm, () => + tools.ratePlace({ tripId: s.alps.id, placeId: s.cafe.id, rating: 1 }, { ...ctx, userId: stranger.id }), + ); + expect(refused).toMatchObject({ isError: true }); + }); + + it('a token writes the copies of the kinds its scopes allow only', async () => { + const s = await seed(); + const tools = app.get(PlaceVotesMcp); + const libraryTools = app.get(PlaceVotesLibraryMcp); + const placesOnly: McpContext = { userId: s.me.id, scopes: ['places:write'], isStaticToken: false }; + await withRequestContext(orm, () => + tools.ratePlace({ tripId: s.alps.id, placeId: s.cafe.id, rating: 5 }, placesOnly), + ); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 5 }); + expect(await listVotes(s.saved.id)).toEqual({}); + + const listsOnly: McpContext = { userId: s.me.id, scopes: ['collections:write'], isStaticToken: false }; + await withRequestContext(orm, () => + libraryTools.rateCollectionPlace({ placeId: s.saved.id, rating: 2 }, listsOnly), + ); + expect(await listVotes(s.saved.id)).toEqual({ [s.me.id]: 2 }); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 5 }); + }); +}); + +describe('with the Collections addon off', () => { + it('a vote on a trip place stays off the saved copies', async () => { + const s = await seed(); + await setAddonEnabled(orm, 'collections', false); + try { + const res = await request(server) + .put(`/api/trips/${s.alps.id}/places/${s.cafe.id}/rating`) + .set(as(s.me.id)) + .send({ rating: 3 }); + expect(res.status).toBe(200); + expect(await tripVotes(s.cafe.id)).toEqual({ [s.me.id]: 3 }); + expect(await listVotes(s.saved.id)).toEqual({}); + } finally { + await setAddonEnabled(orm, 'collections', true); + } + }); +}); diff --git a/server/tests/e2e/places-library-tags.e2e.test.ts b/server/tests/e2e/places-library-tags.e2e.test.ts new file mode 100644 index 000000000..b0bb5351b --- /dev/null +++ b/server/tests/e2e/places-library-tags.e2e.test.ts @@ -0,0 +1,183 @@ +/** + * The tags of "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: an entry carries the tags of its + * lists and trips, the list filters by tag names in the query string, the + * detail names each origin's tags with whether they may be changed there, a + * list tag set through the saved place shows at once, and a copy into a trip + * brings the list tags asked for along as tags of the trip. + */ +import { CollectionLabels } from '../../src/db/entities/CollectionLabels.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 { labelCollectionPlace } from '../helpers/factories/collections'; +import { makeTag, tagPlace } from '../helpers/factories/places'; +import { createRow, 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 { joinLibraryTagNames } from '@trek/shared'; + +import cookieParser from 'cookie-parser'; +import type { Server } from 'http'; +import request from 'supertest'; +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +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 COLLECTIONS = '/api/addons/collections'; +const LIBRARY = `${COLLECTIONS}/library/places`; + +let app: INestApplication; +let server: Server; +let orm: TestOrm; +let f: LibraryFixture; +let view: number; +let coffee: number; + +const as = (userId: number) => ({ Cookie: sessionCookie(userId) }); +const keysOf = (body: { entries: { key: string }[] }) => body.entries.map((entry) => entry.key).sort(); + +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); + // The trip Alps tags Café Central "View"; the list Food has "Food, drinks" on Lunch spot. + view = (await makeTag(orm, f.me.id, { name: 'View', color: '#00aa00', trip: f.alps.id })).id; + await tagPlace(orm, f.places.cafe.id, [view]); + coffee = ( + await createRow(orm, CollectionLabels, { collection: f.lists.food.id, name: 'Food, drinks', sort_order: 1 }) + ).id; + await labelCollectionPlace(orm, f.saved.lunch.id, coffee); +}); +afterAll(async () => { + await app.close(); + await orm.close(); + db.close(); +}); + +describe('All places tags e2e (real guards + temp SQLite)', () => { + it('carries the tags of the lists and trips and filters by their names in the query string', async () => { + const cafe = `trip:${f.places.cafe.id}`; + const lunch = `list:${f.saved.lunch.id}`; + const all = await request(server).get(LIBRARY).query({ limit: 200 }).set(as(f.me.id)); + expect(all.status).toBe(200); + const byKey = new Map( + (all.body.entries as { key: string; tags: unknown }[]).map((entry) => [entry.key, entry.tags]), + ); + expect(byKey.get(cafe)).toEqual([ + { name: 'Must', color: '#ff0000' }, + { name: 'View', color: '#00aa00' }, + ]); + expect(byKey.get(lunch)).toEqual([{ name: 'Food, drinks', color: '#6366f1' }]); + + const view = await request(server).get(LIBRARY).query({ tags: 'view' }).set(as(f.me.id)); + expect(view.status).toBe(200); + expect(keysOf(view.body)).toEqual([cafe]); + // A comma inside a name travels escaped, and two names find either. + const joined = joinLibraryTagNames(['food, DRINKS', 'View']); + const either = await request(server).get(LIBRARY).query({ tags: joined }).set(as(f.me.id)); + expect(either.status).toBe(200); + expect(keysOf(either.body)).toEqual([cafe, lunch].sort()); + expect(either.body.counts).toEqual({ all: 2, trip: 1, list: 2 }); + // Nobody else reads the tags of a trip and a list they cannot open. + const stranger = await request(server).get(LIBRARY).query({ tags: 'View' }).set(as(f.stranger.id)); + expect(stranger.body.total).toBe(0); + }); + + it('refuses the old id filter, an empty one and too many names', async () => { + const many = Array.from({ length: 51 }, (_, i) => `t${i}`).join(','); + const bad = await oneByOne([{ tag_ids: '3' }, { tags: '' }, { tags: ',, ' }, { tags: many }], (query) => + request(server).get(LIBRARY).query(query).set(as(f.me.id)), + ); + expect(bad.map((res) => res.status)).toEqual([400, 400, 400, 400]); + }); + + it('names each origin’s tags in detail, and a list tag set on the saved place shows at once', async () => { + const detail = await request(server).get(`${LIBRARY}/trip/${f.places.cafe.id}`).set(as(f.me.id)); + expect(detail.status).toBe(200); + const [trip, list] = detail.body.details; + expect(trip).toMatchObject({ + kind: 'trip', + tags: [{ id: view, name: 'View', color: '#00aa00' }], + available_tags: [{ id: view, name: 'View', color: '#00aa00' }], + can_edit_tags: true, + }); + expect(list).toMatchObject({ + kind: 'list', + tags: [{ id: f.label.id, name: 'Must', color: '#ff0000' }], + available_tags: [ + { id: f.label.id, name: 'Must', color: '#ff0000' }, + { id: coffee, name: 'Food, drinks', color: '#6366f1' }, + ], + can_edit_tags: true, + }); + + const set = await request(server) + .patch(`${COLLECTIONS}/places/${f.saved.savedCafe.id}`) + .set(as(f.me.id)) + .send({ label_ids: [f.label.id, coffee] }); + expect(set.status).toBe(200); + const again = await request(server).get(`${LIBRARY}/list/${f.saved.savedCafe.id}`).set(as(f.me.id)); + expect(again.body.details[1].tags.map((tag: { name: string }) => tag.name)).toEqual(['Must', 'Food, drinks']); + expect(again.body.entry.tags.map((tag: { name: string }) => tag.name)).toEqual(['Food, drinks', 'Must', 'View']); + + // A viewer of a list reads its tags and may not change them there. + const pantheon = await request(server).get(`${LIBRARY}/list/${f.saved.pantheon.id}`).set(as(f.me.id)); + expect(pantheon.body.details[0]).toMatchObject({ kind: 'list', tags: [], can_edit_tags: false }); + }); + + it('brings the list tags asked for along as tags of the trip when a saved place is copied', async () => { + await makeTag(orm, f.me.id, { name: 'food, drinks', trip: f.alps.id, color: '#111111' }); + const res = await request(server) + .post(`${COLLECTIONS}/copy-to-trip`) + .set(as(f.me.id)) + .send({ trip_id: f.alps.id, place_ids: [f.saved.lunch.id], force: true, label_ids: [coffee, 999_999] }); + expect(res.status).toBe(200); + const placeId = res.body.created[0].id as number; + // The trip's own tag of that name is reused, whatever its case, and nothing new is made. + const carried = await findRows(orm, Tags, { place_tags_inverse: placeId }); + expect(carried.map((tag) => [tag.name, tag.trip_id])).toEqual([['food, drinks', f.alps.id]]); + expect(await findRows(orm, Tags, { trip: f.alps.id })).toHaveLength(2); + }); +}); diff --git a/server/tests/helpers/plugin-host.ts b/server/tests/helpers/plugin-host.ts index bbcb0eff4..ff21e4d86 100644 --- a/server/tests/helpers/plugin-host.ts +++ b/server/tests/helpers/plugin-host.ts @@ -579,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), await createTestUnitOfWork(db))), + new TagsRpc(new TagsService(await createTestTagsRepo(db))), new CategoriesRpc(new CategoriesService(await createTestCategoriesRepo(db))), new WeatherRpc(new WeatherService()), new ExchangeRatesRpc(exchangeRates), diff --git a/server/tests/integration/broadcast-parity/user.cases.ts b/server/tests/integration/broadcast-parity/user.cases.ts index a1dfcab15..826eb098e 100644 --- a/server/tests/integration/broadcast-parity/user.cases.ts +++ b/server/tests/integration/broadcast-parity/user.cases.ts @@ -20,7 +20,6 @@ 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'; @@ -58,13 +57,6 @@ 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' }; @@ -1397,20 +1389,6 @@ 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 a056b6030..7bb7d1e04 100644 --- a/server/tests/unit/db/entities-index.test.ts +++ b/server/tests/unit/db/entities-index.test.ts @@ -65,15 +65,14 @@ describe('ALL_ENTITIES', () => { * a user's own place identities, the uses they group, the merges and the dismissed pairs * + 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) + * + place_activity_links, the bookings and tours a trip place or a saved place names) * 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 182 entities, every class name unique', () => { - expect(ALL_ENTITIES.length).toBe(182); + it('ENT-003: exactly 181 entities, every class name unique', () => { + expect(ALL_ENTITIES.length).toBe(181); 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 3d91bc8f6..f3ee9d2d8 100644 --- a/server/tests/unit/db/entity-class-fields.test.ts +++ b/server/tests/unit/db/entity-class-fields.test.ts @@ -72,8 +72,7 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'; // trip_collection_links: id, trip_id, collection_id (each row is written whole by the places library or the trip). // + 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; +const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 656; 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 21a4fd568..2956fc9bb 100644 --- a/server/tests/unit/db/legacy-baseline.test.ts +++ b/server/tests/unit/db/legacy-baseline.test.ts @@ -124,6 +124,9 @@ const UNNUMBERED = [ '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', + 'Migration20200101046590_a_place_carries_the_tags_of_its_lists_and_trips', + 'Migration20200101046600_a_list_tour_link_keeps_its_full_unique_name', + 'Migration20200101046610_a_vote_remembers_when_it_last_changed', ]; // The last step the positional runner ever had; planLegacyBaseline refuses a // schema_version past it. diff --git a/server/tests/unit/db/personal-place-tags-drop-migration.test.ts b/server/tests/unit/db/personal-place-tags-drop-migration.test.ts new file mode 100644 index 000000000..83831453b --- /dev/null +++ b/server/tests/unit/db/personal-place-tags-drop-migration.test.ts @@ -0,0 +1,83 @@ +/** + * `Migration20200101046590_a_place_carries_the_tags_of_its_lists_and_trips`: + * the private tags on the entries of All places go, and nothing else does. A + * list's labels, a trip's tags, the personal tags themselves and every + * assignment of them stay exactly as they were. On Postgres the same drop runs + * in the Postgres lane, where PARITY-PG holds the migrated schema to the + * entities, which no longer name the table. + */ +import { createMigrationOrm, migrateTo, pendingNames, rawExec, rawQuery } from '../../helpers/migration-step'; +import type { MikroORM } from '@mikro-orm/sqlite'; + +import { describe, expect, it } from 'vitest'; + +const TARGET = 'Migration20200101046590_a_place_carries_the_tags_of_its_lists_and_trips'; + +async function ormBeforeTarget(): Promise { + const orm = await createMigrationOrm(); + const names = await pendingNames(orm); + const index = names.indexOf(TARGET); + expect(index).toBeGreaterThan(0); + await migrateTo(orm, names[index - 1]); + return orm; +} + +/** The tables and indexes SQLite still has whose name mentions the dropped table. */ +async function leftovers(orm: MikroORM): Promise { + return rawQuery(orm, "SELECT type, name FROM sqlite_master WHERE name LIKE '%personal_place_tags%' ORDER BY name"); +} + +describe('a place carries the tags of its lists and trips', () => { + it('PPTDROP-001: drops the private tags with their indexes and keeps every list label and trip tag', async () => { + const orm = await ormBeforeTarget(); + try { + await rawExec(orm, "INSERT INTO users (id, username, email, password_hash) VALUES (1, 'owner', 'o@test', 'x')"); + await rawExec(orm, "INSERT INTO trips (id, user_id, title) VALUES (10, 1, 'Lisbon')"); + await rawExec(orm, "INSERT INTO places (id, trip_id, name) VALUES (20, 10, 'Belem Tower')"); + await rawExec(orm, "INSERT INTO collections (id, owner_id, name) VALUES (40, 1, 'Food')"); + await rawExec( + orm, + "INSERT INTO collection_places (id, collection_id, owner_id, name) VALUES (50, 40, 1, 'Cafe')", + ); + await rawExec( + orm, + "INSERT INTO collection_labels (id, collection_id, name, color) VALUES (60, 40, 'Coffee', '#111111')", + ); + await rawExec(orm, 'INSERT INTO collection_place_labels (collection_place_id, label_id) VALUES (50, 60)'); + await rawExec( + orm, + "INSERT INTO tags (id, user_id, trip_id, name, color) VALUES (30, 1, 10, 'Monument', '#222222')", + ); + await rawExec(orm, "INSERT INTO tags (id, user_id, name, color) VALUES (31, 1, 'Mine', '#333333')"); + await rawExec(orm, 'INSERT INTO place_tags (place_id, tag_id) VALUES (20, 30)'); + await rawExec(orm, 'INSERT INTO collection_place_tags (collection_place_id, tag_id) VALUES (50, 31)'); + await rawExec(orm, 'INSERT INTO personal_place_tags (id, tag_id, place_id) VALUES (70, 31, 20)'); + await rawExec(orm, 'INSERT INTO personal_place_tags (id, tag_id, collection_place_id) VALUES (71, 31, 50)'); + expect(await leftovers(orm)).not.toEqual([]); + + await migrateTo(orm, TARGET); + + expect(await leftovers(orm)).toEqual([]); + expect(await rawQuery(orm, 'SELECT id, user_id, trip_id, name, color FROM tags ORDER BY id')).toEqual([ + { id: 30, user_id: 1, trip_id: 10, name: 'Monument', color: '#222222' }, + { id: 31, user_id: 1, trip_id: null, name: 'Mine', color: '#333333' }, + ]); + expect(await rawQuery(orm, 'SELECT place_id, tag_id FROM place_tags')).toEqual([{ place_id: 20, tag_id: 30 }]); + expect(await rawQuery(orm, 'SELECT collection_place_id, tag_id FROM collection_place_tags')).toEqual([ + { collection_place_id: 50, tag_id: 31 }, + ]); + expect(await rawQuery(orm, 'SELECT id, collection_id, name, color FROM collection_labels')).toEqual([ + { id: 60, collection_id: 40, name: 'Coffee', color: '#111111' }, + ]); + expect(await rawQuery(orm, 'SELECT collection_place_id, label_id FROM collection_place_labels')).toEqual([ + { collection_place_id: 50, label_id: 60 }, + ]); + // Deleting a tag, a place or a saved place no longer reaches for the dropped table. + await rawExec(orm, 'DELETE FROM tags WHERE id = 31'); + await rawExec(orm, 'DELETE FROM places WHERE id = 20'); + await rawExec(orm, 'DELETE FROM collection_places WHERE id = 50'); + } finally { + await orm.close(true); + } + }, 30000); +}); diff --git a/server/tests/unit/db/repositories/PlaceChangeLog.repository.test.ts b/server/tests/unit/db/repositories/PlaceChangeLog.repository.test.ts index e95d45840..b95fec0b2 100644 --- a/server/tests/unit/db/repositories/PlaceChangeLog.repository.test.ts +++ b/server/tests/unit/db/repositories/PlaceChangeLog.repository.test.ts @@ -90,10 +90,13 @@ describe('PlaceChangeLogRepository', () => { 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)); + // An id of its own: the places the other cases seed stay in the shared database. + const googleId = 'g-pclrepo-002'; + const plain = await makePlace(t, s.trip.id, { google_place_id: googleId }); + const pictured = await makePlace(t, s.trip.id, { google_place_id: googleId, image_url: '/uploads/places/a.jpg' }); + const blank = await makePlace(t, s.trip.id, { google_place_id: googleId, image_url: '' }); + const ids = await repo.tripPlaceIdsWithoutImage(googleId); + expect([...ids].sort((a, b) => a - b)).toEqual([plain.id, blank.id].sort((a, b) => a - b)); expect(ids).not.toContain(pictured.id); }); diff --git a/server/tests/unit/nest/collections.controller.test.ts b/server/tests/unit/nest/collections.controller.test.ts index c9ae3ec03..fe85a5177 100644 --- a/server/tests/unit/nest/collections.controller.test.ts +++ b/server/tests/unit/nest/collections.controller.test.ts @@ -114,7 +114,7 @@ describe('CollectionsController', () => { await c.savePlace(user, { collection_id: 3, name: 'A' } as never, 'sid'); expect(svc.savePlace).toHaveBeenCalledWith(1, { collection_id: 3, name: 'A' }, 'sid'); await c.updatePlace(user, 9, { name: 'B' } as never, 'sid'); - expect(svc.updatePlace).toHaveBeenCalledWith(1, 9, { name: 'B' }, 'sid'); + expect(svc.updatePlace).toHaveBeenCalledWith(1, 9, { name: 'B' }, 'sid', { editor: user }); await c.setStatus(user, 9, { status: 'want' } as never, 'sid'); expect(svc.setStatus).toHaveBeenCalledWith(1, 9, 'want', 'sid'); expect(await c.deletePlace(user, 9, 'sid')).toEqual({ success: true }); @@ -371,7 +371,7 @@ describe('CollectionsController', () => { ), ).toEqual({ id: 9 }); expect(storageStub.put).toHaveBeenCalledWith('places', 'x.jpg', { tmpPath: undefined }); - expect(svc.setPlaceImage).toHaveBeenCalledWith(1, 9, '/uploads/places/x.jpg', 'sid'); + expect(svc.setPlaceImage).toHaveBeenCalledWith(1, 9, '/uploads/places/x.jpg', 'sid', { editor: user }); }); }); diff --git a/server/tests/unit/nest/collections.copy-to-trip.test.ts b/server/tests/unit/nest/collections.copy-to-trip.test.ts index fec300157..89f8777f8 100644 --- a/server/tests/unit/nest/collections.copy-to-trip.test.ts +++ b/server/tests/unit/nest/collections.copy-to-trip.test.ts @@ -238,4 +238,32 @@ describe('CollectionsService.copyToTrip: notes and tags only when asked for (D9) expect(await countRows(orm, Tags, { trip: trip.id })).toBe(0); expect(tripTagEvents()).toEqual([]); }); + + it('COLLECTIONS-SVC-232: the list tags asked for (its labels) arrive as tags of the trip, a trip tag of the name reused', async () => { + const { user } = await makeUser(orm); + await makeCategory(orm); + const trip = await makeTrip(orm, user.id); + const existing = await makeTag(orm, user.id, { name: 'coffee', trip: trip.id }); + const col = await svc.createCollection(user.id, { name: 'Lisbon' }); + const coffee = await svc.createLabel(user.id, col.id, 'Coffee', '#111111'); + const view = await svc.createLabel(user.id, col.id, 'View', '#222222'); + const unasked = await svc.createLabel(user.id, col.id, 'Later'); + const spot = await saved(user.id, { collection_id: col.id, name: 'Miradouro' }); + await svc.updatePlace(user.id, spot.id, { label_ids: [coffee.id, view.id, unasked.id] }); + t.realtime.broadcastMock.mockClear(); + + await svc.copyToTrip( + user.id, + { trip_id: trip.id, place_ids: [spot.id], label_ids: [coffee.id, view.id] }, + svc.tripEvents(trip.id, undefined), + ); + + const copy = await findRow(orm, Places, { trip: trip.id, name: 'Miradouro' }); + if (!copy) throw new Error('the copy is missing'); + const carried = await findRows(orm, Tags, { place_tags_inverse: copy.id }); + expect(carried.map((tag) => tag.name).sort()).toEqual(['View', 'coffee']); + expect(carried.map((tag) => tag.id)).toContain(existing.id); + expect(carried.find((tag) => tag.name === 'View')).toMatchObject({ trip_id: trip.id, color: '#222222' }); + expect(tripTagEvents()).toHaveLength(1); + }); }); diff --git a/server/tests/unit/nest/collections.service.test.ts b/server/tests/unit/nest/collections.service.test.ts index 90650ad31..987a1927e 100644 --- a/server/tests/unit/nest/collections.service.test.ts +++ b/server/tests/unit/nest/collections.service.test.ts @@ -902,24 +902,24 @@ describe('custom saved-place image', () => { // ── Collaborative ratings (#1435) ──────────────────────────────────────────── +/** A vote through writeRating (its check and write), then the saved place as the vote route answers it. */ +const rateAndRead = (userId: number, placeId: number, rating: number | null) => + svc.writeRating(userId, placeId, rating).then(() => svc.getPlaceById(placeId)); + describe('collaborative ratings (#1435)', () => { - it('COLLECTIONS-SVC-070: setRating stores a vote, updates it, and clears with null', async () => { + it('COLLECTIONS-SVC-070: writeRating stores a vote, updates it, and clears with null', async () => { const u = createUser(testDb).user; const col = await svc.createCollection(u.id, { name: 'Rate' }); const p = (await svc.savePlace(u.id, { collection_id: col.id, name: 'Louvre' })).place!; - let updated = await svc.setRating(u.id, p.id, 5); - expect(updated.rating_avg).toBe(5); - expect(updated.rating_count).toBe(1); + let updated = await rateAndRead(u.id, p.id, 5); + expect(updated).toMatchObject({ rating_avg: 5, rating_count: 1 }); expect(updated.ratings?.find(r => r.user_id === u.id)?.rating).toBe(5); - updated = await svc.setRating(u.id, p.id, 3); // same user re-votes → replaces, not appends - expect(updated.rating_avg).toBe(3); - expect(updated.rating_count).toBe(1); - - updated = await svc.setRating(u.id, p.id, null); // clear - expect(updated.rating_avg).toBeNull(); - expect(updated.rating_count).toBe(0); + updated = await rateAndRead(u.id, p.id, 3); // same user re-votes → replaces, not appends + expect(updated).toMatchObject({ rating_avg: 3, rating_count: 1 }); + updated = await rateAndRead(u.id, p.id, null); // clear + expect(updated).toMatchObject({ rating_avg: null, rating_count: 0 }); }); it('COLLECTIONS-SVC-071: every accepted member may vote; the value is the average', async () => { @@ -930,8 +930,8 @@ describe('collaborative ratings (#1435)', () => { await joinCollection(col.id, member.id, 'viewer'); const p = (await svc.savePlace(owner.id, { collection_id: col.id, name: 'Notre-Dame' })).place!; - await svc.setRating(owner.id, p.id, 5); - const updated = await svc.setRating(member.id, p.id, 2); + await rateAndRead(owner.id, p.id, 5); + const updated = await rateAndRead(member.id, p.id, 2); expect(updated.rating_count).toBe(2); expect(updated.rating_avg).toBe(3.5); }); @@ -941,7 +941,7 @@ describe('collaborative ratings (#1435)', () => { const outsider = createUser(testDb).user; const col = await svc.createCollection(owner.id, { name: 'Private rate' }); const p = (await svc.savePlace(owner.id, { collection_id: col.id, name: 'Secret' })).place!; - await expect(svc.setRating(outsider.id, p.id, 4)).rejects.toThrow(); + await expect(rateAndRead(outsider.id, p.id, 4)).rejects.toThrow(); }); it('COLLECTIONS-SVC-073: saving a trip place copies only the saver + shared-member votes', async () => { @@ -975,8 +975,8 @@ describe('collaborative ratings (#1435)', () => { const col = await svc.createCollection(owner.id, { name: 'Copyable' }); await joinCollection(col.id, member.id, 'editor'); const cp = (await svc.savePlace(owner.id, { collection_id: col.id, name: 'Trevi' })).place!; - await svc.setRating(owner.id, cp.id, 5); - await svc.setRating(member.id, cp.id, 3); + await rateAndRead(owner.id, cp.id, 5); + await rateAndRead(member.id, cp.id, 3); const trip = createTrip(testDb, owner.id); addTripMember(testDb, trip.id, member.id); // member is on the trip, so their vote carries @@ -1018,9 +1018,9 @@ describe('collaborative ratings (#1435)', () => { await joinCollection(col.id, u.id, 'editor'); } const cp = (await svc.savePlace(owner.id, { collection_id: col.id, name: 'Pantheon' })).place!; - await svc.setRating(owner.id, cp.id, 5); - await svc.setRating(inTrip.id, cp.id, 4); - await svc.setRating(notInTrip.id, cp.id, 1); + await rateAndRead(owner.id, cp.id, 5); + await rateAndRead(inTrip.id, cp.id, 4); + await rateAndRead(notInTrip.id, cp.id, 1); const trip = createTrip(testDb, owner.id); addTripMember(testDb, trip.id, inTrip.id); @@ -1278,7 +1278,7 @@ describe('exportCollection / importCollection (#2198)', () => { const member = createUser(testDb).user; const { col, market } = await seedList(owner.id); await addMember(col.id, member.id, 'editor'); - await svc.setRating(member.id, market.id, 5); + await rateAndRead(member.id, market.id, 5); const file = await svc.exportCollection(owner.id, col.id); const serialised = JSON.stringify(file); @@ -1726,8 +1726,8 @@ describe('Plan 3h Task 1 — repository conversion parity', () => { const place = (await svc.savePlace(owner.id, { collection_id: col.id, name: 'Cafe', lat: 1, lng: 2, tag_ids: [tag.id], })).place!; - await svc.setRating(owner.id, place.id, 5); - await svc.setRating(admin.id, place.id, 3); + await rateAndRead(owner.id, place.id, 5); + await rateAndRead(admin.id, place.id, 3); const result = await svc.getCollection(owner.id, col.id); diff --git a/server/tests/unit/nest/collections.tags-to-carry.test.ts b/server/tests/unit/nest/collections.tags-to-carry.test.ts index 8c49661d2..4c93fad8d 100644 --- a/server/tests/unit/nest/collections.tags-to-carry.test.ts +++ b/server/tests/unit/nest/collections.tags-to-carry.test.ts @@ -1,55 +1,54 @@ /** * 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. + * saved place: the tags (`tag_ids`) and the list's own tags, its labels + * (`label_ids`), each only where the place carries it and only when asked for. */ import { tagsToCarry } from '../../../src/nest/collections/collections.helpers'; import { describe, expect, it, vi } from 'vitest'; -const listTags = [ +const placeTags = [ { 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 }, +const labels = [ + { pid: 1, id: 30, name: 'Coffee', color: '#111111' }, + { pid: 2, id: 30, name: 'Coffee', color: '#111111' }, + { pid: 2, id: 31, name: 'Old', color: null }, ]; 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(); + const lists = { loadTagsByPlaceIds: vi.fn(), loadLabelsByPlaceIds: vi.fn() }; + expect(await tagsToCarry({}, [1, 2], lists)).toBeNull(); + expect(await tagsToCarry({ tag_ids: [], label_ids: [] }, [1], lists)).toBeNull(); expect(lists.loadTagsByPlaceIds).not.toHaveBeenCalled(); - expect(mine).not.toHaveBeenCalled(); + expect(lists.loadLabelsByPlaceIds).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({ + it('COLL-CARRY-002: the tags and the list tags asked for, each where a place carries it', async () => { + const lists = { + loadTagsByPlaceIds: vi.fn().mockResolvedValue(placeTags), + loadLabelsByPlaceIds: vi.fn().mockResolvedValue(labels), + }; + expect(await tagsToCarry({ tag_ids: [10], label_ids: [30, 31, 99] }, [1, 2, 3], lists)).toEqual({ 1: [ { name: 'Must', color: '#ff0000' }, - { name: 'Wine', color: '#aa0000' }, - { name: 'Old', color: '#10b981' }, + { name: 'Coffee', color: '#111111' }, ], 2: [ - { name: 'Wine', color: '#aa0000' }, + { name: 'Coffee', color: '#111111' }, { name: 'Old', color: '#10b981' }, ], + 3: [], }); - expect(lists.loadTagsByPlaceIds).toHaveBeenCalledWith([1, 2]); + expect(lists.loadTagsByPlaceIds).toHaveBeenCalledWith([1, 2, 3]); + expect(lists.loadLabelsByPlaceIds).toHaveBeenCalledWith([1, 2, 3]); }); - 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' }], - }); + it('COLL-CARRY-003: list tags alone read no other tags', async () => { + const lists = { loadTagsByPlaceIds: vi.fn(), loadLabelsByPlaceIds: vi.fn().mockResolvedValue(labels) }; + expect(await tagsToCarry({ label_ids: [31] }, [2], lists)).toEqual({ 2: [{ name: 'Old', color: '#10b981' }] }); expect(lists.loadTagsByPlaceIds).not.toHaveBeenCalled(); }); }); diff --git a/server/tests/unit/nest/places-library/library-tags.helpers.test.ts b/server/tests/unit/nest/places-library/library-tags.helpers.test.ts new file mode 100644 index 000000000..41b46b561 --- /dev/null +++ b/server/tests/unit/nest/places-library/library-tags.helpers.test.ts @@ -0,0 +1,89 @@ +/** + * The pure half of the tags on "All places" (PLC-21): how a filter's names are + * folded for both engines, how an entry gathers the tags of its trip places + * and saved places, how the tags of each trip or list are grouped, and which + * tags an origin offers. + */ +import { + entryTagsOf, + foldTagNames, + offeredTags, + tagsByOwner, +} from '../../../../src/nest/places-library/library-tags.helpers'; +import type { EntryRows } from '../../../../src/nest/places-library/places-library.helpers'; + +import { describe, expect, it } from 'vitest'; + +/** An entry with the trip places and saved places of these ids; only their ids are read. */ +const entryOf = (placeIds: number[], savedIds: number[]): EntryRows => + ({ + anchor: 0, + identity: null, + trips: placeIds.map((id) => ({ id })), + saved: savedIds.map((id) => ({ id })), + linked: new Set(), + }) as unknown as EntryRows; + +describe('foldTagNames', () => { + it('LIBTAG-H-001: folds each name trimmed, the way SQLite and Postgres lower it, each spelling once', () => { + expect(foldTagNames([' Coffee ', 'coffee'])).toEqual(['coffee']); + // SQLite lowers ASCII letters only, Postgres every letter: both spellings are asked for. + expect(foldTagNames(['Über'])).toEqual(['über', 'Über']); + expect(foldTagNames([])).toEqual([]); + }); +}); + +describe('entryTagsOf', () => { + it('LIBTAG-H-010: gathers the tags of every use, a name once whatever its case, sorted by name', () => { + const tripTags = [ + { place_id: 1, id: 10, name: 'View', color: '#00aa00' }, + { place_id: 2, id: 11, name: 'Other trip', color: null }, + ]; + const labels = [ + { collection_place_id: 5, id: 20, name: 'coffee', color: '#553311' }, + { collection_place_id: 5, id: 21, name: ' view ', color: '#0000aa' }, + { collection_place_id: 6, id: 22, name: 'Elsewhere', color: null }, + { collection_place_id: 5, id: 23, name: ' ', color: null }, + ]; + expect(entryTagsOf([entryOf([1], [5]), entryOf([], [6]), entryOf([3], [])], tripTags, labels)).toEqual([ + [ + { name: 'coffee', color: '#553311' }, + { name: 'View', color: '#00aa00' }, + ], + [{ name: 'Elsewhere', color: null }], + [], + ]); + }); +}); + +describe('tagsByOwner', () => { + it('LIBTAG-H-020: groups the tags by the trip or list that owns them, in their order', () => { + const grouped = tagsByOwner([ + { owner_id: 1, id: 10, name: 'A', color: null }, + { owner_id: 2, id: 11, name: 'B', color: '#111111' }, + { owner_id: 1, id: 12, name: 'C', color: null }, + ]); + expect(grouped.get(1)).toEqual([ + { id: 10, name: 'A', color: null }, + { id: 12, name: 'C', color: null }, + ]); + expect(grouped.get(2)).toEqual([{ id: 11, name: 'B', color: '#111111' }]); + expect(grouped.get(3)).toBeUndefined(); + }); +}); + +describe('offeredTags', () => { + it('LIBTAG-H-030: offers the owned tags, then a tag the place carries that is none of them, each once', () => { + const owned = [ + { id: 10, name: 'A', color: null }, + { id: 12, name: 'C', color: null }, + ]; + const assigned = [ + { id: 12, name: 'C', color: null }, + { id: 30, name: 'Mine', color: '#222222' }, + ]; + expect(offeredTags(owned, assigned)).toEqual([...owned, { id: 30, name: 'Mine', color: '#222222' }]); + expect(offeredTags(owned, [])).toEqual(owned); + expect(offeredTags([], assigned)).toEqual(assigned); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-copies.helpers.test.ts b/server/tests/unit/nest/places-library/place-copies.helpers.test.ts new file mode 100644 index 000000000..f3e8114b5 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-copies.helpers.test.ts @@ -0,0 +1,106 @@ +/** + * The pure half of the copies in step (place-copies.helpers.ts): the facts of + * a copy, what an edit changed, what a copy does not hold yet, and which + * copies an edit follows onto. + */ +import type { + LibraryCollectionPlaceRow, + LibraryTripPlaceRow, +} from '../../../../src/db/repositories/PlacesLibrary.repository'; +import { + changesOf, + copyTargetsOf, + factsOf, + ownChangesOf, +} from '../../../../src/nest/places-library/place-copies.helpers'; +import type { EntryRows } from '../../../../src/nest/places-library/places-library.helpers'; + +import { describe, expect, it } from 'vitest'; + +const base = { + name: 'Café', + address: null, + lat: 48.2, + lng: 16.3, + image_url: null, + updated_at: null, + description: null, + website: null, + phone: null, + google_place_id: null, + google_ftid: null, + osm_id: null, + category_id: 1, + category_name: 'Food', + category_color: null, + category_icon: null, +}; +const trip = (id: number, tripId: number): LibraryTripPlaceRow => ({ + ...base, + id, + trip_id: tripId, + trip_title: 'Alps', + trip_start: null, + trip_end: null, + trip_owner_id: 1, +}); +const saved = (id: number, collectionId: number): LibraryCollectionPlaceRow => ({ + ...base, + id, + collection_id: collectionId, + collection_name: 'Food', + status: 'want', +}); +const entry = (trips: LibraryTripPlaceRow[], lists: LibraryCollectionPlaceRow[]): EntryRows => ({ + anchor: 1, + identity: null, + trips, + saved: lists, + linked: new Set(), +}); + +describe('place-copies helpers', () => { + it('reads the general facts of a copy and nothing else', () => { + expect(factsOf(trip(3, 9))).toEqual({ + name: 'Café', + description: null, + address: null, + lat: 48.2, + lng: 16.3, + category_id: 1, + image_url: null, + website: null, + phone: null, + }); + }); + + it('names the facts an edit changed, with their value after', () => { + const before = factsOf(trip(3, 9)); + expect(changesOf(before, { ...before, name: 'Central', lat: 48.21, description: null })).toEqual({ + name: 'Central', + lat: 48.21, + }); + expect(changesOf(before, before)).toEqual({}); + }); + + it('keeps of the changes only what a copy does not hold already', () => { + const facts = { ...factsOf(saved(20, 5)), name: 'Central' }; + expect(ownChangesOf({ name: 'Central', phone: '+43' }, facts)).toEqual({ phone: '+43' }); + expect(ownChangesOf({ image_url: null }, facts)).toEqual({}); + }); + + it('follows onto every other copy the editor may edit, of the kinds the edit reaches', () => { + const rows = entry([trip(3, 9), trip(4, 10)], [saved(20, 5), saved(21, 6)]); + const all = { trips: true, lists: true, canEditTrip: () => true, canEditList: () => true }; + expect(copyTargetsOf(rows, { fromList: 0, id: 3 }, all).map((t) => [t.kind, t.containerId, t.placeId])).toEqual([ + ['trip', 10, 4], + ['list', 5, 20], + ['list', 6, 21], + ]); + const some = { ...all, canEditTrip: () => false, canEditList: (row: LibraryCollectionPlaceRow) => row.id !== 21 }; + expect(copyTargetsOf(rows, { fromList: 1, id: 20 }, some)).toEqual([]); + expect(copyTargetsOf(rows, { fromList: 1, id: 21 }, some).map((t) => t.placeId)).toEqual([20]); + expect(copyTargetsOf(rows, { fromList: 0, id: 3 }, { ...all, lists: false }).map((t) => t.placeId)).toEqual([4]); + expect(copyTargetsOf(rows, { fromList: 1, id: 20 }, { ...all, trips: false }).map((t) => t.placeId)).toEqual([21]); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-copies.service.test.ts b/server/tests/unit/nest/places-library/place-copies.service.test.ts new file mode 100644 index 000000000..43bd45f59 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-copies.service.test.ts @@ -0,0 +1,149 @@ +/** + * PlaceCopiesService over stand-ins for its collaborators: the edges the end + * to end suite (tests/e2e/place-copies.e2e.test.ts) does not reach, a use + * outside All places, the Collections addon off, a copy gone meanwhile, the + * origin gone after the write, and what goes out after the commit. + */ +import { PlacesLibraryRepository } from '../../../../src/db/repositories/PlacesLibrary.repository'; +import { AddonsService } from '../../../../src/nest/addons/addons.service'; +import { CollectionsService } from '../../../../src/nest/collections/collections.service'; +import { PlaceCopiesSlot } from '../../../../src/nest/common/place-copies.port'; +import { UnitOfWork } from '../../../../src/nest/database/unit-of-work'; +import { PlaceCopiesService } from '../../../../src/nest/places-library/place-copies.service'; +import { PlacesLibraryService } from '../../../../src/nest/places-library/places-library.service'; +import { PlacesService } from '../../../../src/nest/places/places.service'; +import { Test } from '@nestjs/testing'; + +import { describe, expect, it, vi } from 'vitest'; + +const ME = { id: 7, role: 'user' }; +const facts = { + name: 'Café', + address: null, + lat: 1, + lng: 2, + image_url: null, + description: null, + website: null, + phone: null, + category_id: null, +}; +const trip = (id: number, tripId: number, extra = {}) => ({ + ...facts, + id, + trip_id: tripId, + trip_owner_id: 7, + ...extra, +}); +const saved = (id: number, collectionId: number, extra = {}) => ({ + ...facts, + id, + collection_id: collectionId, + ...extra, +}); + +async function build(options: { addonOn?: boolean; anchor?: number | null } = {}) { + const entry = { + anchor: 1, + identity: null, + trips: [trip(3, 9), trip(4, 10)], + saved: [saved(20, 5)], + linked: new Set(), + }; + const library = { + reach: vi.fn(async () => ({ userId: ME.id, tripIds: [9, 10], collectionIds: [5] })), + anchorOfUse: vi.fn(async () => (options.anchor === undefined ? 1 : options.anchor)), + rows: vi.fn(async (): Promise => [entry]), + access: vi.fn(async () => ({ canEditTrip: () => true, canEditList: () => true })), + }; + const repo = { + tripPlaces: vi.fn(async (): Promise => [trip(3, 9, { name: 'Central' })]), + savedPlaces: vi.fn(async (): Promise => []), + }; + const places = { + copies: new PlaceCopiesSlot(), + writeCopy: vi.fn(async (): Promise<{ previousImage: string | null } | null> => ({ previousImage: null })), + get: vi.fn(async (tripId: string, placeId: string): Promise => ({ + id: Number(placeId), + trip_id: Number(tripId), + })), + broadcast: vi.fn(), + onUpdated: vi.fn(async () => undefined), + }; + const collections = { + copies: new PlaceCopiesSlot(), + writeCopy: vi.fn(async () => ({ collectionId: 5, previousImage: '/uploads/places/old.jpg' })), + notifyCollectionUsers: vi.fn(async () => undefined), + }; + const addons = { isAddonEnabled: vi.fn(async () => options.addonOn ?? true) }; + const uow = { transactional: vi.fn(async (fn: () => Promise) => fn()) }; + const moduleRef = await Test.createTestingModule({ + providers: [ + PlaceCopiesService, + { provide: PlacesLibraryService, useValue: library }, + { provide: PlacesLibraryRepository, useValue: repo }, + { provide: CollectionsService, useValue: collections }, + { provide: PlacesService, useValue: places }, + { provide: AddonsService, useValue: addons }, + { provide: UnitOfWork, useValue: uow }, + ], + }).compile(); + return { copies: moduleRef.get(PlaceCopiesService), library, repo, places, collections, addons }; +} + +describe('PlaceCopiesService', () => { + it('registers with both services and follows an edit through their slots', async () => { + const t = await build(); + t.copies.onModuleInit(); + const step = await t.places.copies.plan({ editor: ME }, { kind: 'trip', id: 3 }); + if (!step) throw new Error('expected a plan'); + const followed = await step(); + expect(t.places.writeCopy).toHaveBeenCalledWith(10, 4, { name: 'Central' }, ME.id); + expect(t.collections.writeCopy).toHaveBeenCalledWith(20, { name: 'Central' }, ME.id); + expect(followed).toEqual({ + trips: [{ tripId: 10, placeId: 4 }], + lists: [{ collectionId: 5, placeId: 20 }], + previousImages: [null, '/uploads/places/old.jpg'], + }); + await t.places.copies.announce(followed); + expect(t.places.broadcast).toHaveBeenCalledWith( + '10', + 'place:updated', + { place: { id: 4, trip_id: 10 } }, + undefined, + ); + expect(t.places.onUpdated).toHaveBeenCalledWith(4); + expect(t.collections.notifyCollectionUsers).toHaveBeenCalledWith(5, undefined, 'collections:updated'); + }); + + it('plans nothing outside All places, for a use the rows lost, or with nothing to follow onto', async () => { + expect(await (await build({ anchor: null })).copies.plan({ editor: ME }, { kind: 'trip', id: 3 })).toBeNull(); + const lost = await build(); + lost.library.rows.mockResolvedValueOnce([]); + expect(await lost.copies.plan({ editor: ME }, { kind: 'trip', id: 3 })).toBeNull(); + const gone = await build(); + expect(await gone.copies.plan({ editor: ME }, { kind: 'list', id: 99 })).toBeNull(); + const narrow = await build({ addonOn: false }); + const plan = await narrow.copies.plan( + { editor: ME, reach: { trips: false, lists: true } }, + { kind: 'trip', id: 3 }, + ); + expect(plan).toBeNull(); + }); + + it('writes nothing when the origin is gone or unchanged, and skips a trip copy gone meanwhile', async () => { + const t = await build(); + const plan = await t.copies.plan({ editor: ME }, { kind: 'list', id: 20 }); + if (!plan) throw new Error('expected a plan'); + expect(plan.targets.map((target) => target.placeId)).toEqual([3, 4]); + expect(await t.copies.apply(plan)).toEqual({ trips: [], lists: [], previousImages: [] }); + t.repo.savedPlaces.mockResolvedValueOnce([saved(20, 5)]); + expect(await t.copies.apply(plan)).toEqual({ trips: [], lists: [], previousImages: [] }); + t.repo.savedPlaces.mockResolvedValueOnce([saved(20, 5, { phone: '+43' })]); + t.places.writeCopy.mockResolvedValueOnce(null); + expect((await t.copies.apply(plan)).trips).toEqual([{ tripId: 10, placeId: 4 }]); + t.places.get.mockResolvedValueOnce(null); + await t.copies.announce({ trips: [{ tripId: 10, placeId: 4 }], lists: [], previousImages: [] }); + expect(t.places.broadcast).not.toHaveBeenCalled(); + }); +}); 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 deleted file mode 100644 index ff23ee806..000000000 --- a/server/tests/unit/nest/places-library/place-tags.controller.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -/** - * 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 deleted file mode 100644 index 8c254a10b..000000000 --- a/server/tests/unit/nest/places-library/place-tags.helpers.test.ts +++ /dev/null @@ -1,90 +0,0 @@ -/** - * 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 deleted file mode 100644 index 522c8a2ad..000000000 --- a/server/tests/unit/nest/places-library/place-tags.mcp.test.ts +++ /dev/null @@ -1,106 +0,0 @@ -/** - * 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 deleted file mode 100644 index c1dca07a8..000000000 --- a/server/tests/unit/nest/places-library/place-tags.service.test.ts +++ /dev/null @@ -1,251 +0,0 @@ -/** - * 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-votes-carry.job.test.ts b/server/tests/unit/nest/places-library/place-votes-carry.job.test.ts new file mode 100644 index 000000000..990aac006 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-votes-carry.job.test.ts @@ -0,0 +1,97 @@ +import { CARRY_MAX_RUNS, PlaceVotesCarryJob } from '../../../../src/nest/places-library/place-votes-carry.job'; +import type { PlaceVotesService } from '../../../../src/nest/places-library/place-votes.service'; +import type { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service'; +import type { SettingsService } from '../../../../src/nest/settings/settings.service'; + +import { describe, expect, it, vi } from 'vitest'; + +vi.mock('../../../../src/nest/audit/audit-log.logger', () => ({ + logInfo: vi.fn(), + logError: vi.fn(), + logWarn: vi.fn(), +})); + +function build(options: { + voters: number[]; + mark?: string | null; + runs?: string | null; + failFor?: number[]; + enabled?: boolean; +}) { + const carried: number[] = []; + const votes = { + voters: vi.fn(async (after: number, limit: number) => options.voters.filter((id) => id > after).slice(0, limit)), + carryOver: vi.fn(async (userId: number) => { + if (options.failFor?.includes(userId)) throw new Error('gone'); + carried.push(userId); + return 1; + }), + }; + const settings = { + getAppSetting: vi.fn(async (key: string) => + key === 'place_votes_carry_runs' ? (options.runs ?? null) : (options.mark ?? null), + ), + setAppSettings: vi.fn(async () => undefined), + insertAppSettingIfAbsent: vi.fn(async () => undefined), + }; + const registrar = { + isEnabled: () => options.enabled ?? true, + runOnBoot: vi.fn(async (_name: string, fn: () => Promise | void) => { + await fn(); + }), + }; + const job = new PlaceVotesCarryJob( + votes as unknown as PlaceVotesService, + settings as unknown as SettingsService, + registrar as unknown as CronRegistrarService, + ); + return { job, votes, settings, carried }; +} + +describe('PlaceVotesCarryJob', () => { + it('carries every voter page by page, then marks the pass as finished', async () => { + const voters = Array.from({ length: 205 }, (_, index) => index + 1); + const t = build({ voters }); + await t.job.run(); + expect(t.carried).toEqual(voters); + expect(t.votes.voters.mock.calls.map((call) => call[0])).toEqual([0, 100, 200]); + expect(t.settings.insertAppSettingIfAbsent).toHaveBeenCalledWith('place_votes_carried_over', expect.any(String)); + }); + + it('does nothing once the pass has finished', async () => { + const t = build({ voters: [1, 2], mark: '2026-11-29T00:00:00.000Z' }); + await t.job.run(); + expect(t.votes.voters).not.toHaveBeenCalled(); + expect(t.settings.insertAppSettingIfAbsent).not.toHaveBeenCalled(); + }); + + it('keeps going past a person whose carry-over fails and leaves the pass to run again', async () => { + const t = build({ voters: [1, 2, 3], failFor: [2] }); + await t.job.run(); + expect(t.carried).toEqual([1, 3]); + expect(t.settings.setAppSettings).toHaveBeenCalledWith({ place_votes_carry_runs: '1' }); + expect(t.settings.insertAppSettingIfAbsent).not.toHaveBeenCalled(); + }); + + it('counts its runs and marks the pass finished on its last run even when somebody still fails', async () => { + const again = build({ voters: [1, 2], failFor: [2], runs: String(CARRY_MAX_RUNS - 2) }); + await again.job.run(); + expect(again.settings.setAppSettings).toHaveBeenCalledWith({ place_votes_carry_runs: String(CARRY_MAX_RUNS - 1) }); + expect(again.settings.insertAppSettingIfAbsent).not.toHaveBeenCalled(); + + const last = build({ voters: [1, 2], failFor: [2], runs: String(CARRY_MAX_RUNS - 1) }); + await last.job.run(); + expect(last.settings.setAppSettings).toHaveBeenCalledWith({ place_votes_carry_runs: String(CARRY_MAX_RUNS) }); + expect(last.settings.insertAppSettingIfAbsent).toHaveBeenCalledWith('place_votes_carried_over', expect.any(String)); + }); + + it('starts at boot only where the scheduler runs', async () => { + const off = build({ voters: [1], enabled: false }); + off.job.onApplicationBootstrap(); + await Promise.resolve(); + expect(off.settings.getAppSetting).not.toHaveBeenCalled(); + const on = build({ voters: [] }); + on.job.onApplicationBootstrap(); + await vi.waitFor(() => expect(on.settings.insertAppSettingIfAbsent).toHaveBeenCalled()); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-votes.controller.test.ts b/server/tests/unit/nest/places-library/place-votes.controller.test.ts new file mode 100644 index 000000000..85c5a6140 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-votes.controller.test.ts @@ -0,0 +1,97 @@ +import { DomainError } from '../../../../src/nest/common/domain-error'; +import { + PlaceVotesListController, + PlaceVotesTripController, +} from '../../../../src/nest/places-library/place-votes.controller'; +import type { PlaceVotesService, VoteEvents } from '../../../../src/nest/places-library/place-votes.service'; +import type { PlacesService } from '../../../../src/nest/places/places.service'; +import type { User } from '../../../../src/types'; + +import { describe, expect, it, vi } from 'vitest'; + +const user = { id: 7, role: 'user' } as User; +const place = { id: 3, trip_id: 9, name: 'Café', ratings: [], rating_avg: null, rating_count: 0 }; + +function build(access: unknown = { id: 9, user_id: 7 }) { + const votes = { + voteOnSavedPlace: vi.fn(async () => ({ id: 4, collection_id: 2, name: 'Café' })), + voteOnEntry: vi.fn(async (_userId: number, key: string) => ({ key, rating: { average: 5, count: 1, mine: 5 } })), + voteOnTripPlace: vi.fn(async (): Promise => place), + }; + const places = { verifyTripAccess: vi.fn(async () => access), broadcast: vi.fn() }; + const asVotes = votes as unknown as PlaceVotesService; + const asPlaces = places as unknown as PlacesService; + return { + votes, + places, + list: new PlaceVotesListController(asVotes, asPlaces), + trip: new PlaceVotesTripController(asVotes, asPlaces), + }; +} + +/** The events a call handed the service. */ +function eventsOf(mock: { mock: { calls: unknown[][] } }, at: number): VoteEvents { + return mock.mock.calls[0]?.[at] as VoteEvents; +} + +describe('PlaceVotesListController', () => { + it('forwards a vote and its removal on a saved place with the caller socket', async () => { + const t = build(); + expect(await t.list.setRating(user, 4, { rating: 3 }, 's1')).toEqual({ id: 4, collection_id: 2, name: 'Café' }); + expect(t.votes.voteOnSavedPlace).toHaveBeenCalledWith(7, 4, 3, expect.objectContaining({ socketId: 's1' })); + await t.list.clearRating(user, 4, undefined); + expect(t.votes.voteOnSavedPlace).toHaveBeenLastCalledWith( + 7, + 4, + null, + expect.objectContaining({ socketId: undefined }), + ); + }); + + it('sends a trip place of the vote to its room, skipping the socket only on the copy voted on', async () => { + const t = build(); + await t.list.setRating(user, 4, { rating: 3 }, 's1'); + const events = eventsOf(t.votes.voteOnSavedPlace, 3); + events.trip(9, place as never, false); + expect(t.places.broadcast).toHaveBeenCalledWith('9', 'place:updated', { place }, undefined); + events.trip(9, place as never, true); + expect(t.places.broadcast).toHaveBeenLastCalledWith('9', 'place:updated', { place }, 's1'); + }); + + it('forwards the vote by entry key and its removal from the query', async () => { + const t = build(); + expect(await t.list.rateEntry(user, { key: 'trip:3', rating: 5 }, 's2')).toEqual({ + key: 'trip:3', + rating: { average: 5, count: 1, mine: 5 }, + }); + await t.list.unrateEntry(user, { key: 'list:4' }, undefined); + expect(t.votes.voteOnEntry).toHaveBeenLastCalledWith(7, 'list:4', null, expect.anything()); + }); +}); + +describe('PlaceVotesTripController', () => { + it('answers the place of the vote', async () => { + const t = build(); + expect(await t.trip.rate(user, '9', '3', { rating: 4 }, 's3')).toEqual({ place }); + expect(t.votes.voteOnTripPlace).toHaveBeenCalledWith(7, '9', '3', 4, expect.objectContaining({ socketId: 's3' })); + expect(await t.trip.unrate(user, '9', '3', undefined)).toEqual({ place }); + expect(t.votes.voteOnTripPlace).toHaveBeenLastCalledWith(7, '9', '3', null, expect.anything()); + }); + + it("answers 404 { error: 'Trip not found' } for a trip out of reach, before any vote", async () => { + const t = build(null); + const err = await t.trip.rate(user, '9', '3', { rating: 4 }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(DomainError); + expect((err as DomainError).getStatus()).toBe(404); + expect((err as DomainError).toBody()).toEqual({ error: 'Trip not found' }); + expect(t.votes.voteOnTripPlace).not.toHaveBeenCalled(); + }); + + it("answers 404 { error: 'Place not found' } for a place the trip does not hold", async () => { + const t = build(); + t.votes.voteOnTripPlace.mockResolvedValueOnce(null); + const err = await t.trip.unrate(user, '9', '99').catch((e: unknown) => e); + expect((err as DomainError).getStatus()).toBe(404); + expect((err as DomainError).toBody()).toEqual({ error: 'Place not found' }); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-votes.helpers.test.ts b/server/tests/unit/nest/places-library/place-votes.helpers.test.ts new file mode 100644 index 000000000..fa21c0865 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-votes.helpers.test.ts @@ -0,0 +1,128 @@ +import type { + LibraryCollectionPlaceRow, + LibraryOwnVoteRow, + LibraryTripPlaceRow, + LibraryUseRow, +} from '../../../../src/db/repositories/PlacesLibrary.repository'; +import { votesToCarry, voteTargetsOf } from '../../../../src/nest/places-library/place-votes.helpers'; +import { castAfter, unifiedRatingOf, type EntryRows } from '../../../../src/nest/places-library/places-library.helpers'; + +import { describe, expect, it } from 'vitest'; + +const use = (anchor: number, fromList: number, id: number): LibraryUseRow => ({ + anchor_key: anchor, + from_list: fromList, + use_id: id, + linked: false, +}); +const vote = (fromList: number, id: number, rating: number, at: string | null, rowId: number): LibraryOwnVoteRow => ({ + from_list: fromList, + use_id: id, + rating, + changed_at: at, + id: rowId, +}); + +describe('castAfter', () => { + it('orders by the time last changed, then by the row', () => { + expect(castAfter({ changed_at: '2026-02-01 00:00:00', id: 1 }, { changed_at: '2026-01-01 00:00:00', id: 9 })).toBe( + true, + ); + expect(castAfter({ changed_at: '2026-01-01 00:00:00', id: 2 }, { changed_at: '2026-01-01 00:00:00', id: 1 })).toBe( + true, + ); + expect(castAfter({ changed_at: null, id: 5 }, { changed_at: '2026-01-01 00:00:00', id: 1 })).toBe(false); + expect(castAfter({}, {})).toBe(false); + }); +}); + +describe('unifiedRatingOf', () => { + it('counts each person once with the vote they cast last, and the reader as mine', () => { + const rating = unifiedRatingOf( + [ + { target_id: 1, user_id: 7, rating: 5, changed_at: '2026-01-01 10:00:00', id: 1, username: 'me' }, + { target_id: 2, user_id: 7, rating: 1, changed_at: '2026-03-01 10:00:00', id: 1, username: 'me' }, + { + target_id: 1, + user_id: 8, + rating: 4, + changed_at: '2026-01-01 10:00:00', + id: 2, + username: 'ana', + avatar: 'a.png', + }, + ], + 7, + ); + // The votes name each person once, with the vote that counts, in the order they were cast. + expect(rating).toEqual({ + average: 2.5, + count: 2, + mine: 1, + votes: [ + { user_id: 8, username: 'ana', avatar_url: '/uploads/avatars/a.png', rating: 4 }, + { user_id: 7, username: 'me', avatar_url: null, rating: 1 }, + ], + }); + }); + + it('answers no votes as an empty rating', () => { + expect(unifiedRatingOf([], 7)).toEqual({ average: null, count: 0, mine: null, votes: [] }); + }); +}); + +describe('voteTargetsOf', () => { + const rows = { + anchor: 5, + identity: null, + trips: [{ id: 10, trip_id: 1 } as LibraryTripPlaceRow, { id: 11, trip_id: 2 } as LibraryTripPlaceRow], + saved: [{ id: 20, collection_id: 3 } as LibraryCollectionPlaceRow], + linked: new Set(), + } satisfies EntryRows; + + it('names every copy of the entry, but the one voted on', () => { + expect(voteTargetsOf(rows, { fromList: 0, id: 10 })).toEqual({ + trips: [{ tripId: 2, placeId: 11 }], + lists: [{ placeId: 20 }], + }); + expect(voteTargetsOf(rows, { fromList: 1, id: 20 }).lists).toEqual([]); + expect(voteTargetsOf(rows, null).trips).toHaveLength(2); + }); + + it('keeps a saved place whose id a trip place shares', () => { + expect( + voteTargetsOf( + { ...rows, saved: [{ id: 10, collection_id: 3 } as LibraryCollectionPlaceRow] }, + { fromList: 0, id: 10 }, + ).lists, + ).toEqual([{ placeId: 10 }]); + }); +}); + +describe('votesToCarry', () => { + const uses = [use(1, 0, 10), use(1, 1, 20), use(1, 1, 21), use(2, 0, 30), use(3, 0, 40), use(3, 1, 41)]; + + it("carries the person's last vote onto each copy without one", () => { + const votes = [vote(0, 10, 2, '2026-01-01 00:00:00', 1), vote(1, 20, 5, '2026-02-01 00:00:00', 1)]; + expect(votesToCarry(uses, votes)).toEqual([ + { fromList: 1, useId: 21, rating: 5, changedAt: '2026-02-01 00:00:00' }, + ]); + }); + + it('leaves a place alone with one copy, with no vote, or with a vote on every copy', () => { + expect(votesToCarry(uses, [vote(0, 30, 4, null, 1)])).toEqual([]); + expect(votesToCarry(uses, [])).toEqual([]); + expect(votesToCarry(uses, [vote(0, 40, 1, null, 1), vote(1, 41, 5, null, 2)])).toEqual([]); + }); + + it('adds nothing a second time: run over what it added, it finds no gap', () => { + const votes = [vote(0, 40, 3, null, 1)]; + const first = votesToCarry(uses, votes); + expect(first).toEqual([{ fromList: 1, useId: 41, rating: 3, changedAt: null }]); + const after = [ + ...votes, + ...first.map((carried, index) => vote(carried.fromList, carried.useId, carried.rating, null, 9 + index)), + ]; + expect(votesToCarry(uses, after)).toEqual([]); + }); +}); diff --git a/server/tests/unit/nest/places-library/place-votes.service.test.ts b/server/tests/unit/nest/places-library/place-votes.service.test.ts new file mode 100644 index 000000000..d3f742e53 --- /dev/null +++ b/server/tests/unit/nest/places-library/place-votes.service.test.ts @@ -0,0 +1,308 @@ +/** + * PlaceVotesService over stand-ins for its collaborators: which copies a vote + * lands on (the person's reach, the token's kinds, the Collections addon), + * that a sibling copy whose check refuses is skipped while any other failure + * fails the vote, how the changes go out after the commit (each trip place + * and each list once, the caller's socket skipped on the copy voted on only), + * the vote by entry key and the carry-over's inserts. The SQL behind it and + * the whole path run in tests/e2e/place-votes.e2e.test.ts. + */ +import { PlacesLibraryRepository } from '../../../../src/db/repositories/PlacesLibrary.repository'; +import { AddonsService } from '../../../../src/nest/addons/addons.service'; +import { CollectionsService } from '../../../../src/nest/collections/collections.service'; +import { notFound } from '../../../../src/nest/common/domain-error'; +import { JoinListeners } from '../../../../src/nest/common/join-listeners'; +import { UnitOfWork } from '../../../../src/nest/database/unit-of-work'; +import { PlaceVotesService, type VoteEvents } from '../../../../src/nest/places-library/place-votes.service'; +import { PlacesLibraryService } from '../../../../src/nest/places-library/places-library.service'; +import { PlacesService } from '../../../../src/nest/places/places.service'; +import { TripMembershipService } from '../../../../src/nest/trip-membership/trip-membership.service'; +import { Test } from '@nestjs/testing'; + +import { describe, expect, it, vi } from 'vitest'; + +const ME = 7; + +interface Copies { + trips?: { id: number; trip_id: number }[]; + saved?: { id: number; collection_id: number }[]; +} + +/** The service with the library answering `copies` as the one entry of every place, and the lists of the saved places. */ +async function build(copies: Copies, options: { addonOn?: boolean; uses?: unknown[]; votes?: unknown[] } = {}) { + const listOf = new Map((copies.saved ?? []).map((row) => [row.id, row.collection_id])); + const entry = { anchor: 1, identity: null, trips: copies.trips ?? [], saved: copies.saved ?? [], linked: new Set() }; + const library = { + reach: vi.fn(async () => ({ userId: ME })), + anchorOfUse: vi.fn(async (): Promise => 1), + rows: vi.fn(async (): Promise => [entry]), + usesOf: vi.fn(async () => options.uses ?? []), + ratingsOf: vi.fn(async () => [{ average: 4, count: 1, mine: 4 }]), + }; + const places = { + rate: vi.fn(async (tripId: string, placeId: string) => ({ id: Number(placeId), trip_id: Number(tripId) })), + carryRating: vi.fn(async () => true), + get: vi.fn(async (tripId: string, placeId: string) => ({ id: Number(placeId), trip_id: Number(tripId) })), + broadcast: vi.fn(), + }; + const collections = { + writeRating: vi.fn(async (_userId: number, placeId: number) => listOf.get(placeId) ?? 0), + getPlaceById: vi.fn(async (placeId: number) => ({ id: placeId })), + notifyCollectionUsers: vi.fn(async () => undefined), + joins: new JoinListeners(), + }; + const membership = { joins: new JoinListeners() }; + const uow = { transactional: vi.fn(async (fn: () => Promise) => fn()) }; + const repo = { votesOfUser: vi.fn(async () => options.votes ?? []), voterIds: vi.fn(async () => [1, 2]) }; + const addons = { isAddonEnabled: vi.fn(async () => options.addonOn ?? true) }; + const moduleRef = await Test.createTestingModule({ + providers: [ + PlaceVotesService, + { provide: PlacesLibraryService, useValue: library }, + { provide: CollectionsService, useValue: collections }, + { provide: PlacesService, useValue: places }, + { provide: UnitOfWork, useValue: uow }, + { provide: PlacesLibraryRepository, useValue: repo }, + { provide: AddonsService, useValue: addons }, + { provide: TripMembershipService, useValue: membership }, + ], + }).compile(); + return { votes: moduleRef.get(PlaceVotesService), library, places, collections, uow, repo, addons, membership }; +} + +function events(extra: Partial = {}): VoteEvents & { trip: ReturnType } { + return { trip: vi.fn(), socketId: 's1', ...extra } as VoteEvents & { trip: ReturnType }; +} + +describe('PlaceVotesService: a vote on one copy', () => { + it('lands on every other copy and announces each trip place and each list once', async () => { + const t = await build({ + trips: [ + { id: 3, trip_id: 9 }, + { id: 4, trip_id: 10 }, + ], + saved: [ + { id: 20, collection_id: 5 }, + { id: 21, collection_id: 5 }, + ], + }); + const ev = events(); + const place = await t.votes.voteOnTripPlace(ME, '9', '3', 4, ev); + expect(place).toMatchObject({ id: 3 }); + expect(t.places.rate.mock.calls).toEqual([ + ['9', '3', ME, 4], + ['10', '4', ME, 4], + ]); + expect(t.collections.writeRating.mock.calls.map((call) => call[1])).toEqual([20, 21]); + expect(t.uow.transactional).toHaveBeenCalledTimes(1); + // The copy voted on keeps the socket rule, the others reach the caller's other views. + expect(ev.trip.mock.calls.map((call) => [call[0], call[2]])).toEqual([ + [9, true], + [10, false], + ]); + // Two saved copies in one list: the list hears of it once, its socket not skipped. + expect(t.collections.notifyCollectionUsers.mock.calls).toEqual([[5, undefined]]); + }); + + it('skips the caller socket only on the list voted on, even when a sibling sits in the same list', async () => { + const t = await build({ + saved: [ + { id: 20, collection_id: 5 }, + { id: 21, collection_id: 5 }, + { id: 22, collection_id: 6 }, + ], + }); + expect(await t.votes.voteOnSavedPlace(ME, 20, 2, events())).toEqual({ id: 20 }); + expect(t.collections.writeRating.mock.calls.map((call) => call[1])).toEqual([20, 21, 22]); + expect(t.collections.notifyCollectionUsers.mock.calls).toEqual([ + [5, 's1'], + [6, undefined], + ]); + }); + + it('answers null and writes nothing more when the trip holds no such place', async () => { + const t = await build({ saved: [{ id: 20, collection_id: 5 }] }); + t.places.rate.mockResolvedValueOnce(null as never); + expect(await t.votes.voteOnTripPlace(ME, '9', '99', 4, events())).toBeNull(); + expect(t.collections.writeRating).not.toHaveBeenCalled(); + }); + + it('reaches only the kinds the token may write, and no list while the Collections addon is off', async () => { + const copies = { trips: [{ id: 3, trip_id: 9 }], saved: [{ id: 20, collection_id: 5 }] }; + const scoped = await build(copies); + await scoped.votes.voteOnTripPlace(ME, '9', '3', 4, events({ reach: { trips: true, lists: false } })); + expect(scoped.collections.writeRating).not.toHaveBeenCalled(); + + const listOnly = await build(copies); + await listOnly.votes.voteOnSavedPlace(ME, 20, 4, events({ reach: { trips: false, lists: true } })); + expect(listOnly.places.rate).not.toHaveBeenCalled(); + expect(listOnly.collections.writeRating).toHaveBeenCalledTimes(1); + + const off = await build(copies, { addonOn: false }); + await off.votes.voteOnTripPlace(ME, '9', '3', 4, events()); + expect(off.collections.writeRating).not.toHaveBeenCalled(); + expect(off.collections.notifyCollectionUsers).not.toHaveBeenCalled(); + }); + + it('skips a sibling copy whose check refuses, and fails the vote on any other error', async () => { + const copies = { + trips: [{ id: 3, trip_id: 9 }], + saved: [ + { id: 20, collection_id: 5 }, + { id: 21, collection_id: 6 }, + ], + }; + const t = await build(copies); + t.collections.writeRating.mockRejectedValueOnce(notFound('Collection not found')); + await t.votes.voteOnTripPlace(ME, '9', '3', 4, events()); + expect(t.collections.writeRating).toHaveBeenCalledTimes(2); + expect(t.collections.notifyCollectionUsers.mock.calls).toEqual([[6, undefined]]); + + const broken = await build(copies); + broken.collections.writeRating.mockRejectedValueOnce(new Error('disk full')); + await expect(broken.votes.voteOnTripPlace(ME, '9', '3', 4, events())).rejects.toThrow('disk full'); + expect(broken.collections.notifyCollectionUsers).not.toHaveBeenCalled(); + }); + + it('has no other copy outside All places', async () => { + const t = await build({ saved: [{ id: 20, collection_id: 5 }] }); + t.library.anchorOfUse.mockResolvedValueOnce(null); + expect(await t.votes.otherCopies(ME, 'trip', 3, events())).toEqual({ trips: [], lists: [] }); + t.library.rows.mockResolvedValueOnce([]); + expect(await t.votes.otherCopies(ME, 'trip', 3, events())).toEqual({ trips: [], lists: [] }); + }); +}); + +describe('PlaceVotesService: the vote by entry key', () => { + it('writes every copy of the entry and answers its rating after the change', async () => { + const t = await build({ trips: [{ id: 3, trip_id: 9 }], saved: [{ id: 20, collection_id: 5 }] }); + const ev = events(); + expect(await t.votes.voteOnEntry(ME, 'trip:3', 4, ev)).toEqual({ + key: 'trip:3', + rating: { average: 4, count: 1, mine: 4 }, + }); + expect(t.places.rate).toHaveBeenCalledWith('9', '3', ME, 4); + expect(t.collections.writeRating).toHaveBeenCalledWith(ME, 20, 4); + // No copy was the one voted on: nothing skips the caller's socket. + expect(ev.trip).toHaveBeenCalledWith(9, expect.anything(), false); + expect(t.collections.notifyCollectionUsers).toHaveBeenCalledWith(5, undefined); + }); + + it('an own place with no copy writes nothing and answers an empty rating', async () => { + const t = await build({}); + t.library.ratingsOf.mockResolvedValueOnce([]); + expect(await t.votes.voteOnEntry(ME, 'own:4', null, events())).toEqual({ + key: 'own:4', + rating: { average: null, count: 0, mine: null, votes: [] }, + }); + expect(t.places.rate).not.toHaveBeenCalled(); + expect(t.collections.writeRating).not.toHaveBeenCalled(); + }); + + it('refuses a key that names nothing the user reaches as Place not found', async () => { + const t = await build({}); + await expect(t.votes.voteOnEntry(ME, 'nonsense', 4, events())).rejects.toThrow('Place not found'); + t.library.rows.mockResolvedValueOnce([]); + await expect(t.votes.voteOnEntry(ME, 'trip:3', 4, events())).rejects.toThrow('Place not found'); + }); +}); + +describe('PlaceVotesService: the carry-over', () => { + const uses = [ + { anchor_key: 1, from_list: 0, use_id: 3, linked: false }, + { anchor_key: 1, from_list: 1, use_id: 20, linked: false }, + { anchor_key: 1, from_list: 1, use_id: 21, linked: false }, + ]; + + it('inserts the last vote where a copy has none, with the time it was changed, and skips a refused copy', async () => { + const t = await build( + { + trips: [{ id: 3, trip_id: 9 }], + saved: [ + { id: 20, collection_id: 5 }, + { id: 21, collection_id: 6 }, + ], + }, + { uses, votes: [{ from_list: 1, use_id: 20, rating: 5, changed_at: '2026-02-01 10:00:00', id: 1 }] }, + ); + t.collections.writeRating.mockRejectedValueOnce(notFound('Collection not found')); + expect(await t.votes.carryOver(ME)).toBe(1); + expect(t.places.carryRating).toHaveBeenCalledWith(9, 3, ME, 5, '2026-02-01 10:00:00'); + // Only ever as an insert that leaves a vote already there alone, never through the overwriting vote path. + expect(t.collections.writeRating.mock.calls).toEqual([[ME, 21, 5, { at: '2026-02-01 10:00:00' }]]); + expect(t.places.rate).not.toHaveBeenCalled(); + expect(t.collections.notifyCollectionUsers).not.toHaveBeenCalled(); + }); + + it('counts no trip copy the rows no longer hold, and nothing at all without a gap', async () => { + const t = await build( + { trips: [], saved: [{ id: 20, collection_id: 5 }] }, + { uses: uses.slice(0, 2), votes: [{ from_list: 1, use_id: 20, rating: 2, changed_at: null, id: 1 }] }, + ); + expect(await t.votes.carryOver(ME)).toBe(0); + expect(t.places.carryRating).not.toHaveBeenCalled(); + + const none = await build({}, { uses, votes: [] }); + expect(await none.votes.carryOver(ME)).toBe(0); + expect(none.library.rows).not.toHaveBeenCalled(); + }); + + it('pages the voters through the repository', async () => { + const t = await build({}); + expect(await t.votes.voters(0, 100)).toEqual([1, 2]); + expect(t.repo.voterIds).toHaveBeenCalledWith(0, 100); + }); +}); + +describe('PlaceVotesService: somebody joins a list or a trip', () => { + const uses = [ + { anchor_key: 1, from_list: 0, use_id: 3, linked: false }, + { anchor_key: 1, from_list: 0, use_id: 4, linked: false }, + { anchor_key: 1, from_list: 1, use_id: 20, linked: false }, + { anchor_key: 1, from_list: 1, use_id: 21, linked: false }, + ]; + const copies = { + trips: [ + { id: 3, trip_id: 9 }, + { id: 4, trip_id: 10 }, + ], + saved: [ + { id: 20, collection_id: 5 }, + { id: 21, collection_id: 6 }, + ], + }; + const votes = [{ from_list: 1, use_id: 20, rating: 4, changed_at: '2026-03-01 08:00:00', id: 1 }]; + + it('carries their last vote onto the joined trip only and tells its room of each place', async () => { + const t = await build(copies, { uses, votes }); + t.votes.onModuleInit(); + await t.membership.joins.joined(9, ME); + expect(t.places.carryRating.mock.calls).toEqual([[9, 3, ME, 4, '2026-03-01 08:00:00']]); + expect(t.collections.writeRating).not.toHaveBeenCalled(); + expect(t.places.broadcast).toHaveBeenCalledWith('9', 'place:updated', { place: { id: 3, trip_id: 9 } }, undefined); + expect(t.places.rate).not.toHaveBeenCalled(); + }); + + it('carries onto the joined list only, as an insert, and leaves the announcement to the join', async () => { + const t = await build(copies, { uses, votes: [{ ...votes[0], from_list: 0, use_id: 4 }] }); + t.votes.onModuleInit(); + await t.collections.joins.joined(6, ME); + expect(t.collections.writeRating.mock.calls).toEqual([[ME, 21, 4, { at: '2026-03-01 08:00:00' }]]); + expect(t.places.carryRating).not.toHaveBeenCalled(); + expect(t.places.broadcast).not.toHaveBeenCalled(); + expect(t.collections.notifyCollectionUsers).not.toHaveBeenCalled(); + }); + + it('adds nothing without a vote, and a failure never fails the join', async () => { + const none = await build(copies, { uses, votes: [] }); + none.votes.onModuleInit(); + await none.membership.joins.joined(9, ME); + expect(none.places.carryRating).not.toHaveBeenCalled(); + + const broken = await build(copies, { uses, votes }); + broken.votes.onModuleInit(); + broken.places.carryRating.mockRejectedValueOnce(new Error('disk full')); + await expect(broken.membership.joins.joined(9, ME)).resolves.toBeUndefined(); + expect(broken.places.broadcast).not.toHaveBeenCalled(); + }); +}); diff --git a/server/tests/unit/nest/places-library/places-library.helpers.test.ts b/server/tests/unit/nest/places-library/places-library.helpers.test.ts index c26d06ace..53d3f03c5 100644 --- a/server/tests/unit/nest/places-library/places-library.helpers.test.ts +++ b/server/tests/unit/nest/places-library/places-library.helpers.test.ts @@ -88,23 +88,52 @@ describe('places-library helpers', () => { }); it('hands out a cursor that only its own sort reads back', () => { - const cursor = encodeLibraryCursor('name', { anchor_key: -4, sort_name: 'café', sort_time: '2026' }); + const cursor = encodeLibraryCursor('name', { + anchor_key: -4, + sort_name: 'café', + sort_time: '2026', + sort_rating: 0, + }); expect(decodeLibraryCursor('name', cursor)).toEqual({ value: 'café', key: -4 }); expect(decodeLibraryCursor('updated', cursor)).toBeNull(); - const byTime = encodeLibraryCursor('updated', { anchor_key: 3, sort_name: 'x', sort_time: '2026-01-01' }); + const byTime = encodeLibraryCursor('updated', { + anchor_key: 3, + sort_name: 'x', + sort_time: '2026-01-01', + sort_rating: 0, + }); expect(decodeLibraryCursor('updated', byTime)).toEqual({ value: '2026-01-01', key: 3 }); + const byVotes = encodeLibraryCursor('rating', { + anchor_key: 5, + sort_name: 'x', + sort_time: '', + sort_rating: 4_500_000, + }); + expect(decodeLibraryCursor('rating', byVotes)).toEqual({ value: '4500000', key: 5 }); + expect(decodeLibraryCursor('name', byVotes)).toBeNull(); + // A rating cursor carries a whole score, nothing else. + const forged = Buffer.from(JSON.stringify(['rating', '4.5 OR 1', 5])).toString('base64url'); + expect(decodeLibraryCursor('rating', forged)).toBeNull(); expect(decodeLibraryCursor('name', '%%%')).toBeNull(); expect(decodeLibraryCursor('name', Buffer.from('{"a":1}').toString('base64url'))).toBeNull(); }); it('sums the votes and finds the user’s own', () => { - expect(ratingOf([], 1)).toEqual({ average: null, count: 0, mine: null }); + expect(ratingOf([], 1)).toEqual({ average: null, count: 0, mine: null, votes: [] }); const rows = [ - { target_id: 1, user_id: 1, rating: 5 }, - { target_id: 1, user_id: 2, rating: 2 }, + { target_id: 1, user_id: 1, rating: 5, username: 'ana', avatar: 'https://idp.example/a.png' }, + { target_id: 1, user_id: 2, rating: 2, username: 'ben', avatar: null }, ]; - expect(ratingOf(rows, 1)).toEqual({ average: 3.5, count: 2, mine: 5 }); - expect(ratingOf(rows, 9)).toEqual({ average: 3.5, count: 2, mine: null }); + expect(ratingOf(rows, 1)).toEqual({ + average: 3.5, + count: 2, + mine: 5, + votes: [ + { user_id: 1, username: 'ana', avatar_url: 'https://idp.example/a.png', rating: 5 }, + { user_id: 2, username: 'ben', avatar_url: null, rating: 2 }, + ], + }); + expect(ratingOf(rows, 9)).toMatchObject({ average: 3.5, count: 2, mine: null }); }); it('puts an entry together from its rows, the trip place leading', () => { 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 6da8c2928..c808058ce 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 @@ -237,7 +237,7 @@ describe('PlacesLibraryService.detail', () => { place_id: f.places.cafe.id, info: expect.objectContaining({ name: 'Café Central', description: 'A coffee house' }), notes: 'Book a table', - rating: { average: 3, count: 2, mine: 4 }, + rating: expect.objectContaining({ average: 3, count: 2, mine: 4 }), days: [{ day_id: f.day1.id, day_number: 1, date: '2026-07-01', title: null, time: '09:00', end_time: null }], has_accommodation: false, has_reservation: false, @@ -248,7 +248,7 @@ describe('PlacesLibraryService.detail', () => { info: expect.objectContaining({ name: ' café central ' }), notes: 'Try the cake', labels: [{ id: f.label.id, name: 'Must', color: '#ff0000' }], - rating: { average: 5, count: 1, mine: 5 }, + rating: expect.objectContaining({ average: 5, count: 1, mine: 5 }), }), ]); }); @@ -283,7 +283,7 @@ describe('PlacesLibraryService.detail', () => { kind: 'list', notes: null, labels: [], - rating: { average: null, count: 0, mine: null }, + rating: { average: null, count: 0, mine: null, votes: [] }, }), ]); }); diff --git a/server/tests/unit/nest/places-library/places-library.tags.test.ts b/server/tests/unit/nest/places-library/places-library.tags.test.ts new file mode 100644 index 000000000..2a111b44a --- /dev/null +++ b/server/tests/unit/nest/places-library/places-library.tags.test.ts @@ -0,0 +1,232 @@ +/** + * PLC-21: the tags of "All places". A place carries the tags of the lists and + * trips it is in, a list's labels on its saved place and a trip's tags on its + * trip place, gathered on the entry by name; the list filters by those names, + * and the detail names each origin's tags with every tag of that list or trip + * and whether the user may change them there. Over the real repository on a + * migrated test db; only the trip permission check is replaced, to deny + * 'place_edit' to trip members. + */ +import { CollectionLabels } from '../../../../src/db/entities/CollectionLabels.entity'; +import { PermissionsService } from '../../../../src/nest/permissions/permissions.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 { labelCollectionPlace } from '../../../helpers/factories/collections'; +import { makeTag, tagPlace } from '../../../helpers/factories/places'; +import { createRow } 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 { placesLibraryQuerySchema, type PlacesLibraryPageResponse, type PlacesLibraryQueryInput } from '@trek/shared'; + +import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +const db = createSnapshotTestDb(); +let t: TestModule; +let orm: TestOrm; +let library: PlacesLibraryService; +let f: LibraryFixture; +let tags: Awaited>; + +/** + * On top of the library seed: the trip Alps owns View (on Café Central) and + * Unused, the trip Rome owns Ancient (on Forum Romanum), the list Food has + * its label Must (on the saved Café Central, from the seed) and Coffee (on + * the saved Café Central and on Lunch spot), and the list Rome sights the + * label view (on Pantheon), which differs from the trip's View only in case. + */ +async function seedTags(fixture: LibraryFixture) { + const view = await makeTag(orm, fixture.me.id, { name: 'View', color: '#00aa00', trip: fixture.alps.id }); + const unused = await makeTag(orm, fixture.me.id, { name: 'Unused', color: '#999999', trip: fixture.alps.id }); + const ancient = await makeTag(orm, fixture.friend.id, { name: 'Ancient', color: '#aa0000', trip: fixture.rome.id }); + await tagPlace(orm, fixture.places.cafe.id, [view.id]); + await tagPlace(orm, fixture.places.forum.id, [ancient.id]); + const coffee = await createRow(orm, CollectionLabels, { + collection: fixture.lists.food.id, + name: 'Coffee', + color: '#553311', + sort_order: 1, + }); + await labelCollectionPlace(orm, fixture.saved.savedCafe.id, coffee.id); + await labelCollectionPlace(orm, fixture.saved.lunch.id, coffee.id); + const sightsView = await createRow(orm, CollectionLabels, { + collection: fixture.lists.sights.id, + name: 'view', + color: '#0000aa', + }); + await labelCollectionPlace(orm, fixture.saved.pantheon.id, sightsView.id); + // A trip and a list `me` cannot open: their tags never show. + const secret = await makeTag(orm, fixture.stranger.id, { name: 'Secret', trip: fixture.elsewhere.id }); + await tagPlace(orm, fixture.places.hidden.id, [secret.id]); + const secretLabel = await createRow(orm, CollectionLabels, { collection: fixture.lists.secrets.id, name: 'Secret' }); + await labelCollectionPlace(orm, fixture.saved.secret.id, secretLabel.id); + return { view, unused, ancient, coffee, sightsView }; +} + +beforeAll(async () => { + t = await createTestModule({ db, imports: [PlacesLibraryModule] }); + library = t.get(PlacesLibraryService); + orm = await createTestOrm(db); +}); +beforeEach(async () => { + resetTestDb(db); + orm.clear(); + vi.restoreAllMocks(); + // A trip's owner may edit its places, a member may not. + vi.spyOn(t.get(PermissionsService), 'checkPermission').mockImplementation( + async (_action, _role, tripOwner, userId) => tripOwner === userId, + ); + f = await seedLibrary(orm); + tags = await seedTags(f); +}); +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); +/** A page as the route reads it: the query through its schema, a query string's spellings included. */ +const page = (query: PlacesLibraryQueryInput) => library.list(as(f.me.id), placesLibraryQuerySchema.parse(query)); + +describe('PlacesLibraryService: the tags of an entry', () => { + it('PLIBTAG-001: an entry carries the trip tags and list tags of its uses, a name once, sorted by name', async () => { + const all = await page({ limit: 200 }); + const byKey = new Map(all.entries.map((entry) => [entry.key, entry.tags])); + expect(byKey.get(`trip:${f.places.cafe.id}`)).toEqual([ + { name: 'Coffee', color: '#553311' }, + { name: 'Must', color: '#ff0000' }, + { name: 'View', color: '#00aa00' }, + ]); + expect(byKey.get(`trip:${f.places.forum.id}`)).toEqual([{ name: 'Ancient', color: '#aa0000' }]); + expect(byKey.get(`list:${f.saved.lunch.id}`)).toEqual([{ name: 'Coffee', color: '#553311' }]); + expect(byKey.get(`list:${f.saved.pantheon.id}`)).toEqual([{ name: 'view', color: '#0000aa' }]); + // A place without a tag carries none; a tag no place carries shows nowhere. + expect(byKey.get(`trip:${f.places.hotel.id}`)).toEqual([]); + expect(all.entries.flatMap((entry) => entry.tags ?? []).map((tag) => tag.name)).not.toContain('Unused'); + expect(all.entries.flatMap((entry) => entry.tags ?? []).map((tag) => tag.name)).not.toContain('Secret'); + }); + + it('PLIBTAG-002: one name of two cases is one tag, with the colour read first', async () => { + await tagPlace(orm, f.places.museum.id, [tags.view.id]); + const label = await createRow(orm, CollectionLabels, { + collection: f.lists.food.id, + name: ' VIEW ', + color: '#123456', + }); + await labelCollectionPlace(orm, f.saved.savedMuseum.id, label.id); + const answer = await library.detail(as(f.me.id), 'trip', f.places.museum.id); + expect(answer.entry.tags).toEqual([{ name: 'View', color: '#00aa00' }]); + }); +}); + +describe('PlacesLibraryService: the tag filter', () => { + it('PLIBTAG-010: keeps the entries carrying a tag of one of the names, case ignored, on either side', async () => { + const coffee = await page({ tags: 'coffee' }); + expect(keys(coffee).sort()).toEqual([`list:${f.saved.lunch.id}`, `trip:${f.places.cafe.id}`].sort()); + expect(coffee.total).toBe(2); + expect(coffee.counts).toEqual({ all: 2, trip: 1, list: 2 }); + // The trip's View and the list's view are one name, matched on a trip place and on a saved place. + const view = await page({ tags: ['VIEW'] }); + expect(keys(view).sort()).toEqual([`list:${f.saved.pantheon.id}`, `trip:${f.places.cafe.id}`].sort()); + const either = await page({ tags: 'Ancient,Must' }); + expect(keys(either).sort()).toEqual([`trip:${f.places.cafe.id}`, `trip:${f.places.forum.id}`].sort()); + }); + + it('PLIBTAG-011: goes with the other filters, and a tag on a use another filter leaves out still counts', async () => { + // Café Central carries View on its trip place; the list tab still finds it by that tag. + const listsOnly = await page({ tags: 'View', kind: 'list' }); + expect(keys(listsOnly).sort()).toEqual([`list:${f.saved.pantheon.id}`, `trip:${f.places.cafe.id}`].sort()); + expect(keys(await page({ tags: 'View', q: 'pantheon' }))).toEqual([`list:${f.saved.pantheon.id}`]); + expect(keys(await page({ tags: 'Ancient', collection_id: f.lists.food.id }))).toEqual([]); + }); + + it('PLIBTAG-012: a name no tag of the reachable lists and trips has matches nothing', async () => { + expect((await page({ tags: 'Secret' })).total).toBe(0); + expect((await page({ tags: 'Unused' })).total).toBe(0); + expect((await page({ tags: 'nothing like it' })).entries).toEqual([]); + }); +}); + +describe('PlacesLibraryService: the tags in detail', () => { + it('PLIBTAG-020: each origin names its tags, every tag of its list or trip, and whether the user may change them', async () => { + const answer = await library.detail(as(f.me.id), 'trip', f.places.cafe.id); + expect(answer.details).toEqual([ + expect.objectContaining({ + kind: 'trip', + tags: [{ id: tags.view.id, name: 'View', color: '#00aa00' }], + available_tags: [ + { id: tags.unused.id, name: 'Unused', color: '#999999' }, + { id: tags.view.id, name: 'View', color: '#00aa00' }, + ], + can_edit_tags: true, + }), + expect.objectContaining({ + kind: 'list', + labels: [ + { id: f.label.id, name: 'Must', color: '#ff0000' }, + { id: tags.coffee.id, name: 'Coffee', color: '#553311' }, + ], + tags: [ + { id: f.label.id, name: 'Must', color: '#ff0000' }, + { id: tags.coffee.id, name: 'Coffee', color: '#553311' }, + ], + available_tags: [ + { id: f.label.id, name: 'Must', color: '#ff0000' }, + { id: tags.coffee.id, name: 'Coffee', color: '#553311' }, + ], + can_edit_tags: true, + }), + ]); + }); + + it('PLIBTAG-021: a member without place_edit and a viewer of a list read the tags but may not change them', async () => { + const forum = await library.detail(as(f.me.id), 'trip', f.places.forum.id); + expect(forum.details[0]).toMatchObject({ + kind: 'trip', + tags: [{ id: tags.ancient.id, name: 'Ancient', color: '#aa0000' }], + available_tags: [{ id: tags.ancient.id, name: 'Ancient', color: '#aa0000' }], + can_edit_tags: false, + }); + const pantheon = await library.detail(as(f.me.id), 'list', f.saved.pantheon.id); + expect(pantheon.details[0]).toMatchObject({ + kind: 'list', + tags: [{ id: tags.sightsView.id, name: 'view', color: '#0000aa' }], + available_tags: [{ id: tags.sightsView.id, name: 'view', color: '#0000aa' }], + can_edit_tags: false, + }); + }); + + it('PLIBTAG-022: the owner of the trip and the list may change them there', async () => { + const forum = await library.detail(as(f.friend.id), 'trip', f.places.forum.id); + expect(forum.details[0]).toMatchObject({ kind: 'trip', can_edit_tags: true }); + const pantheon = await library.detail(as(f.friend.id), 'list', f.saved.pantheon.id); + expect(pantheon.details[0]).toMatchObject({ kind: 'list', can_edit_tags: true }); + }); + + it('PLIBTAG-023: a place without tags names none, and still every tag its trip or list has', async () => { + const hotel = await library.detail(as(f.me.id), 'trip', f.places.hotel.id); + expect(hotel.entry.tags).toEqual([]); + expect(hotel.details[0]).toMatchObject({ tags: [], can_edit_tags: true }); + expect((hotel.details[0] as { available_tags: unknown[] }).available_tags).toHaveLength(2); + }); + + it('PLIBTAG-024: an older personal tag on a trip place shows, is offered back and is found by the filter', async () => { + const mine = await makeTag(orm, f.me.id, { name: 'Mine', color: '#222222' }); + await tagPlace(orm, f.places.hotel.id, [mine.id]); + const hotel = await library.detail(as(f.me.id), 'trip', f.places.hotel.id); + expect(hotel.entry.tags).toEqual([{ name: 'Mine', color: '#222222' }]); + expect(hotel.details[0]).toMatchObject({ + tags: [{ id: mine.id, name: 'Mine', color: '#222222' }], + available_tags: [ + { id: tags.unused.id, name: 'Unused', color: '#999999' }, + { id: tags.view.id, name: 'View', color: '#00aa00' }, + { id: mine.id, name: 'Mine', color: '#222222' }, + ], + }); + expect(keys(await page({ tags: 'mine' }))).toEqual([`trip:${f.places.hotel.id}`]); + }); +}); diff --git a/server/tests/unit/nest/places.controller.test.ts b/server/tests/unit/nest/places.controller.test.ts index 03c581e52..5ccc40146 100644 --- a/server/tests/unit/nest/places.controller.test.ts +++ b/server/tests/unit/nest/places.controller.test.ts @@ -654,7 +654,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou 'sock', ), ).toEqual({ updated: [1, 2], count: 2 }); - expect(updateMany).toHaveBeenCalledWith('5', [1, 2], { category_id: 3 }); + expect(updateMany).toHaveBeenCalledWith('5', [1, 2], { category_id: 3 }, user.id, { editor: user }); expect(onUpdated).toHaveBeenCalledTimes(2); expect(broadcast).toHaveBeenCalledWith('5', 'place:updated', { place: { id: 1 } }, 'sock'); }); @@ -667,7 +667,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou category_id: null, }), ).toEqual({ updated: [1], count: 1 }); - expect(updateMany).toHaveBeenCalledWith('5', [1], { category_id: null }); + expect(updateMany).toHaveBeenCalledWith('5', [1], { category_id: null }, user.id, { editor: user }); }); }); @@ -764,7 +764,14 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou 'sock', ), ).toEqual({ place: { id: 9, route_color: '#e11d48' } }); - expect(update).toHaveBeenCalledWith('5', '9', expect.objectContaining({ route_color: '#e11d48' }), undefined); + expect(update).toHaveBeenCalledWith( + '5', + '9', + expect.objectContaining({ route_color: '#e11d48' }), + undefined, + user.id, + { editor: user }, + ); // The colour has to reach the other members too, not just the DB. expect(broadcast).toHaveBeenCalledWith( '5', @@ -779,7 +786,14 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou storageStub, kmlStub, ).update(user, '5', '9', { route_color: null }); - expect(update).toHaveBeenLastCalledWith('5', '9', expect.objectContaining({ route_color: null }), undefined); + expect(update).toHaveBeenLastCalledWith( + '5', + '9', + expect.objectContaining({ route_color: null }), + undefined, + user.id, + { editor: user }, + ); }); it('accepts the short #abc form', async () => { @@ -863,7 +877,7 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou expect(await ctl({ update } as Partial).update(user, '5', '9', { website })).toEqual({ place: { id: 9 }, }); - expect(update).toHaveBeenLastCalledWith('5', '9', { website }, undefined); + expect(update).toHaveBeenLastCalledWith('5', '9', { website }, undefined, user.id, { editor: user }); } }); @@ -878,7 +892,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou const update = vi.fn().mockReturnValue({ id: 9 }); await ctl({ update } as Partial).update(user, '5', '9', { website: '//www.example.fr' }); - expect(update).toHaveBeenCalledWith('5', '9', { website: 'https://www.example.fr' }, undefined); + expect(update).toHaveBeenCalledWith('5', '9', { website: 'https://www.example.fr' }, undefined, user.id, { + editor: user, + }); }); }); @@ -902,7 +918,14 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou status: 409, body: { error: 'conflict', server: { id: 9, name: 'Theirs' } }, }); - expect(update).toHaveBeenCalledWith('5', '9', expect.objectContaining({ name: 'Mine' }), '2026-01-01 00:00:00'); + expect(update).toHaveBeenCalledWith( + '5', + '9', + expect.objectContaining({ name: 'Mine' }), + '2026-01-01 00:00:00', + user.id, + { editor: user }, + ); expect(broadcast).not.toHaveBeenCalled(); expect(onUpdated).not.toHaveBeenCalled(); }); @@ -1093,7 +1116,9 @@ describe('PlacesController (parity with the legacy /api/trips/:tripId/places rou ), ).toEqual({ place: { id: 9 } }); expect(storageStub.put).toHaveBeenCalledWith('places', 'abc.jpg', { tmpPath: undefined }); - expect(update).toHaveBeenCalledWith('5', '9', { image_url: '/uploads/places/abc.jpg' }); + expect(update).toHaveBeenCalledWith('5', '9', { image_url: '/uploads/places/abc.jpg' }, undefined, user.id, { + editor: user, + }); expect(broadcast).toHaveBeenCalledWith('5', 'place:updated', { place: { id: 9 } }, 'sock'); expect(onUpdated).toHaveBeenCalledWith(9); }); diff --git a/server/tests/unit/nest/tag-writes.service.test.ts b/server/tests/unit/nest/tag-writes.service.test.ts deleted file mode 100644 index fd02e3b95..000000000 --- a/server/tests/unit/nest/tag-writes.service.test.ts +++ /dev/null @@ -1,71 +0,0 @@ -/** - * 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 d68873e29..cba2909c3 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, uow)) over a + * service is constructed directly (new TagsService(repo)) 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, createTestUnitOfWork, sharedTestOrm } from '../../helpers/test-uow'; +import { createTestTagsRepo, 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), await createTestUnitOfWork(testDb)); + svc = new TagsService(await createTestTagsRepo(testDb)); }); beforeEach(() => { @@ -186,30 +186,3 @@ 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/places/places.rpc.test.ts b/server/tests/unit/places/places.rpc.test.ts index 554f43cd3..da9f8f7d3 100644 --- a/server/tests/unit/places/places.rpc.test.ts +++ b/server/tests/unit/places/places.rpc.test.ts @@ -235,7 +235,7 @@ describe('PlacesRpc', () => { (await host.dispatch(req('places.update', { tripId: 1, placeId: 7, input: { website: '//www.example.fr' } }), 42)) .ok, ).toBe(true); - expect(f.places.update).toHaveBeenCalledWith('1', '7', { website: 'https://www.example.fr' }); + expect(f.places.update).toHaveBeenCalledWith('1', '7', { website: 'https://www.example.fr' }, undefined, 42); const refused = (await host.dispatch( req('places.create', { tripId: 1, input: { name: 'X', website: 'javascript:alert(1)' } }),