feat(places): own place identities, duplicate merging and lists linked to a trip

- A user can group the uses of one place (trip places and saved places) into a
  place identity of their own (user_places, user_place_links). It is personal:
  it groups their "All places" and is never written into a shared trip or list
  row. An identity without a use they can still reach is not shown, and one
  left without links is pruned on their next write and nightly.
- Possible duplicates are suggested server side (same provider id, or the same
  name at the same spot), each pair with what differs and whether the user may
  merge it. A merge joins two identities in one transaction and can be undone;
  a dismissed pair does not come back. No trip or list row is deleted or changed.
- A trip can link lists (trip_collection_links, needs place_edit and access to
  the list). A member sees a linked list only with their own access to it; the
  map layer lists its places and whether each is already in the trip.
  tripCollections:changed tells the members to read their view again.
- REST, MCP tools and client data layer for all of it; migrations on both
  engines, additive only.
- CI: the stage 1 to 2 places-library helper types, and the await-in-loop and
  non-null counts it had raised.
This commit is contained in:
Maurice
2026-11-29 15:57:05 +01:00
parent 01d327b502
commit f69a4c1a24
87 changed files with 4882 additions and 221 deletions
+5
View File
@@ -147,6 +147,7 @@
"TrekPhotos": "photos",
"TripAddonOverrides": "addons",
"TripAlbumLinks": "memories",
"TripCollectionLinks": "trip-collections",
"TripDocumentLinks": "doc-sync",
"TripFiles": "files",
"TripInviteTokens": "trip-invite",
@@ -157,6 +158,10 @@
"TripPhotos": "photos",
"Trips": "trips",
"UserNoticeDismissals": "system-notices",
"UserPlaceLinks": "places-library",
"UserPlaceMergeDismissals": "places-library",
"UserPlaceMerges": "places-library",
"UserPlaces": "places-library",
"UserSessions": "sessions",
"Users": "auth",
"VacayCompanyHolidays": "vacay",
@@ -3,6 +3,7 @@ import { CategoriesRepository } from '../repositories/Categories.repository';
import { DbTimestampType } from '../types';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { Places } from './Places.entity';
import { UserPlaces } from './UserPlaces.entity';
import { Users } from './Users.entity';
export class Categories {
@@ -16,6 +17,7 @@ export class Categories {
created_at?: string | null;
collection_places_collection = new Collection<CollectionPlaces>(this);
places_collection = new Collection<Places>(this);
user_places_collection = new Collection<UserPlaces>(this);
}
export const CategoriesSchema = defineEntity({
@@ -31,5 +33,6 @@ export const CategoriesSchema = defineEntity({
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
collection_places_collection: () => p.oneToMany(CollectionPlaces).mappedBy('category').hidden(),
places_collection: () => p.oneToMany(Places).mappedBy('category').hidden(),
user_places_collection: () => p.oneToMany(UserPlaces).mappedBy('category').hidden(),
},
});
@@ -6,6 +6,7 @@ import { CollectionLabels } from './CollectionLabels.entity';
import { CollectionPlaceRatings } from './CollectionPlaceRatings.entity';
import { Collections } from './Collections.entity';
import { Tags } from './Tags.entity';
import { UserPlaceLinks } from './UserPlaceLinks.entity';
import { Users } from './Users.entity';
export class CollectionPlaces {
@@ -43,6 +44,7 @@ export class CollectionPlaces {
collection_place_labels = new Collection<CollectionLabels>(this);
collection_place_tags = new Collection<Tags>(this);
collection_place_ratings_collection = new Collection<CollectionPlaceRatings>(this);
user_place_links_collection = new Collection<UserPlaceLinks>(this);
}
export const CollectionPlacesSchema = defineEntity({
@@ -82,5 +84,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(),
user_place_links_collection: () => p.oneToMany(UserPlaceLinks).mappedBy('collectionPlace').hidden(),
},
});
@@ -5,6 +5,7 @@ import { CollectionLabels } from './CollectionLabels.entity';
import { CollectionMembers } from './CollectionMembers.entity';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { CollectionTours } from './CollectionTours.entity';
import { TripCollectionLinks } from './TripCollectionLinks.entity';
import { Users } from './Users.entity';
export class Collections {
@@ -25,6 +26,7 @@ export class Collections {
collection_members_collection = new Collection<CollectionMembers>(this);
collection_places_collection = new Collection<CollectionPlaces>(this);
collection_tours_collection = new Collection<CollectionTours>(this);
trip_collection_links_collection = new Collection<TripCollectionLinks>(this);
}
export const CollectionsSchema = defineEntity({
@@ -47,5 +49,6 @@ export const CollectionsSchema = defineEntity({
collection_members_collection: () => p.oneToMany(CollectionMembers).mappedBy('collection').hidden(),
collection_places_collection: () => p.oneToMany(CollectionPlaces).mappedBy('collection').hidden(),
collection_tours_collection: () => p.oneToMany(CollectionTours).mappedBy('collection').hidden(),
trip_collection_links_collection: () => p.oneToMany(TripCollectionLinks).mappedBy('collection').hidden(),
},
});
+3
View File
@@ -20,6 +20,7 @@ import { TourWaypoints } from './TourWaypoints.entity';
import { Tours } from './Tours.entity';
import { TripFiles } from './TripFiles.entity';
import { Trips } from './Trips.entity';
import { UserPlaceLinks } from './UserPlaceLinks.entity';
export class Places {
[EntityRepositoryType]?: PlacesRepository;
@@ -77,6 +78,7 @@ export class Places {
tours: Ref<Tours> | null = null;
tours_collection = new Collection<Tours>(this);
trip_files_collection = new Collection<TripFiles>(this);
user_place_links_collection = new Collection<UserPlaceLinks>(this);
}
export const PlacesSchema = defineEntity({
@@ -137,5 +139,6 @@ export const PlacesSchema = defineEntity({
tours: () => p.oneToOne(Tours).ref().mappedBy('place').hidden(),
tours_collection: () => p.oneToMany(Tours).mappedBy('derivedFromPlace').hidden(),
trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('place').hidden(),
user_place_links_collection: () => p.oneToMany(UserPlaceLinks).mappedBy('place').hidden(),
},
});
@@ -0,0 +1,34 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TripCollectionLinksRepository } from '../repositories/TripCollectionLinks.repository';
import { DbTimestampType } from '../types';
import { Collections } from './Collections.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class TripCollectionLinks {
[EntityRepositoryType]?: TripCollectionLinksRepository;
id!: number & Opt;
trip!: Ref<Trips>;
trip_id!: number;
collection!: Ref<Collections>;
collection_id!: number;
linked_by?: number | null;
created_at?: string | null;
linkedByRef?: Ref<Users> | null;
}
export const TripCollectionLinksSchema = defineEntity({
class: TripCollectionLinks,
repository: () => TripCollectionLinksRepository,
uniques: [{ properties: ['trip', 'collection'] }],
properties: {
id: p.integer().primary(),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').hidden(),
trip_id: p.integer().persist(false),
collection: () => p.manyToOne(Collections).ref().deleteRule('cascade').hidden().index('idx_trip_collection_links_collection_id'),
collection_id: p.integer().persist(false).index('idx_trip_collection_links_collection_id'),
linked_by: p.integer().nullable().persist(false).index('idx_trip_collection_links_linked_by'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
linkedByRef: () => p.manyToOne(Users).ref().joinColumn('linked_by').nullable().hidden().index('idx_trip_collection_links_linked_by'),
},
});
+3
View File
@@ -37,6 +37,7 @@ import { TodoItems } from './TodoItems.entity';
import { TourDrafts } from './TourDrafts.entity';
import { TripAddonOverrides } from './TripAddonOverrides.entity';
import { TripAlbumLinks } from './TripAlbumLinks.entity';
import { TripCollectionLinks } from './TripCollectionLinks.entity';
import { TripDocumentLinks } from './TripDocumentLinks.entity';
import { TripFiles } from './TripFiles.entity';
import { TripInviteTokens } from './TripInviteTokens.entity';
@@ -101,6 +102,7 @@ export class Trips {
tour_drafts_collection = new Collection<TourDrafts>(this);
trip_addon_overrides_collection = new Collection<TripAddonOverrides>(this);
trip_album_links_collection = new Collection<TripAlbumLinks>(this);
trip_collection_links_collection = new Collection<TripCollectionLinks>(this);
trip_document_links_collection = new Collection<TripDocumentLinks>(this);
trip_files_collection = new Collection<TripFiles>(this);
trip_invite_tokens_collection = new Collection<TripInviteTokens>(this);
@@ -181,6 +183,7 @@ export const TripsSchema = defineEntity({
tour_drafts_collection: () => p.oneToMany(TourDrafts).mappedBy('trip').hidden(),
trip_addon_overrides_collection: () => p.oneToMany(TripAddonOverrides).mappedBy('trip').hidden(),
trip_album_links_collection: () => p.oneToMany(TripAlbumLinks).mappedBy('trip').hidden(),
trip_collection_links_collection: () => p.oneToMany(TripCollectionLinks).mappedBy('trip').hidden(),
trip_document_links_collection: () => p.oneToMany(TripDocumentLinks).mappedBy('trip').hidden(),
trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('trip').hidden(),
trip_invite_tokens_collection: () => p.oneToMany(TripInviteTokens).mappedBy('trip').hidden(),
@@ -0,0 +1,57 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { UserPlaceLinksRepository } from '../repositories/UserPlaceLinks.repository';
import { DbTimestampType } from '../types';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { Places } from './Places.entity';
import { UserPlaces } from './UserPlaces.entity';
import { Users } from './Users.entity';
export class UserPlaceLinks {
[EntityRepositoryType]?: UserPlaceLinksRepository;
id!: number & Opt;
userPlace!: Ref<UserPlaces>;
user_place_id!: number;
user!: Ref<Users>;
user_id!: number;
place?: Ref<Places> | null;
place_id?: number | null;
collectionPlace?: Ref<CollectionPlaces> | null;
collection_place_id?: number | null;
linked_by: TUserPlaceLinksLinkedBy & Opt = UserPlaceLinksLinkedBy.USER;
created_at?: string | null;
}
export const UserPlaceLinksLinkedBy = {
USER: 'user',
MERGE: 'merge',
} as const;
export type TUserPlaceLinksLinkedBy = (typeof UserPlaceLinksLinkedBy)[keyof typeof UserPlaceLinksLinkedBy];
export const UserPlaceLinksSchema = defineEntity({
class: UserPlaceLinks,
repository: () => UserPlaceLinksRepository,
uniques: [
{ properties: ['user', 'collectionPlace'] },
{ properties: ['user', 'place'] },
],
checks: [
{
name: 'user_place_links_collection_place_id_check',
expression: '(place_id IS NULL) <> (collection_place_id IS NULL)',
},
],
properties: {
id: p.integer().primary(),
userPlace: () => p.manyToOne(UserPlaces).ref().deleteRule('cascade').hidden().index('idx_user_place_links_user_place_id'),
user_place_id: p.integer().persist(false).index('idx_user_place_links_user_place_id'),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
place: () => p.manyToOne(Places).ref().deleteRule('cascade').nullable().hidden().index('idx_user_place_links_place_id'),
place_id: p.integer().nullable().persist(false).index('idx_user_place_links_place_id'),
collectionPlace: () => p.manyToOne(CollectionPlaces).ref().deleteRule('cascade').nullable().hidden().index('idx_user_place_links_collection_place_id'),
collection_place_id: p.integer().nullable().persist(false).index('idx_user_place_links_collection_place_id'),
linked_by: p.enum(() => UserPlaceLinksLinkedBy).default('user'),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,28 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { UserPlaceMergeDismissalsRepository } from '../repositories/UserPlaceMergeDismissals.repository';
import { DbTimestampType } from '../types';
import { Users } from './Users.entity';
export class UserPlaceMergeDismissals {
[EntityRepositoryType]?: UserPlaceMergeDismissalsRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
key_a!: string;
key_b!: string;
created_at?: string | null;
}
export const UserPlaceMergeDismissalsSchema = defineEntity({
class: UserPlaceMergeDismissals,
repository: () => UserPlaceMergeDismissalsRepository,
uniques: [{ properties: ['user', 'key_a', 'key_b'] }],
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden(),
user_id: p.integer().persist(false),
key_a: p.text(),
key_b: p.text(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,34 @@
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { UserPlaceMergesRepository } from '../repositories/UserPlaceMerges.repository';
import { DbTimestampType } from '../types';
import { UserPlaces } from './UserPlaces.entity';
import { Users } from './Users.entity';
export class UserPlaceMerges {
[EntityRepositoryType]?: UserPlaceMergesRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
leading!: Ref<UserPlaces>;
leading_id!: number;
merged!: Ref<UserPlaces>;
merged_id!: number;
moved_link_ids!: string;
created_at?: string | null;
}
export const UserPlaceMergesSchema = defineEntity({
class: UserPlaceMerges,
repository: () => UserPlaceMergesRepository,
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_user_place_merges_user_id'),
user_id: p.integer().persist(false).index('idx_user_place_merges_user_id'),
leading: () => p.manyToOne(UserPlaces).ref().deleteRule('cascade').hidden().index('idx_user_place_merges_leading_id'),
leading_id: p.integer().persist(false).index('idx_user_place_merges_leading_id'),
merged: () => p.manyToOne(UserPlaces).ref().deleteRule('cascade').hidden().index('idx_user_place_merges_merged_id'),
merged_id: p.integer().persist(false).index('idx_user_place_merges_merged_id'),
moved_link_ids: p.text(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
@@ -0,0 +1,58 @@
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
import { UserPlacesRepository } from '../repositories/UserPlaces.repository';
import { DbTimestampType } from '../types';
import { Categories } from './Categories.entity';
import { UserPlaceLinks } from './UserPlaceLinks.entity';
import { UserPlaceMerges } from './UserPlaceMerges.entity';
import { Users } from './Users.entity';
export class UserPlaces {
[EntityRepositoryType]?: UserPlacesRepository;
id!: number & Opt;
user!: Ref<Users>;
user_id!: number;
name!: string;
lat?: number | null;
lng?: number | null;
address?: string | null;
category?: Ref<Categories> | null;
category_id?: number | null;
google_place_id?: string | null;
google_ftid?: string | null;
osm_id?: string | null;
mergedInto?: Ref<UserPlaces> | null;
merged_into_id?: number | null;
created_at?: string | null;
updated_at?: string | null;
user_place_links_collection = new Collection<UserPlaceLinks>(this);
user_place_merges_collection = new Collection<UserPlaceMerges>(this);
user_place_merges_collection1 = new Collection<UserPlaceMerges>(this);
user_places_collection = new Collection<UserPlaces>(this);
}
export const UserPlacesSchema = defineEntity({
class: UserPlaces,
repository: () => UserPlacesRepository,
properties: {
id: p.integer().primary(),
user: () => p.manyToOne(Users).ref().deleteRule('cascade').hidden().index('idx_user_places_user_id'),
user_id: p.integer().persist(false).index('idx_user_places_user_id'),
name: p.text(),
lat: p.double().nullable(),
lng: p.double().nullable(),
address: p.text().nullable(),
category: () => p.manyToOne(Categories).ref().nullable().hidden().index('idx_user_places_category_id'),
category_id: p.integer().nullable().persist(false).index('idx_user_places_category_id'),
google_place_id: p.text().nullable(),
google_ftid: p.text().nullable(),
osm_id: p.text().nullable(),
mergedInto: () => p.manyToOne(UserPlaces).ref().nullable().hidden().index('idx_user_places_merged_into_id'),
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`),
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(),
user_places_collection: () => p.oneToMany(UserPlaces).mappedBy('mergedInto').hidden(),
},
});
+15
View File
@@ -71,6 +71,7 @@ import { TourSourceHints } from './TourSourceHints.entity';
import { TourSources } from './TourSources.entity';
import { TrekPhotos } from './TrekPhotos.entity';
import { TripAlbumLinks } from './TripAlbumLinks.entity';
import { TripCollectionLinks } from './TripCollectionLinks.entity';
import { TripDocumentLinks } from './TripDocumentLinks.entity';
import { TripFiles } from './TripFiles.entity';
import { TripInviteTokens } from './TripInviteTokens.entity';
@@ -81,6 +82,10 @@ import { TripMembers } from './TripMembers.entity';
import { TripPhotos } from './TripPhotos.entity';
import { Trips } from './Trips.entity';
import { UserNoticeDismissals } from './UserNoticeDismissals.entity';
import { UserPlaceLinks } from './UserPlaceLinks.entity';
import { UserPlaceMergeDismissals } from './UserPlaceMergeDismissals.entity';
import { UserPlaceMerges } from './UserPlaceMerges.entity';
import { UserPlaces } from './UserPlaces.entity';
import { UserSessions } from './UserSessions.entity';
import { VacayEntries } from './VacayEntries.entity';
import { VacayPlanMembers } from './VacayPlanMembers.entity';
@@ -216,6 +221,7 @@ export class Users {
tour_sources_collection = new Collection<TourSources>(this);
trek_photos_collection = new Collection<TrekPhotos>(this);
trip_album_links_collection = new Collection<TripAlbumLinks>(this);
trip_collection_links_collection = new Collection<TripCollectionLinks>(this);
trip_document_links_collection = new Collection<TripDocumentLinks>(this);
trip_files_collection = new Collection<TripFiles>(this);
trip_invite_tokens_collection = new Collection<TripInviteTokens>(this);
@@ -227,6 +233,10 @@ export class Users {
trip_photos_collection = new Collection<TripPhotos>(this);
trips_collection = new Collection<Trips>(this);
user_notice_dismissals_collection = new Collection<UserNoticeDismissals>(this);
user_place_links_collection = new Collection<UserPlaceLinks>(this);
user_place_merge_dismissals_collection = new Collection<UserPlaceMergeDismissals>(this);
user_place_merges_collection = new Collection<UserPlaceMerges>(this);
user_places_collection = new Collection<UserPlaces>(this);
user_sessions_collection = new Collection<UserSessions>(this);
vacay_entries_collection = new Collection<VacayEntries>(this);
vacay_plan_members_collection = new Collection<VacayPlanMembers>(this);
@@ -379,6 +389,7 @@ export const UsersSchema = defineEntity({
tour_sources_collection: () => p.oneToMany(TourSources).mappedBy('importedByRef').hidden(),
trek_photos_collection: () => p.oneToMany(TrekPhotos).mappedBy('owner').hidden(),
trip_album_links_collection: () => p.oneToMany(TripAlbumLinks).mappedBy('user').hidden(),
trip_collection_links_collection: () => p.oneToMany(TripCollectionLinks).mappedBy('linkedByRef').hidden(),
trip_document_links_collection: () => p.oneToMany(TripDocumentLinks).mappedBy('createdByRef').hidden(),
trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('uploadedByRef').hidden(),
trip_invite_tokens_collection: () => p.oneToMany(TripInviteTokens).mappedBy('createdByRef').hidden(),
@@ -390,6 +401,10 @@ export const UsersSchema = defineEntity({
trip_photos_collection: () => p.oneToMany(TripPhotos).mappedBy('user').hidden(),
trips_collection: () => p.oneToMany(Trips).mappedBy('user').hidden(),
user_notice_dismissals_collection: () => p.oneToMany(UserNoticeDismissals).mappedBy('user').hidden(),
user_place_links_collection: () => p.oneToMany(UserPlaceLinks).mappedBy('user').hidden(),
user_place_merge_dismissals_collection: () => p.oneToMany(UserPlaceMergeDismissals).mappedBy('user').hidden(),
user_place_merges_collection: () => p.oneToMany(UserPlaceMerges).mappedBy('user').hidden(),
user_places_collection: () => p.oneToMany(UserPlaces).mappedBy('user').hidden(),
user_sessions_collection: () => p.oneToMany(UserSessions).mappedBy('user').hidden(),
vacay_entries_collection: () => p.oneToMany(VacayEntries).mappedBy('user').hidden(),
vacay_plan_members_collection: () => p.oneToMany(VacayPlanMembers).mappedBy('user').hidden(),
+10
View File
@@ -146,6 +146,7 @@ import { TrekPhotoSignalsSchema } from './TrekPhotoSignals.entity';
import { TrekPhotosSchema } from './TrekPhotos.entity';
import { TripAddonOverridesSchema } from './TripAddonOverrides.entity';
import { TripAlbumLinksSchema } from './TripAlbumLinks.entity';
import { TripCollectionLinksSchema } from './TripCollectionLinks.entity';
import { TripDocumentLinksSchema } from './TripDocumentLinks.entity';
import { TripFilesSchema } from './TripFiles.entity';
import { TripInviteTokensSchema } from './TripInviteTokens.entity';
@@ -156,6 +157,10 @@ import { TripMembersSchema } from './TripMembers.entity';
import { TripPhotosSchema } from './TripPhotos.entity';
import { TripsSchema } from './Trips.entity';
import { UserNoticeDismissalsSchema } from './UserNoticeDismissals.entity';
import { UserPlaceLinksSchema } from './UserPlaceLinks.entity';
import { UserPlaceMergeDismissalsSchema } from './UserPlaceMergeDismissals.entity';
import { UserPlaceMergesSchema } from './UserPlaceMerges.entity';
import { UserPlacesSchema } from './UserPlaces.entity';
import { UserSessionsSchema } from './UserSessions.entity';
import { UsersSchema } from './Users.entity';
import { VacayCompanyHolidaysSchema } from './VacayCompanyHolidays.entity';
@@ -322,6 +327,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TrekPhotosSchema,
TripAddonOverridesSchema,
TripAlbumLinksSchema,
TripCollectionLinksSchema,
TripDocumentLinksSchema,
TripFilesSchema,
TripInviteTokensSchema,
@@ -332,6 +338,10 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TripPhotosSchema,
TripsSchema,
UserNoticeDismissalsSchema,
UserPlaceLinksSchema,
UserPlaceMergeDismissalsSchema,
UserPlaceMergesSchema,
UserPlacesSchema,
UserSessionsSchema,
UsersSchema,
VacayCompanyHolidaysSchema,
+7
View File
@@ -616,3 +616,10 @@ export const MAIL_INGEST_ATTACHMENTS: JsonColumn<MailIngestAttachment[]> = {
schema: z.array(mailIngestAttachmentSchema),
fallback: () => [],
};
/** The links a merge of two own places moved (D6), for its undo. A broken row moves nothing back. */
export const USER_PLACE_MERGE_MOVED_LINKS: JsonColumn<number[]> = {
column: 'user_place_merges.moved_link_ids',
schema: idList,
fallback: () => [],
};
@@ -0,0 +1,11 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface TripCollectionLinksTable {
id: InsertOptional<number>;
trip_id: number;
collection_id: number;
linked_by: InsertOptional<number | null>;
created_at: InsertOptional<string | null>;
}
@@ -0,0 +1,13 @@
// 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 UserPlaceLinksTable {
id: InsertOptional<number>;
user_place_id: number;
user_id: number;
place_id: InsertOptional<number | null>;
collection_place_id: InsertOptional<number | null>;
linked_by: InsertOptional<string>;
created_at: InsertOptional<string | null>;
}
@@ -0,0 +1,11 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface UserPlaceMergeDismissalsTable {
id: InsertOptional<number>;
user_id: number;
key_a: string;
key_b: string;
created_at: InsertOptional<string | null>;
}
@@ -0,0 +1,12 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface UserPlaceMergesTable {
id: InsertOptional<number>;
user_id: number;
leading_id: number;
merged_id: number;
moved_link_ids: string;
created_at: InsertOptional<string | null>;
}
+19
View File
@@ -0,0 +1,19 @@
// 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 UserPlacesTable {
id: InsertOptional<number>;
user_id: number;
name: string;
lat: InsertOptional<number | null>;
lng: InsertOptional<number | null>;
address: InsertOptional<string | null>;
category_id: InsertOptional<number | null>;
google_place_id: InsertOptional<string | null>;
google_ftid: InsertOptional<string | null>;
osm_id: InsertOptional<string | null>;
merged_into_id: InsertOptional<number | null>;
created_at: InsertOptional<string | null>;
updated_at: InsertOptional<string | null>;
}
+10
View File
@@ -152,6 +152,7 @@ import type { TrekPhotoSignalsTable } from './TrekPhotoSignals.table';
import type { TrekPhotosTable } from './TrekPhotos.table';
import type { TripAddonOverridesTable } from './TripAddonOverrides.table';
import type { TripAlbumLinksTable } from './TripAlbumLinks.table';
import type { TripCollectionLinksTable } from './TripCollectionLinks.table';
import type { TripDocumentLinksTable } from './TripDocumentLinks.table';
import type { TripFilesTable } from './TripFiles.table';
import type { TripInviteTokensTable } from './TripInviteTokens.table';
@@ -162,6 +163,10 @@ import type { TripMembersTable } from './TripMembers.table';
import type { TripPhotosTable } from './TripPhotos.table';
import type { TripsTable } from './Trips.table';
import type { UserNoticeDismissalsTable } from './UserNoticeDismissals.table';
import type { UserPlaceLinksTable } from './UserPlaceLinks.table';
import type { UserPlaceMergeDismissalsTable } from './UserPlaceMergeDismissals.table';
import type { UserPlaceMergesTable } from './UserPlaceMerges.table';
import type { UserPlacesTable } from './UserPlaces.table';
import type { UserSessionsTable } from './UserSessions.table';
import type { UsersTable } from './Users.table';
import type { VacayCompanyHolidaysTable } from './VacayCompanyHolidays.table';
@@ -334,6 +339,7 @@ export interface DB {
trek_photos: TrekPhotosTable;
trip_addon_overrides: TripAddonOverridesTable;
trip_album_links: TripAlbumLinksTable;
trip_collection_links: TripCollectionLinksTable;
trip_document_links: TripDocumentLinksTable;
trip_files: TripFilesTable;
trip_invite_tokens: TripInviteTokensTable;
@@ -344,6 +350,10 @@ export interface DB {
trip_photos: TripPhotosTable;
trips: TripsTable;
user_notice_dismissals: UserNoticeDismissalsTable;
user_place_links: UserPlaceLinksTable;
user_place_merge_dismissals: UserPlaceMergeDismissalsTable;
user_place_merges: UserPlaceMergesTable;
user_places: UserPlacesTable;
user_sessions: UserSessionsTable;
users: UsersTable;
vacay_company_holidays: VacayCompanyHolidaysTable;
@@ -0,0 +1,115 @@
import { engineDdl } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* D5/PLC-13: a person's own idea of which trip places and saved places are one
* place. Nothing here is shared: every row belongs to one account and only
* groups that account's "All places".
*
* `user_places` is one place as the user sees it, with the name and position
* they chose for it. It is never written back into a trip or a list. A row
* only comes into being by an explicit action (assigning or merging); one that
* was merged into another keeps `merged_into_id` so the merge can be taken back.
*
* `user_place_links` ties one use (a trip place or a saved place, exactly one
* of the two) to an identity. A use belongs to at most one identity per user.
* The links go with the use, so a deleted place or list drops them; an identity
* left without links is removed by the service, not here.
*
* `user_place_merges` keeps what a merge moved (the link ids, JSON) so it can
* be undone, and `user_place_merge_dismissals` the duplicate suggestions the
* user turned down, by the two entry keys in order.
*/
export class Migration20200101046530_a_user_keeps_their_own_place_identities extends Migration {
override name = 'Migration20200101046530_a_user_keeps_their_own_place_identities';
override up(): void {
engineDdl(this, {
sqlite: [
`CREATE TABLE user_places (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
name TEXT NOT NULL,
lat REAL,
lng REAL,
address TEXT,
category_id INTEGER REFERENCES categories(id) ON DELETE SET NULL,
google_place_id TEXT,
google_ftid TEXT,
osm_id TEXT,
merged_into_id INTEGER REFERENCES user_places(id) ON DELETE SET NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
'CREATE INDEX idx_user_places_user_id ON user_places(user_id)',
'CREATE INDEX idx_user_places_category_id ON user_places(category_id)',
'CREATE INDEX idx_user_places_merged_into_id ON user_places(merged_into_id)',
`CREATE TABLE user_place_links (
id INTEGER PRIMARY KEY,
user_place_id INTEGER NOT NULL REFERENCES user_places(id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
place_id INTEGER REFERENCES places(id) ON DELETE CASCADE,
collection_place_id INTEGER REFERENCES collection_places(id) ON DELETE CASCADE
CHECK ((place_id IS NULL) <> (collection_place_id IS NULL)),
linked_by TEXT NOT NULL DEFAULT 'user' CHECK (linked_by IN ('user', 'merge')),
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE (user_id, place_id),
UNIQUE (user_id, collection_place_id)
)`,
'CREATE INDEX idx_user_place_links_user_place_id ON user_place_links(user_place_id)',
'CREATE INDEX idx_user_place_links_place_id ON user_place_links(place_id)',
'CREATE INDEX idx_user_place_links_collection_place_id ON user_place_links(collection_place_id)',
`CREATE TABLE user_place_merges (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
leading_id INTEGER NOT NULL REFERENCES user_places(id) ON DELETE CASCADE,
merged_id INTEGER NOT NULL REFERENCES user_places(id) ON DELETE CASCADE,
moved_link_ids TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)`,
'CREATE INDEX idx_user_place_merges_user_id ON user_place_merges(user_id)',
'CREATE INDEX idx_user_place_merges_leading_id ON user_place_merges(leading_id)',
'CREATE INDEX idx_user_place_merges_merged_id ON user_place_merges(merged_id)',
`CREATE TABLE user_place_merge_dismissals (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
key_a TEXT NOT NULL,
key_b TEXT NOT NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE (user_id, key_a, key_b)
)`,
],
postgres: [
'create table "user_places" ("id" bigserial primary key, "user_id" bigint not null, "name" text not null, "lat" double precision null, "lng" double precision null, "address" text null, "category_id" bigint null, "google_place_id" text null, "google_ftid" text null, "osm_id" text null, "merged_into_id" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'), "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'))',
'create index "idx_user_places_user_id" on "user_places" ("user_id")',
'create index "idx_user_places_category_id" on "user_places" ("category_id")',
'create index "idx_user_places_merged_into_id" on "user_places" ("merged_into_id")',
'create table "user_place_links" ("id" bigserial primary key, "user_place_id" bigint not null, "user_id" bigint not null, "place_id" bigint null, "collection_place_id" bigint null, "linked_by" text not null default \'user\', "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'))',
'create index "idx_user_place_links_user_place_id" on "user_place_links" ("user_place_id")',
'create index "idx_user_place_links_place_id" on "user_place_links" ("place_id")',
'create index "idx_user_place_links_collection_place_id" on "user_place_links" ("collection_place_id")',
'alter table "user_place_links" add constraint "user_place_links_user_id_collection_place_id_unique" unique ("user_id", "collection_place_id")',
'alter table "user_place_links" add constraint "user_place_links_user_id_place_id_unique" unique ("user_id", "place_id")',
'alter table "user_place_links" add constraint "user_place_links_collection_place_id_check" check ((place_id IS NULL) <> (collection_place_id IS NULL))',
'alter table "user_place_links" add constraint "user_place_links_linked_by_check" check ("linked_by" in (\'user\', \'merge\'))',
'create table "user_place_merges" ("id" bigserial primary key, "user_id" bigint not null, "leading_id" bigint not null, "merged_id" bigint not null, "moved_link_ids" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'))',
'create index "idx_user_place_merges_user_id" on "user_place_merges" ("user_id")',
'create index "idx_user_place_merges_leading_id" on "user_place_merges" ("leading_id")',
'create index "idx_user_place_merges_merged_id" on "user_place_merges" ("merged_id")',
'create table "user_place_merge_dismissals" ("id" bigserial primary key, "user_id" bigint not null, "key_a" text not null, "key_b" text not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'))',
'alter table "user_place_merge_dismissals" add constraint "user_place_merge_dismissals_user_id_key_a_key_b_unique" unique ("user_id", "key_a", "key_b")',
'alter table "user_places" add constraint "user_places_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade',
'alter table "user_places" add constraint "user_places_category_id_foreign" foreign key ("category_id") references "categories" ("id") on delete set null',
'alter table "user_places" add constraint "user_places_merged_into_id_foreign" foreign key ("merged_into_id") references "user_places" ("id") on delete set null',
'alter table "user_place_links" add constraint "user_place_links_user_place_id_foreign" foreign key ("user_place_id") references "user_places" ("id") on delete cascade',
'alter table "user_place_links" add constraint "user_place_links_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade',
'alter table "user_place_links" add constraint "user_place_links_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade',
'alter table "user_place_links" add constraint "user_place_links_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on delete cascade',
'alter table "user_place_merges" add constraint "user_place_merges_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade',
'alter table "user_place_merges" add constraint "user_place_merges_leading_id_foreign" foreign key ("leading_id") references "user_places" ("id") on delete cascade',
'alter table "user_place_merges" add constraint "user_place_merges_merged_id_foreign" foreign key ("merged_id") references "user_places" ("id") on delete cascade',
'alter table "user_place_merge_dismissals" add constraint "user_place_merge_dismissals_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete cascade',
],
});
}
}
@@ -0,0 +1,38 @@
import { engineDdl } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* PLC-15/PLC-16: a trip can name lists of saved places it draws on. The link
* gives nobody access: a member of the trip sees a linked list only when the
* list is open to them anyway. It goes with the trip and with the list;
* `linked_by` names who linked it, kept as unknown when that account goes.
*/
export class Migration20200101046540_a_trip_links_its_collections extends Migration {
override name = 'Migration20200101046540_a_trip_links_its_collections';
override up(): void {
engineDdl(this, {
sqlite: [
`CREATE TABLE trip_collection_links (
id INTEGER PRIMARY KEY,
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
collection_id INTEGER NOT NULL REFERENCES collections(id) ON DELETE CASCADE,
linked_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
UNIQUE (trip_id, collection_id)
)`,
'CREATE INDEX idx_trip_collection_links_collection_id ON trip_collection_links(collection_id)',
'CREATE INDEX idx_trip_collection_links_linked_by ON trip_collection_links(linked_by)',
],
postgres: [
'create table "trip_collection_links" ("id" bigserial primary key, "trip_id" bigint not null, "collection_id" bigint not null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'), "linked_by" bigint null)',
'create index "idx_trip_collection_links_collection_id" on "trip_collection_links" ("collection_id")',
'create index "idx_trip_collection_links_linked_by" on "trip_collection_links" ("linked_by")',
'alter table "trip_collection_links" add constraint "trip_collection_links_trip_id_collection_id_unique" unique ("trip_id", "collection_id")',
'alter table "trip_collection_links" add constraint "trip_collection_links_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on delete cascade',
'alter table "trip_collection_links" add constraint "trip_collection_links_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade',
'alter table "trip_collection_links" add constraint "trip_collection_links_linked_by_foreign" foreign key ("linked_by") references "users" ("id") on delete set null',
],
});
}
}
@@ -151,14 +151,16 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
/** `UPDATE collection_places SET sort_order=? WHERE id=? AND collection_id=?`, per place, inside the caller's transaction. */
async setSortOrders(collectionId: number, orderedIds: number[]): Promise<void> {
for (const [position, id] of orderedIds.entries()) {
await this.db_()
.updateTable('collection_places')
.set({ sort_order: position })
.where('id', '=', id)
.where('collection_id', '=', collectionId)
.execute();
}
await Promise.all(
orderedIds.map((id, position) =>
this.db_()
.updateTable('collection_places')
.set({ sort_order: position })
.where('id', '=', id)
.where('collection_id', '=', collectionId)
.execute(),
),
);
}
// ---------------------------------------------------------------------
@@ -25,6 +25,8 @@ type LibraryDB = Pick<
| 'place_ratings'
| 'day_assignments'
| 'days'
| 'user_places'
| 'user_place_links'
>;
/**
@@ -35,18 +37,33 @@ type LibraryDB = Pick<
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 };
/**
* The road trip stops that belong to the drive rather than to the places of
* the trip. Lodging ('hotel') is a place like any other, as it is in Days.
*/
const DRIVE_STOP_TYPES = SERVICE_STOP_TYPES.filter((type) => type !== 'hotel');
/**
* How one number names an entry: `id * 4 + kind`, the id being the user's own
* place (D5), else the trip place, else the saved place the entry stands for.
* Being one number, it orders, pages and counts like a column.
*/
export const ANCHOR_TRIP = 1;
export const ANCHOR_LIST = 2;
export const ANCHOR_OWN = 3;
export const ANCHOR_SPAN = 4;
/**
* What the list reads. A side turned off by a filter (only lists, one trip)
* comes with no ids for it; `reachableTripIds` stays every trip the user can
* open, because a saved place groups with a place of any of them.
* open, because a saved place groups with a place of any of them. `userId`
* names whose own places group the entries.
*/
export interface LibraryArms {
userId: number;
/** The trips whose places are listed. */
tripIds: number[];
/** The lists whose saved places are listed. */
@@ -72,10 +89,7 @@ export interface LibraryPosition {
export type LibrarySort = 'name' | 'updated';
/**
* One entry of a page: `key` is the trip place id when the entry has one,
* else the saved place id negated, so one number names an entry.
*/
/** One entry of a page, named by its anchor (see `ANCHOR_SPAN`). */
export interface LibraryAnchorRow {
anchor_key: number;
sort_name: string;
@@ -85,6 +99,18 @@ export interface LibraryAnchorRow {
interface UnionRow extends LibraryAnchorRow {
/** 1 when the row came from a list of saved places. */
from_list: number;
/** The trip place or saved place of the row. */
use_id: number;
/** 1 when the user assigned this use to an own place of theirs. */
linked: number;
}
/** One use of an entry: a trip place (from_list 0) or a saved place, and whether the user linked it. */
export interface LibraryUseRow {
anchor_key: number;
from_list: number;
use_id: number;
linked: boolean;
}
interface LibraryCounts {
@@ -103,6 +129,9 @@ interface PlaceFactsRow {
description: string | null;
website: string | null;
phone: string | null;
google_place_id: string | null;
google_ftid: string | null;
osm_id: string | null;
category_id: number | null;
category_name: string | null;
category_color: string | null;
@@ -123,8 +152,23 @@ export interface LibraryCollectionPlaceRow extends PlaceFactsRow {
collection_id: number;
collection_name: string;
status: string;
/** The trip place this saved place is grouped with, if any. */
grouped_place_id: number | null;
}
/** A user's own place (D5), with its category. */
export interface LibraryIdentityRow {
id: number;
name: string;
address: string | null;
lat: number | null;
lng: number | null;
google_place_id: string | null;
google_ftid: string | null;
osm_id: string | null;
updated_at: string | null;
category_id: number | null;
category_name: string | null;
category_color: string | null;
category_icon: string | null;
}
interface LibraryCollectionRole {
@@ -175,6 +219,12 @@ interface LibraryDayRow {
* the two agree: the same provider id, or the same name (trimmed, case
* ignored) within `COORD_DEDUP_TOLERANCE` and no provider id that differs.
* A name alone never groups anything.
*
* Above that, a use the user linked to an own place of theirs (D5,
* `user_place_links`) stands for that place's entry, and so does a saved place
* grouped with a linked trip place unless it is linked itself. Only uses the
* user reaches today come out, so an own place none of whose uses is open to
* them any more has no entry.
*/
export class PlacesLibraryRepository {
constructor(private readonly em: EntityManager) {}
@@ -244,16 +294,37 @@ export class PlacesLibraryRepository {
});
}
/** The trip places of the list, one row each. */
/** The trip places of the list, one row each; one the user linked stands for their own place's entry. */
private tripArm(db: Kysely<LibraryDB>, arms: LibraryArms, match: LibraryMatch) {
const platform = this.em.getPlatform();
return db
.selectFrom('places as p')
.leftJoin('user_place_links as ul', (join) =>
join.onRef('ul.place_id', '=', 'p.id').on('ul.user_id', '=', arms.userId),
)
.leftJoin('user_places as up', 'up.id', 'ul.user_place_id')
.select((eb) => [
'p.id as anchor_key',
eb.fn<string>('lower', ['p.name']).as('sort_name'),
eb.fn.coalesce('p.updated_at', eb.val('')).as('sort_time'),
eb.fn
.coalesce(
eb(
eb('ul.user_place_id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(),
'+',
eb.lit(ANCHOR_OWN),
).$castTo<number>(),
eb(eb('p.id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(), '+', eb.lit(ANCHOR_TRIP)).$castTo<number>(),
)
.as('anchor_key'),
eb.fn<string>('lower', [eb.fn.coalesce('up.name', 'p.name')]).as('sort_name'),
eb
.case()
.when('up.id', 'is not', null)
.then(eb.fn.coalesce('up.updated_at', eb.val('')))
.else(eb.fn.coalesce('p.updated_at', eb.val('')))
.end()
.as('sort_time'),
eb.cast<number>(eb.lit(0), 'integer').as('from_list'),
'p.id as use_id',
eb.case().when('ul.id', 'is not', null).then(eb.lit(1)).else(eb.lit(0)).end().as('linked'),
])
.where((eb) => {
const conditions: Expression<SqlBool>[] = [
@@ -275,24 +346,60 @@ export class PlacesLibraryRepository {
.$castTo<UnionRow>();
}
/** The saved places of the list; one grouped with a trip place stands for that place's entry. */
/**
* The saved places of the list. One the user linked stands for their own
* place's entry; one grouped with a trip place stands for that place's entry,
* or for the own place that trip place is linked to.
*/
private listArm(db: Kysely<LibraryDB>, arms: LibraryArms, match: LibraryMatch) {
const platform = this.em.getPlatform();
return db
.selectFrom('collection_places as cp')
.leftJoin(this.groupLinks(db, arms.reachableTripIds).as('gl'), 'gl.collection_place_id', 'cp.id')
.leftJoin('places as g', 'g.id', 'gl.place_id')
.leftJoin('user_place_links as ulc', (join) =>
join.onRef('ulc.collection_place_id', '=', 'cp.id').on('ulc.user_id', '=', arms.userId),
)
.leftJoin('user_place_links as ulg', (join) =>
join.onRef('ulg.place_id', '=', 'gl.place_id').on('ulg.user_id', '=', arms.userId),
)
.leftJoin('user_places as up', (join) =>
join.on((eb) => eb('up.id', '=', eb.fn.coalesce('ulc.user_place_id', 'ulg.user_place_id'))),
)
.select((eb) => [
eb.fn.coalesce('gl.place_id', eb.neg('cp.id')).as('anchor_key'),
eb.fn<string>('lower', [eb.fn.coalesce('g.name', 'cp.name')]).as('sort_name'),
eb.fn
.coalesce(
eb(
eb('ulc.user_place_id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(),
'+',
eb.lit(ANCHOR_OWN),
).$castTo<number>(),
eb(
eb('ulg.user_place_id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(),
'+',
eb.lit(ANCHOR_OWN),
).$castTo<number>(),
eb(
eb('gl.place_id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(),
'+',
eb.lit(ANCHOR_TRIP),
).$castTo<number>(),
eb(eb('cp.id', '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(), '+', eb.lit(ANCHOR_LIST)).$castTo<number>(),
)
.as('anchor_key'),
eb.fn<string>('lower', [eb.fn.coalesce('up.name', 'g.name', 'cp.name')]).as('sort_name'),
eb
.case()
.when('up.id', 'is not', null)
.then(eb.fn.coalesce('up.updated_at', eb.val('')))
.when('gl.place_id', 'is not', null)
.then(eb.fn.coalesce('g.updated_at', eb.val('')))
.else(eb.fn.coalesce('cp.updated_at', eb.val('')))
.end()
.as('sort_time'),
eb.cast<number>(eb.lit(1), 'integer').as('from_list'),
'cp.id as use_id',
eb.case().when('ulc.id', 'is not', null).then(eb.lit(1)).else(eb.lit(0)).end().as('linked'),
])
.where((eb) => {
const conditions: Expression<SqlBool>[] = [eb('cp.collection_id', 'in', idsOrNone(arms.collectionIds))];
@@ -325,7 +432,7 @@ export class PlacesLibraryRepository {
.select((eb) => [
eb.fn.count<number>('u.anchor_key').distinct().as('all'),
eb.fn
.count<number>(eb.case().when('u.anchor_key', '>', 0).then(eb.ref('u.anchor_key')).end())
.count<number>(eb.case().when('u.from_list', '=', 0).then(eb.ref('u.anchor_key')).end())
.distinct()
.as('trip'),
eb.fn
@@ -373,31 +480,36 @@ export class PlacesLibraryRepository {
}));
}
/** The trip place `placeId` when it is a normal place of one of `tripIds`. */
async findTripPlace(placeId: number, tripIds: number[]): Promise<number | null> {
/**
* The uses of the entries `anchors` the user reaches (every use when
* `anchors` is null), with the entry each stands for: trip places first,
* then saved places, each in id order.
*/
async usesOf(arms: LibraryArms, anchors: number[] | null): Promise<LibraryUseRow[]> {
const db = this.db();
const row = await db
.selectFrom('places as p')
.select('p.id')
.where('p.id', '=', placeId)
.where('p.id', 'in', this.normalPlaceIds(db, tripIds))
.executeTakeFirst();
return row ? row.id : null;
const rows = await db
.selectFrom(this.entries(db, arms, NO_MATCH))
.select(['u.anchor_key', 'u.from_list', 'u.use_id', 'u.linked'])
.$if(anchors !== null, (qb) => qb.where('u.anchor_key', 'in', idsOrNone(anchors ?? [])))
.orderBy('u.from_list')
.orderBy('u.use_id')
.execute();
return rows.map((row) => ({
anchor_key: Number(row.anchor_key),
from_list: Number(row.from_list),
use_id: Number(row.use_id),
linked: Number(row.linked) === 1,
}));
}
/** The entry key of the saved place `collectionPlaceId` when it is in one of `collectionIds`. */
async findSavedPlaceKey(
collectionPlaceId: number,
collectionIds: number[],
reachableTripIds: number[],
): Promise<number | null> {
/** The entry the use stands for (from_list 0: a trip place, 1: a saved place), when the user reaches it. */
async anchorOfUse(arms: LibraryArms, fromList: number, useId: number): Promise<number | null> {
const db = this.db();
const row = await db
.selectFrom('collection_places as cp')
.leftJoin(this.groupLinks(db, reachableTripIds).as('gl'), 'gl.collection_place_id', 'cp.id')
.select((eb) => eb.fn.coalesce('gl.place_id', eb.neg('cp.id')).as('anchor_key'))
.where('cp.id', '=', collectionPlaceId)
.where('cp.collection_id', 'in', idsOrNone(collectionIds))
.selectFrom(this.entries(db, arms, NO_MATCH))
.select('u.anchor_key')
.where('u.from_list', '=', fromList)
.where('u.use_id', '=', useId)
.executeTakeFirst();
return row ? Number(row.anchor_key) : null;
}
@@ -420,6 +532,9 @@ export class PlacesLibraryRepository {
'p.description',
'p.website',
'p.phone',
'p.google_place_id',
'p.google_ftid',
'p.osm_id',
'c.id as category_id',
'c.name as category_name',
'c.color as category_color',
@@ -431,25 +546,15 @@ export class PlacesLibraryRepository {
])
.where('p.id', 'in', idsOrNone(placeIds))
.where('p.trip_id', 'in', idsOrNone(tripIds))
.orderBy('p.id')
.execute();
}
/**
* The saved places of `collectionIds` that are named by `ids` or grouped
* with one of the trip places `groupedTo`, each with its list and the trip
* place it is grouped with, ordered by list name.
*/
async savedPlaces(
collectionIds: number[],
reachableTripIds: number[],
ids: number[],
groupedTo: number[],
): Promise<LibraryCollectionPlaceRow[]> {
const db = this.db();
const rows = await db
/** The saved places `ids` of `collectionIds`, each with its list, ordered by list name. */
async savedPlaces(collectionIds: number[], ids: number[]): Promise<LibraryCollectionPlaceRow[]> {
return await this.db()
.selectFrom('collection_places as cp')
.innerJoin('collections as col', 'col.id', 'cp.collection_id')
.leftJoin(this.groupLinks(db, reachableTripIds).as('gl'), 'gl.collection_place_id', 'cp.id')
.leftJoin('categories as c', 'c.id', 'cp.category_id')
.select([
'cp.id',
@@ -465,21 +570,44 @@ export class PlacesLibraryRepository {
'cp.description',
'cp.website',
'cp.phone',
'cp.google_place_id',
'cp.google_ftid',
'cp.osm_id',
'c.id as category_id',
'c.name as category_name',
'c.color as category_color',
'c.icon as category_icon',
'gl.place_id as grouped_place_id',
])
.where('cp.collection_id', 'in', idsOrNone(collectionIds))
.where((eb) => eb.or([eb('cp.id', 'in', idsOrNone(ids)), eb('gl.place_id', 'in', idsOrNone(groupedTo))]))
.where('cp.id', 'in', idsOrNone(ids))
.orderBy('col.name')
.orderBy('cp.id')
.execute();
return rows.map((row) => ({
...row,
grouped_place_id: row.grouped_place_id === null ? null : Number(row.grouped_place_id),
}));
}
/** The user's own places `ids`, with their category. */
async identities(userId: number, ids: number[]): Promise<LibraryIdentityRow[]> {
return await this.db()
.selectFrom('user_places as up')
.leftJoin('categories as c', 'c.id', 'up.category_id')
.select([
'up.id',
'up.name',
'up.address',
'up.lat',
'up.lng',
'up.google_place_id',
'up.google_ftid',
'up.osm_id',
'up.updated_at',
'c.id as category_id',
'c.name as category_name',
'c.color as category_color',
'c.icon as category_icon',
])
.where('up.user_id', '=', userId)
.where('up.id', 'in', idsOrNone(ids))
.execute();
}
/**
@@ -0,0 +1,173 @@
import type { TripCollectionLinks } from '../entities/TripCollectionLinks.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
import { COORD_DEDUP_TOLERANCE } from '@trek/shared';
type TripCollectionLinksDB = Pick<
DB,
'trip_collection_links' | 'collections' | 'collection_places' | 'categories' | 'places'
>;
/** Kysely cannot bind an empty IN list and no row has the id 0, so none reads as this. */
const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [0]);
/** A list linked to a trip, with how many saved places it holds. */
interface TripCollectionLinkRow {
collection_id: number;
name: string;
color: string | null;
owner_id: number;
linked_by: number | null;
created_at: string | null;
place_count: number;
}
/** A saved place of a linked list with a position, and the trip place it already is, if any. */
interface TripCollectionLayerRow {
id: number;
collection_id: number;
name: string;
lat: number;
lng: number;
status: string;
category_id: number | null;
category_name: string | null;
category_color: string | null;
category_icon: string | null;
trip_place_id: number | null;
}
/**
* `trip_collection_links` (PLC-15/PLC-16): the lists a trip draws on. Every
* method takes ids the caller checked; who may see which list is decided in
* the service, never here.
*/
export class TripCollectionLinksRepository extends TrekRepository<TripCollectionLinks> {
private db() {
return this.kysely<TripCollectionLinksDB>();
}
/** The lists linked to the trip, by list name. */
async listForTrip(tripId: number): Promise<TripCollectionLinkRow[]> {
const rows = await this.db()
.selectFrom('trip_collection_links as l')
.innerJoin('collections as c', 'c.id', 'l.collection_id')
.select((eb) => [
'l.collection_id',
'c.name',
'c.color',
'c.owner_id',
'l.linked_by',
'l.created_at',
eb
.selectFrom('collection_places as cp')
.select((inner) => inner.fn.countAll<number>().as('n'))
.whereRef('cp.collection_id', '=', 'l.collection_id')
.as('place_count'),
])
.where('l.trip_id', '=', tripId)
.orderBy('c.name')
.orderBy('l.collection_id')
.execute();
return rows.map((row) => ({ ...row, place_count: Number(row.place_count ?? 0) }));
}
/** Links the list to the trip; linking it twice keeps the first link. */
async link(tripId: number, collectionId: number, userId: number): Promise<void> {
await this.db()
.insertInto('trip_collection_links')
.values({ trip_id: tripId, collection_id: collectionId, linked_by: userId })
.onConflict((oc) => oc.columns(['trip_id', 'collection_id']).doNothing())
.execute();
}
/** Unlinks the list from the trip; answers whether there was a link. */
async unlink(tripId: number, collectionId: number): Promise<boolean> {
const result = await this.db()
.deleteFrom('trip_collection_links')
.where('trip_id', '=', tripId)
.where('collection_id', '=', collectionId)
.executeTakeFirst();
return Number(result.numDeletedRows) > 0;
}
/**
* The saved places with a position of `collectionIds`, each with the place
* of the trip it already is, by the rule "All places" groups a saved place
* with the trip place it came from: the same provider id, or the same name
* (trimmed, case ignored) within `COORD_DEDUP_TOLERANCE` and no provider id
* that differs. The stored source alone proves nothing, since any editor of
* the list may have written it. By list, then by name.
*/
async layerPlaces(tripId: number, collectionIds: number[]): Promise<TripCollectionLayerRow[]> {
const rows = await this.db()
.selectFrom('collection_places as cp')
.leftJoin('categories as c', 'c.id', 'cp.category_id')
.select((eb) => [
'cp.id',
'cp.collection_id',
'cp.name',
'cp.lat',
'cp.lng',
'cp.status',
'c.id as category_id',
'c.name as category_name',
'c.color as category_color',
'c.icon as category_icon',
eb
.selectFrom('places as p')
.select('p.id')
.where('p.trip_id', '=', tripId)
.where((m) => {
const given = (ref: 'cp.google_place_id' | 'cp.google_ftid' | 'cp.osm_id') =>
m.and([m(ref, 'is not', null), m(ref, '<>', '')]);
const near = (saved: 'cp.lat' | 'cp.lng', trip: 'p.lat' | 'p.lng') =>
m(m.fn<number>('abs', [m(saved, '-', m.ref(trip))]), '<=', COORD_DEDUP_TOLERANCE);
const providers = [
['cp.google_place_id', 'p.google_place_id'],
['cp.google_ftid', 'p.google_ftid'],
['cp.osm_id', 'p.osm_id'],
] as const;
const same = providers.map(([saved, trip]) => m.and([given(saved), m(saved, '=', m.ref(trip))]));
const differ = providers.map(([saved, trip]) =>
m.and([given(saved), m(trip, 'is not', null), m(trip, '<>', ''), m(saved, '<>', m.ref(trip))]),
);
return m.or([
...same,
m.and([
m(
m.fn<string>('lower', [m.fn<string>('trim', ['cp.name'])]),
'=',
m.fn<string>('lower', [m.fn<string>('trim', ['p.name'])]),
),
near('cp.lat', 'p.lat'),
near('cp.lng', 'p.lng'),
m.not(m.or(differ)),
]),
]);
})
.orderBy('p.id')
.limit(1)
.as('trip_place_id'),
])
.where('cp.collection_id', 'in', idsOrNone(collectionIds))
.where('cp.lat', 'is not', null)
.where('cp.lng', 'is not', null)
.orderBy('cp.collection_id')
.orderBy('cp.name')
.orderBy('cp.id')
.execute();
return rows.flatMap((row) =>
row.lat === null || row.lng === null
? []
: [
{
...row,
lat: row.lat,
lng: row.lng,
trip_place_id: row.trip_place_id === null ? null : Number(row.trip_place_id),
},
],
);
}
}
@@ -0,0 +1,113 @@
import type { TUserPlaceLinksLinkedBy, UserPlaceLinks } from '../entities/UserPlaceLinks.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type UserPlaceLinksDB = Pick<DB, 'user_place_links'>;
/** One use as a link names it: a trip place or a saved place. */
export interface LinkedUse {
kind: 'trip' | 'list';
id: number;
}
/** A link as the writes read it. */
interface UserPlaceLinkRef {
id: number;
user_place_id: number;
}
/**
* `user_place_links`: which use belongs to which own place of a person (D5).
* A use belongs to one own place per person at most, which the unique keys on
* (user, place) and (user, saved place) hold.
*/
export class UserPlaceLinksRepository extends TrekRepository<UserPlaceLinks> {
private db() {
return this.kysely<UserPlaceLinksDB>();
}
async findForUse(userId: number, use: LinkedUse): Promise<UserPlaceLinkRef | null> {
const row = await this.db()
.selectFrom('user_place_links')
.select(['id', 'user_place_id'])
.where('user_id', '=', userId)
.where(use.kind === 'trip' ? 'place_id' : 'collection_place_id', '=', use.id)
.executeTakeFirst();
return row ?? null;
}
/** Takes the uses out of whichever own place of the user holds them. */
async detach(userId: number, uses: readonly LinkedUse[]): Promise<void> {
if (uses.length === 0) return;
const placeIds = uses.filter((use) => use.kind === 'trip').map((use) => use.id);
const savedIds = uses.filter((use) => use.kind === 'list').map((use) => use.id);
await this.db()
.deleteFrom('user_place_links')
.where('user_id', '=', userId)
.where((eb) =>
eb.or([
eb('place_id', 'in', placeIds.length > 0 ? placeIds : [0]),
eb('collection_place_id', 'in', savedIds.length > 0 ? savedIds : [0]),
]),
)
.execute();
}
/** Links uses no own place of the user holds (`detach` first) to `userPlaceId`; answers the new ids. */
async insert(
userId: number,
userPlaceId: number,
uses: readonly LinkedUse[],
linkedBy: TUserPlaceLinksLinkedBy,
): Promise<number[]> {
if (uses.length === 0) return [];
const rows = await this.db()
.insertInto('user_place_links')
.values(
uses.map((use) => ({
user_place_id: userPlaceId,
user_id: userId,
place_id: use.kind === 'trip' ? use.id : null,
collection_place_id: use.kind === 'list' ? use.id : null,
linked_by: linkedBy,
})),
)
.returning('id')
.execute();
return rows.map((row) => row.id);
}
async deleteOwn(userId: number, id: number): Promise<void> {
await this.db().deleteFrom('user_place_links').where('id', '=', id).where('user_id', '=', userId).execute();
}
/** The ids of the links the own place holds. */
async idsOf(userId: number, userPlaceId: number): Promise<number[]> {
const rows = await this.db()
.selectFrom('user_place_links')
.select('id')
.where('user_id', '=', userId)
.where('user_place_id', '=', userPlaceId)
.orderBy('id')
.execute();
return rows.map((row) => row.id);
}
/** Moves the user's links `ids` to the own place `userPlaceId`; a link gone by now is skipped. */
async moveTo(userId: number, ids: number[], userPlaceId: number): Promise<void> {
if (ids.length === 0) return;
await this.db()
.updateTable('user_place_links')
.set({ user_place_id: userPlaceId })
.where('user_id', '=', userId)
.where('id', 'in', ids)
.execute();
}
/** Which of the links `ids` still exist. */
async existing(ids: number[]): Promise<number[]> {
if (ids.length === 0) return [];
const rows = await this.db().selectFrom('user_place_links').select('id').where('id', 'in', ids).execute();
return rows.map((row) => row.id);
}
}
@@ -0,0 +1,35 @@
import type { UserPlaceMergeDismissals } from '../entities/UserPlaceMergeDismissals.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type DismissalsDB = Pick<DB, 'user_place_merge_dismissals'>;
/** A turned-down suggestion by its two entry keys, the smaller first. */
interface DismissedPair {
key_a: string;
key_b: string;
}
/** `user_place_merge_dismissals`: the duplicate suggestions a person turned down, so they do not come back. */
export class UserPlaceMergeDismissalsRepository extends TrekRepository<UserPlaceMergeDismissals> {
private db() {
return this.kysely<DismissalsDB>();
}
/** Keeps the pair; turning it down twice changes nothing. */
async dismiss(userId: number, pair: DismissedPair): Promise<void> {
await this.db()
.insertInto('user_place_merge_dismissals')
.values({ user_id: userId, key_a: pair.key_a, key_b: pair.key_b })
.onConflict((oc) => oc.columns(['user_id', 'key_a', 'key_b']).doNothing())
.execute();
}
async listForUser(userId: number): Promise<DismissedPair[]> {
return await this.db()
.selectFrom('user_place_merge_dismissals')
.select(['key_a', 'key_b'])
.where('user_id', '=', userId)
.execute();
}
}
@@ -0,0 +1,54 @@
import type { UserPlaceMerges } from '../entities/UserPlaceMerges.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type UserPlaceMergesDB = Pick<DB, 'user_place_merges'>;
/** A merge as its undo reads it; `moved_link_ids` is the stored JSON, decoded by the service. */
interface UserPlaceMergeRow {
id: number;
leading_id: number;
merged_id: number;
moved_link_ids: string;
}
/** `user_place_merges`: what a merge of two own places moved, kept until it is undone or nothing of it is left. */
export class UserPlaceMergesRepository extends TrekRepository<UserPlaceMerges> {
private db() {
return this.kysely<UserPlaceMergesDB>();
}
async create(userId: number, leadingId: number, mergedId: number, movedLinkIds: string): Promise<number> {
const row = await this.db()
.insertInto('user_place_merges')
.values({ user_id: userId, leading_id: leadingId, merged_id: mergedId, moved_link_ids: movedLinkIds })
.returning('id')
.executeTakeFirstOrThrow();
return row.id;
}
async findOwn(userId: number, id: number): Promise<UserPlaceMergeRow | null> {
const row = await this.db()
.selectFrom('user_place_merges')
.select(['id', 'leading_id', 'merged_id', 'moved_link_ids'])
.where('id', '=', id)
.where('user_id', '=', userId)
.executeTakeFirst();
return row ?? null;
}
/** The merges of `userId`, of everyone when null. */
async list(userId: number | null): Promise<UserPlaceMergeRow[]> {
return await this.db()
.selectFrom('user_place_merges')
.select(['id', 'leading_id', 'merged_id', 'moved_link_ids'])
.$if(userId !== null, (qb) => qb.where('user_id', '=', userId ?? 0))
.orderBy('id')
.execute();
}
async deleteIds(ids: number[]): Promise<void> {
if (ids.length === 0) return;
await this.db().deleteFrom('user_place_merges').where('id', 'in', ids).execute();
}
}
@@ -0,0 +1,126 @@
import type { UserPlaces } from '../entities/UserPlaces.entity';
import type { DB } from '../kysely/db';
import { dbNow } from '../types';
import { TrekRepository } from './_shared/trek-repository';
type UserPlacesDB = Pick<DB, 'user_places' | 'user_place_links' | 'user_place_merges'>;
/** The facts a new own place starts from, taken from the use the user picked. */
export interface UserPlaceFacts {
name: string;
lat: number | null;
lng: number | null;
address: string | null;
category_id: number | null;
google_place_id: string | null;
google_ftid: string | null;
osm_id: string | null;
}
/** An own place as the writes check it. */
interface UserPlaceRef {
id: number;
merged_into_id: number | null;
}
/** How many links an own place holds, reachable or not. */
interface UserPlaceLinkCount {
id: number;
links: number;
}
/**
* `user_places`: a person's own places (D5). Every method takes the owner
* along, so one account never reads or writes another's.
*/
export class UserPlacesRepository extends TrekRepository<UserPlaces> {
private db() {
return this.kysely<UserPlacesDB>();
}
async create(userId: number, facts: UserPlaceFacts): Promise<number> {
const row = await this.db()
.insertInto('user_places')
.values({ user_id: userId, ...facts })
.returning('id')
.executeTakeFirstOrThrow();
return row.id;
}
async findOwn(userId: number, id: number): Promise<UserPlaceRef | null> {
const row = await this.db()
.selectFrom('user_places')
.select(['id', 'merged_into_id'])
.where('id', '=', id)
.where('user_id', '=', userId)
.executeTakeFirst();
return row ?? null;
}
/** Marks the place merged into `into` (null: on its own again) and changed now. */
async setMergedInto(userId: number, id: number, into: number | null): Promise<void> {
await this.db()
.updateTable('user_places')
.set({ merged_into_id: into, updated_at: dbNow() })
.where('id', '=', id)
.where('user_id', '=', userId)
.execute();
}
async touch(userId: number, id: number): Promise<void> {
await this.db()
.updateTable('user_places')
.set({ updated_at: dbNow() })
.where('id', '=', id)
.where('user_id', '=', userId)
.execute();
}
/** The links each of the own places `ids` holds, uses the user no longer reaches included. */
async linkCounts(userId: number, ids: number[]): Promise<UserPlaceLinkCount[]> {
if (ids.length === 0) return [];
const rows = await this.db()
.selectFrom('user_place_links')
.select((eb) => ['user_place_id as id', eb.fn.countAll<number>().as('links')])
.where('user_id', '=', userId)
.where('user_place_id', 'in', ids)
.groupBy('user_place_id')
.execute();
return rows.map((row) => ({ id: Number(row.id), links: Number(row.links) }));
}
/**
* Deletes the own places of `userId` (of everyone when null) that hold no
* link and no merge still names, so nothing copied from a trip or list stays
* behind once its last use is gone. Answers how many went.
*/
async pruneEmpty(userId: number | null): Promise<number> {
const result = await this.db()
.deleteFrom('user_places')
.$if(userId !== null, (qb) => qb.where('user_id', '=', userId ?? 0))
.where((eb) =>
eb.and([
eb.not(
eb.exists(
eb.selectFrom('user_place_links as l').select('l.id').whereRef('l.user_place_id', '=', 'user_places.id'),
),
),
eb.not(
eb.exists(
eb
.selectFrom('user_place_merges as m')
.select('m.id')
.where((inner) =>
inner.or([
inner('m.leading_id', '=', inner.ref('user_places.id')),
inner('m.merged_id', '=', inner.ref('user_places.id')),
]),
),
),
),
]),
)
.executeTakeFirst();
return Number(result.numDeletedRows);
}
}
+2
View File
@@ -108,6 +108,7 @@ import { TagsModule } from './tags/tags.module';
import { TodoModule } from './todo/todo.module';
import { ToursModule } from './tours/tours.module';
import { TransitModule } from './transit/transit.module';
import { TripCollectionsModule } from './trip-collections/trip-collections.module';
import { TripInviteModule } from './trip-invite/trip-invite.module';
import { TripAccessService } from './trip-membership/trip-access.service';
import { TripMembershipModule } from './trip-membership/trip-membership.module';
@@ -204,6 +205,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
TripJournalLinkModule,
CollectionsModule,
PlacesLibraryModule,
TripCollectionsModule,
ShareModule,
TripInviteModule,
TransitModule,
@@ -1112,13 +1112,15 @@ export class CollectionsService {
/** The trip's own tag of each name: the one it has, or one made now; `known` keeps the new ones for the next place. */
private async tripTagIds(tripId: number, userId: number, tags: { name: string; color: string }[], known: Map<string, number>): Promise<number[]> {
const ids: number[] = [];
for (const { name, color } of tags) {
const key = name.trim().toLowerCase();
if (!known.has(key)) known.set(key, (await this.tags.createTag({ user_id: userId, trip_id: tripId, name: name.trim(), color })).id);
ids.push(known.get(key)!);
}
return ids;
const keyOf = (name: string) => name.trim().toLowerCase();
const missing = [...new Map(tags.filter(t => !known.has(keyOf(t.name))).map(t => [keyOf(t.name), t])).entries()];
const made = await Promise.all(missing.map(async ([key, { name, color }]) =>
[key, (await this.tags.createTag({ user_id: userId, trip_id: tripId, name: name.trim(), color })).id] as const));
for (const [key, id] of made) known.set(key, id);
return tags.flatMap(({ name }): number[] => {
const id = known.get(keyOf(name));
return id === undefined ? [] : [id];
});
}
// -------------------------------------------------------------------------
@@ -0,0 +1,141 @@
import {
COORD_DEDUP_TOLERANCE,
normalizePlaceName,
type PLACES_LIBRARY_DUPLICATE_FIELDS,
type PLACES_LIBRARY_DUPLICATE_REASONS,
} from '@trek/shared';
type DuplicateReason = (typeof PLACES_LIBRARY_DUPLICATE_REASONS)[number];
type DuplicateField = (typeof PLACES_LIBRARY_DUPLICATE_FIELDS)[number];
/** An entry as the duplicate search reads it: its key, its facts and every provider id one of its uses carries. */
export interface DuplicateCandidate {
key: string;
name: string;
lat: number | null;
lng: number | null;
address: string | null;
category_id: number | null;
google_place_id: string | null;
google_ftid: string | null;
osm_id: string | null;
/** Every provider id of the entry's own place and of its uses, trimmed. */
provider_ids: readonly string[];
}
/** Two entries that look like one place; `a` has the smaller key. */
interface DuplicatePair {
a: DuplicateCandidate;
b: DuplicateCandidate;
reasons: DuplicateReason[];
}
/**
* More entries than this under one provider id or in one name cell are not a
* duplicate but a pattern (a chain's shared id, a placeholder name); they are
* left out rather than paired with each other.
*/
export const DUPLICATE_BUCKET_MAX = 20;
/** The pair's key, `a` before `b`: what a dismissal stores and the page order follows. */
export function pairKey(a: string, b: string): string {
return a < b ? `${a}|${b}` : `${b}|${a}`;
}
function near(a: DuplicateCandidate, b: DuplicateCandidate): boolean {
if (a.lat === null || a.lng === null || b.lat === null || b.lng === null) return false;
return Math.abs(a.lat - b.lat) <= COORD_DEDUP_TOLERANCE && Math.abs(a.lng - b.lng) <= COORD_DEDUP_TOLERANCE;
}
/** The grid cell of a position, one tolerance wide, so a neighbour is in this cell or one of the eight around it. */
function cellOf(lat: number, lng: number): [number, number] {
return [Math.floor(lat / COORD_DEDUP_TOLERANCE), Math.floor(lng / COORD_DEDUP_TOLERANCE)];
}
/** A cell and the eight around it. */
const NEIGHBOURS: ReadonlyArray<readonly [number, number]> = [-1, 0, 1].flatMap((dx) =>
[-1, 0, 1].map((dy) => [dx, dy] as const),
);
function addTo<K, V>(map: Map<K, V[]>, key: K, value: V): void {
const list = map.get(key);
if (list) list.push(value);
else map.set(key, [value]);
}
/**
* The likely duplicates among `entries`, without comparing every entry with
* every other: entries are bucketed by provider id and by normalized name in a
* grid one `COORD_DEDUP_TOLERANCE` wide, and only entries sharing a bucket (or
* a neighbouring cell) are compared. Ordered by pair key.
*/
export function findDuplicates(entries: readonly DuplicateCandidate[]): DuplicatePair[] {
const pairs = new Map<string, DuplicatePair>();
const add = (x: DuplicateCandidate, y: DuplicateCandidate, reason: DuplicateReason) => {
if (x.key === y.key) return;
const key = pairKey(x.key, y.key);
const [a, b] = x.key < y.key ? [x, y] : [y, x];
const pair = pairs.get(key) ?? { a, b, reasons: [] };
if (!pair.reasons.includes(reason)) pair.reasons.push(reason);
pairs.set(key, pair);
};
const byProvider = new Map<string, DuplicateCandidate[]>();
for (const entry of entries) for (const id of new Set(entry.provider_ids)) addTo(byProvider, id, entry);
for (const bucket of byProvider.values()) {
if (bucket.length > DUPLICATE_BUCKET_MAX) continue;
bucket.forEach((p, i) => {
for (const q of bucket.slice(i + 1)) add(p, q, 'provider_id');
});
}
const byCell = new Map<string, DuplicateCandidate[]>();
for (const entry of entries) {
const name = normalizePlaceName(entry.name);
if (name === null || entry.lat === null || entry.lng === null) continue;
const [x, y] = cellOf(entry.lat, entry.lng);
addTo(byCell, `${name}|${x}|${y}`, entry);
}
for (const [cellKey, bucket] of byCell) {
if (bucket.length > DUPLICATE_BUCKET_MAX) continue;
const [name, xs, ys] = cellKey.split('|') as [string, string, string];
const x = Number(xs);
const y = Number(ys);
for (const [dx, dy] of NEIGHBOURS) {
const other = byCell.get(`${name}|${x + dx}|${y + dy}`) ?? [];
if (other.length > DUPLICATE_BUCKET_MAX) continue;
for (const p of bucket) for (const q of other) if (near(p, q)) add(p, q, 'name_nearby');
}
}
return [...pairs.entries()].sort(([k1], [k2]) => (k1 < k2 ? -1 : k1 > k2 ? 1 : 0)).map(([, pair]) => pair);
}
const sameText = (a: string | null, b: string | null) =>
(a ?? '').trim().toLowerCase() === (b ?? '').trim().toLowerCase();
/** The facts the two sides of a pair differ in. */
export function differingFields(a: DuplicateCandidate, b: DuplicateCandidate): DuplicateField[] {
const fields: DuplicateField[] = [];
if (normalizePlaceName(a.name) !== normalizePlaceName(b.name)) fields.push('name');
const bothPlaced = a.lat !== null && a.lng !== null && b.lat !== null && b.lng !== null;
const neitherPlaced = (a.lat === null || a.lng === null) && (b.lat === null || b.lng === null);
if (!neitherPlaced && !(bothPlaced && near(a, b))) fields.push('position');
if (!sameText(a.address, b.address)) fields.push('address');
if (a.category_id !== b.category_id) fields.push('category');
if (!sameText(a.google_place_id, b.google_place_id)) fields.push('google_place_id');
if (!sameText(a.google_ftid, b.google_ftid)) fields.push('google_ftid');
if (!sameText(a.osm_id, b.osm_id)) fields.push('osm_id');
return fields;
}
/** A page cursor: the pair key of the page's last pair, opaque to the client. */
export function encodeDuplicatesCursor(key: string): string {
return Buffer.from(key, 'utf8').toString('base64url');
}
/** The pair key a cursor names, or null for one this route did not hand out. */
export function decodeDuplicatesCursor(cursor: string): string | null {
const key = Buffer.from(cursor, 'base64url').toString('utf8');
return /^(own|trip|list):\d+\|(own|trip|list):\d+$/.test(key) ? key : null;
}
@@ -0,0 +1,126 @@
import { badRequest } from '../common/domain-error';
import {
decodeDuplicatesCursor,
differingFields,
encodeDuplicatesCursor,
findDuplicates,
pairKey,
type DuplicateCandidate,
} from './place-duplicates.helpers';
import { PlaceIdentitiesService } from './place-identities.service';
import { categoryOf, entryKey, leadOf, originsOf, type EntryRows, type OriginAccess } from './places-library.helpers';
import { PlacesLibraryService, type LibraryUser } from './places-library.service';
import { Injectable } from '@nestjs/common';
import {
externalIdsOf,
PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT,
type PlacesLibraryDuplicateSide,
type PlacesLibraryDuplicatesQuery,
type PlacesLibraryDuplicatesResponse,
} from '@trek/shared';
/** The first of the entry's values for one provider id: its own place's, else its first use's that has one. */
function providerId(rows: EntryRows, field: 'google_place_id' | 'google_ftid' | 'osm_id'): string | null {
const own = rows.identity?.[field] ?? null;
if (own) return own;
return [...rows.trips, ...rows.saved].find((row) => row[field])?.[field] ?? null;
}
/** An entry as the duplicate search compares it. */
function candidateOf(rows: EntryRows): DuplicateCandidate {
const lead = leadOf(rows);
const ids = [rows.identity, ...rows.trips, ...rows.saved].flatMap((row) => (row ? externalIdsOf(row) : []));
return {
key: entryKey(rows.anchor),
name: lead.name,
lat: lead.lat,
lng: lead.lng,
address: lead.address,
category_id: lead.category_id,
google_place_id: providerId(rows, 'google_place_id'),
google_ftid: providerId(rows, 'google_ftid'),
osm_id: providerId(rows, 'osm_id'),
provider_ids: [...new Set(ids)],
};
}
function sideOf(rows: EntryRows, candidate: DuplicateCandidate, access: OriginAccess): PlacesLibraryDuplicateSide {
return {
key: candidate.key,
identity_id: rows.identity?.id ?? null,
name: candidate.name,
address: candidate.address,
lat: candidate.lat,
lng: candidate.lng,
category: categoryOf(leadOf(rows)),
google_place_id: candidate.google_place_id,
google_ftid: candidate.google_ftid,
osm_id: candidate.osm_id,
origins: originsOf(rows, access),
};
}
/**
* PLC-13: the likely duplicates among the user's own "All places", computed
* on request over the entries they reach today and paged: two entries that
* share a provider id, or carry the same name (trimmed, case ignored) within
* `COORD_DEDUP_TOLERANCE`. Entries are bucketed first (`findDuplicates`), so
* no entry is compared with every other. Pairs the user turned down stay out.
*/
@Injectable()
export class PlaceDuplicatesService {
constructor(
private readonly library: PlacesLibraryService,
private readonly identities: PlaceIdentitiesService,
) {}
async list(user: LibraryUser, query: PlacesLibraryDuplicatesQuery): Promise<PlacesLibraryDuplicatesResponse> {
const after = query.cursor === undefined ? null : decodeDuplicatesCursor(query.cursor);
if (query.cursor !== undefined && after === null) {
throw badRequest('Invalid cursor: pass the next_cursor of the page before');
}
const limit = query.limit ?? PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT;
const reach = await this.library.reach(user.id);
const uses = await this.library.usesOf(reach, null);
const rows = await this.library.rows(reach, [...new Set(uses.map((use) => use.anchor_key))], uses);
const rowsByKey = new Map(rows.map((row) => [entryKey(row.anchor), row]));
const dismissed = await this.identities.dismissedPairs(user.id);
const pairs = findDuplicates(rows.map(candidateOf)).filter((pair) => {
const key = pairKey(pair.a.key, pair.b.key);
return !dismissed.has(key) && (after === null || key > after);
});
const page = pairs.slice(0, limit);
const pageRows = [...new Set(page.flatMap((pair) => [pair.a.key, pair.b.key]))].flatMap((key): EntryRows[] => {
const row = rowsByKey.get(key);
return row ? [row] : [];
});
const access = await this.library.access(
user,
pageRows.flatMap((row) => row.trips),
pageRows.flatMap((row) => row.saved),
);
const whole = await this.identities.wholeIdentitiesOf(user.id, pageRows);
const mergeable = new Map(pageRows.map((row, index) => [entryKey(row.anchor), whole[index] ?? false]));
const duplicates = page.flatMap((pair) => {
const a = rowsByKey.get(pair.a.key);
const b = rowsByKey.get(pair.b.key);
if (!a || !b) return [];
return [
{
a: sideOf(a, pair.a, access),
b: sideOf(b, pair.b, access),
reasons: pair.reasons,
differing: differingFields(pair.a, pair.b),
can_merge: (mergeable.get(pair.a.key) ?? false) && (mergeable.get(pair.b.key) ?? false),
},
];
});
const last = page[page.length - 1];
return {
duplicates,
next_cursor: pairs.length > limit && last ? encodeDuplicatesCursor(pairKey(last.a.key, last.b.key)) : null,
};
}
}
@@ -0,0 +1,32 @@
import { logError, logInfo } from '../audit/audit-log.logger';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { PlaceIdentitiesService } from './place-identities.service';
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
/**
* Nightly removal of the own places (D5) nothing holds any more. A deleted
* trip, place or list takes its links along, and the own place they made up
* would otherwise keep the name, position and address it copied from them
* until its owner next changes an own place.
*/
@Injectable()
export class PlaceIdentitiesPruneJob implements OnApplicationBootstrap {
constructor(
private readonly identities: PlaceIdentitiesService,
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
this.registrar.register('place-identities-prune', '20 4 * * *', () => this.tick());
}
async tick(): Promise<void> {
try {
const removed = await this.identities.pruneAll();
if (removed > 0) logInfo(`Own places: removed ${removed} without a place left`);
} catch (err: unknown) {
logError(`Own places prune: ${err instanceof Error ? err.message : String(err)}`);
}
}
}
@@ -0,0 +1,82 @@
import { ADDON_IDS } from '../../addons';
import type { User } from '../../types';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import { PlaceDuplicatesService } from './place-duplicates.service';
import { PlaceIdentitiesService } from './place-identities.service';
import {
PlacesLibraryDuplicatesQueryDto,
PlacesLibraryLinkDto,
PlacesLibraryMergeDto,
PlacesLibraryPairDto,
PlacesLibraryUnlinkDto,
} from './places-library.dto';
import { Body, Controller, Get, HttpCode, Param, Post, Query, UseGuards } from '@nestjs/common';
import {
placesLibraryDuplicatesResponseSchema,
placesLibraryEntryResponseSchema,
placesLibraryMergeResponseSchema,
successResponseSchema,
} from '@trek/shared';
/**
* D5/PLC-13 under /api/addons/collections/library: the user's own places in
* "All places". Assigning uses to one, taking one out, the duplicate
* suggestions, merging two entries and undoing it. Everything here is the
* user's own and changes no trip place and no saved place, so nothing is
* broadcast. Behind the Collections addon like the rest of the library.
*/
@Controller('api/addons/collections/library')
@UseGuards(AddonGuard, JwtAuthGuard)
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
export class PlaceIdentitiesController {
constructor(
private readonly identities: PlaceIdentitiesService,
private readonly duplicates: PlaceDuplicatesService,
) {}
@Post('places/link')
@HttpCode(200)
@ResponseContract(placesLibraryEntryResponseSchema)
async link(@CurrentUser() user: User, @Body() body: PlacesLibraryLinkDto) {
return this.identities.link({ id: user.id, role: user.role }, body);
}
@Post('places/unlink')
@HttpCode(200)
@ResponseContract(placesLibraryEntryResponseSchema)
async unlink(@CurrentUser() user: User, @Body() body: PlacesLibraryUnlinkDto) {
return this.identities.unlink({ id: user.id, role: user.role }, body);
}
@Get('duplicates')
@ResponseContract(placesLibraryDuplicatesResponseSchema)
async listDuplicates(@CurrentUser() user: User, @Query() query: PlacesLibraryDuplicatesQueryDto) {
return this.duplicates.list({ id: user.id, role: user.role }, query);
}
@Post('duplicates/dismiss')
@HttpCode(200)
@ResponseContract(successResponseSchema)
async dismiss(@CurrentUser() user: User, @Body() body: PlacesLibraryPairDto) {
return this.identities.dismiss(user.id, body.a, body.b);
}
@Post('merges')
@HttpCode(200)
@ResponseContract(placesLibraryMergeResponseSchema)
async merge(@CurrentUser() user: User, @Body() body: PlacesLibraryMergeDto) {
return this.identities.merge({ id: user.id, role: user.role }, body.leading, body.other);
}
@Post('merges/:id/undo')
@HttpCode(200)
@ResponseContract(successResponseSchema)
async undoMerge(@CurrentUser() user: User, @Param('id', rowId('Merge not found')) id: number) {
return this.identities.undoMerge({ id: user.id, role: user.role }, id);
}
}
@@ -0,0 +1,135 @@
import { ADDON_IDS } from '../../addons';
import { canRead, canReadTrips, canWrite } from '../../mcp/scopes';
import {
McpController,
Tool,
TOOL_ANNOTATIONS_NON_IDEMPOTENT,
TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_WRITE,
ok,
type McpContext,
} from '../../nest-mcp';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { PlaceDuplicatesService } from './place-duplicates.service';
import { PlaceIdentitiesService } from './place-identities.service';
import type { LibraryUser } from './places-library.service';
import {
PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT,
PLACES_LIBRARY_DUPLICATES_PAGE_MAX,
placesLibraryDuplicatesQuerySchema,
placesLibraryLinkRequestSchema,
placesLibraryMergeRequestSchema,
placesLibraryPairRequestSchema,
placesLibraryUndoMergeRequestSchema,
placesLibraryUnlinkRequestSchema,
type PlacesLibraryDuplicatesQuery,
type PlacesLibraryLinkRequest,
type PlacesLibraryMergeRequest,
type PlacesLibraryPairRequest,
type PlacesLibraryUndoMergeRequest,
type PlacesLibraryUse,
} from '@trek/shared';
/** The own places group trips and lists, so a token reads trips and lists. */
const readsTripsAndLists = (ctx: McpContext) => canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
/** Changing them writes only the user's own grouping, under the lists' write scope. */
const writesOwnPlaces = (ctx: McpContext) => canWrite(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
const OWN_ONLY =
'Only your own view of All places changes: no trip place and no saved place is renamed, moved or deleted, and no one else sees it.';
/**
* D5/PLC-13 over the same services and checks as the REST routes under
* /api/addons/collections/library: the user's own places, the duplicate
* suggestions and merges.
*/
@McpController()
export class PlaceIdentitiesMcp {
constructor(
private readonly identities: PlaceIdentitiesService,
private readonly duplicates: PlaceDuplicatesService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of every tool here.
readonly addons: AddonsService,
) {}
private async user(userId: number): Promise<LibraryUser> {
return { id: userId, role: (await this.guards.isAdminUser(userId)) ? 'admin' : 'user' };
}
@Tool({
name: 'link_library_places',
description: `Put trip places and saved places together as one place of your own in All places (list_all_places then shows them as one entry, key own:<id>). Name each by kind trip (place_id) or kind list (collection_place_id). With identity_id they join that own place; without it a new one is made, named and placed like the first one listed. A place that was part of another own place of yours moves. ${OWN_ONLY}`,
inputSchema: placesLibraryLinkRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: writesOwnPlaces,
})
async linkLibraryPlaces(input: PlacesLibraryLinkRequest, ctx: McpContext) {
return ok(await this.identities.link(await this.user(ctx.userId), input));
}
@Tool({
name: 'unlink_library_place',
description: `Take one trip place (kind trip) or saved place (kind list) out of the own place of yours it is part of; it is an entry of its own again. Answers the entry it belongs to now. ${OWN_ONLY}`,
inputSchema: placesLibraryUnlinkRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: writesOwnPlaces,
})
async unlinkLibraryPlace(input: PlacesLibraryUse, ctx: McpContext) {
return ok(await this.identities.unlink(await this.user(ctx.userId), input));
}
@Tool({
name: 'list_library_duplicates',
description: `Likely duplicates in All places, ${PLACES_LIBRARY_DUPLICATES_PAGE_DEFAULT} pairs at a time unless limit says otherwise (at most ${PLACES_LIBRARY_DUPLICATES_PAGE_MAX}): two entries that share a provider id (reason provider_id) or carry the same name a few metres apart (reason name_nearby). Each pair has both entries (key, name, position, address, category, provider ids, origins), the fields they differ in and can_merge (false while one side holds a place you can no longer open). Pairs you dismissed stay out. Go on with next_cursor.`,
inputSchema: placesLibraryDuplicatesQuerySchema.shape,
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: readsTripsAndLists,
})
async listLibraryDuplicates(input: PlacesLibraryDuplicatesQuery, ctx: McpContext) {
return ok(await this.duplicates.list(await this.user(ctx.userId), input));
}
@Tool({
name: 'dismiss_library_duplicate',
description:
'Turn a duplicate suggestion of list_library_duplicates down by the keys of its two entries, so it is not suggested again. Changes nothing else.',
inputSchema: placesLibraryPairRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: writesOwnPlaces,
})
async dismissLibraryDuplicate(input: PlacesLibraryPairRequest, ctx: McpContext) {
return ok(await this.identities.dismiss(ctx.userId, input.a, input.b));
}
@Tool({
name: 'merge_library_places',
description: `Merge two entries of All places (by their keys) into one own place that keeps the name and position of leading; every trip place and saved place of both stays where it is and now shows under the merged entry. Refused while either side holds a place you can no longer open. Answers merge_id for undo_library_merge and the merged entry. ${OWN_ONLY}`,
inputSchema: placesLibraryMergeRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: writesOwnPlaces,
})
async mergeLibraryPlaces(input: PlacesLibraryMergeRequest, ctx: McpContext) {
return ok(await this.identities.merge(await this.user(ctx.userId), input.leading, input.other));
}
@Tool({
name: 'undo_library_merge',
description:
'Take a merge of merge_library_places back by its merge_id: the places the merged entry brought along are an own place of their own again.',
inputSchema: placesLibraryUndoMergeRequestSchema.shape,
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: writesOwnPlaces,
})
async undoLibraryMerge(input: PlacesLibraryUndoMergeRequest, ctx: McpContext) {
return ok(await this.identities.undoMerge(await this.user(ctx.userId), input.merge_id));
}
}
@@ -0,0 +1,271 @@
import { UserPlaceLinks } from '../../db/entities/UserPlaceLinks.entity';
import { UserPlaceMergeDismissals } from '../../db/entities/UserPlaceMergeDismissals.entity';
import { UserPlaceMerges } from '../../db/entities/UserPlaceMerges.entity';
import { UserPlaces } from '../../db/entities/UserPlaces.entity';
import { USER_PLACE_MERGE_MOVED_LINKS } from '../../db/json-columns';
import type { LinkedUse, UserPlaceLinksRepository } from '../../db/repositories/UserPlaceLinks.repository';
import type { UserPlaceMergeDismissalsRepository } from '../../db/repositories/UserPlaceMergeDismissals.repository';
import type { UserPlaceMergesRepository } from '../../db/repositories/UserPlaceMerges.repository';
import type { UserPlaceFacts, UserPlacesRepository } from '../../db/repositories/UserPlaces.repository';
import { decodeJson, encodeJson } from '../../utils/json-column';
import { badRequest, forbidden, notFound } from '../common/domain-error';
import { UnitOfWork } from '../database/unit-of-work';
import { pairKey } from './place-duplicates.helpers';
import { anchorOfIdentity, anchorOfKey, firstUseOf, useKey, 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 {
PlacesLibraryEntryResponse,
PlacesLibraryLinkRequest,
PlacesLibraryMergeResponse,
PlacesLibraryUse,
SuccessResponse,
} from '@trek/shared';
const notAssigned = () => notFound('This place is not part of one of your own places');
const mergeNotFound = () => notFound('Merge not found');
/** The uses of an entry, as the links name them. */
function usesOfRows(rows: EntryRows): LinkedUse[] {
return [
...rows.trips.map((row) => ({ kind: 'trip' as const, id: row.id })),
...rows.saved.map((row) => ({ kind: 'list' as const, id: row.id })),
];
}
/**
* D5/D6: the user's own places. Assigning uses to one, taking one out,
* merging two entries and undoing a merge change only the user's own rows
* (`user_places`, `user_place_links`, `user_place_merges`); no trip place and
* no saved place is written, so nothing reaches anyone else and nothing needs
* a realtime event. Every use named must be one the user reaches today
* (the library's checks), else it is not found.
*
* An own place left without a link is removed in the same transaction as the
* write that emptied it; one emptied by a deleted trip, place or list goes at
* the user's next write here or with the nightly sweep
* (`PlaceIdentitiesPruneJob`).
*
* Copies and restores make new rows, and a link names a row: a trip copy
* (`TripsService` copy, `insertPlaceCopy`, also `copy_trip`) takes no link
* along, so the copy's places start as entries of their own, and the planner's
* undo of a deleted place (`placeRestorePayload` → `addPlace`) makes a new
* place whose old link went with the deleted one (ON DELETE CASCADE). Neither
* is linked again on its own; the user assigns it again. The lists a trip
* draws on (`trip_collection_links`) are not copied with a trip either.
*/
@Injectable()
export class PlaceIdentitiesService {
constructor(
private readonly library: PlacesLibraryService,
@InjectRepository(UserPlaces) private readonly identities: UserPlacesRepository,
@InjectRepository(UserPlaceLinks) private readonly links: UserPlaceLinksRepository,
@InjectRepository(UserPlaceMerges) private readonly merges: UserPlaceMergesRepository,
@InjectRepository(UserPlaceMergeDismissals) private readonly dismissals: UserPlaceMergeDismissalsRepository,
private readonly uow: UnitOfWork,
) {}
/** Puts the uses into one own place: `identity_id`'s, or a new one named after the first use. */
async link(user: LibraryUser, request: PlacesLibraryLinkRequest): Promise<PlacesLibraryEntryResponse> {
const uses = uniqueUses(request.uses);
const reach = await this.library.reach(user.id);
const reachable = new Set((await this.library.usesOf(reach, null)).map((use) => useKey(use.from_list, use.use_id)));
if (uses.some((use) => !reachable.has(useKey(use.kind === 'trip' ? 0 : 1, use.id)))) throw placeNotFound();
if (request.identity_id !== undefined) {
const own = await this.identities.findOwn(user.id, request.identity_id);
if (!own || own.merged_into_id !== null) throw placeNotFound();
}
const first = uses[0];
if (!first) throw placeNotFound();
const target =
request.identity_id === undefined ? { facts: await this.factsOfUse(reach, first) } : { id: request.identity_id };
const identityId = await this.uow.transactional(async () => {
const id = 'id' in target ? target.id : await this.identities.create(user.id, target.facts);
await this.attach(user.id, id, uses, 'user');
await this.identities.touch(user.id, id);
await this.prune(user.id);
return id;
});
return { entry: await this.library.entry(user, anchorOfIdentity(identityId)) };
}
/** Takes one use out of the own place it is in; it is an entry of its own (or of its source) again. */
async unlink(user: LibraryUser, use: PlacesLibraryUse): Promise<PlacesLibraryEntryResponse> {
const reach = await this.library.reach(user.id);
if ((await this.library.anchorOfUse(reach, use.kind, use.id)) === null) throw placeNotFound();
const link = await this.links.findForUse(user.id, use);
if (!link) throw notAssigned();
await this.uow.transactional(async () => {
await this.links.deleteOwn(user.id, link.id);
await this.identities.touch(user.id, link.user_place_id);
await this.prune(user.id);
});
return { entry: await this.library.entry(user, await this.library.anchorOfUse(reach, use.kind, use.id)) };
}
/**
* Merges `otherKey`'s entry into `leadingKey`'s: both become own places (an
* entry that was none becomes one with all its uses), the other's links move
* to the leading one, and the other is marked merged into it. The merged
* place keeps the leading entry's name and position; neither is written into
* a trip or a list. Refused while either side holds a use the user cannot
* open any more, since they could not see what they merge.
*/
async merge(user: LibraryUser, leadingKey: string, otherKey: string): Promise<PlacesLibraryMergeResponse> {
const leading = anchorOfKey(leadingKey);
const other = anchorOfKey(otherKey);
if (leading === null || other === null) throw placeNotFound();
if (leading === other) throw badRequest('Pick two different places to merge');
const reach = await this.library.reach(user.id);
const [lead, rest] = await this.library.rows(reach, [leading, other]);
if (!lead || !rest) throw placeNotFound();
if (!(await this.wholeIdentities(user.id, [lead, rest]))) {
throw forbidden('One of these places holds a trip place or saved place you can no longer open');
}
const { mergeId, leadId } = await this.uow.transactional(async () => {
const leadId = await this.materialize(user.id, lead);
const restId = await this.materialize(user.id, rest);
const moved = await this.links.idsOf(user.id, restId);
await this.links.moveTo(user.id, moved, leadId);
await this.identities.setMergedInto(user.id, restId, leadId);
await this.identities.touch(user.id, leadId);
const mergeId = await this.merges.create(
user.id,
leadId,
restId,
encodeJson(USER_PLACE_MERGE_MOVED_LINKS, moved),
);
return { mergeId, leadId };
});
return { merge_id: mergeId, entry: await this.library.entry(user, anchorOfIdentity(leadId)) };
}
/** Takes a merge back: the moved links return to the merged place, which stands on its own again. */
async undoMerge(user: LibraryUser, mergeId: number): Promise<SuccessResponse> {
const merge = await this.merges.findOwn(user.id, mergeId);
if (!merge) throw mergeNotFound();
const moved = decodeJson(USER_PLACE_MERGE_MOVED_LINKS, merge.moved_link_ids, `user_place_merges ${merge.id}`);
await this.uow.transactional(async () => {
await this.links.moveTo(user.id, moved, merge.merged_id);
await this.identities.setMergedInto(user.id, merge.merged_id, null);
await this.identities.touch(user.id, merge.leading_id);
await this.merges.deleteIds([merge.id]);
await this.prune(user.id);
});
return { success: true };
}
/** Turns a duplicate suggestion down, so it is not suggested again. */
async dismiss(userId: number, a: string, b: string): Promise<SuccessResponse> {
if (anchorOfKey(a) === null || anchorOfKey(b) === null) throw placeNotFound();
if (a === b) throw badRequest('Pick two different places');
const [keyA, keyB] = pairKey(a, b).split('|') as [string, string];
await this.dismissals.dismiss(userId, { key_a: keyA, key_b: keyB });
return { success: true };
}
/** The suggestions the user turned down, by pair key. */
async dismissedPairs(userId: number): Promise<Set<string>> {
return new Set((await this.dismissals.listForUser(userId)).map((row) => pairKey(row.key_a, row.key_b)));
}
/**
* Whether every own place among `rows` holds only uses the user reaches
* today, so merging moves nothing they cannot see. Answers per entry.
*/
async wholeIdentitiesOf(userId: number, rows: readonly EntryRows[]): Promise<boolean[]> {
const ids = rows.flatMap((row) => (row.identity ? [row.identity.id] : []));
const counts = new Map((await this.identities.linkCounts(userId, ids)).map((row) => [row.id, row.links]));
return rows.map((row) => !row.identity || (counts.get(row.identity.id) ?? 0) <= row.linked.size);
}
/** Removes every own place, of every user, nothing holds any more: the nightly sweep. */
async pruneAll(): Promise<number> {
return this.uow.transactional(async () => this.prune(null));
}
private async wholeIdentities(userId: number, rows: readonly EntryRows[]): Promise<boolean> {
return (await this.wholeIdentitiesOf(userId, rows)).every(Boolean);
}
/** Moves the uses into the own place `id`, out of any other of the user's. Runs inside the caller's transaction. */
private async attach(
userId: number,
id: number,
uses: readonly LinkedUse[],
linkedBy: 'user' | 'merge',
): Promise<void> {
await this.links.detach(userId, uses);
await this.links.insert(userId, id, uses, linkedBy);
}
/** The entry's own place, made from its first use when it has none yet. Runs inside the caller's transaction. */
private async materialize(userId: number, rows: EntryRows): Promise<number> {
if (rows.identity) return rows.identity.id;
const first = firstUseOf(rows);
const id = await this.identities.create(userId, {
name: first.name,
lat: first.lat,
lng: first.lng,
address: first.address,
category_id: first.category_id,
google_place_id: first.google_place_id,
google_ftid: first.google_ftid,
osm_id: first.osm_id,
});
await this.attach(userId, id, usesOfRows(rows), 'merge');
return id;
}
/** The facts a new own place takes from the use it is named after. */
private async factsOfUse(reach: LibraryReach, use: LinkedUse): Promise<UserPlaceFacts> {
const anchor = await this.library.anchorOfUse(reach, use.kind, use.id);
const rows = anchor === null ? [] : await this.library.rows(reach, [anchor]);
const row =
use.kind === 'trip'
? rows[0]?.trips.find((trip) => trip.id === use.id)
: rows[0]?.saved.find((saved) => saved.id === use.id);
if (!row) throw placeNotFound();
return {
name: row.name,
lat: row.lat,
lng: row.lng,
address: row.address,
category_id: row.category_id,
google_place_id: row.google_place_id,
google_ftid: row.google_ftid,
osm_id: row.osm_id,
};
}
/**
* Drops the merges none of whose moved links is left, then the own places of
* the user (of everyone when null) that hold no link and no merge names.
* Runs inside the caller's transaction.
*/
private async prune(userId: number | null): Promise<number> {
const merges = await this.merges.list(userId);
const moved = new Map(
merges.map((merge) => [
merge.id,
decodeJson(USER_PLACE_MERGE_MOVED_LINKS, merge.moved_link_ids, `user_place_merges ${merge.id}`),
]),
);
const alive = new Set(await this.links.existing([...new Set([...moved.values()].flat())]));
const spent = merges.filter((merge) => !(moved.get(merge.id) ?? []).some((id) => alive.has(id)));
await this.merges.deleteIds(spent.map((merge) => merge.id));
return this.identities.pruneEmpty(userId);
}
}
/** The uses once each, in the order given. */
function uniqueUses(uses: readonly PlacesLibraryUse[]): LinkedUse[] {
const seen = new Set<string>();
return uses.filter((use) => {
const key = `${use.kind}:${use.id}`;
if (seen.has(key)) return false;
seen.add(key);
return true;
});
}
@@ -1,5 +1,18 @@
import { placesLibraryQuerySchema } from '@trek/shared';
import {
placesLibraryDuplicatesQuerySchema,
placesLibraryQuerySchema,
placesLibraryLinkRequestSchema,
placesLibraryMergeRequestSchema,
placesLibraryPairRequestSchema,
placesLibraryUnlinkRequestSchema,
} from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class PlacesLibraryQueryDto extends createZodDto(placesLibraryQuerySchema) {}
export class PlacesLibraryLinkDto extends createZodDto(placesLibraryLinkRequestSchema) {}
export class PlacesLibraryUnlinkDto extends createZodDto(placesLibraryUnlinkRequestSchema) {}
export class PlacesLibraryDuplicatesQueryDto extends createZodDto(placesLibraryDuplicatesQuerySchema) {}
export class PlacesLibraryPairDto extends createZodDto(placesLibraryPairRequestSchema) {}
export class PlacesLibraryMergeDto extends createZodDto(placesLibraryMergeRequestSchema) {}
@@ -1,17 +1,25 @@
import type {
LibraryAnchorRow,
LibraryCollectionPlaceRow,
LibraryPosition,
LibraryRatingRow,
LibrarySort,
LibraryTripPlaceRow,
import {
ANCHOR_LIST,
ANCHOR_OWN,
ANCHOR_SPAN,
ANCHOR_TRIP,
type LibraryAnchorRow,
type LibraryCollectionPlaceRow,
type LibraryIdentityRow,
type LibraryPosition,
type LibraryRatingRow,
type LibrarySort,
type LibraryTripPlaceRow,
type LibraryUseRow,
} from '../../db/repositories/PlacesLibrary.repository';
import {
collectionStatusSchema,
PLACES_LIBRARY_KEY_PATTERN,
PLACES_LIBRARY_SORTS,
type PlacesLibraryCategory,
type PlacesLibraryEntry,
type PlacesLibraryInfo,
type PlacesLibraryKind,
type PlacesLibraryListOrigin,
type PlacesLibraryRating,
type PlacesLibraryTripOrigin,
@@ -22,9 +30,41 @@ import { z } from 'zod';
/** A cursor as it is encoded: the sort it belongs to, the last entry's sort value and its key. */
const cursorSchema = z.tuple([z.enum(PLACES_LIBRARY_SORTS), z.string(), z.number().int()]);
/** The key an entry is known by: its trip place id when it has one, else its saved place id negated. */
const PREFIX_OF_KIND: Record<number, string> = { [ANCHOR_TRIP]: 'trip', [ANCHOR_LIST]: 'list', [ANCHOR_OWN]: 'own' };
const KIND_OF_PREFIX: Record<string, number> = { trip: ANCHOR_TRIP, list: ANCHOR_LIST, own: ANCHOR_OWN };
/** The key an entry is known by: own:<id>, trip:<place id> or list:<saved place id>. */
export function entryKey(anchor: number): string {
return anchor > 0 ? `trip:${anchor}` : `list:${-anchor}`;
return `${PREFIX_OF_KIND[anchor % ANCHOR_SPAN] ?? 'list'}:${Math.floor(anchor / ANCHOR_SPAN)}`;
}
/** The anchor an entry key names, or null for a key no entry can have. */
export function anchorOfKey(key: string): number | null {
if (!PLACES_LIBRARY_KEY_PATTERN.test(key)) return null;
const [prefix = '', digits = ''] = key.split(':');
const kind = KIND_OF_PREFIX[prefix];
const anchor = Number(digits) * ANCHOR_SPAN + (kind ?? 0);
return kind === undefined || !Number.isSafeInteger(anchor) ? null : anchor;
}
/** The own place an anchor names, or null for an entry no one put together. */
export function identityOfAnchor(anchor: number): number | null {
return anchor % ANCHOR_SPAN === ANCHOR_OWN ? Math.floor(anchor / ANCHOR_SPAN) : null;
}
/** The anchor of the user's own place `id`. */
export function anchorOfIdentity(id: number): number {
return id * ANCHOR_SPAN + ANCHOR_OWN;
}
/** How a use is named: `trip:<place id>` or `list:<saved place id>`. */
export function useKey(fromList: number, id: number): string {
return `${fromList === 0 ? 'trip' : 'list'}:${id}`;
}
/** The `from_list` of a use kind. */
export function fromListOf(kind: PlacesLibraryKind): number {
return kind === 'trip' ? 0 : 1;
}
/** The position after which the next page starts, opaque to the client. */
@@ -58,8 +98,9 @@ export function ratingOf(rows: readonly LibraryRatingRow[], userId: number): Pla
}
type FactsRow = LibraryTripPlaceRow | LibraryCollectionPlaceRow;
type LeadRow = FactsRow | LibraryIdentityRow;
function categoryOf(row: FactsRow): PlacesLibraryCategory | null {
export function categoryOf(row: LeadRow): PlacesLibraryCategory | null {
if (row.category_id === null || row.category_name === null) return null;
return { id: row.category_id, name: row.category_name, color: row.category_color, icon: row.category_icon };
}
@@ -79,7 +120,7 @@ export function infoOf(row: FactsRow): PlacesLibraryInfo {
};
}
function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean): PlacesLibraryTripOrigin {
function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean, linked: boolean): PlacesLibraryTripOrigin {
return {
kind: 'trip',
trip_id: row.trip_id,
@@ -89,10 +130,11 @@ function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean): PlacesLibrary
place_id: row.id,
can_edit: canEdit,
read_only: !canEdit,
linked,
};
}
function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean): PlacesLibraryListOrigin {
function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean, linked: boolean): PlacesLibraryListOrigin {
return {
kind: 'list',
collection_id: row.collection_id,
@@ -100,6 +142,7 @@ function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean): PlacesL
collection_place_id: row.id,
status: collectionStatusSchema.parse(row.status),
can_edit: canEdit,
linked,
};
}
@@ -109,52 +152,91 @@ export interface OriginAccess {
canEditList: (row: LibraryCollectionPlaceRow) => boolean;
}
/** One entry's rows: its trip place where it has one, and its saved places. */
/** One entry's rows: the user's own place where it is one, its trip places and its saved places. */
export interface EntryRows {
anchor: number;
trip: LibraryTripPlaceRow | null;
identity: LibraryIdentityRow | null;
trips: LibraryTripPlaceRow[];
saved: LibraryCollectionPlaceRow[];
/** The uses the user linked themselves, by `useKey`. */
linked: ReadonlySet<string>;
}
/**
* The rows of each anchor, in the anchors' order. An anchor whose rows went
* away between the reads (a place deleted in between) is left out.
* away between the reads (a place deleted in between, an own place pruned) is
* left out.
*/
export function rowsByAnchor(
anchors: readonly number[],
uses: readonly LibraryUseRow[],
trips: readonly LibraryTripPlaceRow[],
saved: readonly LibraryCollectionPlaceRow[],
identities: readonly LibraryIdentityRow[],
): EntryRows[] {
const tripById = new Map(trips.map((row) => [row.id, row]));
const savedById = new Map(saved.map((row) => [row.id, row]));
const identityById = new Map(identities.map((row) => [row.id, row]));
return anchors.flatMap((anchor) => {
if (anchor > 0) {
const trip = tripById.get(anchor);
if (!trip) return [];
return [{ anchor, trip, saved: saved.filter((row) => row.grouped_place_id === anchor) }];
}
const own = saved.filter((row) => row.id === -anchor && row.grouped_place_id === null);
return own.length > 0 ? [{ anchor, trip: null, saved: own }] : [];
const own = uses.filter((use) => use.anchor_key === anchor);
const identityId = identityOfAnchor(anchor);
const identity = identityId === null ? null : (identityById.get(identityId) ?? null);
if (identityId !== null && identity === null) return [];
const entry: EntryRows = {
anchor,
identity,
trips: own.flatMap((use) => {
const row = use.from_list === 0 ? tripById.get(use.use_id) : undefined;
return row ? [row] : [];
}),
saved: own.flatMap((use) => {
const row = use.from_list === 1 ? savedById.get(use.use_id) : undefined;
return row ? [row] : [];
}),
linked: new Set(own.filter((use) => use.linked).map((use) => useKey(use.from_list, use.use_id))),
};
return entry.trips.length > 0 || entry.saved.length > 0 ? [entry] : [];
});
}
/** An entry of the list: the trip place's facts where there is one, the trip origin first. */
export function entryOf(rows: EntryRows, access: OriginAccess): PlacesLibraryEntry {
/** The facts an entry shows: its own place's, else its first trip place's, else its first saved place's. */
export function leadOf(rows: EntryRows): LeadRow {
const lead = rows.identity ?? rows.trips[0] ?? rows.saved[0];
// rowsByAnchor never hands out an entry with neither a trip place nor a saved place.
const lead: FactsRow = rows.trip ?? rows.saved[0];
const origins = [
...(rows.trip ? [tripOriginOf(rows.trip, access.canEditTrip(rows.trip))] : []),
...rows.saved.map((row) => listOriginOf(row, access.canEditList(row))),
if (!lead) throw new Error('An entry without a place');
return lead;
}
/** The facts of the use that stands first in an entry: its first trip place, else its first saved place. */
export function firstUseOf(rows: EntryRows): FactsRow {
const first = rows.trips[0] ?? rows.saved[0];
if (!first) throw new Error('An entry without a place');
return first;
}
/** The origins of an entry: its trip places first, then its saved places. */
export function originsOf(rows: EntryRows, access: OriginAccess): PlacesLibraryEntry['origins'] {
return [
...rows.trips.map((row) => tripOriginOf(row, access.canEditTrip(row), rows.linked.has(useKey(0, row.id)))),
...rows.saved.map((row) => listOriginOf(row, access.canEditList(row), rows.linked.has(useKey(1, row.id)))),
];
}
/** An entry of the list: its own place's facts, else its trip place's where there is one. */
export function entryOf(rows: EntryRows, access: OriginAccess): PlacesLibraryEntry {
const lead = leadOf(rows);
const facts: FactsRow[] = [...rows.trips, ...rows.saved];
return {
key: entryKey(rows.anchor),
identity_id: rows.identity?.id ?? null,
name: lead.name,
address: lead.address,
lat: lead.lat,
lng: lead.lng,
category: categoryOf(lead),
image_url: lead.image_url ?? rows.saved.find((row) => row.image_url !== null)?.image_url ?? null,
image_url: facts.find((row) => row.image_url !== null)?.image_url ?? null,
updated_at: lead.updated_at,
origins,
origins: originsOf(rows, access),
};
}
@@ -1,24 +1,45 @@
import { UserPlaceLinks } from '../../db/entities/UserPlaceLinks.entity';
import { UserPlaceMergeDismissals } from '../../db/entities/UserPlaceMergeDismissals.entity';
import { UserPlaceMerges } from '../../db/entities/UserPlaceMerges.entity';
import { UserPlaces } from '../../db/entities/UserPlaces.entity';
import { PlacesLibraryRepository } from '../../db/repositories/PlacesLibrary.repository';
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 { SchedulingModule } from '../scheduling/scheduling.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { PlaceDuplicatesService } from './place-duplicates.service';
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 { PlacesLibraryController } from './places-library.controller';
import { PlacesLibraryMcp } from './places-library.mcp';
import { PlacesLibraryService } from './places-library.service';
import { EntityManager } from '@mikro-orm/core';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
/**
* PLC-07/PLC-08 "All places" under the Collections addon: the saved places of
* every list and the places of every trip the user can open, read only. The
* repository reads across both, so it backs no entity and is built here over
* the context-resolving EntityManager, the way MaintenanceModule builds its own.
* every list and the places of every trip the user can open, read only, plus
* (D5/PLC-13) the user's own places that group them, the duplicate
* suggestions and merges. The library repository reads across trips and
* lists, so it backs no entity and is built here over the context-resolving
* EntityManager, the way MaintenanceModule builds its own.
*/
@Module({
imports: [AddonsModule, CollectionsModule, TripMembershipModule, PermissionsModule, McpSharedModule],
controllers: [PlacesLibraryController],
imports: [
AddonsModule,
CollectionsModule,
TripMembershipModule,
PermissionsModule,
McpSharedModule,
SchedulingModule,
MikroOrmModule.forFeature([UserPlaces, UserPlaceLinks, UserPlaceMerges, UserPlaceMergeDismissals]),
],
controllers: [PlacesLibraryController, PlaceIdentitiesController],
providers: [
{
provide: PlacesLibraryRepository,
@@ -27,6 +48,10 @@ import { Module } from '@nestjs/common';
},
PlacesLibraryService,
PlacesLibraryMcp,
PlaceIdentitiesService,
PlaceDuplicatesService,
PlaceIdentitiesMcp,
PlaceIdentitiesPruneJob,
],
})
export class PlacesLibraryModule {}
@@ -5,6 +5,7 @@ import {
type LibraryMatch,
type LibrarySort,
type LibraryTripPlaceRow,
type LibraryUseRow,
} from '../../db/repositories/PlacesLibrary.repository';
import { CollectionsService } from '../collections/collections.service';
import { badRequest, notFound } from '../common/domain-error';
@@ -15,7 +16,9 @@ import {
encodeLibraryCursor,
entryKey,
entryOf,
fromListOf,
groupBy,
identityOfAnchor,
infoOf,
ratingOf,
rowsByAnchor,
@@ -40,7 +43,8 @@ export interface LibraryUser {
}
/** What the user reaches right now, read anew for every call. */
interface Reach {
export interface LibraryReach {
userId: number;
tripIds: number[];
collectionIds: number[];
}
@@ -50,7 +54,17 @@ interface LibraryListOptions {
maxChars?: number;
}
const placeNotFound = () => notFound('Place not found');
export const placeNotFound = () => notFound('Place not found');
/** Everything the user reaches, as the repository reads it. */
function armsOfReach(reach: LibraryReach): LibraryArms {
return {
userId: reach.userId,
tripIds: reach.tripIds,
collectionIds: reach.collectionIds,
reachableTripIds: reach.tripIds,
};
}
/**
* PLC-07/PLC-08 "All places": the saved places of every list the user can
@@ -61,6 +75,10 @@ const placeNotFound = () => notFound('Place not found');
* `TripMembershipService.listAccessibleTripIds`, the list roles for editing a
* saved place and the trip's 'place_edit' for editing a trip place. A list or
* trip out of reach is not found, never hinted at.
*
* Uses the user put together as one place of their own (D5) are one entry,
* named and placed as that own place; only the uses the user reaches today
* belong to it.
*/
@Injectable()
export class PlacesLibraryService {
@@ -89,8 +107,7 @@ export class PlacesLibraryService {
status: query.status ?? null,
};
const facets = { ...arms, tripIds: reach.tripIds, collectionIds: reach.collectionIds };
const counts = await this.repo.countEntries(facets, { ...match, status: null });
const counts = await this.repo.countEntries(armsOfReach(reach), { ...match, status: null });
const narrowed =
query.kind !== undefined ||
query.collection_id !== undefined ||
@@ -128,49 +145,71 @@ export class PlacesLibraryService {
/** One entry, opened from the trip place or the saved place `id`, with what each origin keeps. */
async detail(user: LibraryUser, kind: PlacesLibraryKind, id: number): Promise<PlacesLibraryDetailResponse> {
const reach = await this.reach(user.id);
const anchor =
kind === 'trip'
? await this.repo.findTripPlace(id, reach.tripIds)
: await this.repo.findSavedPlaceKey(id, reach.collectionIds, reach.tripIds);
const anchor = await this.repo.anchorOfUse(armsOfReach(reach), fromListOf(kind), id);
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.trip ? [rows.trip] : [], rows.saved));
const entry = entryOf(rows, await this.access(user, rows.trips, rows.saved));
return { entry, details: await this.details(user.id, rows) };
}
private async reach(userId: number): Promise<Reach> {
/** The trips and lists the user reaches right now. */
async reach(userId: number): Promise<LibraryReach> {
const tripIds = await this.membership.listAccessibleTripIds(userId);
const collectionIds = await this.collections.accessibleCollectionIds(userId);
return { tripIds, collectionIds };
return { userId, tripIds, collectionIds };
}
private async rows(reach: Reach, anchors: number[]): Promise<EntryRows[]> {
const tripPlaceIds = anchors.filter((anchor) => anchor > 0);
const savedIds = anchors.filter((anchor) => anchor < 0).map((anchor) => -anchor);
/** The entry a use stands for, or null when the user does not reach it. */
async anchorOfUse(reach: LibraryReach, kind: PlacesLibraryKind, id: number): Promise<number | null> {
return this.repo.anchorOfUse(armsOfReach(reach), fromListOf(kind), id);
}
/** The uses the user reaches, of the entries `anchors` or of all of them. */
async usesOf(reach: LibraryReach, anchors: number[] | null): Promise<LibraryUseRow[]> {
return this.repo.usesOf(armsOfReach(reach), anchors);
}
/** The rows of the entries `anchors`, in their order, from the uses read for them (or read here). */
async rows(reach: LibraryReach, anchors: number[], uses?: LibraryUseRow[]): Promise<EntryRows[]> {
if (anchors.length === 0) return [];
const own = uses ?? (await this.usesOf(reach, anchors));
const tripPlaceIds = own.filter((use) => use.from_list === 0).map((use) => use.use_id);
const savedIds = own.filter((use) => use.from_list === 1).map((use) => use.use_id);
const identityIds = anchors.flatMap((anchor): number[] => {
const id = identityOfAnchor(anchor);
return id === null ? [] : [id];
});
const trips = tripPlaceIds.length > 0 ? await this.repo.tripPlaces(tripPlaceIds, reach.tripIds) : [];
const saved =
anchors.length > 0 ? await this.repo.savedPlaces(reach.collectionIds, reach.tripIds, savedIds, tripPlaceIds) : [];
return rowsByAnchor(anchors, trips, saved);
const saved = savedIds.length > 0 ? await this.repo.savedPlaces(reach.collectionIds, savedIds) : [];
const identities = identityIds.length > 0 ? await this.repo.identities(reach.userId, identityIds) : [];
return rowsByAnchor(anchors, own, trips, saved, identities);
}
private async entries(user: LibraryUser, reach: Reach, anchors: number[]): Promise<PlacesLibraryEntry[]> {
/** The entries `anchors` as the list shows them, in their order. */
async entries(user: LibraryUser, reach: LibraryReach, anchors: number[]): Promise<PlacesLibraryEntry[]> {
const rows = await this.rows(reach, anchors);
const access = await this.access(
user,
rows.flatMap((row) => (row.trip ? [row.trip] : [])),
rows.flatMap((row) => row.trips),
rows.flatMap((row) => row.saved),
);
return rows.map((row) => entryOf(row, access));
}
/** One entry, or null when it has no use the user reaches. */
async entry(user: LibraryUser, anchor: number | null): Promise<PlacesLibraryEntry | null> {
if (anchor === null) return null;
return (await this.entries(user, await this.reach(user.id), [anchor]))[0] ?? null;
}
/**
* Whether the user may change each origin: a saved place with any list role
* but viewer (assertCanEdit's rule), a trip place with 'place_edit', which
* reads the same for every trip the user owns and for every one they are a
* member of, so it is asked once for each.
*/
private async access(
async access(
user: LibraryUser,
trips: readonly LibraryTripPlaceRow[],
saved: readonly LibraryCollectionPlaceRow[],
@@ -190,32 +229,34 @@ export class PlacesLibraryService {
};
}
/** What each origin keeps, in the entry's origin order: the trip place first, then the saved places. */
/** 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<PlacesLibraryDetail[]> {
const details: PlacesLibraryDetail[] = [];
if (rows.trip) {
const placeIds = [rows.trip.id];
const notes = await this.repo.tripPlaceNotes(placeIds);
const ratings = await this.repo.tripPlaceRatings(placeIds);
const days = await this.repo.plannedDays(placeIds);
if (rows.trips.length > 0) {
const placeIds = rows.trips.map((row) => row.id);
const notes = new Map((await this.repo.tripPlaceNotes(placeIds)).map((row) => [row.id, row.notes]));
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);
details.push({
kind: 'trip',
place_id: rows.trip.id,
info: infoOf(rows.trip),
notes: notes[0]?.notes ?? null,
rating: ratingOf(ratings, userId),
days: days.map((day) => ({
day_id: day.day_id,
day_number: day.day_number,
date: day.date,
title: day.title,
time: day.time,
end_time: day.end_time,
})),
has_accommodation: booked.stays.includes(rows.trip.id),
has_reservation: booked.bookings.includes(rows.trip.id),
});
for (const row of rows.trips) {
details.push({
kind: 'trip',
place_id: row.id,
info: infoOf(row),
notes: notes.get(row.id) ?? null,
rating: ratingOf(ratings.get(row.id) ?? [], userId),
days: (days.get(row.id) ?? []).map((day) => ({
day_id: day.day_id,
day_number: day.day_number,
date: day.date,
title: day.title,
time: day.time,
end_time: day.end_time,
})),
has_accommodation: booked.stays.includes(row.id),
has_reservation: booked.bookings.includes(row.id),
});
}
}
if (rows.saved.length > 0) {
const savedIds = rows.saved.map((row) => row.id);
@@ -242,13 +283,14 @@ export class PlacesLibraryService {
* list, a status) leaves the trips out, a filter on a trip the lists; a list
* or trip out of reach reads as none, so it answers like an empty one.
*/
function armsFor(reach: Reach, query: PlacesLibraryQuery): LibraryArms {
function armsFor(reach: LibraryReach, query: PlacesLibraryQuery): LibraryArms {
const listsOnly = query.kind === 'list' || query.collection_id !== undefined || query.status !== undefined;
const tripsOnly = query.kind === 'trip' || query.trip_id !== undefined;
if (listsOnly && tripsOnly) throw badRequest('Filter by a trip or by a list, not both');
const only = (ids: number[], id: number | undefined) =>
id === undefined ? ids : ids.filter((reachable) => reachable === id);
return {
userId: reach.userId,
tripIds: listsOnly ? [] : only(reach.tripIds, query.trip_id),
collectionIds: tripsOnly ? [] : only(reach.collectionIds, query.collection_id),
reachableTripIds: reach.tripIds,
@@ -0,0 +1,70 @@
import { ADDON_IDS } from '../../addons';
import type { TripAccess } from '../../db/repositories/Trips.repository';
import type { User } from '../../types';
import { AddonGuard } from '../addons/addon.guard';
import { RequireAddon } from '../addons/require-addon.decorator';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { rowId } from '../common/row-id.pipe';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { Trip } from '../permissions/trip.decorator';
import { TripCollectionLinkDto } from './trip-collections.dto';
import { TripCollectionsService } from './trip-collections.service';
import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common';
import { tripCollectionLayerResponseSchema, tripCollectionLinksResponseSchema } from '@trek/shared';
/**
* PLC-15/PLC-16 at /api/trips/:tripId/collections: the lists of saved places
* a trip draws on, and their saved places for the trip map. Every member reads
* the lists open to them; linking and unlinking take 'place_edit'. Behind the
* Collections addon: with it off the routes answer 404.
*/
@Controller('api/trips/:tripId/collections')
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
export class TripCollectionsController {
constructor(private readonly tripCollections: TripCollectionsService) {}
@Get()
@ResponseContract(tripCollectionLinksResponseSchema)
async list(@CurrentUser() user: User, @Trip() trip: TripAccess) {
return this.tripCollections.list(trip.id, user);
}
@Get('places')
@ResponseContract(tripCollectionLayerResponseSchema)
async layer(@CurrentUser() user: User, @Trip() trip: TripAccess) {
return this.tripCollections.layer(trip.id, user);
}
@Post()
@HttpCode(200)
@RequirePermission('place_edit')
@ResponseContract(tripCollectionLinksResponseSchema)
async link(
@CurrentUser() user: User,
@Trip() trip: TripAccess,
@Body() body: TripCollectionLinkDto,
@Headers('x-socket-id') socketId?: string,
) {
return this.tripCollections.link(
trip.id,
body.collection_id,
this.tripCollections.restWriter(trip.id, user, socketId),
);
}
@Delete(':collectionId')
@HttpCode(200)
@RequirePermission('place_edit')
@ResponseContract(tripCollectionLinksResponseSchema)
async unlink(
@CurrentUser() user: User,
@Trip() trip: TripAccess,
@Param('collectionId', rowId('Collection not found')) collectionId: number,
@Headers('x-socket-id') socketId?: string,
) {
return this.tripCollections.unlink(trip.id, collectionId, this.tripCollections.restWriter(trip.id, user, socketId));
}
}
@@ -0,0 +1,5 @@
import { tripCollectionLinkRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class TripCollectionLinkDto extends createZodDto(tripCollectionLinkRequestSchema) {}
@@ -0,0 +1,97 @@
import { ADDON_IDS } from '../../addons';
import { canRead, canReadTrips, canWrite } from '../../mcp/scopes';
import {
McpController,
Tool,
TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_WRITE,
ok,
type McpContext,
} from '../../nest-mcp';
import { addonGate } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { TripCollectionsService } from './trip-collections.service';
import { idSchema, tripCollectionLinkRequestSchema } from '@trek/shared';
/** Reading a trip's linked lists reads the trip and the lists. */
const readsTripAndLists = (ctx: McpContext) => canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
/** Linking changes the trip's places panel and needs the list to be readable. */
const linksLists = (ctx: McpContext) => canWrite(ctx.scopes, 'places') && canRead(ctx.scopes, 'collections');
const tripInput = { tripId: idSchema };
const linkInput = { tripId: idSchema, collection_id: tripCollectionLinkRequestSchema.shape.collection_id };
/**
* PLC-15/PLC-16 over MCP: the same service, the same 'place_edit' and list
* checks as `/api/trips/:tripId/collections`, behind the Collections addon.
*/
@McpController()
export class TripCollectionsMcp {
constructor(
private readonly tripCollections: TripCollectionsService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of every tool here.
readonly addons: AddonsService,
) {}
@Tool({
name: 'list_trip_collections',
description:
'The lists of saved places linked to a trip that you can open (lists linked by others that are closed to you are left out), with your role on each, how many places it holds, and whether you may link or unlink lists on this trip.',
inputSchema: tripInput,
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: readsTripAndLists,
})
async listTripCollections({ tripId }: { tripId: number }, ctx: McpContext) {
const { role } = await this.guards.tripWriter(tripId, ctx.userId);
return ok(await this.tripCollections.list(tripId, { id: ctx.userId, role }));
}
@Tool({
name: 'get_trip_collection_places',
description:
'The saved places with a position of every list linked to the trip that you can open, for the trip map: id, collection_id, name, lat, lng, category, status and in_trip (with trip_place_id) when the trip already has that place. Add one to the trip with copy_collection_places_to_trip.',
inputSchema: tripInput,
annotations: TOOL_ANNOTATIONS_READONLY,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: readsTripAndLists,
})
async getTripCollectionPlaces({ tripId }: { tripId: number }, ctx: McpContext) {
const { role } = await this.guards.tripWriter(tripId, ctx.userId);
return ok(await this.tripCollections.layer(tripId, { id: ctx.userId, role }));
}
@Tool({
name: 'link_collection_to_trip',
description:
'Link one of the lists of saved places you can open to a trip, so the trip can show its places. Gives no one access: members see the list only if it is open to them anyway. Needs the permission to edit the trip places.',
inputSchema: linkInput,
annotations: TOOL_ANNOTATIONS_WRITE,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: linksLists,
})
async linkCollectionToTrip({ tripId, collection_id }: { tripId: number; collection_id: number }, ctx: McpContext) {
const writer = await this.guards.tripWriter(tripId, ctx.userId);
return ok(await this.tripCollections.link(tripId, collection_id, writer));
}
@Tool({
name: 'unlink_collection_from_trip',
description:
'Unlink a list of saved places from a trip. The list and its places stay as they are. Needs the permission to edit the trip places and the list to be open to you.',
inputSchema: linkInput,
annotations: TOOL_ANNOTATIONS_DELETE,
when: addonGate(ADDON_IDS.COLLECTIONS),
access: linksLists,
})
async unlinkCollectionFromTrip(
{ tripId, collection_id }: { tripId: number; collection_id: number },
ctx: McpContext,
) {
const writer = await this.guards.tripWriter(tripId, ctx.userId);
return ok(await this.tripCollections.unlink(tripId, collection_id, writer));
}
}
@@ -0,0 +1,28 @@
import { TripCollectionLinks } from '../../db/entities/TripCollectionLinks.entity';
import { AddonsModule } from '../addons/addons.module';
import { CollectionsModule } from '../collections/collections.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { TripCollectionsController } from './trip-collections.controller';
import { TripCollectionsMcp } from './trip-collections.mcp';
import { TripCollectionsService } from './trip-collections.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
/** PLC-15/PLC-16: the lists of saved places a trip draws on, their routes and MCP tools. */
@Module({
imports: [
AddonsModule,
CollectionsModule,
TripMembershipModule,
PermissionsModule,
RealtimeModule,
McpSharedModule,
MikroOrmModule.forFeature([TripCollectionLinks]),
],
controllers: [TripCollectionsController],
providers: [TripCollectionsService, TripCollectionsMcp],
})
export class TripCollectionsModule {}
@@ -0,0 +1,155 @@
import { TripCollectionLinks } from '../../db/entities/TripCollectionLinks.entity';
import type { TripCollectionLinksRepository } from '../../db/repositories/TripCollectionLinks.repository';
import type { User } from '../../types';
import { CollectionsService } from '../collections/collections.service';
import { notFound } from '../common/domain-error';
import { requireTripWrite, restTripWriter, tripNotFound, type TripWriter } from '../common/trip-writer';
import { PermissionsService } from '../permissions/permissions.service';
import { RealtimeService } from '../realtime/realtime.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
collectionStatusSchema,
TRIP_COLLECTION_ROLES,
type TripCollectionLayerResponse,
type TripCollectionLink,
type TripCollectionLinksResponse,
} from '@trek/shared';
/** Who reads: their id and their account role, for the admin bypass of trip permissions. */
interface TripCollectionsReader {
id: number;
role: string;
}
/**
* Linking a list to a trip or unlinking it changes the trip's places panel
* for everyone on it, so it takes 'place_edit': the right to change the
* trip's places, which copying a saved place into the trip already needs.
* 'trip_edit' (the trip's own settings, owner-only by default) would keep
* the members who plan the places from using their own lists.
*/
const LINK_PERMISSION = 'place_edit';
const collectionNotFound = () => notFound('Collection not found');
/**
* PLC-15/PLC-16: the lists of saved places a trip draws on. A link gives no
* one access: each member sees a linked list, its count included, only while
* the list is open to them on their own (owner or accepted member), and
* nothing of a list that is not. Linking and unlinking take 'place_edit' on
* the trip and a list the caller can see; a list they cannot see is not
* found. A trip or list deleted takes its links along (ON DELETE CASCADE).
* Nothing here writes a trip place or a saved place.
*/
@Injectable()
export class TripCollectionsService {
constructor(
@InjectRepository(TripCollectionLinks) private readonly links: TripCollectionLinksRepository,
private readonly collections: CollectionsService,
private readonly trips: TripAccessService,
private readonly permissions: PermissionsService,
private readonly realtime: RealtimeService,
) {}
/** The REST caller of a link write: skips the sender's socket. */
restWriter(tripId: number, user: User, socketId: string | undefined): TripWriter {
return restTripWriter(this.realtime, tripId, user, socketId);
}
private async requireTrip(tripId: number, userId: number) {
const trip = await this.trips.findAccessible(tripId, userId);
if (!trip) throw tripNotFound();
return trip;
}
/** The trip's linked lists the reader can open, with their role there, and whether they may change the links. */
async list(tripId: number, reader: TripCollectionsReader): Promise<TripCollectionLinksResponse> {
const trip = await this.requireTrip(tripId, reader.id);
const canLink = await this.permissions.checkPermission(
LINK_PERMISSION,
reader.role,
trip.user_id,
reader.id,
trip.user_id !== reader.id,
);
const visible = new Set(await this.collections.accessibleCollectionIds(reader.id));
const rows = (await this.links.listForTrip(tripId)).filter((row) => visible.has(row.collection_id));
const roles = await Promise.all(
rows.map(async (row) =>
row.owner_id === reader.id ? 'owner' : await this.collections.roleOf(reader.id, row.collection_id),
),
);
const links = rows.flatMap((row, index): TripCollectionLink[] => {
const role = TRIP_COLLECTION_ROLES.find((known) => known === roles[index]);
if (!role) return [];
return [
{
collection_id: row.collection_id,
name: row.name,
color: row.color,
role,
place_count: row.place_count,
linked_by: row.linked_by,
created_at: row.created_at,
},
];
});
return { links, can_link: canLink };
}
/** Links a list the writer can open to the trip. Linking it again changes nothing and sends nothing. */
async link(tripId: number, collectionId: number, writer: TripWriter): Promise<TripCollectionLinksResponse> {
await this.gate(tripId, collectionId, writer);
const before = (await this.links.listForTrip(tripId)).some((row) => row.collection_id === collectionId);
if (!before) {
await this.links.link(tripId, collectionId, writer.userId);
writer.events.emit('tripCollections:changed', {});
}
return this.list(tripId, { id: writer.userId, role: writer.role });
}
/** Unlinks a list the writer can open from the trip; the list itself stays as it is. */
async unlink(tripId: number, collectionId: number, writer: TripWriter): Promise<TripCollectionLinksResponse> {
await this.gate(tripId, collectionId, writer);
if (!(await this.links.unlink(tripId, collectionId))) throw notFound('This list is not linked to the trip');
writer.events.emit('tripCollections:changed', {});
return this.list(tripId, { id: writer.userId, role: writer.role });
}
/**
* The saved places with a position of every linked list the reader can
* open, for the trip map, each with whether the trip already has it.
*/
async layer(tripId: number, reader: TripCollectionsReader): Promise<TripCollectionLayerResponse> {
await this.requireTrip(tripId, reader.id);
const visible = new Set(await this.collections.accessibleCollectionIds(reader.id));
const linked = (await this.links.listForTrip(tripId))
.map((row) => row.collection_id)
.filter((id) => visible.has(id));
const rows = linked.length > 0 ? await this.links.layerPlaces(tripId, linked) : [];
return {
places: rows.map((row) => ({
id: row.id,
collection_id: row.collection_id,
name: row.name,
lat: row.lat,
lng: row.lng,
category:
row.category_id === null || row.category_name === null
? null
: { id: row.category_id, name: row.category_name, color: row.category_color, icon: row.category_icon },
status: collectionStatusSchema.parse(row.status),
in_trip: row.trip_place_id !== null,
trip_place_id: row.trip_place_id,
})),
};
}
/** The trip with 'place_edit' (404, 403) and a list the writer can see (404). */
private async gate(tripId: number, collectionId: number, writer: TripWriter): Promise<void> {
await requireTripWrite({ access: this.trips, permissions: this.permissions }, LINK_PERMISSION, tripId, writer);
if ((await this.collections.roleOf(writer.userId, collectionId)) === null) throw collectionNotFound();
}
}
+5 -7
View File
@@ -25,6 +25,7 @@ import {
createDayAssignment,
} from '../helpers/factories';
import { countRows, findRow } from '../helpers/factories/rows';
import { oneByOne } from '../helpers/one-by-one';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
@@ -892,13 +893,10 @@ describe('Collections e2e (real auth guard + real service + temp SQLite)', () =>
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const col = (await request(server).post('/api/addons/collections').set(as(ownerId)).send({ name: 'Ordered' })).body;
const ids: number[] = [];
for (const name of ['One', 'Two', 'Three']) {
const saved = await request(server)
.post('/api/addons/collections/places')
.set(as(ownerId))
.send({ collection_id: col.id, name });
ids.push(saved.body.place.id);
}
const saves = await oneByOne(['One', 'Two', 'Three'], (name) =>
request(server).post('/api/addons/collections/places').set(as(ownerId)).send({ collection_id: col.id, name }),
);
ids.push(...saves.map((saved) => saved.body.place.id as number));
const reorder = (userId: number | null, orderedIds: number[]) => {
const req = request(server).put(`/api/addons/collections/${col.id}/places/reorder`);
return (userId === null ? req : req.set(as(userId))).send({ orderedIds });
+93 -5
View File
@@ -12,6 +12,7 @@ import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { setAddonEnabled } from '../helpers/factories/settings';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { oneByOne } from '../helpers/one-by-one';
import { expectedKeysByName, seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture';
import { resetTestDb } from '../helpers/test-db';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
@@ -107,9 +108,11 @@ describe('Places library e2e (real guards + temp SQLite)', () => {
.set(as(f.me.id));
expect(trips.status).toBe(200);
expect(trips.body.entries.map((entry: { key: string }) => entry.key)).toEqual([`trip:${f.places.forum.id}`]);
for (const query of [{ category_id: '0x5' }, { kind: 'tour' }, { limit: '1000' }, { notes: 'x' }]) {
expect((await request(server).get(BASE).query(query).set(as(f.me.id))).status).toBe(400);
}
const refused = await oneByOne(
[{ category_id: '0x5' }, { kind: 'tour' }, { limit: '1000' }, { notes: 'x' }],
(query) => request(server).get(BASE).query(query).set(as(f.me.id)),
);
expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400]);
const both = await request(server)
.get(BASE)
.query({ kind: 'list', trip_id: String(f.alps.id) })
@@ -128,10 +131,95 @@ describe('Places library e2e (real guards + temp SQLite)', () => {
expect(saved.status).toBe(200);
expect(saved.body.entry.origins[0]).toMatchObject({ kind: 'list', can_edit: false });
for (const path of [`trip/${f.places.hidden.id}`, `list/${f.saved.secret.id}`, 'trip/abc', 'list/0x5']) {
const res = await request(server).get(`${BASE}/${path}`).set(as(f.me.id));
const missing = await oneByOne(
[`trip/${f.places.hidden.id}`, `list/${f.saved.secret.id}`, 'trip/abc', 'list/0x5'],
(path) => request(server).get(`${BASE}/${path}`).set(as(f.me.id)),
);
for (const res of missing) {
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Place not found' });
}
});
});
describe('Own places, duplicates and merges e2e (real guards + temp SQLite)', () => {
const LIBRARY = '/api/addons/collections/library';
it('answers 404 while Collections is off and 401 without a session', async () => {
await setAddonEnabled(orm, 'collections', false);
expect((await request(server).get(`${LIBRARY}/duplicates`)).status).toBe(404);
await setAddonEnabled(orm, 'collections', true);
expect((await request(server).post(`${LIBRARY}/places/link`).send({ uses: [] })).status).toBe(401);
});
it('links, unlinks, suggests, merges and undoes, each answer checked against its contract', async () => {
const link = await request(server)
.post(`${LIBRARY}/places/link`)
.set(as(f.me.id))
.send({
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
});
expect(link.status).toBe(200);
expect(link.body.entry.key).toBe(`own:${link.body.entry.identity_id}`);
const unlink = await request(server)
.post(`${LIBRARY}/places/unlink`)
.set(as(f.me.id))
.send({ kind: 'list', id: f.saved.pantheon.id });
expect(unlink.status).toBe(200);
expect(unlink.body.entry.key).toBe(`list:${f.saved.pantheon.id}`);
const duplicates = await request(server).get(`${LIBRARY}/duplicates`).query({ limit: '1' }).set(as(f.me.id));
expect(duplicates.status).toBe(200);
expect(duplicates.body.duplicates).toHaveLength(1);
expect(duplicates.body.next_cursor).not.toBeNull();
const [pair] = duplicates.body.duplicates;
const merge = await request(server)
.post(`${LIBRARY}/merges`)
.set(as(f.me.id))
.send({ leading: pair.a.key, other: pair.b.key });
expect(merge.status).toBe(200);
const undo = await request(server).post(`${LIBRARY}/merges/${merge.body.merge_id}/undo`).set(as(f.me.id));
expect(undo.status).toBe(200);
expect(undo.body).toEqual({ success: true });
const dismiss = await request(server)
.post(`${LIBRARY}/duplicates/dismiss`)
.set(as(f.me.id))
.send({ a: pair.a.key, b: pair.b.key });
expect(dismiss.body).toEqual({ success: true });
});
it('refuses what it does not take, and what the user cannot reach', async () => {
const bad = [
{ uses: [{ kind: 'trip', id: '0x5' }] },
{ uses: [] },
{ uses: [{ kind: 'tour', id: 1 }] },
{ uses: [{ kind: 'trip', id: 1 }], extra: true },
];
const refused = await oneByOne(bad, (body) =>
request(server).post(`${LIBRARY}/places/link`).set(as(f.me.id)).send(body),
);
expect(refused.map((res) => res.status)).toEqual(bad.map(() => 400));
const hidden = await request(server)
.post(`${LIBRARY}/places/link`)
.set(as(f.me.id))
.send({ uses: [{ kind: 'trip', id: f.places.hidden.id }] });
expect(hidden.status).toBe(404);
expect(hidden.body).toEqual({ error: 'Place not found' });
const merge = await request(server)
.post(`${LIBRARY}/merges`)
.set(as(f.me.id))
.send({ leading: 'trip:abc', other: 'list:1' });
expect(merge.status).toBe(400);
const undos = await oneByOne(['abc', '0x5', '999999'], (id) =>
request(server).post(`${LIBRARY}/merges/${id}/undo`).set(as(f.me.id)),
);
for (const undo of undos) {
expect(undo.status).toBe(404);
expect(undo.body).toEqual({ error: 'Merge not found' });
}
});
});
@@ -0,0 +1,141 @@
/**
* The lists a trip draws on (PLC-15/PLC-16) through the real AddonGuard,
* JwtAuthGuard and TripAccessGuard against a migrated and seeded temp SQLite
* db, every answer checked against its response contract.
*/
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { TripCollectionsModule } from '../../src/nest/trip-collections/trip-collections.module';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { setAddonEnabled } from '../helpers/factories/settings';
import { addTripMember } from '../helpers/factories/trips';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { oneByOne } from '../helpers/one-by-one';
import { 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 } from 'vitest';
const db = createSnapshotTestDb();
const realtime = new FakeRealtimeService();
let app: INestApplication;
let server: Server;
let orm: TestOrm;
let f: LibraryFixture;
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const base = (tripId: number) => `/api/trips/${tripId}/collections`;
beforeAll(async () => {
const moduleRef = await Test.createTestingModule({
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
RealtimeModule,
TripCollectionsModule,
],
})
.overrideProvider(RealtimeService)
.useValue(realtime)
.compile();
app = moduleRef.createNestApplication();
app.use(cookieParser());
app.useGlobalPipes(new ZodValidationPipe());
app.useGlobalFilters(new TrekExceptionFilter());
await app.init();
server = app.getHttpServer() as Server;
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
realtime.reset();
f = await seedLibrary(orm);
await setAddonEnabled(orm, 'collections', true);
});
afterAll(async () => {
await app.close();
await orm.close();
db.close();
});
describe('Trip collections e2e (real guards + temp SQLite)', () => {
it('answers 404 while Collections is off, 401 without a session and 404 for a trip out of reach', async () => {
await setAddonEnabled(orm, 'collections', false);
expect((await request(server).get(base(f.alps.id))).status).toBe(404);
await setAddonEnabled(orm, 'collections', true);
expect((await request(server).get(base(f.alps.id))).status).toBe(401);
const hidden = await request(server).get(base(f.elsewhere.id)).set(as(f.me.id));
expect(hidden.status).toBe(404);
expect(hidden.body).toEqual({ error: 'Trip not found' });
});
it('links a list, lists it, maps its places and unlinks it, skipping the sender socket', async () => {
const link = await request(server)
.post(base(f.alps.id))
.set(as(f.me.id))
.set('X-Socket-Id', '42')
.send({ collection_id: f.lists.food.id });
expect(link.status).toBe(200);
expect(link.body.links).toEqual([expect.objectContaining({ collection_id: f.lists.food.id, role: 'owner' })]);
expect(realtime.broadcastMock).toHaveBeenCalledWith(f.alps.id, 'tripCollections:changed', {}, '42');
const layer = await request(server)
.get(`${base(f.alps.id)}/places`)
.set(as(f.me.id));
expect(layer.status).toBe(200);
expect(layer.body.places.some((place: { in_trip: boolean }) => place.in_trip)).toBe(true);
const unlink = await request(server)
.delete(`${base(f.alps.id)}/${f.lists.food.id}`)
.set(as(f.me.id));
expect(unlink.status).toBe(200);
expect(unlink.body).toEqual({ links: [], can_link: true });
});
it('refuses a body it does not take, a list out of reach and a bad id', async () => {
const refused = await oneByOne(
[{}, { collection_id: '0x5' }, { collection_id: 1.5 }, { collection_id: 1, x: 1 }],
(body) => request(server).post(base(f.alps.id)).set(as(f.me.id)).send(body),
);
expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400]);
const secret = await request(server)
.post(base(f.alps.id))
.set(as(f.me.id))
.send({ collection_id: f.lists.secrets.id });
expect(secret.status).toBe(404);
expect(secret.body).toEqual({ error: 'Collection not found' });
const missing = await oneByOne(['abc', '0x5'], (id) =>
request(server)
.delete(`${base(f.alps.id)}/${id}`)
.set(as(f.me.id)),
);
for (const res of missing) {
expect(res.status).toBe(404);
expect(res.body).toEqual({ error: 'Collection not found' });
}
});
it('shows a member nothing of a list closed to them', async () => {
await request(server).post(base(f.alps.id)).set(as(f.me.id)).send({ collection_id: f.lists.food.id });
await addTripMember(orm, f.alps.id, f.friend.id);
const res = await request(server).get(base(f.alps.id)).set(as(f.friend.id));
expect(res.status).toBe(200);
expect(res.body.links).toEqual([]);
const layer = await request(server)
.get(`${base(f.alps.id)}/places`)
.set(as(f.friend.id));
expect(layer.body).toEqual({ places: [] });
});
});
@@ -0,0 +1,43 @@
import { TripCollectionLinks } from '../../../src/db/entities/TripCollectionLinks.entity';
import { UserPlaceLinks } from '../../../src/db/entities/UserPlaceLinks.entity';
import { UserPlaces } from '../../../src/db/entities/UserPlaces.entity';
import { nextSeq, type FactoryOrm } from './context';
import { createRow } from './rows';
import type { EntityData, EntityDTO } from '@mikro-orm/core';
export type UserPlaceRow = EntityDTO<UserPlaces>;
export type UserPlaceLinkRow = EntityDTO<UserPlaceLinks>;
/** An own place (D5) of `userId`. */
export function makeUserPlace(
orm: FactoryOrm,
userId: number,
overrides: EntityData<UserPlaces> = {},
): Promise<UserPlaceRow> {
return createRow(orm, UserPlaces, { user: userId, name: `Own place ${nextSeq('user-place')}` }, overrides);
}
/** Links one use (a trip place or a saved place) of `userId` to the own place. */
export function linkUserPlace(
orm: FactoryOrm,
userId: number,
userPlaceId: number,
use: { place?: number; collectionPlace?: number },
): Promise<UserPlaceLinkRow> {
return createRow(orm, UserPlaceLinks, {
userPlace: userPlaceId,
user: userId,
place: use.place ?? null,
collectionPlace: use.collectionPlace ?? null,
});
}
/** Links a list to a trip (PLC-15). */
export function linkTripCollection(
orm: FactoryOrm,
tripId: number,
collectionId: number,
linkedBy: number | null = null,
): Promise<EntityDTO<TripCollectionLinks>> {
return createRow(orm, TripCollectionLinks, { trip: tripId, collection: collectionId, linkedByRef: linkedBy });
}
+14 -3
View File
@@ -153,12 +153,15 @@ export async function seedLibrary(orm: FactoryOrm) {
export type LibraryFixture = Awaited<ReturnType<typeof seedLibrary>>;
/** The keys of `me`'s entries by name, ties by key (a saved place's negative key first). */
/**
* The keys of `me`'s entries by name. Café Central's two entries tie on the
* name and then go by their anchor (`id * 4 + kind`, a trip place's kind 1,
* a saved place's 2), so their order follows the ids the seed got.
*/
export function expectedKeysByName(f: LibraryFixture): string[] {
const { places, saved } = f;
return [
`list:${saved.conflicting.id}`,
`trip:${places.cafe.id}`,
...cafeTie(f),
`trip:${places.camp.id}`,
`trip:${places.forum.id}`,
`list:${saved.hiddenCopy.id}`,
@@ -169,3 +172,11 @@ export function expectedKeysByName(f: LibraryFixture): string[] {
`list:${saved.pantheon.id}`,
];
}
/** The two entries named Café Central, in the order their anchors give. */
export function cafeTie(f: LibraryFixture): string[] {
const conflicting = f.saved.conflicting.id * 4 + 2;
const cafe = f.places.cafe.id * 4 + 1;
const pair = [`list:${f.saved.conflicting.id}`, `trip:${f.places.cafe.id}`];
return conflicting < cafe ? pair : [...pair].reverse();
}
@@ -7,6 +7,7 @@ import { StorageService } from '../../../src/nest/storage/storage.service';
import { makeDayAssignment } from '../../helpers/factories/itinerary';
import { makeTag } from '../../helpers/factories/places';
import { insertRow, updateRows } from '../../helpers/factories/rows';
import { linkTripCollection } from '../../helpers/factories/user-places';
import type { CaseGroup, Scene } from './types';
import { MikroORM } from '@mikro-orm/core';
import type { INestApplication } from '@nestjs/common';
@@ -380,6 +381,28 @@ export const plan: CaseGroup = {
},
expect: ['place:created'],
},
{
// PLC-15: content-free, so every member asks again with their own list rights.
tool: 'link_collection_to_trip',
needs: ['collection'],
args: (s) => ({ tripId: s.trip.id, collection_id: s.collection.id }),
rest: {
method: 'post',
path: (s) => `/api/trips/${s.trip.id}/collections`,
body: (s) => ({ collection_id: s.collection.id }),
},
expect: ['tripCollections:changed'],
},
{
tool: 'unlink_collection_from_trip',
needs: ['collection'],
setup: async (s, app) => {
await linkTripCollection(app.get(MikroORM), s.trip.id, s.collection.id, s.owner.id);
},
args: (s) => ({ tripId: s.trip.id, collection_id: s.collection.id }),
rest: { method: 'delete', path: (s) => `/api/trips/${s.trip.id}/collections/${s.collection.id}` },
expect: ['tripCollections:changed'],
},
{
tool: 'create_day_note',
args: (s) => ({ tripId: s.trip.id, dayId: s.days[0].id, text: 'Bring the museum pass' }),
@@ -15,10 +15,12 @@ import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.s
import { JourneyRecordedDaysService } from '../../../src/nest/journey/journey-recorded-days.service';
import { PhotoCaptureBackfillService } from '../../../src/nest/memories/photo-capture-backfill.service';
import { NotificationsService } from '../../../src/nest/notifications/notifications.service';
import { PlaceIdentitiesService } from '../../../src/nest/places-library/place-identities.service';
import { addCollectionMember } from '../../helpers/factories/collections';
import { inContext } from '../../helpers/factories/context';
import { addJourneyContributor, linkTripToJourney, makeJourneyEntry } from '../../helpers/factories/journeys';
import { createRow, insertRow, updateRows } from '../../helpers/factories/rows';
import { linkUserPlace, makeUserPlace } from '../../helpers/factories/user-places';
import { addVacayPlanMember } from '../../helpers/factories/vacay';
import { holidayCode } from './harness';
import type { CaseGroup, ParityCase, RestCall, Scene } from './types';
@@ -35,6 +37,25 @@ import { vi } from 'vitest';
* that asked, MCP none, so the tab the assistant runs in shows the change.
*/
const HOLIDAY_CATALOG = "the admin's school holiday catalog is global: no room, and the registry has no event for it";
const OWN_PLACES =
"changes only the caller's own grouping of All places (D5): no trip place or saved place is written and nobody else sees it, so there is nothing to send";
const placeKeys = (s: Scene) => ({ a: `trip:${s.place.id}`, b: `trip:${s.place2.id}` });
/** The owner's own place holding the scene's first place, for the unlink. */
async function ownPlace(s: Scene, app: INestApplication): Promise<void> {
const own = await makeUserPlace(ormOf(app), s.owner.id);
await linkUserPlace(ormOf(app), s.owner.id, own.id, { place: s.place.id });
}
/** The scene's two places merged by the owner, for the undo. */
async function mergedPlaces(s: Scene, app: INestApplication): Promise<void> {
const merged = await withRequestContext(ormOf(app), () =>
app
.get(PlaceIdentitiesService)
.merge({ id: s.owner.id, role: 'user' }, `trip:${s.place.id}`, `trip:${s.place2.id}`),
);
keep(s, 'merge', merged.merge_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' };
@@ -1305,6 +1326,38 @@ export const user: CaseGroup = {
setup: recordStay,
args: (s) => ({ suggestionId: kept(s, 'stay') }),
},
{
tool: 'link_library_places',
reason: OWN_PLACES,
needs: ['place', 'place2'],
args: (s) => ({
uses: [
{ kind: 'trip', id: s.place.id },
{ kind: 'trip', id: s.place2.id },
],
}),
},
{
tool: 'unlink_library_place',
reason: OWN_PLACES,
needs: ['place'],
setup: ownPlace,
args: (s) => ({ kind: 'trip', id: s.place.id }),
},
{ tool: 'dismiss_library_duplicate', reason: OWN_PLACES, needs: ['place', 'place2'], args: placeKeys },
{
tool: 'merge_library_places',
reason: OWN_PLACES,
needs: ['place', 'place2'],
args: (s) => ({ leading: `trip:${s.place.id}`, other: `trip:${s.place2.id}` }),
},
{
tool: 'undo_library_merge',
reason: OWN_PLACES,
needs: ['place', 'place2'],
setup: mergedPlaces,
args: (s) => ({ merge_id: kept(s, 'merge') }),
},
{
tool: 'create_manual_school_holiday_country',
reason: HOLIDAY_CATALOG,
@@ -119,6 +119,8 @@ const UNNUMBERED = [
'Migration20200101046500_an_address_moved_before_an_admin_saved_the_account',
'Migration20200101046510_a_session_knows_its_provider_session',
'Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to',
'Migration20200101046530_a_user_keeps_their_own_place_identities',
'Migration20200101046540_a_trip_links_its_collections',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -490,9 +490,9 @@ describe('CollectionsController', () => {
new RuntimeEnvService(),
storageStub,
);
for (const code of ['not-map', 'unreadable', 'too-many-places'] as const) {
expect(await rejected(refuse(code).readMap(upload))).toEqual({ status: 400, body: { error: 'refused', code } });
}
const codes = ['not-map', 'unreadable', 'too-many-places'] as const;
const answers = await Promise.all(codes.map((code) => rejected(refuse(code).readMap(upload))));
expect(answers).toEqual(codes.map((code) => ({ status: 400, body: { error: 'refused', code } })));
expect(await rejected(refuse('too-large').readMap(upload))).toEqual({
status: 413,
body: { error: 'refused', code: 'too-large' },
@@ -152,8 +152,9 @@ describe('CollectionsService.copyToTrip: notes and tags only when asked for (D9)
await svc.copyToTrip(user.id, { trip_id: trip.id, place_ids: [spot.id] }, svc.tripEvents(trip.id, undefined));
const copy = await findRow(orm, Places, { trip: trip.id, name: 'Cafe' });
expect(copy?.notes).toBeNull();
expect(await tagsOf(copy!.id)).toEqual([]);
if (!copy) throw new Error('the copy is missing');
expect(copy.notes).toBeNull();
expect(await tagsOf(copy.id)).toEqual([]);
expect(tripTagEvents()).toEqual([]);
});
@@ -201,7 +202,8 @@ describe('CollectionsService.copyToTrip: notes and tags only when asked for (D9)
const skyBar = await findRow(orm, Places, { trip: trip.id, name: 'Sky Bar' });
const garden = await findRow(orm, Places, { trip: trip.id, name: 'Garden' });
const sky = await tagsOf(skyBar!.id);
if (!skyBar || !garden) throw new Error('a copy is missing');
const sky = await tagsOf(skyBar.id);
expect(sky).toHaveLength(2);
expect(sky).toEqual(
expect.arrayContaining([
@@ -209,10 +211,10 @@ describe('CollectionsService.copyToTrip: notes and tags only when asked for (D9)
['Brunch', trip.id, owner.id],
]),
);
expect(await tagsOf(garden!.id)).toEqual([['Brunch', trip.id, owner.id]]);
expect(await tagsOf(garden.id)).toEqual([['Brunch', trip.id, owner.id]]);
// One new trip tag for both places, the trip's own one reused, the personal tags left where they were.
expect(await countRows(orm, Tags, { trip: trip.id })).toBe(2);
expect((await findRows(orm, Tags, { place_tags_inverse: skyBar!.id })).map((tag) => tag.id)).toContain(existing.id);
expect((await findRows(orm, Tags, { place_tags_inverse: skyBar.id })).map((tag) => tag.id)).toContain(existing.id);
expect(tripTagEvents()).toEqual([[trip.id, 'tripTags:changed', {}, 'sock-1']]);
});
@@ -18,6 +18,7 @@ import { makeCategory, makePlace } from '../../helpers/factories/places';
import { findRow, findRows } from '../../helpers/factories/rows';
import { makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { oneByOne } from '../../helpers/one-by-one';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
@@ -100,15 +101,17 @@ describe('reorderPlaces (PLC-03)', () => {
const foreign = await save(user.id, other.id, 'Foreign');
t.realtime.reset();
for (const ids of [
[b.id, foreign.id],
[b.id, b.id, a.id],
]) {
await expect(svc.reorderPlaces(user.id, col.id, ids)).rejects.toMatchObject({
status: 400,
message: 'Every place of the order must be in this list, once',
});
}
await oneByOne(
[
[b.id, foreign.id],
[b.id, b.id, a.id],
],
(ids) =>
expect(svc.reorderPlaces(user.id, col.id, ids)).rejects.toMatchObject({
status: 400,
message: 'Every place of the order must be in this list, once',
}),
);
expect(await namesInOrder(user.id, col.id)).toEqual(['A', 'B']);
expect(t.realtime.broadcastToUserMock).not.toHaveBeenCalled();
});
@@ -185,13 +188,14 @@ describe('a new place goes after the last one (PLC-03)', () => {
const { user } = await makeUser(orm());
const col = await svc.createCollection(user.id, { name: 'Coords' });
const { place } = await svc.savePlace(user.id, { collection_id: col.id, name: 'Pin', lat: 38.7, lng: -9.1 });
if (!place) throw new Error('nothing saved');
await svc.updatePlace(user.id, place!.id, { address: 'Rua Augusta 1' });
expect(await findRow(orm(), CollectionPlaces, { id: place!.id })).toMatchObject({ lat: 38.7, lng: -9.1 });
await svc.updatePlace(user.id, place!.id, { lat: null, lng: null });
expect(await findRow(orm(), CollectionPlaces, { id: place!.id })).toMatchObject({ lat: null, lng: null });
await svc.updatePlace(user.id, place!.id, { lat: 38.71, lng: -9.14 });
expect(await findRow(orm(), CollectionPlaces, { id: place!.id })).toMatchObject({ lat: 38.71, lng: -9.14 });
await svc.updatePlace(user.id, place.id, { address: 'Rua Augusta 1' });
expect(await findRow(orm(), CollectionPlaces, { id: place.id })).toMatchObject({ lat: 38.7, lng: -9.1 });
await svc.updatePlace(user.id, place.id, { lat: null, lng: null });
expect(await findRow(orm(), CollectionPlaces, { id: place.id })).toMatchObject({ lat: null, lng: null });
await svc.updatePlace(user.id, place.id, { lat: 38.71, lng: -9.14 });
expect(await findRow(orm(), CollectionPlaces, { id: place.id })).toMatchObject({ lat: 38.71, lng: -9.14 });
});
});
@@ -229,10 +233,12 @@ describe('savePlace keeps only a provenance the caller can stand behind', () =>
{ source_trip_id: mine.id }, // half a pair
{ source_place_id: minePlace.id },
];
for (const [i, claim] of claims.entries()) {
const rows = await oneByOne([...claims.entries()], async ([i, claim]) => {
const { place } = await svc.savePlace(user.id, { collection_id: col.id, name: `Claim ${i}`, ...claim });
const row = await findRow(orm(), CollectionPlaces, { id: place!.id });
expect([row?.source_trip_id, row?.source_place_id], JSON.stringify(claim)).toEqual([null, null]);
}
return place ? await findRow(orm(), CollectionPlaces, { id: place.id }) : null;
});
rows.forEach((row, i) =>
expect([row?.source_trip_id, row?.source_place_id], JSON.stringify(claims[i])).toEqual([null, null]),
);
});
});
@@ -0,0 +1,93 @@
/**
* The pure half of the duplicate suggestions (PLC-13): which entries pair up,
* found by bucket and never by comparing every entry with every other, which
* facts differ, and the page cursor.
*/
import {
decodeDuplicatesCursor,
differingFields,
DUPLICATE_BUCKET_MAX,
encodeDuplicatesCursor,
findDuplicates,
pairKey,
type DuplicateCandidate,
} from '../../../../src/nest/places-library/place-duplicates.helpers';
import { COORD_DEDUP_TOLERANCE } from '@trek/shared';
import { describe, expect, it } from 'vitest';
const candidate = (key: string, extra: Partial<DuplicateCandidate> = {}): DuplicateCandidate => ({
key,
name: 'Café',
lat: 48.2,
lng: 16.3,
address: null,
category_id: null,
google_place_id: null,
google_ftid: null,
osm_id: null,
provider_ids: [],
...extra,
});
describe('place duplicates helpers', () => {
it('PDUP-001: pairs the same name within the tolerance, across a cell border too, and nothing farther', () => {
const edge = Math.floor(48.2 / COORD_DEDUP_TOLERANCE) * COORD_DEDUP_TOLERANCE;
const pairs = findDuplicates([
candidate('trip:1', { lat: edge - COORD_DEDUP_TOLERANCE / 4 }),
candidate('list:2', { name: ' CAFÉ ', lat: edge + COORD_DEDUP_TOLERANCE / 4 }),
candidate('list:3', { lat: 48.3 }),
candidate('list:4', { name: 'Bar' }),
candidate('list:5', { lat: null, lng: null }),
]);
expect(pairs.map((pair) => [pair.a.key, pair.b.key, pair.reasons])).toEqual([
['list:2', 'trip:1', ['name_nearby']],
]);
});
it('PDUP-002: pairs a shared provider id whatever the names and positions, once per pair with both reasons', () => {
const pairs = findDuplicates([
candidate('own:1', { provider_ids: ['g-1', 'node/2'] }),
candidate('trip:9', { name: 'Elsewhere', lat: 1, lng: 1, provider_ids: ['g-1'] }),
candidate('list:3', { provider_ids: ['g-1'] }),
]);
expect(pairs.map((pair) => pairKey(pair.a.key, pair.b.key))).toEqual([
'list:3|own:1',
'list:3|trip:9',
'own:1|trip:9',
]);
expect(pairs[0]?.reasons).toEqual(['provider_id', 'name_nearby']);
expect(pairs[1]?.reasons).toEqual(['provider_id']);
});
it('PDUP-003: leaves a bucket out that is too full to be a duplicate', () => {
const crowd = Array.from({ length: DUPLICATE_BUCKET_MAX + 1 }, (_, index) =>
candidate(`list:${index + 1}`, { provider_ids: ['chain'], lat: index, lng: index, name: `Shop ${index}` }),
);
expect(findDuplicates(crowd)).toEqual([]);
});
it('PDUP-004: names the facts two sides differ in', () => {
const a = candidate('trip:1', { address: 'Main 1', category_id: 2, google_place_id: 'g' });
expect(
differingFields(a, candidate('list:2', { address: ' main 1 ', category_id: 2, google_place_id: 'g' })),
).toEqual([]);
expect(differingFields(a, candidate('list:3', { name: 'Bar', lat: 50, osm_id: 'n' }))).toEqual([
'name',
'position',
'address',
'category',
'google_place_id',
'osm_id',
]);
expect(differingFields(candidate('a:1', { lat: null }), candidate('b:1', { lng: null }))).not.toContain('position');
expect(differingFields(candidate('a:1', { lat: null }), candidate('b:1'))).toContain('position');
});
it('PDUP-005: hands out a cursor it reads back, and refuses anything else', () => {
const cursor = encodeDuplicatesCursor('list:3|trip:9');
expect(decodeDuplicatesCursor(cursor)).toBe('list:3|trip:9');
expect(decodeDuplicatesCursor('nonsense')).toBeNull();
expect(decodeDuplicatesCursor(encodeDuplicatesCursor('list:3'))).toBeNull();
});
});
@@ -0,0 +1,69 @@
/**
* PlaceIdentitiesController over stub services: each route hands the user and
* its input 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 type { PlaceDuplicatesService } from '../../../../src/nest/places-library/place-duplicates.service';
import { PlaceIdentitiesController } from '../../../../src/nest/places-library/place-identities.controller';
import type { PlaceIdentitiesService } from '../../../../src/nest/places-library/place-identities.service';
import type { User } from '../../../../src/types';
import {
placesLibraryDuplicatesResponseSchema,
placesLibraryEntryResponseSchema,
placesLibraryMergeResponseSchema,
successResponseSchema,
} 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' };
function controller(identities: Partial<PlaceIdentitiesService>, duplicates: Partial<PlaceDuplicatesService> = {}) {
return new PlaceIdentitiesController(
identities as unknown as PlaceIdentitiesService,
duplicates as unknown as PlaceDuplicatesService,
);
}
describe('PlaceIdentitiesController', () => {
it('PIDC-001: link and unlink hand the uses on with the user', async () => {
const answer = { entry: null };
const link = vi.fn().mockResolvedValue(answer);
const unlink = vi.fn().mockResolvedValue(answer);
const c = controller({ link, unlink });
const body = { uses: [{ kind: 'trip' as const, id: 3 }] };
expect(await c.link(user, body)).toBe(answer);
expect(await c.unlink(user, { kind: 'list', id: 4 })).toBe(answer);
expect(link).toHaveBeenCalledWith(me, body);
expect(unlink).toHaveBeenCalledWith(me, { kind: 'list', id: 4 });
});
it('PIDC-002: duplicates, dismiss, merge and undo reach their service methods', async () => {
const list = vi.fn().mockResolvedValue({ duplicates: [], next_cursor: null });
const dismiss = vi.fn().mockResolvedValue({ success: true });
const merge = vi.fn().mockResolvedValue({ merge_id: 2, entry: null });
const undoMerge = vi.fn().mockResolvedValue({ success: true });
const c = controller({ dismiss, merge, undoMerge }, { list });
await c.listDuplicates(user, { limit: 5 });
await c.dismiss(user, { a: 'trip:1', b: 'list:2' });
await c.merge(user, { leading: 'trip:1', other: 'list:2' });
await c.undoMerge(user, 2);
expect(list).toHaveBeenCalledWith(me, { limit: 5 });
expect(dismiss).toHaveBeenCalledWith(7, 'trip:1', 'list:2');
expect(merge).toHaveBeenCalledWith(me, 'trip:1', 'list:2');
expect(undoMerge).toHaveBeenCalledWith(me, 2);
});
it('PIDC-003: declares the shared response contracts', () => {
const proto = PlaceIdentitiesController.prototype;
const contract = (handler: unknown) => Reflect.getMetadata(RESPONSE_CONTRACT_KEY, handler as object) as unknown;
expect(contract(proto.link)).toBe(placesLibraryEntryResponseSchema);
expect(contract(proto.unlink)).toBe(placesLibraryEntryResponseSchema);
expect(contract(proto.listDuplicates)).toBe(placesLibraryDuplicatesResponseSchema);
expect(contract(proto.dismiss)).toBe(successResponseSchema);
expect(contract(proto.merge)).toBe(placesLibraryMergeResponseSchema);
expect(contract(proto.undoMerge)).toBe(successResponseSchema);
});
});
@@ -0,0 +1,138 @@
/**
* PlaceIdentitiesMcp (D5/PLC-13): the own-place, duplicate and merge tools
* over the same services as REST, with the addon gate and the scopes they
* need, and the nightly sweep. Taken from the container over a snapshot db.
*/
import { UserPlaces } from '../../../../src/db/entities/UserPlaces.entity';
import type { McpContext } from '../../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
import { AddonsService } from '../../../../src/nest/addons/addons.service';
import { PlaceIdentitiesPruneJob } from '../../../../src/nest/places-library/place-identities-prune.job';
import { PlaceIdentitiesMcp } from '../../../../src/nest/places-library/place-identities.mcp';
import { PlaceIdentitiesService } from '../../../../src/nest/places-library/place-identities.service';
import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-library.module';
import { CronRegistrarService } from '../../../../src/nest/scheduling/cron-registrar.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { countRows } from '../../../helpers/factories/rows';
import { makeUserPlace } from '../../../helpers/factories/user-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 { 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: PlaceIdentitiesMcp;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [PlacesLibraryModule] });
mcp = t.get(PlaceIdentitiesMcp);
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(PlaceIdentitiesMcp as unknown as ClassRef, name);
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
describe('PlaceIdentitiesMcp', () => {
it('PID-MCP-001: links, unlinks, merges and undoes as REST does', async () => {
const linked = read(
await mcp.linkLibraryPlaces(
{
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
},
ctx(f.me.id),
),
);
expect(linked.entry.key).toBe(`own:${linked.entry.identity_id}`);
const out = read(await mcp.unlinkLibraryPlace({ kind: 'list', id: f.saved.pantheon.id }, ctx(f.me.id)));
expect(out.entry.key).toBe(`list:${f.saved.pantheon.id}`);
const page = read(await mcp.listLibraryDuplicates({}, ctx(f.me.id)));
expect(page.duplicates).toHaveLength(2);
const [pair] = page.duplicates;
const merged = read(await mcp.mergeLibraryPlaces({ leading: pair.a.key, other: pair.b.key }, ctx(f.me.id)));
expect(merged.merge_id).toBeGreaterThan(0);
expect(read(await mcp.undoLibraryMerge({ merge_id: merged.merge_id }, ctx(f.me.id)))).toEqual({ success: true });
expect(read(await mcp.dismissLibraryDuplicate({ a: pair.a.key, b: pair.b.key }, ctx(f.me.id)))).toEqual({
success: true,
});
await expect(
mcp.linkLibraryPlaces({ uses: [{ kind: 'trip', id: f.places.hidden.id }] }, ctx(f.me.id)),
).rejects.toThrow('Place not found');
});
it('PID-MCP-002: the tools are there only with Collections on, and for tokens that may', async () => {
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false);
expect(await options('mergeLibraryPlaces').when?.(ctx(1), mcp)).toBe(false);
enabled.mockResolvedValue(true);
expect(await options('mergeLibraryPlaces').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 [
'linkLibraryPlaces',
'unlinkLibraryPlace',
'dismissLibraryDuplicate',
'mergeLibraryPlaces',
'undoLibraryMerge',
]) {
expect(allowed(name, ['collections:write', 'trips:read'])).toBe(true);
expect(allowed(name, ['collections:read', 'trips:read'])).toBe(false);
expect(options(name).annotations?.readOnlyHint).not.toBe(true);
}
expect(allowed('listLibraryDuplicates', ['collections:read', 'trips:read'])).toBe(true);
expect(allowed('listLibraryDuplicates', ['collections:read'])).toBe(false);
expect(options('listLibraryDuplicates').annotations).toMatchObject({ readOnlyHint: true });
});
it('PID-MCP-003: the nightly sweep removes own places nothing holds, and keeps going on a failure', async () => {
await makeUserPlace(orm, f.me.id);
const job = t.get(PlaceIdentitiesPruneJob);
await job.tick();
expect(await countRows(orm, UserPlaces, {})).toBe(0);
vi.spyOn(t.get(PlaceIdentitiesService), 'pruneAll').mockRejectedValue(new Error('boom'));
await expect(job.tick()).resolves.toBeUndefined();
const registrar = t.get(CronRegistrarService);
vi.spyOn(registrar, 'isEnabled').mockReturnValue(true);
const register = vi.spyOn(registrar, 'register').mockImplementation(() => undefined);
job.onApplicationBootstrap();
expect(register).toHaveBeenCalledWith('place-identities-prune', '20 4 * * *', expect.any(Function));
});
});
@@ -0,0 +1,283 @@
/**
* PlaceIdentitiesService and PlaceDuplicatesService (D5/D6, PLC-13) over the
* real repositories on a migrated test db: putting uses together as an own
* place, taking one out, what is left once a trip or list is out of reach,
* merging two entries and undoing it, the duplicate suggestions and turning
* one down. Only the trip permission check is replaced, as in the library
* suite. No trip place and no saved place may change along the way.
*/
import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity';
import { Places } from '../../../../src/db/entities/Places.entity';
import { TripMembers } from '../../../../src/db/entities/TripMembers.entity';
import { Trips } from '../../../../src/db/entities/Trips.entity';
import { UserPlaceLinks } from '../../../../src/db/entities/UserPlaceLinks.entity';
import { UserPlaceMerges } from '../../../../src/db/entities/UserPlaceMerges.entity';
import { UserPlaces } from '../../../../src/db/entities/UserPlaces.entity';
import { DomainError } from '../../../../src/nest/common/domain-error';
import { PermissionsService } from '../../../../src/nest/permissions/permissions.service';
import { PlaceDuplicatesService } from '../../../../src/nest/places-library/place-duplicates.service';
import { PlaceIdentitiesService } from '../../../../src/nest/places-library/place-identities.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 { countRows, deleteRows, findRows, updateRows } from '../../../helpers/factories/rows';
import { linkUserPlace, makeUserPlace } from '../../../helpers/factories/user-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 { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let identities: PlaceIdentitiesService;
let duplicates: PlaceDuplicatesService;
let library: PlacesLibraryService;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [PlacesLibraryModule] });
identities = t.get(PlaceIdentitiesService);
duplicates = t.get(PlaceDuplicatesService);
library = t.get(PlacesLibraryService);
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);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const as = (id: number): LibraryUser => ({ id, role: 'user' });
const keysOf = async (userId: number) => (await library.list(as(userId), {})).entries.map((entry) => entry.key);
async function refusal(promise: Promise<unknown>): 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');
}
/** The trip places and saved places as they are, to prove nothing of them changed. */
async function sharedRows() {
const places = await findRows(orm, Places, {}, { id: 'asc' });
const saved = await findRows(orm, CollectionPlaces, {}, { id: 'asc' });
return JSON.stringify([
places.map((p) => [p.id, p.name, p.lat, p.lng, p.updated_at]),
saved.map((s) => [s.id, s.name, s.lat, s.lng, s.updated_at]),
]);
}
describe('PlaceIdentitiesService.link and unlink', () => {
it('PID-001: puts a trip place and a saved place together as one own place named after the first', async () => {
const before = await sharedRows();
const { entry } = await identities.link(as(f.me.id), {
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
});
expect(entry).toMatchObject({ name: 'Forum Romanum', lat: 41.8925, lng: 12.4853 });
expect(entry?.key).toBe(`own:${entry?.identity_id}`);
expect(entry?.origins.map((origin) => [origin.kind, origin.linked])).toEqual([
['trip', true],
['list', true],
]);
const keys = await keysOf(f.me.id);
expect(keys).toContain(entry?.key);
expect(keys).not.toContain(`trip:${f.places.forum.id}`);
expect(keys).not.toContain(`list:${f.saved.pantheon.id}`);
expect(keys).toHaveLength(9);
expect(await sharedRows()).toBe(before);
// Only `me` sees it as one place; the friend's view stays as it was.
expect(await keysOf(f.friend.id)).toContain(`trip:${f.places.forum.id}`);
});
it('PID-002: refuses a use out of reach or an own place of someone else, and writes nothing', async () => {
const notFound = { status: 404, message: 'Place not found' };
expect(await refusal(identities.link(as(f.me.id), { uses: [{ kind: 'trip', id: f.places.hidden.id }] }))).toEqual(
notFound,
);
expect(await refusal(identities.link(as(f.me.id), { uses: [{ kind: 'list', id: f.saved.secret.id }] }))).toEqual(
notFound,
);
const theirs = await makeUserPlace(orm, f.stranger.id);
expect(
await refusal(
identities.link(as(f.me.id), { uses: [{ kind: 'trip', id: f.places.cafe.id }], identity_id: theirs.id }),
),
).toEqual(notFound);
expect(await countRows(orm, UserPlaceLinks, {})).toBe(0);
expect(await countRows(orm, UserPlaces, { user: f.me.id })).toBe(0);
});
it('PID-003: joins an existing own place, and one left empty by the move goes', async () => {
const first = await identities.link(as(f.me.id), { uses: [{ kind: 'trip', id: f.places.forum.id }] });
const second = await identities.link(as(f.me.id), { uses: [{ kind: 'list', id: f.saved.pantheon.id }] });
const joined = await identities.link(as(f.me.id), {
uses: [{ kind: 'list', id: f.saved.pantheon.id }],
identity_id: first.entry?.identity_id ?? 0,
});
expect(joined.entry?.origins).toHaveLength(2);
expect(await countRows(orm, UserPlaces, { id: second.entry?.identity_id ?? 0 })).toBe(0);
});
it('PID-004: takes one use out again; the last one out removes the own place', async () => {
const { entry } = await identities.link(as(f.me.id), {
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
});
const out = await identities.unlink(as(f.me.id), { kind: 'list', id: f.saved.pantheon.id });
expect(out.entry?.key).toBe(`list:${f.saved.pantheon.id}`);
expect(await refusal(identities.unlink(as(f.me.id), { kind: 'list', id: f.saved.pantheon.id }))).toEqual({
status: 404,
message: 'This place is not part of one of your own places',
});
expect(await refusal(identities.unlink(as(f.me.id), { kind: 'trip', id: f.places.hidden.id }))).toMatchObject({
status: 404,
});
const last = await identities.unlink(as(f.me.id), { kind: 'trip', id: f.places.forum.id });
expect(last.entry?.key).toBe(`trip:${f.places.forum.id}`);
expect(await countRows(orm, UserPlaces, { id: entry?.identity_id ?? 0 })).toBe(0);
});
it('PID-005: an own place shows only the uses still in reach, none once all are gone, and the sweep removes it', async () => {
const { entry } = await identities.link(as(f.me.id), {
uses: [
{ kind: 'trip', id: f.places.forum.id },
{ kind: 'list', id: f.saved.pantheon.id },
],
});
await deleteRows(orm, TripMembers, { trip: f.rome.id, user: f.me.id });
const page = await library.list(as(f.me.id), {});
const own = page.entries.find((candidate) => candidate.key === entry?.key);
expect(own?.origins.map((origin) => origin.kind)).toEqual(['list']);
const alone = await identities.link(as(f.me.id), { uses: [{ kind: 'trip', id: f.places.cafe.id }] });
await deleteRows(orm, Trips, { id: f.alps.id });
expect(await keysOf(f.me.id)).not.toContain(alone.entry?.key);
expect(await identities.pruneAll()).toBe(1);
expect(await countRows(orm, UserPlaces, { id: alone.entry?.identity_id ?? 0 })).toBe(0);
expect(await countRows(orm, UserPlaces, { id: entry?.identity_id ?? 0 })).toBe(1);
});
});
describe('PlaceIdentitiesService.merge and undo', () => {
it('PID-010: merges two entries into one own place with the leading name, and undoes it', async () => {
const before = await sharedRows();
const cafeKey = `trip:${f.places.cafe.id}`;
const conflictingKey = `list:${f.saved.conflicting.id}`;
const merged = await identities.merge(as(f.me.id), cafeKey, conflictingKey);
expect(merged.entry).toMatchObject({ name: 'Café Central', address: 'Herrengasse 14, Wien' });
expect(
merged.entry?.origins.map((origin) => (origin.kind === 'trip' ? origin.place_id : origin.collection_place_id)),
).toEqual([f.places.cafe.id, f.saved.savedCafe.id, f.saved.conflicting.id]);
const keys = await keysOf(f.me.id);
expect(keys).not.toContain(cafeKey);
expect(keys).not.toContain(conflictingKey);
expect(keys).toHaveLength(9);
expect(await sharedRows()).toBe(before);
expect(await identities.undoMerge(as(f.me.id), merged.merge_id)).toEqual({ success: true });
expect(await keysOf(f.me.id)).toHaveLength(10);
expect(await countRows(orm, UserPlaceMerges, {})).toBe(0);
expect(await refusal(identities.undoMerge(as(f.me.id), merged.merge_id))).toEqual({
status: 404,
message: 'Merge not found',
});
expect(await sharedRows()).toBe(before);
});
it('PID-011: refuses one entry twice, a key no entry has and a merge of someone else', async () => {
const key = `trip:${f.places.cafe.id}`;
expect(await refusal(identities.merge(as(f.me.id), key, key))).toEqual({
status: 400,
message: 'Pick two different places to merge',
});
expect(await refusal(identities.merge(as(f.me.id), key, `trip:${f.places.hidden.id}`))).toEqual({
status: 404,
message: 'Place not found',
});
expect(await refusal(identities.merge(as(f.me.id), key, 'nonsense'))).toMatchObject({ status: 404 });
const merged = await identities.merge(as(f.me.id), key, `list:${f.saved.lunch.id}`);
expect(await refusal(identities.undoMerge(as(f.friend.id), merged.merge_id))).toMatchObject({ status: 404 });
});
it('PID-012: refuses while an own place still holds a use the user can no longer open', async () => {
const own = await makeUserPlace(orm, f.me.id, { name: 'Mixed' });
await linkUserPlace(orm, f.me.id, own.id, { collectionPlace: f.saved.namesake.id });
await linkUserPlace(orm, f.me.id, own.id, { place: f.places.hidden.id });
expect(await refusal(identities.merge(as(f.me.id), `own:${own.id}`, `trip:${f.places.museum.id}`))).toEqual({
status: 403,
message: 'One of these places holds a trip place or saved place you can no longer open',
});
});
});
describe('PlaceDuplicatesService', () => {
it('PID-020: suggests the same name a few metres apart, says what differs, and pages', async () => {
const page = await duplicates.list(as(f.me.id), {});
const pairs = page.duplicates.map((pair) => new Set([pair.a.key, pair.b.key]));
expect(pairs).toEqual(
expect.arrayContaining([
new Set([`trip:${f.places.cafe.id}`, `list:${f.saved.conflicting.id}`]),
new Set([`trip:${f.places.museum.id}`, `list:${f.saved.namesake.id}`]),
]),
);
expect(page.duplicates).toHaveLength(2);
const cafe = page.duplicates.find((pair) => [pair.a.key, pair.b.key].includes(`list:${f.saved.conflicting.id}`));
expect(cafe).toMatchObject({ reasons: ['name_nearby'], can_merge: true });
expect(cafe?.differing).toEqual(expect.arrayContaining(['address', 'google_place_id']));
expect(cafe?.differing).not.toContain('name');
const first = await duplicates.list(as(f.me.id), { limit: 1 });
expect(first.duplicates).toHaveLength(1);
const second = await duplicates.list(as(f.me.id), { cursor: first.next_cursor ?? '' });
expect(second.duplicates).toHaveLength(1);
expect(second.next_cursor).toBeNull();
expect(await refusal(duplicates.list(as(f.me.id), { cursor: 'nonsense' }))).toMatchObject({ status: 400 });
});
it('PID-021: a turned-down pair does not come back; a shared provider id is a reason of its own', async () => {
await identities.dismiss(f.me.id, `list:${f.saved.namesake.id}`, `trip:${f.places.museum.id}`);
await identities.dismiss(f.me.id, `trip:${f.places.museum.id}`, `list:${f.saved.namesake.id}`);
expect(await refusal(identities.dismiss(f.me.id, 'own:1', 'own:1'))).toMatchObject({ status: 400 });
const page = await duplicates.list(as(f.me.id), {});
expect(page.duplicates).toHaveLength(1);
await updateRows(orm, CollectionPlaces, { id: f.saved.lunch.id }, { osm_id: 'node/1' });
await updateRows(orm, Places, { id: f.places.forum.id }, { osm_id: 'node/1' });
const shared = await duplicates.list(as(f.me.id), {});
const byProvider = shared.duplicates.find((pair) => pair.reasons.includes('provider_id'));
expect(new Set([byProvider?.a.key, byProvider?.b.key])).toEqual(
new Set([`list:${f.saved.lunch.id}`, `trip:${f.places.forum.id}`]),
);
expect(byProvider?.differing).toEqual(expect.arrayContaining(['name', 'position']));
});
it('PID-022: cannot be merged while one side holds a use out of reach', async () => {
const own = await makeUserPlace(orm, f.me.id, { name: 'Museum', lat: 47.2681, lng: 11.3933 });
await linkUserPlace(orm, f.me.id, own.id, { collectionPlace: f.saved.namesake.id });
await linkUserPlace(orm, f.me.id, own.id, { place: f.places.hidden.id });
const page = await duplicates.list(as(f.me.id), {});
const museum = page.duplicates.find((pair) => [pair.a.key, pair.b.key].includes(`own:${own.id}`));
expect(museum?.can_merge).toBe(false);
});
});
@@ -4,14 +4,22 @@
*/
import type {
LibraryCollectionPlaceRow,
LibraryIdentityRow,
LibraryTripPlaceRow,
LibraryUseRow,
} from '../../../../src/db/repositories/PlacesLibrary.repository';
import {
anchorOfIdentity,
anchorOfKey,
decodeLibraryCursor,
encodeLibraryCursor,
entryKey,
entryOf,
firstUseOf,
fromListOf,
groupBy,
identityOfAnchor,
leadOf,
ratingOf,
rowsByAnchor,
} from '../../../../src/nest/places-library/places-library.helpers';
@@ -27,6 +35,9 @@ const facts = {
description: null,
website: null,
phone: null,
google_place_id: null,
google_ftid: null,
osm_id: null,
category_id: 3,
category_name: 'Food',
category_color: '#f00',
@@ -42,7 +53,7 @@ const trip: LibraryTripPlaceRow = {
trip_end: null,
trip_owner_id: 1,
};
const saved = (id: number, grouped: number | null, extra: Partial<LibraryCollectionPlaceRow> = {}) =>
const saved = (id: number, extra: Partial<LibraryCollectionPlaceRow> = {}) =>
({
...facts,
id,
@@ -50,7 +61,6 @@ const saved = (id: number, grouped: number | null, extra: Partial<LibraryCollect
collection_name: 'Food',
status: 'odd-status',
name: `Saved ${id}`,
grouped_place_id: grouped,
category_id: null,
category_name: null,
...extra,
@@ -59,9 +69,20 @@ const saved = (id: number, grouped: number | null, extra: Partial<LibraryCollect
const access = { canEditTrip: () => true, canEditList: () => false };
describe('places-library helpers', () => {
it('names an entry by its trip place, else by its saved place', () => {
expect(entryKey(10)).toBe('trip:10');
expect(entryKey(-4)).toBe('list:4');
it('names an entry by its own place, its trip place or its saved place, and reads the key back', () => {
expect(entryKey(10 * 4 + 1)).toBe('trip:10');
expect(entryKey(4 * 4 + 2)).toBe('list:4');
expect(entryKey(anchorOfIdentity(7))).toBe('own:7');
expect(anchorOfKey('trip:10')).toBe(41);
expect(anchorOfKey('list:4')).toBe(18);
expect(anchorOfKey('own:7')).toBe(31);
for (const bad of ['trip:0', 'trip:01', 'place:3', 'own:', 'own:1e3', 'list:99999999999999999']) {
expect(anchorOfKey(bad)).toBeNull();
}
expect(identityOfAnchor(31)).toBe(7);
expect(identityOfAnchor(41)).toBeNull();
expect(fromListOf('trip')).toBe(0);
expect(fromListOf('list')).toBe(1);
});
it('hands out a cursor that only its own sort reads back', () => {
@@ -85,25 +106,69 @@ describe('places-library helpers', () => {
});
it('puts an entry together from its rows, the trip place leading', () => {
const rows = rowsByAnchor([10, -7, -99, 42], [trip], [saved(6, 10, { image_url: '/u/6.jpg' }), saved(7, null)]);
expect(rows.map((row) => row.anchor)).toEqual([10, -7]);
const uses: LibraryUseRow[] = [
{ anchor_key: 41, from_list: 0, use_id: 10, linked: false },
{ anchor_key: 41, from_list: 1, use_id: 6, linked: false },
{ anchor_key: 30, from_list: 1, use_id: 7, linked: false },
];
const rows = rowsByAnchor([41, 30, 398, 170], uses, [trip], [saved(6, { image_url: '/u/6.jpg' }), saved(7)], []);
expect(rows.map((row) => row.anchor)).toEqual([41, 30]);
const [first, second] = rows;
if (!first || !second) throw new Error('expected two entries');
const grouped = entryOf(first, access);
expect(grouped).toMatchObject({
key: 'trip:10',
identity_id: null,
name: 'Café',
category: { id: 3, name: 'Food', color: '#f00', icon: null },
image_url: '/u/6.jpg',
});
expect(grouped.origins).toEqual([
expect.objectContaining({ kind: 'trip', can_edit: true, read_only: false }),
expect.objectContaining({ kind: 'list', collection_place_id: 6, status: 'idea', can_edit: false }),
expect.objectContaining({ kind: 'trip', can_edit: true, read_only: false, linked: false }),
expect.objectContaining({ kind: 'list', collection_place_id: 6, status: 'idea', can_edit: false, linked: false }),
]);
const alone = entryOf(second, access);
expect(alone).toMatchObject({ key: 'list:7', name: 'Saved 7', category: null, image_url: null });
});
it('shows an own place under its own name, with every trip and list origin, and leaves a pruned one out', () => {
const own: LibraryIdentityRow = {
id: 5,
name: 'My café',
address: 'Somewhere 1',
lat: 9,
lng: 8,
google_place_id: null,
google_ftid: null,
osm_id: null,
updated_at: '2026-11-02 08:00:00',
category_id: null,
category_name: null,
category_color: null,
category_icon: null,
};
const other = { ...trip, id: 11, trip_id: 6, trip_title: 'Rome' };
const uses: LibraryUseRow[] = [
{ anchor_key: 23, from_list: 0, use_id: 10, linked: true },
{ anchor_key: 23, from_list: 0, use_id: 11, linked: true },
{ anchor_key: 23, from_list: 1, use_id: 6, linked: false },
{ anchor_key: 27, from_list: 1, use_id: 7, linked: true },
];
const rows = rowsByAnchor([23, 27], uses, [trip, other], [saved(6), saved(7)], [own]);
expect(rows).toHaveLength(1);
const [only] = rows;
if (!only) throw new Error('expected one entry');
expect(leadOf(only)).toBe(own);
expect(firstUseOf(only)).toBe(trip);
const shown = entryOf(only, access);
expect(shown).toMatchObject({ key: 'own:5', identity_id: 5, name: 'My café', lat: 9, category: null });
expect(shown.origins.map((origin) => [origin.kind, origin.linked])).toEqual([
['trip', true],
['trip', true],
['list', false],
]);
});
it('groups rows by a numeric field in order', () => {
const groups = groupBy([{ k: 1 }, { k: 2 }, { k: 1 }], (row) => row.k);
expect([...groups.entries()]).toEqual([
@@ -12,7 +12,8 @@ import { PlacesLibraryModule } from '../../../../src/nest/places-library/places-
import { PlacesLibraryService, type LibraryUser } from '../../../../src/nest/places-library/places-library.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { updateRows } from '../../../helpers/factories/rows';
import { expectedKeysByName, seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture';
import { oneByOne } from '../../../helpers/one-by-one';
import { cafeTie, expectedKeysByName, 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';
@@ -97,6 +98,7 @@ describe('PlacesLibraryService.list', () => {
place_id: f.places.cafe.id,
can_edit: true,
read_only: false,
linked: false,
},
{
kind: 'list',
@@ -105,6 +107,7 @@ describe('PlacesLibraryService.list', () => {
collection_place_id: f.saved.savedCafe.id,
status: 'want',
can_edit: true,
linked: false,
},
]);
// The provider id alone is enough, whatever the copy is called.
@@ -142,8 +145,7 @@ describe('PlacesLibraryService.list', () => {
]);
// A grouped entry has a list origin, so it is one of the list's entries too.
expect(await by({ collection_id: f.lists.food.id })).toEqual([
`list:${f.saved.conflicting.id}`,
`trip:${f.places.cafe.id}`,
...cafeTie(f),
`list:${f.saved.hiddenCopy.id}`,
`list:${f.saved.lunch.id}`,
`list:${f.saved.namesake.id}`,
@@ -181,17 +183,15 @@ describe('PlacesLibraryService.list', () => {
});
it('PLIB-008: pages through every entry once, by name and by last change', async () => {
for (const sort of ['name', 'updated'] as const) {
const seen: string[] = [];
let cursor: string | undefined;
for (let round = 0; round < 10; round++) {
const page = await library.list(as(f.me.id), { sort, limit: 3, ...(cursor ? { cursor } : {}) });
seen.push(...keys(page));
if (!page.next_cursor) break;
cursor = page.next_cursor;
}
expect(seen).toHaveLength(10);
expect(new Set(seen)).toEqual(new Set(expectedKeysByName(f)));
const pageThrough = async (sort: 'name' | 'updated', cursor?: string, round = 0): Promise<string[]> => {
const page = await library.list(as(f.me.id), { sort, limit: 3, ...(cursor ? { cursor } : {}) });
if (!page.next_cursor || round >= 10) return keys(page);
return [...keys(page), ...(await pageThrough(sort, page.next_cursor, round + 1))];
};
const seen = await oneByOne(['name', 'updated'] as const, (sort) => pageThrough(sort));
for (const keysSeen of seen) {
expect(keysSeen).toHaveLength(10);
expect(new Set(keysSeen)).toEqual(new Set(expectedKeysByName(f)));
}
});
@@ -0,0 +1,56 @@
/**
* TripCollectionsController over a stub service: each route hands the trip
* the guard resolved, the user and its input (and the X-Socket-Id on writes)
* to one service method. Guards, pipes and contracts run in the e2e suite.
*/
import type { TripAccess } from '../../../../src/db/repositories/Trips.repository';
import { RESPONSE_CONTRACT_KEY } from '../../../../src/nest/common/response-contract';
import type { TripWriter } from '../../../../src/nest/common/trip-writer';
import { TRIP_PERMISSION_KEY } from '../../../../src/nest/permissions/trip-access.guard';
import { TripCollectionsController } from '../../../../src/nest/trip-collections/trip-collections.controller';
import type { TripCollectionsService } from '../../../../src/nest/trip-collections/trip-collections.service';
import type { User } from '../../../../src/types';
import { tripCollectionLayerResponseSchema, tripCollectionLinksResponseSchema } from '@trek/shared';
import { describe, expect, it, vi } from 'vitest';
const user = { id: 7, role: 'user', username: 'ann', email: 'ann@example.test' } as User;
const trip = { id: 4, user_id: 7 } as TripAccess;
const answer = { links: [], can_link: true };
describe('TripCollectionsController', () => {
it('TCLC-001: reads the links and the map layer of the trip for the user', async () => {
const list = vi.fn().mockResolvedValue(answer);
const layer = vi.fn().mockResolvedValue({ places: [] });
const c = new TripCollectionsController({ list, layer } as unknown as TripCollectionsService);
expect(await c.list(user, trip)).toBe(answer);
expect(await c.layer(user, trip)).toEqual({ places: [] });
expect(list).toHaveBeenCalledWith(4, user);
expect(layer).toHaveBeenCalledWith(4, user);
});
it('TCLC-002: links and unlinks with a REST writer that carries the socket id', async () => {
const writer = { userId: 7 } as TripWriter;
const restWriter = vi.fn().mockReturnValue(writer);
const link = vi.fn().mockResolvedValue(answer);
const unlink = vi.fn().mockResolvedValue(answer);
const c = new TripCollectionsController({ restWriter, link, unlink } as unknown as TripCollectionsService);
await c.link(user, trip, { collection_id: 9 }, 'sock-2');
await c.unlink(user, trip, 9, 'sock-2');
expect(restWriter).toHaveBeenCalledWith(4, user, 'sock-2');
expect(link).toHaveBeenCalledWith(4, 9, writer);
expect(unlink).toHaveBeenCalledWith(4, 9, writer);
});
it('TCLC-003: the writes take place_edit, and every route declares its contract', () => {
const proto = TripCollectionsController.prototype;
const meta = (key: string, handler: unknown) => Reflect.getMetadata(key, handler as object) as unknown;
expect(meta(TRIP_PERMISSION_KEY, proto.link)).toBe('place_edit');
expect(meta(TRIP_PERMISSION_KEY, proto.unlink)).toBe('place_edit');
expect(meta(TRIP_PERMISSION_KEY, proto.list)).toBeUndefined();
expect(meta(RESPONSE_CONTRACT_KEY, proto.list)).toBe(tripCollectionLinksResponseSchema);
expect(meta(RESPONSE_CONTRACT_KEY, proto.link)).toBe(tripCollectionLinksResponseSchema);
expect(meta(RESPONSE_CONTRACT_KEY, proto.unlink)).toBe(tripCollectionLinksResponseSchema);
expect(meta(RESPONSE_CONTRACT_KEY, proto.layer)).toBe(tripCollectionLayerResponseSchema);
});
});
@@ -0,0 +1,89 @@
/**
* TripCollectionsMcp (PLC-15/PLC-16): the same service, permission and list
* checks as REST, the addon gate and the scopes. From the container over a
* snapshot db; broadcasts go to the FakeRealtimeService.
*/
import type { McpContext } from '../../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../../src/nest-mcp/metadata';
import { AddonsService } from '../../../../src/nest/addons/addons.service';
import { TripCollectionsMcp } from '../../../../src/nest/trip-collections/trip-collections.mcp';
import { TripCollectionsModule } from '../../../../src/nest/trip-collections/trip-collections.module';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let mcp: TripCollectionsMcp;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [TripCollectionsModule] });
mcp = t.get(TripCollectionsMcp);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
t.realtime.reset();
f = await seedLibrary(orm);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const ctx = (userId: number) => ({ userId }) as McpContext;
const read = (result: { content: Array<{ type: string; text: string }> }) => JSON.parse(result.content[0]?.text ?? '');
const options = (name: string) => {
const entry = getEntry(TripCollectionsMcp as unknown as ClassRef, name);
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
describe('TripCollectionsMcp', () => {
it('TCL-MCP-001: links, reads, maps and unlinks a list, with the event marked as MCP', async () => {
const input = { tripId: f.alps.id, collection_id: f.lists.food.id };
expect(read(await mcp.linkCollectionToTrip(input, ctx(f.me.id))).links).toHaveLength(1);
expect(t.realtime.broadcastMock).toHaveBeenCalledWith(f.alps.id, 'tripCollections:changed', { _source: 'mcp' });
expect(read(await mcp.listTripCollections({ tripId: f.alps.id }, ctx(f.me.id))).can_link).toBe(true);
expect(read(await mcp.getTripCollectionPlaces({ tripId: f.alps.id }, ctx(f.me.id))).places.length).toBeGreaterThan(
0,
);
expect(read(await mcp.unlinkCollectionFromTrip(input, ctx(f.me.id))).links).toEqual([]);
});
it('TCL-MCP-002: refuses a trip out of reach and a list the caller cannot see', async () => {
await expect(mcp.listTripCollections({ tripId: f.elsewhere.id }, ctx(f.me.id))).rejects.toThrow();
await expect(
mcp.linkCollectionToTrip({ tripId: f.alps.id, collection_id: f.lists.secrets.id }, ctx(f.me.id)),
).rejects.toThrow('Collection not found');
});
it('TCL-MCP-003: there only with Collections on, and for tokens that may', async () => {
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(false);
expect(await options('linkCollectionToTrip').when?.(ctx(1), mcp)).toBe(false);
enabled.mockResolvedValue(true);
expect(await options('linkCollectionToTrip').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 ['linkCollectionToTrip', 'unlinkCollectionFromTrip']) {
expect(allowed(name, ['places:write', 'collections:read'])).toBe(true);
expect(allowed(name, ['places:read', 'collections:read'])).toBe(false);
}
for (const name of ['listTripCollections', 'getTripCollectionPlaces']) {
expect(allowed(name, ['trips:read', 'collections:read'])).toBe(true);
expect(allowed(name, ['trips:read'])).toBe(false);
expect(options(name).annotations).toMatchObject({ readOnlyHint: true });
}
});
});
@@ -0,0 +1,138 @@
/**
* TripCollectionsService (PLC-15/PLC-16) over the real repository on a
* migrated test db: linking and unlinking a list, who sees a linked list
* (only someone the list is open to), the permission and the list check, the
* saved places for the trip map with whether the trip already has them, and
* what a deleted list leaves. Broadcasts go to a FakeRealtimeService.
*/
import { Collections } from '../../../../src/db/entities/Collections.entity';
import { TripCollectionLinks } from '../../../../src/db/entities/TripCollectionLinks.entity';
import { DomainError } from '../../../../src/nest/common/domain-error';
import { restTripWriter } from '../../../../src/nest/common/trip-writer';
import { PermissionsService } from '../../../../src/nest/permissions/permissions.service';
import { TripCollectionsModule } from '../../../../src/nest/trip-collections/trip-collections.module';
import { TripCollectionsService } from '../../../../src/nest/trip-collections/trip-collections.service';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { addCollectionMember } from '../../../helpers/factories/collections';
import { countRows, deleteRows } from '../../../helpers/factories/rows';
import { addTripMember } from '../../../helpers/factories/trips';
import { seedLibrary, type LibraryFixture } from '../../../helpers/places-library-fixture';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestModule, type TestModule } from '../../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let service: TripCollectionsService;
let f: LibraryFixture;
beforeAll(async () => {
t = await createTestModule({ db, imports: [TripCollectionsModule] });
service = t.get(TripCollectionsService);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
t.realtime.reset();
f = await seedLibrary(orm);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const reader = (id: number) => ({ id, role: 'user' });
const writer = (id: number) => restTripWriter(t.realtime, f.alps.id, reader(id), 'sock-1');
async function refusal(promise: Promise<unknown>): 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('TripCollectionsService', () => {
it('TCL-001: links a list once, says so to the trip, and lists it with the role and count', async () => {
const broadcast = t.realtime.broadcastMock;
const answer = await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
expect(answer).toEqual({
links: [
expect.objectContaining({
collection_id: f.lists.food.id,
name: 'Food',
role: 'owner',
place_count: 6,
linked_by: f.me.id,
}),
],
can_link: true,
});
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
expect(broadcast).toHaveBeenCalledTimes(1);
expect(broadcast).toHaveBeenCalledWith(f.alps.id, 'tripCollections:changed', {}, 'sock-1');
expect(await countRows(orm, TripCollectionLinks, {})).toBe(1);
});
it('TCL-002: a member sees a linked list only while it is open to them', async () => {
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
expect(await refusal(service.list(f.alps.id, reader(f.friend.id)))).toMatchObject({ status: 404 });
await addTripMember(orm, f.alps.id, f.friend.id);
expect((await service.list(f.alps.id, reader(f.friend.id))).links).toEqual([]);
expect((await service.layer(f.alps.id, reader(f.friend.id))).places).toEqual([]);
await addCollectionMember(orm, f.lists.food.id, f.friend.id, { role: 'viewer', status: 'accepted' });
expect((await service.list(f.alps.id, reader(f.friend.id))).links).toEqual([
expect.objectContaining({ collection_id: f.lists.food.id, role: 'viewer' }),
]);
});
it('TCL-003: refuses a list the writer cannot see, and a writer without place_edit', async () => {
expect(await refusal(service.link(f.alps.id, f.lists.secrets.id, writer(f.me.id)))).toEqual({
status: 404,
message: 'Collection not found',
});
await addTripMember(orm, f.alps.id, f.friend.id);
vi.spyOn(t.get(PermissionsService), 'checkPermission').mockResolvedValue(false);
expect(await refusal(service.link(f.alps.id, f.lists.sights.id, writer(f.friend.id)))).toMatchObject({
status: 403,
});
expect((await service.list(f.alps.id, reader(f.friend.id))).can_link).toBe(false);
expect(await countRows(orm, TripCollectionLinks, {})).toBe(0);
});
it('TCL-004: hands the map the saved places with a position and says which the trip already has', async () => {
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
const { places } = await service.layer(f.alps.id, reader(f.me.id));
const byId = new Map(places.map((place) => [place.id, place]));
expect(byId.has(f.saved.savedMuseum.id)).toBe(false);
expect(byId.get(f.saved.savedCafe.id)).toMatchObject({ in_trip: true, trip_place_id: f.places.cafe.id });
expect(byId.get(f.saved.namesake.id)).toMatchObject({ in_trip: true, trip_place_id: f.places.museum.id });
// A name of its own, or another provider id, is another place, whatever source it names.
expect(byId.get(f.saved.lunch.id)).toMatchObject({ in_trip: false, trip_place_id: null });
expect(byId.get(f.saved.conflicting.id)).toMatchObject({ in_trip: false });
expect(byId.get(f.saved.hiddenCopy.id)).toMatchObject({ in_trip: false, collection_id: f.lists.food.id });
});
it('TCL-005: unlinks, refuses a list that is not linked, and a deleted list takes its link along', async () => {
const broadcast = t.realtime.broadcastMock;
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
expect((await service.unlink(f.alps.id, f.lists.food.id, writer(f.me.id))).links).toEqual([]);
expect(broadcast).toHaveBeenCalledTimes(2);
expect(await refusal(service.unlink(f.alps.id, f.lists.food.id, writer(f.me.id)))).toEqual({
status: 404,
message: 'This list is not linked to the trip',
});
await service.link(f.alps.id, f.lists.food.id, writer(f.me.id));
await deleteRows(orm, Collections, { id: f.lists.food.id });
expect(await countRows(orm, TripCollectionLinks, {})).toBe(0);
});
});
+1
View File
@@ -227,6 +227,7 @@ export default defineConfig({
'src/nest/tokens/**/*.ts': { statements: 99, branches: 97, functions: 99, lines: 99 },
'src/nest/tours/**/*.ts': { statements: 95, branches: 92, functions: 99, lines: 97 },
'src/nest/transit/**/*.ts': { statements: 92, branches: 83, functions: 97, lines: 94 },
'src/nest/trip-collections/**/*.ts': { statements: 80, branches: 80, functions: 80, lines: 80 },
'src/nest/trip-invite/**/*.ts': { statements: 91, branches: 93, functions: 93, lines: 89 },
'src/nest/trip-membership/**/*.ts': { statements: 99, branches: 86, functions: 99, lines: 99 },
'src/nest/trip-members/**/*.ts': { statements: 95, branches: 91, functions: 99, lines: 95 },