mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
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:
@@ -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(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -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'),
|
||||
},
|
||||
});
|
||||
@@ -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(),
|
||||
},
|
||||
});
|
||||
@@ -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(),
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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>;
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
+115
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user