mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 18:54:17 +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);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user