mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 00:20:07 +00:00
feat(places): visits read from trips, change history, linked tours and bookings, personal tags
A visit is a place planned on a day of one of the reader's trips; nothing is kept or confirmed by hand. A place keeps a log of changes to its details, links the tours and bookings it is about, and carries tags private to the reader, which a copy into a trip takes along only when picked. Contracts, routes, MCP tools and migrations for both engines.
This commit is contained in:
@@ -82,9 +82,12 @@
|
||||
"PaddleRegions": "paddle-obstacles",
|
||||
"PaddleWaterGraphs": "paddle-routing",
|
||||
"PasswordResetTokens": "auth",
|
||||
"PersonalPlaceTags": "places-library",
|
||||
"PhotoProviderFields": "addons",
|
||||
"PhotoProviders": "addons",
|
||||
"Photos": "photos",
|
||||
"PlaceActivityLinks": "place-activities",
|
||||
"PlaceChangeLog": "place-changes",
|
||||
"PlaceContribLog": "place-contrib",
|
||||
"PlaceContribOutbox": "place-contrib",
|
||||
"PlaceDetailsCache": "maps",
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"src/nest/atlas/atlas.service.ts": 1166,
|
||||
"src/nest/auth/auth.service.ts": 1115,
|
||||
"src/nest/budget/budget.service.ts": 1607,
|
||||
"src/nest/collections/collections.service.ts": 1398,
|
||||
"src/nest/collections/collections.service.ts": 1397,
|
||||
"src/nest/doc-sync/doc-sync.service.ts": 1060,
|
||||
"src/nest/doc-sync/providers/synology-drive.client.ts": 1160,
|
||||
"src/nest/journey/journey-domain.service.ts": 1659,
|
||||
|
||||
@@ -5,6 +5,9 @@ import { Categories } from './Categories.entity';
|
||||
import { CollectionLabels } from './CollectionLabels.entity';
|
||||
import { CollectionPlaceRatings } from './CollectionPlaceRatings.entity';
|
||||
import { Collections } from './Collections.entity';
|
||||
import { PersonalPlaceTags } from './PersonalPlaceTags.entity';
|
||||
import { PlaceActivityLinks } from './PlaceActivityLinks.entity';
|
||||
import { PlaceChangeLog } from './PlaceChangeLog.entity';
|
||||
import { Tags } from './Tags.entity';
|
||||
import { UserPlaceLinks } from './UserPlaceLinks.entity';
|
||||
import { Users } from './Users.entity';
|
||||
@@ -44,6 +47,9 @@ export class CollectionPlaces {
|
||||
collection_place_labels = new Collection<CollectionLabels>(this);
|
||||
collection_place_tags = new Collection<Tags>(this);
|
||||
collection_place_ratings_collection = new Collection<CollectionPlaceRatings>(this);
|
||||
personal_place_tags_collection = new Collection<PersonalPlaceTags>(this);
|
||||
place_activity_links_collection = new Collection<PlaceActivityLinks>(this);
|
||||
place_change_log_collection = new Collection<PlaceChangeLog>(this);
|
||||
user_place_links_collection = new Collection<UserPlaceLinks>(this);
|
||||
}
|
||||
|
||||
@@ -84,6 +90,9 @@ export const CollectionPlacesSchema = defineEntity({
|
||||
collection_place_labels: () => p.manyToMany(CollectionLabels).pivotTable('collection_place_labels').joinColumn('collection_place_id').inverseJoinColumn('label_id').hidden(),
|
||||
collection_place_tags: () => p.manyToMany(Tags).pivotTable('collection_place_tags').joinColumn('collection_place_id').inverseJoinColumn('tag_id').hidden(),
|
||||
collection_place_ratings_collection: () => p.oneToMany(CollectionPlaceRatings).mappedBy('collectionPlace').hidden(),
|
||||
personal_place_tags_collection: () => p.oneToMany(PersonalPlaceTags).mappedBy('collectionPlace').hidden(),
|
||||
place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('collectionPlace').hidden(),
|
||||
place_change_log_collection: () => p.oneToMany(PlaceChangeLog).mappedBy('collectionPlace').hidden(),
|
||||
user_place_links_collection: () => p.oneToMany(UserPlaceLinks).mappedBy('collectionPlace').hidden(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { CollectionToursRepository } from '../repositories/CollectionTours.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { Collections } from './Collections.entity';
|
||||
import { PlaceActivityLinks } from './PlaceActivityLinks.entity';
|
||||
import { TourTypes } from './TourTypes.entity';
|
||||
import { Users } from './Users.entity';
|
||||
|
||||
@@ -49,6 +50,7 @@ export class CollectionTours {
|
||||
ski_options?: string | null;
|
||||
tourTypeRef!: Ref<TourTypes>;
|
||||
savedByRef?: Ref<Users> | null;
|
||||
place_activity_links_collection = new Collection<PlaceActivityLinks>(this);
|
||||
}
|
||||
|
||||
export const CollectionToursSchema = defineEntity({
|
||||
@@ -97,5 +99,6 @@ export const CollectionToursSchema = defineEntity({
|
||||
ski_options: p.text().nullable(),
|
||||
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_collection_tours_tour_type'),
|
||||
savedByRef: () => p.manyToOne(Users).ref().joinColumn('saved_by').nullable().hidden().index('idx_collection_tours_saved_by'),
|
||||
place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('collectionTour').hidden(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import { CollectionLabels } from './CollectionLabels.entity';
|
||||
import { CollectionMembers } from './CollectionMembers.entity';
|
||||
import { CollectionPlaces } from './CollectionPlaces.entity';
|
||||
import { CollectionTours } from './CollectionTours.entity';
|
||||
import { PlaceChangeLog } from './PlaceChangeLog.entity';
|
||||
import { TripCollectionLinks } from './TripCollectionLinks.entity';
|
||||
import { Users } from './Users.entity';
|
||||
|
||||
@@ -26,6 +27,7 @@ export class Collections {
|
||||
collection_members_collection = new Collection<CollectionMembers>(this);
|
||||
collection_places_collection = new Collection<CollectionPlaces>(this);
|
||||
collection_tours_collection = new Collection<CollectionTours>(this);
|
||||
place_change_log_collection = new Collection<PlaceChangeLog>(this);
|
||||
trip_collection_links_collection = new Collection<TripCollectionLinks>(this);
|
||||
}
|
||||
|
||||
@@ -49,6 +51,7 @@ export const CollectionsSchema = defineEntity({
|
||||
collection_members_collection: () => p.oneToMany(CollectionMembers).mappedBy('collection').hidden(),
|
||||
collection_places_collection: () => p.oneToMany(CollectionPlaces).mappedBy('collection').hidden(),
|
||||
collection_tours_collection: () => p.oneToMany(CollectionTours).mappedBy('collection').hidden(),
|
||||
place_change_log_collection: () => p.oneToMany(PlaceChangeLog).mappedBy('collection').hidden(),
|
||||
trip_collection_links_collection: () => p.oneToMany(TripCollectionLinks).mappedBy('collection').hidden(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { PersonalPlaceTagsRepository } from '../repositories/PersonalPlaceTags.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { CollectionPlaces } from './CollectionPlaces.entity';
|
||||
import { Places } from './Places.entity';
|
||||
import { Tags } from './Tags.entity';
|
||||
import { UserPlaces } from './UserPlaces.entity';
|
||||
|
||||
export class PersonalPlaceTags {
|
||||
[EntityRepositoryType]?: PersonalPlaceTagsRepository;
|
||||
id!: number & Opt;
|
||||
tag!: Ref<Tags>;
|
||||
tag_id!: number;
|
||||
userPlace?: Ref<UserPlaces> | null;
|
||||
user_place_id?: number | null;
|
||||
place?: Ref<Places> | null;
|
||||
place_id?: number | null;
|
||||
collectionPlace?: Ref<CollectionPlaces> | null;
|
||||
collection_place_id?: number | null;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export const PersonalPlaceTagsSchema = defineEntity({
|
||||
class: PersonalPlaceTags,
|
||||
repository: () => PersonalPlaceTagsRepository,
|
||||
uniques: [
|
||||
{ properties: ['tag', 'collectionPlace'] },
|
||||
{ properties: ['tag', 'place'] },
|
||||
{ properties: ['tag', 'userPlace'] },
|
||||
],
|
||||
checks: [
|
||||
{
|
||||
name: 'personal_place_tags_collection_place_id_check',
|
||||
expression: '(user_place_id IS NOT NULL AND place_id IS NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NOT NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NULL AND collection_place_id IS NOT NULL)',
|
||||
},
|
||||
],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
tag: () => p.manyToOne(Tags).ref().deleteRule('cascade').hidden(),
|
||||
tag_id: p.integer().persist(false),
|
||||
userPlace: () => p.manyToOne(UserPlaces).ref().deleteRule('cascade').nullable().hidden().index('idx_personal_place_tags_user_place_id'),
|
||||
user_place_id: p.integer().nullable().persist(false).index('idx_personal_place_tags_user_place_id'),
|
||||
place: () => p.manyToOne(Places).ref().deleteRule('cascade').nullable().hidden().index('idx_personal_place_tags_place_id'),
|
||||
place_id: p.integer().nullable().persist(false).index('idx_personal_place_tags_place_id'),
|
||||
collectionPlace: () => p.manyToOne(CollectionPlaces).ref().deleteRule('cascade').nullable().hidden().index('idx_personal_place_tags_collection_place_id'),
|
||||
collection_place_id: p.integer().nullable().persist(false).index('idx_personal_place_tags_collection_place_id'),
|
||||
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { PlaceActivityLinksRepository } from '../repositories/PlaceActivityLinks.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { CollectionPlaces } from './CollectionPlaces.entity';
|
||||
import { CollectionTours } from './CollectionTours.entity';
|
||||
import { Places } from './Places.entity';
|
||||
import { Reservations } from './Reservations.entity';
|
||||
import { Tours } from './Tours.entity';
|
||||
import { Users } from './Users.entity';
|
||||
|
||||
export class PlaceActivityLinks {
|
||||
[EntityRepositoryType]?: PlaceActivityLinksRepository;
|
||||
id!: number & Opt;
|
||||
place?: Ref<Places> | null;
|
||||
place_id?: number | null;
|
||||
reservation?: Ref<Reservations> | null;
|
||||
reservation_id?: number | null;
|
||||
tourPlace?: Ref<Tours> | null;
|
||||
tour_place_id?: number | null;
|
||||
collectionPlace?: Ref<CollectionPlaces> | null;
|
||||
collection_place_id?: number | null;
|
||||
collectionTour?: Ref<CollectionTours> | null;
|
||||
collection_tour_id?: number | null;
|
||||
linked_by?: number | null;
|
||||
created_at?: string | null;
|
||||
linkedByRef?: Ref<Users> | null;
|
||||
}
|
||||
|
||||
export const PlaceActivityLinksSchema = defineEntity({
|
||||
class: PlaceActivityLinks,
|
||||
repository: () => PlaceActivityLinksRepository,
|
||||
uniques: [
|
||||
{ properties: ['collectionPlace', 'collectionTour'] },
|
||||
{ properties: ['place', 'tourPlace'] },
|
||||
{ properties: ['place', 'reservation'] },
|
||||
],
|
||||
checks: [
|
||||
{
|
||||
name: 'place_activity_links_collection_tour_id_check',
|
||||
expression: '(place_id IS NOT NULL AND collection_place_id IS NULL AND collection_tour_id IS NULL AND (reservation_id IS NULL) <> (tour_place_id IS NULL)) OR (place_id IS NULL AND reservation_id IS NULL AND tour_place_id IS NULL AND collection_place_id IS NOT NULL AND collection_tour_id IS NOT NULL)',
|
||||
},
|
||||
],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
place: () => p.manyToOne(Places).ref().deleteRule('cascade').nullable().hidden(),
|
||||
place_id: p.integer().nullable().persist(false),
|
||||
reservation: () => p.manyToOne(Reservations).ref().deleteRule('cascade').nullable().hidden().index('idx_place_activity_links_reservation_id'),
|
||||
reservation_id: p.integer().nullable().persist(false).index('idx_place_activity_links_reservation_id'),
|
||||
tourPlace: () => p.manyToOne(Tours).ref().joinColumn('tour_place_id').deleteRule('cascade').nullable().hidden().index('idx_place_activity_links_tour_place_id'),
|
||||
tour_place_id: p.integer().nullable().persist(false).index('idx_place_activity_links_tour_place_id'),
|
||||
collectionPlace: () => p.manyToOne(CollectionPlaces).ref().deleteRule('cascade').nullable().hidden(),
|
||||
collection_place_id: p.integer().nullable().persist(false),
|
||||
collectionTour: () => p.manyToOne(CollectionTours).ref().deleteRule('cascade').nullable().hidden().index('idx_place_activity_links_collection_tour_id'),
|
||||
collection_tour_id: p.integer().nullable().persist(false).index('idx_place_activity_links_collection_tour_id'),
|
||||
linked_by: p.integer().nullable().persist(false).index('idx_place_activity_links_linked_by'),
|
||||
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
linkedByRef: () => p.manyToOne(Users).ref().joinColumn('linked_by').nullable().hidden().index('idx_place_activity_links_linked_by'),
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
import { EntityRepositoryType, type Opt, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { PlaceChangeLogRepository } from '../repositories/PlaceChangeLog.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { CollectionPlaces } from './CollectionPlaces.entity';
|
||||
import { Collections } from './Collections.entity';
|
||||
import { Places } from './Places.entity';
|
||||
import { Users } from './Users.entity';
|
||||
|
||||
export class PlaceChangeLog {
|
||||
[EntityRepositoryType]?: PlaceChangeLogRepository;
|
||||
id!: number & Opt;
|
||||
place?: Ref<Places> | null;
|
||||
place_id?: number | null;
|
||||
collectionPlace?: Ref<CollectionPlaces> | null;
|
||||
collection_place_id?: number | null;
|
||||
collection?: Ref<Collections> | null;
|
||||
collection_id?: number | null;
|
||||
field!: string;
|
||||
old_value?: string | null;
|
||||
new_value?: string | null;
|
||||
user?: Ref<Users> | null;
|
||||
user_id?: number | null;
|
||||
automatic: number & Opt = 0;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export const PlaceChangeLogSchema = defineEntity({
|
||||
class: PlaceChangeLog,
|
||||
repository: () => PlaceChangeLogRepository,
|
||||
checks: [
|
||||
{
|
||||
name: 'place_change_log_collection_id_check',
|
||||
expression: '(place_id IS NULL) <> (collection_place_id IS NULL) AND (collection_id IS NULL) = (collection_place_id IS NULL)',
|
||||
},
|
||||
],
|
||||
properties: {
|
||||
id: p.integer().primary(),
|
||||
place: () => p.manyToOne(Places).ref().deleteRule('cascade').nullable().hidden().index('idx_place_change_log_place_id'),
|
||||
place_id: p.integer().nullable().persist(false).index('idx_place_change_log_place_id'),
|
||||
collectionPlace: () => p.manyToOne(CollectionPlaces).ref().deleteRule('cascade').nullable().hidden().index('idx_place_change_log_collection_place_id'),
|
||||
collection_place_id: p.integer().nullable().persist(false).index('idx_place_change_log_collection_place_id'),
|
||||
collection: () => p.manyToOne(Collections).ref().deleteRule('cascade').nullable().hidden().index('idx_place_change_log_collection_id'),
|
||||
collection_id: p.integer().nullable().persist(false).index('idx_place_change_log_collection_id'),
|
||||
field: p.text(),
|
||||
old_value: p.text().nullable(),
|
||||
new_value: p.text().nullable(),
|
||||
user: () => p.manyToOne(Users).ref().nullable().hidden().index('idx_place_change_log_user_id'),
|
||||
user_id: p.integer().nullable().persist(false).index('idx_place_change_log_user_id'),
|
||||
automatic: p.integer().default(0),
|
||||
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
},
|
||||
});
|
||||
@@ -8,7 +8,10 @@ import { DayAccommodations } from './DayAccommodations.entity';
|
||||
import { DayAssignments } from './DayAssignments.entity';
|
||||
import { FileLinks } from './FileLinks.entity';
|
||||
import { JourneyEntries } from './JourneyEntries.entity';
|
||||
import { PersonalPlaceTags } from './PersonalPlaceTags.entity';
|
||||
import { Photos } from './Photos.entity';
|
||||
import { PlaceActivityLinks } from './PlaceActivityLinks.entity';
|
||||
import { PlaceChangeLog } from './PlaceChangeLog.entity';
|
||||
import { PlaceContribOutbox } from './PlaceContribOutbox.entity';
|
||||
import { PlaceFieldOrigin } from './PlaceFieldOrigin.entity';
|
||||
import { PlaceRatings } from './PlaceRatings.entity';
|
||||
@@ -67,7 +70,10 @@ export class Places {
|
||||
day_assignments_collection = new Collection<DayAssignments>(this);
|
||||
file_links_collection = new Collection<FileLinks>(this);
|
||||
journey_entries_collection = new Collection<JourneyEntries>(this);
|
||||
personal_place_tags_collection = new Collection<PersonalPlaceTags>(this);
|
||||
photos_collection = new Collection<Photos>(this);
|
||||
place_activity_links_collection = new Collection<PlaceActivityLinks>(this);
|
||||
place_change_log_collection = new Collection<PlaceChangeLog>(this);
|
||||
place_contrib_outbox_collection = new Collection<PlaceContribOutbox>(this);
|
||||
place_field_origin_collection = new Collection<PlaceFieldOrigin>(this);
|
||||
place_ratings_collection = new Collection<PlaceRatings>(this);
|
||||
@@ -128,7 +134,10 @@ export const PlacesSchema = defineEntity({
|
||||
day_assignments_collection: () => p.oneToMany(DayAssignments).mappedBy('place').hidden(),
|
||||
file_links_collection: () => p.oneToMany(FileLinks).mappedBy('place').hidden(),
|
||||
journey_entries_collection: () => p.oneToMany(JourneyEntries).mappedBy('sourcePlace').hidden(),
|
||||
personal_place_tags_collection: () => p.oneToMany(PersonalPlaceTags).mappedBy('place').hidden(),
|
||||
photos_collection: () => p.oneToMany(Photos).mappedBy('place').hidden(),
|
||||
place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('place').hidden(),
|
||||
place_change_log_collection: () => p.oneToMany(PlaceChangeLog).mappedBy('place').hidden(),
|
||||
place_contrib_outbox_collection: () => p.oneToMany(PlaceContribOutbox).mappedBy('place').hidden(),
|
||||
place_field_origin_collection: () => p.oneToMany(PlaceFieldOrigin).mappedBy('place').hidden(),
|
||||
place_ratings_collection: () => p.oneToMany(PlaceRatings).mappedBy('place').hidden(),
|
||||
|
||||
@@ -5,6 +5,7 @@ import { BudgetItems } from './BudgetItems.entity';
|
||||
import { DayAssignments } from './DayAssignments.entity';
|
||||
import { Days } from './Days.entity';
|
||||
import { FileLinks } from './FileLinks.entity';
|
||||
import { PlaceActivityLinks } from './PlaceActivityLinks.entity';
|
||||
import { Places } from './Places.entity';
|
||||
import { ReservationDayPositions } from './ReservationDayPositions.entity';
|
||||
import { ReservationEndpoints } from './ReservationEndpoints.entity';
|
||||
@@ -48,6 +49,7 @@ export class Reservations {
|
||||
ingest_state: string & Opt = 'live';
|
||||
budget_items_collection = new Collection<BudgetItems>(this);
|
||||
file_links_collection = new Collection<FileLinks>(this);
|
||||
place_activity_links_collection = new Collection<PlaceActivityLinks>(this);
|
||||
reservation_day_positions_collection = new Collection<ReservationDayPositions>(this);
|
||||
reservation_endpoints_collection = new Collection<ReservationEndpoints>(this);
|
||||
reservation_travelers_collection = new Collection<ReservationTravelers>(this);
|
||||
@@ -98,6 +100,7 @@ export const ReservationsSchema = defineEntity({
|
||||
ingest_state: p.text().default('live'),
|
||||
budget_items_collection: () => p.oneToMany(BudgetItems).mappedBy('reservation').hidden(),
|
||||
file_links_collection: () => p.oneToMany(FileLinks).mappedBy('reservation').hidden(),
|
||||
place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('reservation').hidden(),
|
||||
reservation_day_positions_collection: () => p.oneToMany(ReservationDayPositions).mappedBy('reservation').hidden(),
|
||||
reservation_endpoints_collection: () => p.oneToMany(ReservationEndpoints).mappedBy('reservation').hidden(),
|
||||
reservation_travelers_collection: () => p.oneToMany(ReservationTravelers).mappedBy('reservation').hidden(),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p }
|
||||
import { TagsRepository } from '../repositories/Tags.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { CollectionPlaces } from './CollectionPlaces.entity';
|
||||
import { PersonalPlaceTags } from './PersonalPlaceTags.entity';
|
||||
import { Places } from './Places.entity';
|
||||
import { Trips } from './Trips.entity';
|
||||
import { Users } from './Users.entity';
|
||||
@@ -17,6 +18,7 @@ export class Tags {
|
||||
trip?: Ref<Trips> | null;
|
||||
trip_id?: number | null;
|
||||
collection_place_tags_inverse = new Collection<CollectionPlaces>(this);
|
||||
personal_place_tags_collection = new Collection<PersonalPlaceTags>(this);
|
||||
place_tags_inverse = new Collection<Places>(this);
|
||||
}
|
||||
|
||||
@@ -33,6 +35,7 @@ export const TagsSchema = defineEntity({
|
||||
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').nullable().hidden().index('idx_tags_trip_id'),
|
||||
trip_id: p.integer().nullable().persist(false).index('idx_tags_trip_id'),
|
||||
collection_place_tags_inverse: () => p.manyToMany(CollectionPlaces).mappedBy('collection_place_tags').hidden(),
|
||||
personal_place_tags_collection: () => p.oneToMany(PersonalPlaceTags).mappedBy('tag').hidden(),
|
||||
place_tags_inverse: () => p.manyToMany(Places).mappedBy('place_tags').hidden(),
|
||||
},
|
||||
});
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Collection, EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
|
||||
import { ToursRepository } from '../repositories/Tours.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { PlaceActivityLinks } from './PlaceActivityLinks.entity';
|
||||
import { Places } from './Places.entity';
|
||||
import { TourActivities } from './TourActivities.entity';
|
||||
import { TourActivityExclusions } from './TourActivityExclusions.entity';
|
||||
@@ -52,6 +53,7 @@ export class Tours {
|
||||
ski_discipline?: TToursSkiDiscipline | null;
|
||||
ski_options?: string | null;
|
||||
tourTypeRef!: Ref<TourTypes>;
|
||||
place_activity_links_collection = new Collection<PlaceActivityLinks>(this);
|
||||
tour_activities_collection = new Collection<TourActivities>(this);
|
||||
tour_activities_collection1 = new Collection<TourActivities>(this);
|
||||
tour_activity_exclusions_collection = new Collection<TourActivityExclusions>(this);
|
||||
@@ -184,6 +186,7 @@ export const ToursSchema = defineEntity({
|
||||
ski_discipline: p.enum(() => ToursSkiDiscipline).nullable(),
|
||||
ski_options: p.text().nullable(),
|
||||
tourTypeRef: () => p.manyToOne(TourTypes).ref().joinColumn('tour_type').hidden().index('idx_tours_tour_type'),
|
||||
place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('tourPlace').hidden(),
|
||||
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('place').hidden(),
|
||||
tour_activities_collection1: () => p.oneToMany(TourActivities).mappedBy('trackPlace').hidden(),
|
||||
tour_activity_exclusions_collection: () => p.oneToMany(TourActivityExclusions).mappedBy('place').hidden(),
|
||||
|
||||
@@ -2,6 +2,7 @@ import { Collection, EntityRepositoryType, type Opt, type Ref, defineEntity, p }
|
||||
import { UserPlacesRepository } from '../repositories/UserPlaces.repository';
|
||||
import { DbTimestampType } from '../types';
|
||||
import { Categories } from './Categories.entity';
|
||||
import { PersonalPlaceTags } from './PersonalPlaceTags.entity';
|
||||
import { UserPlaceLinks } from './UserPlaceLinks.entity';
|
||||
import { UserPlaceMerges } from './UserPlaceMerges.entity';
|
||||
import { Users } from './Users.entity';
|
||||
@@ -24,6 +25,7 @@ export class UserPlaces {
|
||||
merged_into_id?: number | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
personal_place_tags_collection = new Collection<PersonalPlaceTags>(this);
|
||||
user_place_links_collection = new Collection<UserPlaceLinks>(this);
|
||||
user_place_merges_collection = new Collection<UserPlaceMerges>(this);
|
||||
user_place_merges_collection1 = new Collection<UserPlaceMerges>(this);
|
||||
@@ -50,6 +52,7 @@ export const UserPlacesSchema = defineEntity({
|
||||
merged_into_id: p.integer().nullable().persist(false).index('idx_user_places_merged_into_id'),
|
||||
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
personal_place_tags_collection: () => p.oneToMany(PersonalPlaceTags).mappedBy('userPlace').hidden(),
|
||||
user_place_links_collection: () => p.oneToMany(UserPlaceLinks).mappedBy('userPlace').hidden(),
|
||||
user_place_merges_collection: () => p.oneToMany(UserPlaceMerges).mappedBy('leading').hidden(),
|
||||
user_place_merges_collection1: () => p.oneToMany(UserPlaceMerges).mappedBy('merged').hidden(),
|
||||
|
||||
@@ -55,6 +55,8 @@ import { PackingItemContributors } from './PackingItemContributors.entity';
|
||||
import { PackingItems } from './PackingItems.entity';
|
||||
import { PackingTemplates } from './PackingTemplates.entity';
|
||||
import { PasswordResetTokens } from './PasswordResetTokens.entity';
|
||||
import { PlaceActivityLinks } from './PlaceActivityLinks.entity';
|
||||
import { PlaceChangeLog } from './PlaceChangeLog.entity';
|
||||
import { PlaceRatings } from './PlaceRatings.entity';
|
||||
import { PushSubscriptions } from './PushSubscriptions.entity';
|
||||
import { ReservationTravelers } from './ReservationTravelers.entity';
|
||||
@@ -205,6 +207,8 @@ export class Users {
|
||||
packing_item_recipients_inverse = new Collection<PackingItems>(this);
|
||||
packing_templates_collection = new Collection<PackingTemplates>(this);
|
||||
password_reset_tokens_collection = new Collection<PasswordResetTokens>(this);
|
||||
place_activity_links_collection = new Collection<PlaceActivityLinks>(this);
|
||||
place_change_log_collection = new Collection<PlaceChangeLog>(this);
|
||||
place_ratings_collection = new Collection<PlaceRatings>(this);
|
||||
push_subscriptions_collection = new Collection<PushSubscriptions>(this);
|
||||
reservation_travelers_collection = new Collection<ReservationTravelers>(this);
|
||||
@@ -373,6 +377,8 @@ export const UsersSchema = defineEntity({
|
||||
packing_item_recipients_inverse: () => p.manyToMany(PackingItems).mappedBy('packing_item_recipients').hidden(),
|
||||
packing_templates_collection: () => p.oneToMany(PackingTemplates).mappedBy('createdByRef').hidden(),
|
||||
password_reset_tokens_collection: () => p.oneToMany(PasswordResetTokens).mappedBy('user').hidden(),
|
||||
place_activity_links_collection: () => p.oneToMany(PlaceActivityLinks).mappedBy('linkedByRef').hidden(),
|
||||
place_change_log_collection: () => p.oneToMany(PlaceChangeLog).mappedBy('user').hidden(),
|
||||
place_ratings_collection: () => p.oneToMany(PlaceRatings).mappedBy('user').hidden(),
|
||||
push_subscriptions_collection: () => p.oneToMany(PushSubscriptions).mappedBy('user').hidden(),
|
||||
reservation_travelers_collection: () => p.oneToMany(ReservationTravelers).mappedBy('user').hidden(),
|
||||
|
||||
@@ -83,9 +83,12 @@ import { PaddleRegionRequestsSchema } from './PaddleRegionRequests.entity';
|
||||
import { PaddleRegionsSchema } from './PaddleRegions.entity';
|
||||
import { PaddleWaterGraphsSchema } from './PaddleWaterGraphs.entity';
|
||||
import { PasswordResetTokensSchema } from './PasswordResetTokens.entity';
|
||||
import { PersonalPlaceTagsSchema } from './PersonalPlaceTags.entity';
|
||||
import { PhotoProviderFieldsSchema } from './PhotoProviderFields.entity';
|
||||
import { PhotoProvidersSchema } from './PhotoProviders.entity';
|
||||
import { PhotosSchema } from './Photos.entity';
|
||||
import { PlaceActivityLinksSchema } from './PlaceActivityLinks.entity';
|
||||
import { PlaceChangeLogSchema } from './PlaceChangeLog.entity';
|
||||
import { PlaceContribLogSchema } from './PlaceContribLog.entity';
|
||||
import { PlaceContribOutboxSchema } from './PlaceContribOutbox.entity';
|
||||
import { PlaceDetailsCacheSchema } from './PlaceDetailsCache.entity';
|
||||
@@ -264,9 +267,12 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
|
||||
PaddleRegionsSchema,
|
||||
PaddleWaterGraphsSchema,
|
||||
PasswordResetTokensSchema,
|
||||
PersonalPlaceTagsSchema,
|
||||
PhotoProviderFieldsSchema,
|
||||
PhotoProvidersSchema,
|
||||
PhotosSchema,
|
||||
PlaceActivityLinksSchema,
|
||||
PlaceChangeLogSchema,
|
||||
PlaceContribLogSchema,
|
||||
PlaceContribOutboxSchema,
|
||||
PlaceDetailsCacheSchema,
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface PersonalPlaceTagsTable {
|
||||
id: InsertOptional<number>;
|
||||
tag_id: number;
|
||||
user_place_id: InsertOptional<number | null>;
|
||||
place_id: InsertOptional<number | null>;
|
||||
collection_place_id: InsertOptional<number | null>;
|
||||
created_at: InsertOptional<string | null>;
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface PlaceActivityLinksTable {
|
||||
id: InsertOptional<number>;
|
||||
place_id: InsertOptional<number | null>;
|
||||
reservation_id: InsertOptional<number | null>;
|
||||
tour_place_id: InsertOptional<number | null>;
|
||||
collection_place_id: InsertOptional<number | null>;
|
||||
collection_tour_id: InsertOptional<number | null>;
|
||||
linked_by: InsertOptional<number | null>;
|
||||
created_at: InsertOptional<string | null>;
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
|
||||
// change the migration, then run `npm run gen:db-types`.
|
||||
import type { InsertOptional } from './columns';
|
||||
|
||||
export interface PlaceChangeLogTable {
|
||||
id: InsertOptional<number>;
|
||||
place_id: InsertOptional<number | null>;
|
||||
collection_place_id: InsertOptional<number | null>;
|
||||
collection_id: InsertOptional<number | null>;
|
||||
field: string;
|
||||
old_value: InsertOptional<string | null>;
|
||||
new_value: InsertOptional<string | null>;
|
||||
user_id: InsertOptional<number | null>;
|
||||
automatic: InsertOptional<number>;
|
||||
created_at: InsertOptional<string | null>;
|
||||
}
|
||||
@@ -88,9 +88,12 @@ import type { PaddleRegionRequestsTable } from './PaddleRegionRequests.table';
|
||||
import type { PaddleRegionsTable } from './PaddleRegions.table';
|
||||
import type { PaddleWaterGraphsTable } from './PaddleWaterGraphs.table';
|
||||
import type { PasswordResetTokensTable } from './PasswordResetTokens.table';
|
||||
import type { PersonalPlaceTagsTable } from './PersonalPlaceTags.table';
|
||||
import type { PhotoProviderFieldsTable } from './PhotoProviderFields.table';
|
||||
import type { PhotoProvidersTable } from './PhotoProviders.table';
|
||||
import type { PhotosTable } from './Photos.table';
|
||||
import type { PlaceActivityLinksTable } from './PlaceActivityLinks.table';
|
||||
import type { PlaceChangeLogTable } from './PlaceChangeLog.table';
|
||||
import type { PlaceContribLogTable } from './PlaceContribLog.table';
|
||||
import type { PlaceContribOutboxTable } from './PlaceContribOutbox.table';
|
||||
import type { PlaceDetailsCacheTable } from './PlaceDetailsCache.table';
|
||||
@@ -275,9 +278,12 @@ export interface DB {
|
||||
paddle_regions: PaddleRegionsTable;
|
||||
paddle_water_graphs: PaddleWaterGraphsTable;
|
||||
password_reset_tokens: PasswordResetTokensTable;
|
||||
personal_place_tags: PersonalPlaceTagsTable;
|
||||
photo_provider_fields: PhotoProviderFieldsTable;
|
||||
photo_providers: PhotoProvidersTable;
|
||||
photos: PhotosTable;
|
||||
place_activity_links: PlaceActivityLinksTable;
|
||||
place_change_log: PlaceChangeLogTable;
|
||||
place_contrib_log: PlaceContribLogTable;
|
||||
place_contrib_outbox: PlaceContribOutboxTable;
|
||||
place_details_cache: PlaceDetailsCacheTable;
|
||||
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
import { engineDdl } from '../migration-utils';
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* PLC-14: what changed in the details of a place, and who changed it. One row
|
||||
* is one field of one place that went from one value to another: of a trip
|
||||
* place (`place_id`) or of a saved place (`collection_place_id`), exactly one
|
||||
* of the two, as the CHECK holds. A saved place's change also names the list
|
||||
* it was made in (`collection_id`): a place moved to another list shows the
|
||||
* new list's members only what was changed there, never who edited it in the
|
||||
* old one, and the old changes come back with a move back.
|
||||
*
|
||||
* The rows go with their place, so a deleted place takes its history along,
|
||||
* and with their list, so a deleted list takes the changes made in it.
|
||||
* `user_id` names who made the change and is kept as unknown when that
|
||||
* account goes; `automatic` marks a value TREK filled in itself (a lookup
|
||||
* after an import, a picture from the photo cache), which nobody typed.
|
||||
*
|
||||
* A value that was cleared is no row of its own: clearing a field removes the
|
||||
* rows of that field, so what was deleted on purpose does not live on here.
|
||||
* Nothing existing is read or rewritten, so the history starts empty.
|
||||
*/
|
||||
export class Migration20200101046550_a_place_keeps_the_history_of_its_details extends Migration {
|
||||
override name = 'Migration20200101046550_a_place_keeps_the_history_of_its_details';
|
||||
|
||||
override up(): void {
|
||||
engineDdl(this, {
|
||||
sqlite: [
|
||||
`CREATE TABLE place_change_log (
|
||||
id INTEGER PRIMARY KEY,
|
||||
place_id INTEGER REFERENCES places(id) ON DELETE CASCADE,
|
||||
collection_place_id INTEGER REFERENCES collection_places(id) ON DELETE CASCADE,
|
||||
collection_id INTEGER REFERENCES collections(id) ON DELETE CASCADE
|
||||
CHECK ((place_id IS NULL) <> (collection_place_id IS NULL) AND (collection_id IS NULL) = (collection_place_id IS NULL)),
|
||||
field TEXT NOT NULL,
|
||||
old_value TEXT,
|
||||
new_value TEXT,
|
||||
user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
automatic INTEGER NOT NULL DEFAULT 0,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
)`,
|
||||
'CREATE INDEX idx_place_change_log_place_id ON place_change_log(place_id)',
|
||||
'CREATE INDEX idx_place_change_log_collection_place_id ON place_change_log(collection_place_id)',
|
||||
'CREATE INDEX idx_place_change_log_collection_id ON place_change_log(collection_id)',
|
||||
'CREATE INDEX idx_place_change_log_user_id ON place_change_log(user_id)',
|
||||
],
|
||||
postgres: [
|
||||
'create table "place_change_log" ("id" bigserial primary key, "place_id" bigint null, "collection_place_id" bigint null, "collection_id" bigint null, "field" text not null, "old_value" text null, "new_value" text null, "user_id" bigint null, "automatic" bigint not null default 0, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'))',
|
||||
'create index "idx_place_change_log_place_id" on "place_change_log" ("place_id")',
|
||||
'create index "idx_place_change_log_collection_place_id" on "place_change_log" ("collection_place_id")',
|
||||
'create index "idx_place_change_log_collection_id" on "place_change_log" ("collection_id")',
|
||||
'create index "idx_place_change_log_user_id" on "place_change_log" ("user_id")',
|
||||
'alter table "place_change_log" add constraint "place_change_log_collection_id_check" check ((place_id IS NULL) <> (collection_place_id IS NULL) AND (collection_id IS NULL) = (collection_place_id IS NULL))',
|
||||
'alter table "place_change_log" add constraint "place_change_log_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade',
|
||||
'alter table "place_change_log" add constraint "place_change_log_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on delete cascade',
|
||||
'alter table "place_change_log" add constraint "place_change_log_collection_id_foreign" foreign key ("collection_id") references "collections" ("id") on delete cascade',
|
||||
'alter table "place_change_log" add constraint "place_change_log_user_id_foreign" foreign key ("user_id") references "users" ("id") on delete set null',
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
import { engineDdl } from '../migration-utils';
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* PLC-18: a place names the bookings and tours it is about. One row ties one
|
||||
* place to one activity of the same trip or the same list, never both kinds:
|
||||
* a trip place (`place_id`) to a booking (`reservation_id`) or a tour
|
||||
* (`tour_place_id`, the tour's own place) of its trip, or a saved place
|
||||
* (`collection_place_id`) to a tour kept in its list (`collection_tour_id`).
|
||||
* The CHECK holds that shape; that both ends belong to the same trip or list
|
||||
* is checked by the write, which reads both.
|
||||
*
|
||||
* A row goes with either end, so deleting the place, the booking or the tour
|
||||
* takes the link along and nothing else. `linked_by` names who linked it and
|
||||
* is kept as unknown when that account goes. Nothing existing is read or
|
||||
* rewritten: a booking that names its place already is shown from the
|
||||
* booking itself, never copied in here.
|
||||
*/
|
||||
export class Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about extends Migration {
|
||||
override name = 'Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about';
|
||||
|
||||
override up(): void {
|
||||
engineDdl(this, {
|
||||
sqlite: [
|
||||
`CREATE TABLE place_activity_links (
|
||||
id INTEGER PRIMARY KEY,
|
||||
place_id INTEGER REFERENCES places(id) ON DELETE CASCADE,
|
||||
reservation_id INTEGER REFERENCES reservations(id) ON DELETE CASCADE,
|
||||
tour_place_id INTEGER REFERENCES tours(place_id) ON DELETE CASCADE,
|
||||
collection_place_id INTEGER REFERENCES collection_places(id) ON DELETE CASCADE,
|
||||
collection_tour_id INTEGER REFERENCES collection_tours(id) ON DELETE CASCADE
|
||||
CHECK ((place_id IS NOT NULL AND collection_place_id IS NULL AND collection_tour_id IS NULL AND (reservation_id IS NULL) <> (tour_place_id IS NULL)) OR (place_id IS NULL AND reservation_id IS NULL AND tour_place_id IS NULL AND collection_place_id IS NOT NULL AND collection_tour_id IS NOT NULL)),
|
||||
linked_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (place_id, reservation_id),
|
||||
UNIQUE (place_id, tour_place_id),
|
||||
UNIQUE (collection_place_id, collection_tour_id)
|
||||
)`,
|
||||
'CREATE INDEX idx_place_activity_links_reservation_id ON place_activity_links(reservation_id)',
|
||||
'CREATE INDEX idx_place_activity_links_tour_place_id ON place_activity_links(tour_place_id)',
|
||||
'CREATE INDEX idx_place_activity_links_collection_tour_id ON place_activity_links(collection_tour_id)',
|
||||
'CREATE INDEX idx_place_activity_links_linked_by ON place_activity_links(linked_by)',
|
||||
],
|
||||
postgres: [
|
||||
'create table "place_activity_links" ("id" bigserial primary key, "place_id" bigint null, "reservation_id" bigint null, "tour_place_id" bigint null, "collection_place_id" bigint null, "collection_tour_id" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'), "linked_by" bigint null)',
|
||||
'create index "idx_place_activity_links_reservation_id" on "place_activity_links" ("reservation_id")',
|
||||
'create index "idx_place_activity_links_tour_place_id" on "place_activity_links" ("tour_place_id")',
|
||||
'create index "idx_place_activity_links_collection_tour_id" on "place_activity_links" ("collection_tour_id")',
|
||||
'create index "idx_place_activity_links_linked_by" on "place_activity_links" ("linked_by")',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_collection_place_id_collection_tour_id_unique" unique ("collection_place_id", "collection_tour_id")',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_place_id_tour_place_id_unique" unique ("place_id", "tour_place_id")',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_place_id_reservation_id_unique" unique ("place_id", "reservation_id")',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_collection_tour_id_check" check ((place_id IS NOT NULL AND collection_place_id IS NULL AND collection_tour_id IS NULL AND (reservation_id IS NULL) <> (tour_place_id IS NULL)) OR (place_id IS NULL AND reservation_id IS NULL AND tour_place_id IS NULL AND collection_place_id IS NOT NULL AND collection_tour_id IS NOT NULL))',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_reservation_id_foreign" foreign key ("reservation_id") references "reservations" ("id") on delete cascade',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_tour_place_id_foreign" foreign key ("tour_place_id") references "tours" ("place_id") on delete cascade',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on delete cascade',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_collection_tour_id_foreign" foreign key ("collection_tour_id") references "collection_tours" ("id") on delete cascade',
|
||||
'alter table "place_activity_links" add constraint "place_activity_links_linked_by_foreign" foreign key ("linked_by") references "users" ("id") on delete set null',
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
import { engineDdl } from '../migration-utils';
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
/**
|
||||
* PLC-21: a person puts their own tags on the entries of "All places". The
|
||||
* tags are the personal ones `tags` already holds (`trip_id` null); this
|
||||
* table says which entry carries which of them, and only ever for the person
|
||||
* who owns the tag, so nobody else on a trip or a list sees it.
|
||||
*
|
||||
* One row ties one tag to exactly one target, the one the entry is known by:
|
||||
* the person's own place (`user_place_id`, D5) where they put one together,
|
||||
* else the trip place (`place_id`) or the saved place
|
||||
* (`collection_place_id`) it stands for. The CHECK holds that shape, the
|
||||
* UNIQUEs that a tag sits on a target once. Every row goes with its tag and
|
||||
* with its target (ON DELETE CASCADE), so deleting a tag, an own place, a
|
||||
* trip place or a saved place takes its tags along and nothing else. Nothing
|
||||
* existing is read or rewritten.
|
||||
*/
|
||||
export class Migration20200101046580_a_person_tags_the_places_they_keep extends Migration {
|
||||
override name = 'Migration20200101046580_a_person_tags_the_places_they_keep';
|
||||
|
||||
override up(): void {
|
||||
engineDdl(this, {
|
||||
sqlite: [
|
||||
`CREATE TABLE personal_place_tags (
|
||||
id INTEGER PRIMARY KEY,
|
||||
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
|
||||
user_place_id INTEGER REFERENCES user_places(id) ON DELETE CASCADE,
|
||||
place_id INTEGER REFERENCES places(id) ON DELETE CASCADE,
|
||||
collection_place_id INTEGER REFERENCES collection_places(id) ON DELETE CASCADE
|
||||
CHECK ((user_place_id IS NOT NULL AND place_id IS NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NOT NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NULL AND collection_place_id IS NOT NULL)),
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE (tag_id, user_place_id),
|
||||
UNIQUE (tag_id, place_id),
|
||||
UNIQUE (tag_id, collection_place_id)
|
||||
)`,
|
||||
'CREATE INDEX idx_personal_place_tags_user_place_id ON personal_place_tags(user_place_id)',
|
||||
'CREATE INDEX idx_personal_place_tags_place_id ON personal_place_tags(place_id)',
|
||||
'CREATE INDEX idx_personal_place_tags_collection_place_id ON personal_place_tags(collection_place_id)',
|
||||
],
|
||||
postgres: [
|
||||
'create table "personal_place_tags" ("id" bigserial primary key, "tag_id" bigint not null, "user_place_id" bigint null, "place_id" bigint null, "collection_place_id" bigint null, "created_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'))',
|
||||
'create index "idx_personal_place_tags_user_place_id" on "personal_place_tags" ("user_place_id")',
|
||||
'create index "idx_personal_place_tags_place_id" on "personal_place_tags" ("place_id")',
|
||||
'create index "idx_personal_place_tags_collection_place_id" on "personal_place_tags" ("collection_place_id")',
|
||||
'alter table "personal_place_tags" add constraint "personal_place_tags_tag_id_collection_place_id_unique" unique ("tag_id", "collection_place_id")',
|
||||
'alter table "personal_place_tags" add constraint "personal_place_tags_tag_id_place_id_unique" unique ("tag_id", "place_id")',
|
||||
'alter table "personal_place_tags" add constraint "personal_place_tags_tag_id_user_place_id_unique" unique ("tag_id", "user_place_id")',
|
||||
'alter table "personal_place_tags" add constraint "personal_place_tags_collection_place_id_check" check ((user_place_id IS NOT NULL AND place_id IS NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NOT NULL AND collection_place_id IS NULL) OR (user_place_id IS NULL AND place_id IS NULL AND collection_place_id IS NOT NULL))',
|
||||
'alter table "personal_place_tags" add constraint "personal_place_tags_tag_id_foreign" foreign key ("tag_id") references "tags" ("id") on delete cascade',
|
||||
'alter table "personal_place_tags" add constraint "personal_place_tags_user_place_id_foreign" foreign key ("user_place_id") references "user_places" ("id") on delete cascade',
|
||||
'alter table "personal_place_tags" add constraint "personal_place_tags_place_id_foreign" foreign key ("place_id") references "places" ("id") on delete cascade',
|
||||
'alter table "personal_place_tags" add constraint "personal_place_tags_collection_place_id_foreign" foreign key ("collection_place_id") references "collection_places" ("id") on delete cascade',
|
||||
],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
import type { PersonalPlaceTags } from '../entities/PersonalPlaceTags.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type PersonalPlaceTagsDB = Pick<DB, 'personal_place_tags' | 'tags' | 'user_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]);
|
||||
|
||||
/** How many assignments one INSERT writes at most (four bound values each). */
|
||||
const INSERT_BLOCK = 500;
|
||||
|
||||
/** A personal tag as the places library shows it. */
|
||||
interface PersonalTagRow {
|
||||
id: number;
|
||||
name: string;
|
||||
color: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a tag sits on: the person's own places (and the ones merged into
|
||||
* them), trip places and saved places. Each list may be empty.
|
||||
*/
|
||||
interface PersonalTagTargets {
|
||||
identityIds: readonly number[];
|
||||
placeIds: readonly number[];
|
||||
collectionPlaceIds: readonly number[];
|
||||
}
|
||||
|
||||
/** One tag on one target, exactly one of the three set. */
|
||||
export interface PersonalTagAssignment {
|
||||
tag_id: number;
|
||||
user_place_id: number | null;
|
||||
place_id: number | null;
|
||||
collection_place_id: number | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* PLC-21: which entry of "All places" carries which personal tag of its
|
||||
* owner. Every statement is bounded by the owner: a tag counts only while it
|
||||
* is `userId`'s and personal (`trip_id` null), so no call reaches another
|
||||
* person's tags or a trip's. Which targets a person may tag is the caller's
|
||||
* check (the library's reach); this class checks no access itself.
|
||||
*/
|
||||
export class PersonalPlaceTagsRepository extends TrekRepository<PersonalPlaceTags> {
|
||||
private db() {
|
||||
return this.kysely<PersonalPlaceTagsDB>();
|
||||
}
|
||||
|
||||
/** The personal tags of `userId` among `ids`, by name. */
|
||||
async ownTags(userId: number, ids: readonly number[]): Promise<PersonalTagRow[]> {
|
||||
if (ids.length === 0) return [];
|
||||
return await this.db()
|
||||
.selectFrom('tags')
|
||||
.select(['id', 'name', 'color'])
|
||||
.where('user_id', '=', userId)
|
||||
.where('trip_id', 'is', null)
|
||||
.where('id', 'in', [...ids])
|
||||
.orderBy('name')
|
||||
.orderBy('id')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* Puts the tags on their targets; one already there stays as it is. In
|
||||
* blocks, one after the other, so a large change stays under the engines'
|
||||
* limits on bound parameters.
|
||||
*/
|
||||
async add(rows: readonly PersonalTagAssignment[]): Promise<void> {
|
||||
const blocks = Array.from({ length: Math.ceil(rows.length / INSERT_BLOCK) }, (_, index) =>
|
||||
rows.slice(index * INSERT_BLOCK, (index + 1) * INSERT_BLOCK),
|
||||
);
|
||||
await blocks.reduce<Promise<void>>(async (previous, block) => {
|
||||
await previous;
|
||||
await this.db()
|
||||
.insertInto('personal_place_tags')
|
||||
.values(block.map((row) => ({ ...row })))
|
||||
.onConflict((oc) => oc.doNothing())
|
||||
.execute();
|
||||
}, Promise.resolve());
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes `userId`'s tags (all of them, or `tagIds`) off the targets, an own
|
||||
* place's included the ones merged into it. Returns how many came off.
|
||||
*/
|
||||
async remove(userId: number, targets: PersonalTagTargets, tagIds: readonly number[] | null): Promise<number> {
|
||||
if (tagIds !== null && tagIds.length === 0) return 0;
|
||||
const db = this.db();
|
||||
const own = db
|
||||
.selectFrom('tags')
|
||||
.select('id')
|
||||
.where('user_id', '=', userId)
|
||||
.where('trip_id', 'is', null)
|
||||
.$if(tagIds !== null, (qb) => qb.where('id', 'in', idsOrNone(tagIds ?? [])));
|
||||
const identities = db
|
||||
.selectFrom('user_places')
|
||||
.select('id')
|
||||
.where('user_id', '=', userId)
|
||||
.where((eb) =>
|
||||
eb.or([
|
||||
eb('id', 'in', idsOrNone(targets.identityIds)),
|
||||
eb('merged_into_id', 'in', idsOrNone(targets.identityIds)),
|
||||
]),
|
||||
);
|
||||
const result = await db
|
||||
.deleteFrom('personal_place_tags')
|
||||
.where('tag_id', 'in', own)
|
||||
.where((eb) =>
|
||||
eb.or([
|
||||
eb('user_place_id', 'in', identities),
|
||||
eb('place_id', 'in', idsOrNone(targets.placeIds)),
|
||||
eb('collection_place_id', 'in', idsOrNone(targets.collectionPlaceIds)),
|
||||
]),
|
||||
)
|
||||
.executeTakeFirst();
|
||||
return Number(result.numDeletedRows);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,391 @@
|
||||
import type { PlaceActivityLinks } from '../entities/PlaceActivityLinks.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { accommodationIdMatches } from './_shared/reservation-accommodation';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type PlaceActivityDB = Pick<
|
||||
DB,
|
||||
| 'place_activity_links'
|
||||
| 'places'
|
||||
| 'reservations'
|
||||
| 'tours'
|
||||
| 'days'
|
||||
| 'day_assignments'
|
||||
| 'day_accommodations'
|
||||
| 'tour_waypoints'
|
||||
| 'trips'
|
||||
| 'collection_places'
|
||||
| 'collection_tours'
|
||||
| 'collections'
|
||||
>;
|
||||
|
||||
/** Kysely cannot bind an empty IN list and no row has the id 0, so none reads as this. */
|
||||
const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [0]);
|
||||
|
||||
/** A booking as the place detail shows it, with the place it is shown for (`source_id`). */
|
||||
export interface ActivityBookingRow {
|
||||
source_id: number;
|
||||
trip_id: number;
|
||||
trip_title: string;
|
||||
reservation_id: number;
|
||||
title: string;
|
||||
type: string | null;
|
||||
status: string | null;
|
||||
reservation_time: string | null;
|
||||
reservation_end_time: string | null;
|
||||
date: string | null;
|
||||
day_number: number | null;
|
||||
}
|
||||
|
||||
/** A tour of a trip (its own place) as the place detail shows it. */
|
||||
export interface ActivityTourRow {
|
||||
source_id: number;
|
||||
trip_id: number;
|
||||
trip_title: string;
|
||||
tour_id: number;
|
||||
title: string;
|
||||
tour_type: string;
|
||||
date: string | null;
|
||||
day_number: number | null;
|
||||
}
|
||||
|
||||
/** A tour kept in a list as the saved place detail shows it. */
|
||||
export interface ActivityKeptTourRow {
|
||||
source_id: number;
|
||||
collection_id: number;
|
||||
collection_name: string;
|
||||
collection_tour_id: number;
|
||||
title: string;
|
||||
tour_type: string;
|
||||
}
|
||||
|
||||
/** A trip place with the trip it is in. */
|
||||
interface ActivityTripPlaceRow {
|
||||
id: number;
|
||||
trip_id: number;
|
||||
}
|
||||
|
||||
/** A saved place with the list it is in. */
|
||||
export interface ActivitySavedPlaceRow {
|
||||
id: number;
|
||||
collection_id: number;
|
||||
}
|
||||
|
||||
/** Why a booking belongs to a place without a link: it names the place, its stay or its plan entry. */
|
||||
export type ImplicitVia = 'place' | 'stay' | 'plan';
|
||||
|
||||
const num = (value: unknown): number | null => (value === null || value === undefined ? null : Number(value));
|
||||
|
||||
function tourRowOf(row: {
|
||||
source_id: unknown;
|
||||
trip_id: number;
|
||||
trip_title: string;
|
||||
tour_id: number;
|
||||
title: string;
|
||||
tour_type: string;
|
||||
date: string | null;
|
||||
day_number: unknown;
|
||||
}): ActivityTourRow {
|
||||
return { ...row, source_id: Number(row.source_id), date: row.date ?? null, day_number: num(row.day_number) };
|
||||
}
|
||||
|
||||
function bookingRowOf(row: {
|
||||
source_id: unknown;
|
||||
trip_id: number;
|
||||
trip_title: string;
|
||||
reservation_id: number;
|
||||
title: string;
|
||||
type: string | null;
|
||||
status: string | null;
|
||||
reservation_time: string | null;
|
||||
reservation_end_time: string | null;
|
||||
date: string | null;
|
||||
day_number: unknown;
|
||||
}): ActivityBookingRow {
|
||||
return { ...row, source_id: Number(row.source_id), day_number: num(row.day_number) };
|
||||
}
|
||||
|
||||
/**
|
||||
* `place_activity_links` (PLC-18): the bookings and tours a place names, and
|
||||
* the reads the place detail needs around them (the bookings that name the
|
||||
* place themselves, the candidates of its trip or list). Every method takes
|
||||
* ids the caller checked; who may see or change what is decided in the
|
||||
* service, never here.
|
||||
*/
|
||||
export class PlaceActivityLinksRepository extends TrekRepository<PlaceActivityLinks> {
|
||||
private db() {
|
||||
return this.kysely<PlaceActivityDB>();
|
||||
}
|
||||
|
||||
/** The trip place `placeId` of the trip `tripId`, or undefined. */
|
||||
async tripPlace(tripId: number, placeId: number): Promise<ActivityTripPlaceRow | undefined> {
|
||||
return this.db()
|
||||
.selectFrom('places')
|
||||
.select(['id', 'trip_id'])
|
||||
.where('id', '=', placeId)
|
||||
.where('trip_id', '=', tripId)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
/** The saved place `id` with its list, or undefined. */
|
||||
async savedPlace(id: number): Promise<ActivitySavedPlaceRow | undefined> {
|
||||
return this.db()
|
||||
.selectFrom('collection_places')
|
||||
.select(['id', 'collection_id'])
|
||||
.where('id', '=', id)
|
||||
.executeTakeFirst();
|
||||
}
|
||||
|
||||
/** Whether the booking `reservationId` is one of the trip's. */
|
||||
async bookingInTrip(tripId: number, reservationId: number): Promise<boolean> {
|
||||
const row = await this.db()
|
||||
.selectFrom('reservations')
|
||||
.select('id')
|
||||
.where('id', '=', reservationId)
|
||||
.where('trip_id', '=', tripId)
|
||||
.executeTakeFirst();
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
/** Whether `tourId` is a tour (its own place) of the trip. */
|
||||
async tourInTrip(tripId: number, tourId: number): Promise<boolean> {
|
||||
const row = await this.db()
|
||||
.selectFrom('tours as t')
|
||||
.innerJoin('places as p', 'p.id', 't.place_id')
|
||||
.select('t.place_id')
|
||||
.where('t.place_id', '=', tourId)
|
||||
.where('p.trip_id', '=', tripId)
|
||||
.executeTakeFirst();
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
/** Whether `tourId` is a tour kept in the list. */
|
||||
async keptTourInList(collectionId: number, tourId: number): Promise<boolean> {
|
||||
const row = await this.db()
|
||||
.selectFrom('collection_tours')
|
||||
.select('id')
|
||||
.where('id', '=', tourId)
|
||||
.where('collection_id', '=', collectionId)
|
||||
.executeTakeFirst();
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
/** Links an activity to the place; answers whether a new link was made (a second link of the same pair keeps the first). */
|
||||
async link(
|
||||
target:
|
||||
| { place_id: number; reservation_id: number }
|
||||
| { place_id: number; tour_place_id: number }
|
||||
| { collection_place_id: number; collection_tour_id: number },
|
||||
userId: number,
|
||||
): Promise<boolean> {
|
||||
const row = await this.db()
|
||||
.insertInto('place_activity_links')
|
||||
.values({ ...target, linked_by: userId })
|
||||
.onConflict((oc) => oc.doNothing())
|
||||
.returning('id')
|
||||
.executeTakeFirst();
|
||||
return row !== undefined;
|
||||
}
|
||||
|
||||
/** Takes the link of the trip place to a booking or a tour off; answers whether there was one. */
|
||||
async unlinkTrip(placeId: number, target: { reservation_id: number } | { tour_place_id: number }): Promise<boolean> {
|
||||
let query = this.db().deleteFrom('place_activity_links').where('place_id', '=', placeId);
|
||||
query =
|
||||
'reservation_id' in target
|
||||
? query.where('reservation_id', '=', target.reservation_id)
|
||||
: query.where('tour_place_id', '=', target.tour_place_id);
|
||||
const result = await query.executeTakeFirst();
|
||||
return Number(result.numDeletedRows) > 0;
|
||||
}
|
||||
|
||||
/** Takes the link of the saved place to a kept tour off; answers whether there was one. */
|
||||
async unlinkSaved(collectionPlaceId: number, collectionTourId: number): Promise<boolean> {
|
||||
const result = await this.db()
|
||||
.deleteFrom('place_activity_links')
|
||||
.where('collection_place_id', '=', collectionPlaceId)
|
||||
.where('collection_tour_id', '=', collectionTourId)
|
||||
.executeTakeFirst();
|
||||
return Number(result.numDeletedRows) > 0;
|
||||
}
|
||||
|
||||
/** The bookings the trip places `placeIds` are linked to. */
|
||||
async linkedBookings(placeIds: readonly number[]): Promise<ActivityBookingRow[]> {
|
||||
const rows = await this.bookingQuery()
|
||||
.innerJoin('place_activity_links as l', 'l.reservation_id', 'r.id')
|
||||
.select('l.place_id as source_id')
|
||||
.where('l.place_id', 'in', idsOrNone(placeIds))
|
||||
.execute();
|
||||
return rows.map(bookingRowOf);
|
||||
}
|
||||
|
||||
/**
|
||||
* The bookings that belong to the trip places `placeIds` without a link:
|
||||
* one naming the place, one booked against a stay at the place, one tied
|
||||
* to a plan entry of the place. A booking can belong for more than one reason.
|
||||
*/
|
||||
async implicitBookings(placeIds: readonly number[]): Promise<(ActivityBookingRow & { via: ImplicitVia })[]> {
|
||||
const ids = idsOrNone(placeIds);
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
const named = await this.bookingQuery().select('r.place_id as source_id').where('r.place_id', 'in', ids).execute();
|
||||
const stays = await this.bookingQuery()
|
||||
.innerJoin('day_accommodations as a', (join) =>
|
||||
join.on((eb) => accommodationIdMatches(platform, eb, 'r.accommodation_id', 'a.id')),
|
||||
)
|
||||
.select('a.place_id as source_id')
|
||||
.where('a.place_id', 'in', ids)
|
||||
.execute();
|
||||
const planned = await this.bookingQuery()
|
||||
.innerJoin('day_assignments as da', 'da.id', 'r.assignment_id')
|
||||
.select('da.place_id as source_id')
|
||||
.where('da.place_id', 'in', ids)
|
||||
.execute();
|
||||
const tag = (via: ImplicitVia) => (row: Parameters<typeof bookingRowOf>[0]) => ({ ...bookingRowOf(row), via });
|
||||
return [...named.map(tag('place')), ...stays.map(tag('stay')), ...planned.map(tag('plan'))];
|
||||
}
|
||||
|
||||
/** Every booking of the trip, for the candidates; `source_id` is 0. */
|
||||
async tripBookings(tripId: number): Promise<ActivityBookingRow[]> {
|
||||
const rows = await this.bookingQuery().where('r.trip_id', '=', tripId).execute();
|
||||
return rows.map((row) => bookingRowOf({ ...row, source_id: 0 }));
|
||||
}
|
||||
|
||||
/** The tours the trip places `placeIds` are linked to. */
|
||||
async linkedTours(placeIds: readonly number[]): Promise<ActivityTourRow[]> {
|
||||
const rows = await this.tourQuery()
|
||||
.innerJoin('place_activity_links as l', 'l.tour_place_id', 't.place_id')
|
||||
.select('l.place_id as source_id')
|
||||
.where('l.place_id', 'in', idsOrNone(placeIds))
|
||||
.execute();
|
||||
return rows.map(tourRowOf);
|
||||
}
|
||||
|
||||
/** The tours with a station that stands for one of the trip places `placeIds`, once per tour and place. */
|
||||
async implicitTours(placeIds: readonly number[]): Promise<ActivityTourRow[]> {
|
||||
const rows = await this.tourQuery()
|
||||
.innerJoin('tour_waypoints as w', 'w.place_id', 't.place_id')
|
||||
.select('w.linked_place_id as source_id')
|
||||
.where('w.linked_place_id', 'in', idsOrNone(placeIds))
|
||||
.execute();
|
||||
// Several stations of one tour can stand for the same place; DISTINCT would
|
||||
// refuse the ORDER BY on lower(name) on Postgres, so the pairs are kept once here.
|
||||
const seen = new Set<string>();
|
||||
return rows.map(tourRowOf).filter((row) => {
|
||||
const key = `${row.tour_id}:${row.source_id}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/** Every tour of the trip, for the candidates; `source_id` is 0. */
|
||||
async tripTours(tripId: number): Promise<ActivityTourRow[]> {
|
||||
const rows = await this.tourQuery().where('tp.trip_id', '=', tripId).execute();
|
||||
return rows.map((row) => tourRowOf({ ...row, source_id: 0 }));
|
||||
}
|
||||
|
||||
/**
|
||||
* The kept tours the saved places `collectionPlaceIds` are linked to, of the
|
||||
* list each place is in now: a place moved to another list keeps the links
|
||||
* of its old one unread, and has them again when it moves back.
|
||||
*/
|
||||
async linkedKeptTours(collectionPlaceIds: readonly number[]): Promise<ActivityKeptTourRow[]> {
|
||||
const rows = await this.db()
|
||||
.selectFrom('place_activity_links as l')
|
||||
.innerJoin('collection_places as cp', 'cp.id', 'l.collection_place_id')
|
||||
.innerJoin('collection_tours as ct', (join) =>
|
||||
join.onRef('ct.id', '=', 'l.collection_tour_id').onRef('ct.collection_id', '=', 'cp.collection_id'),
|
||||
)
|
||||
.innerJoin('collections as c', 'c.id', 'ct.collection_id')
|
||||
.select([
|
||||
'l.collection_place_id as source_id',
|
||||
'ct.collection_id',
|
||||
'c.name as collection_name',
|
||||
'ct.id as collection_tour_id',
|
||||
'ct.name as title',
|
||||
'ct.tour_type',
|
||||
])
|
||||
.where('l.collection_place_id', 'in', idsOrNone(collectionPlaceIds))
|
||||
.orderBy((eb) => eb.fn<string>('lower', ['ct.name']))
|
||||
.orderBy('ct.id')
|
||||
.execute();
|
||||
return rows.map((row) => ({ ...row, source_id: Number(row.source_id) }));
|
||||
}
|
||||
|
||||
/** Every tour kept in the list, for the candidates; `source_id` is 0. */
|
||||
async keptTours(collectionId: number): Promise<ActivityKeptTourRow[]> {
|
||||
const rows = await this.db()
|
||||
.selectFrom('collection_tours as ct')
|
||||
.innerJoin('collections as c', 'c.id', 'ct.collection_id')
|
||||
.select([
|
||||
'ct.collection_id',
|
||||
'c.name as collection_name',
|
||||
'ct.id as collection_tour_id',
|
||||
'ct.name as title',
|
||||
'ct.tour_type',
|
||||
])
|
||||
.where('ct.collection_id', '=', collectionId)
|
||||
.orderBy((eb) => eb.fn<string>('lower', ['ct.name']))
|
||||
.orderBy('ct.id')
|
||||
.execute();
|
||||
return rows.map((row) => ({ ...row, source_id: 0 }));
|
||||
}
|
||||
|
||||
/** The booking columns the place detail shows, by time (none last), then by id. */
|
||||
private bookingQuery() {
|
||||
return (
|
||||
this.db()
|
||||
.selectFrom('reservations as r')
|
||||
.innerJoin('trips as tr', 'tr.id', 'r.trip_id')
|
||||
.leftJoin('days as d', 'd.id', 'r.day_id')
|
||||
.select([
|
||||
'r.trip_id',
|
||||
'tr.title as trip_title',
|
||||
'r.id as reservation_id',
|
||||
'r.title',
|
||||
'r.type',
|
||||
'r.status',
|
||||
'r.reservation_time',
|
||||
'r.reservation_end_time',
|
||||
'd.date',
|
||||
'd.day_number',
|
||||
])
|
||||
// Without a time last on both engines (SQLite sorts NULL first, Postgres last).
|
||||
.orderBy((eb) => eb.case().when('r.reservation_time', 'is', null).then(eb.lit(1)).else(eb.lit(0)).end())
|
||||
.orderBy('r.reservation_time')
|
||||
.orderBy('r.id')
|
||||
);
|
||||
}
|
||||
|
||||
/** The tour columns the place detail shows, with the first day it is planned on, by name, then by id. */
|
||||
private tourQuery() {
|
||||
return this.db()
|
||||
.selectFrom('tours as t')
|
||||
.innerJoin('places as tp', 'tp.id', 't.place_id')
|
||||
.innerJoin('trips as tr', 'tr.id', 'tp.trip_id')
|
||||
.select((eb) => [
|
||||
'tp.trip_id',
|
||||
'tr.title as trip_title',
|
||||
't.place_id as tour_id',
|
||||
'tp.name as title',
|
||||
't.tour_type',
|
||||
eb
|
||||
.selectFrom('day_assignments as da')
|
||||
.innerJoin('days as dd', 'dd.id', 'da.day_id')
|
||||
.select('dd.date')
|
||||
.whereRef('da.place_id', '=', 'tp.id')
|
||||
.orderBy('dd.day_number')
|
||||
.limit(1)
|
||||
.as('date'),
|
||||
eb
|
||||
.selectFrom('day_assignments as da')
|
||||
.innerJoin('days as dd', 'dd.id', 'da.day_id')
|
||||
.select('dd.day_number')
|
||||
.whereRef('da.place_id', '=', 'tp.id')
|
||||
.orderBy('dd.day_number')
|
||||
.limit(1)
|
||||
.as('day_number'),
|
||||
])
|
||||
.orderBy((eb) => eb.fn<string>('lower', ['tp.name']))
|
||||
.orderBy('t.place_id');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,232 @@
|
||||
import type { PlaceChangeLog } from '../entities/PlaceChangeLog.entity';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type PlaceChangeLogDB = Pick<
|
||||
DB,
|
||||
'place_change_log' | 'places' | 'tours' | 'collection_places' | 'categories' | 'users'
|
||||
>;
|
||||
|
||||
/** Kysely cannot bind an empty IN list and no row has the id 0, so none reads as this. */
|
||||
const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [0]);
|
||||
|
||||
/** The details of a place its history follows, as the row stores them, with its category's name. */
|
||||
export interface PlaceDetailsRow {
|
||||
id: number;
|
||||
name: string;
|
||||
address: string | null;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
category_name: string | null;
|
||||
description: string | null;
|
||||
notes: string | null;
|
||||
website: string | null;
|
||||
phone: string | null;
|
||||
image_url: string | null;
|
||||
}
|
||||
|
||||
/** A trip place's details; only a trip place keeps opening hours. */
|
||||
export interface TripPlaceDetailsRow extends PlaceDetailsRow {
|
||||
opening_hours: string | null;
|
||||
}
|
||||
|
||||
/** A saved place's details; only a saved place has a list status. */
|
||||
export interface SavedPlaceDetailsRow extends PlaceDetailsRow {
|
||||
status: string;
|
||||
}
|
||||
|
||||
/** One change to write: one field of one trip place or saved place. */
|
||||
export interface PlaceChangeWrite {
|
||||
place_id: number | null;
|
||||
collection_place_id: number | null;
|
||||
field: string;
|
||||
old_value: string | null;
|
||||
new_value: string | null;
|
||||
user_id: number | null;
|
||||
automatic: number;
|
||||
}
|
||||
|
||||
/** The fields cleared on one trip place or saved place, whose changes go. */
|
||||
export interface PlaceChangeClear {
|
||||
place_id: number | null;
|
||||
collection_place_id: number | null;
|
||||
fields: string[];
|
||||
}
|
||||
|
||||
/** A change as the history reads it, with who made it. */
|
||||
export interface PlaceChangeRow {
|
||||
id: number;
|
||||
place_id: number | null;
|
||||
collection_place_id: number | null;
|
||||
field: string;
|
||||
old_value: string | null;
|
||||
new_value: string | null;
|
||||
user_id: number | null;
|
||||
username: string | null;
|
||||
avatar: string | null;
|
||||
automatic: number;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `place_change_log` (PLC-14): what changed in the details of a trip place or
|
||||
* a saved place. Every method takes ids the caller decided on; who may read
|
||||
* which place is the caller's question, never this repository's.
|
||||
*/
|
||||
export class PlaceChangeLogRepository extends TrekRepository<PlaceChangeLog> {
|
||||
private db() {
|
||||
return this.kysely<PlaceChangeLogDB>();
|
||||
}
|
||||
|
||||
/**
|
||||
* The details of the trip places `ids` that still exist and are no tour. A
|
||||
* tour keeps no history: All places leaves tours out, and the planner's save
|
||||
* of a route rewrites its name and start as a whole, so a tour's details are
|
||||
* the tour's own, read with the tour.
|
||||
*/
|
||||
async tripPlaceDetails(ids: readonly number[]): Promise<TripPlaceDetailsRow[]> {
|
||||
return this.db()
|
||||
.selectFrom('places as p')
|
||||
.leftJoin('categories as c', 'c.id', 'p.category_id')
|
||||
.select([
|
||||
'p.id',
|
||||
'p.name',
|
||||
'p.address',
|
||||
'p.lat',
|
||||
'p.lng',
|
||||
'c.name as category_name',
|
||||
'p.description',
|
||||
'p.notes',
|
||||
'p.website',
|
||||
'p.phone',
|
||||
'p.image_url',
|
||||
'p.opening_hours',
|
||||
])
|
||||
.where('p.id', 'in', idsOrNone(ids))
|
||||
.where((eb) =>
|
||||
eb.not(eb.exists(eb.selectFrom('tours as t').select('t.place_id').whereRef('t.place_id', '=', 'p.id'))),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** The details of the saved places `ids` that still exist. */
|
||||
async savedPlaceDetails(ids: readonly number[]): Promise<SavedPlaceDetailsRow[]> {
|
||||
return this.db()
|
||||
.selectFrom('collection_places as cp')
|
||||
.leftJoin('categories as c', 'c.id', 'cp.category_id')
|
||||
.select([
|
||||
'cp.id',
|
||||
'cp.name',
|
||||
'cp.address',
|
||||
'cp.lat',
|
||||
'cp.lng',
|
||||
'c.name as category_name',
|
||||
'cp.description',
|
||||
'cp.notes',
|
||||
'cp.website',
|
||||
'cp.phone',
|
||||
'cp.image_url',
|
||||
'cp.status',
|
||||
])
|
||||
.where('cp.id', 'in', idsOrNone(ids))
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** The trip places with this Google id and no picture, which the photo cache fills in (the write's own filter). */
|
||||
async tripPlaceIdsWithoutImage(googlePlaceId: string): Promise<number[]> {
|
||||
const rows = await this.db()
|
||||
.selectFrom('places')
|
||||
.select('id')
|
||||
.where('google_place_id', '=', googlePlaceId)
|
||||
.where((eb) => eb.or([eb('image_url', 'is', null), eb('image_url', '=', '')]))
|
||||
.execute();
|
||||
return rows.map((row) => row.id);
|
||||
}
|
||||
|
||||
/** Writes the changes; a saved place's change names the list the place is in now, where it was made. */
|
||||
async insertChanges(rows: readonly PlaceChangeWrite[]): Promise<void> {
|
||||
if (rows.length === 0) return;
|
||||
const savedIds = rows.flatMap((row) => (row.collection_place_id === null ? [] : [row.collection_place_id]));
|
||||
const lists = savedIds.length
|
||||
? await this.db()
|
||||
.selectFrom('collection_places')
|
||||
.select(['id', 'collection_id'])
|
||||
.where('id', 'in', savedIds)
|
||||
.execute()
|
||||
: [];
|
||||
const listOf = new Map(lists.map((row) => [row.id, row.collection_id]));
|
||||
await this.db()
|
||||
.insertInto('place_change_log')
|
||||
.values(
|
||||
rows.map((row) => ({
|
||||
...row,
|
||||
collection_id: row.collection_place_id === null ? null : (listOf.get(row.collection_place_id) ?? null),
|
||||
})),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Drops every change of the cleared fields, one statement for all of them. */
|
||||
async deleteCleared(clears: readonly PlaceChangeClear[]): Promise<void> {
|
||||
const wanted = clears.filter((clear) => clear.fields.length > 0);
|
||||
if (wanted.length === 0) return;
|
||||
await this.db()
|
||||
.deleteFrom('place_change_log')
|
||||
.where((eb) =>
|
||||
eb.or(
|
||||
wanted.map((clear) =>
|
||||
eb.and([
|
||||
clear.place_id === null
|
||||
? eb('collection_place_id', '=', clear.collection_place_id ?? 0)
|
||||
: eb('place_id', '=', clear.place_id),
|
||||
eb('field', 'in', clear.fields),
|
||||
]),
|
||||
),
|
||||
),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* The changes of the trip places `placeIds` and the saved places `savedIds`,
|
||||
* newest first, before the change `beforeId` when given, `limit` at most. Of
|
||||
* a saved place only the changes made in the list it is in now: one moved
|
||||
* from another list does not bring along who edited it there.
|
||||
*/
|
||||
async page(
|
||||
placeIds: readonly number[],
|
||||
savedIds: readonly number[],
|
||||
beforeId: number | null,
|
||||
limit: number,
|
||||
): Promise<PlaceChangeRow[]> {
|
||||
if (placeIds.length === 0 && savedIds.length === 0) return [];
|
||||
let query = this.db()
|
||||
.selectFrom('place_change_log as l')
|
||||
.leftJoin('users as u', 'u.id', 'l.user_id')
|
||||
.leftJoin('collection_places as cp', 'cp.id', 'l.collection_place_id')
|
||||
.select([
|
||||
'l.id',
|
||||
'l.place_id',
|
||||
'l.collection_place_id',
|
||||
'l.field',
|
||||
'l.old_value',
|
||||
'l.new_value',
|
||||
'l.user_id',
|
||||
'u.username',
|
||||
'u.avatar',
|
||||
'l.automatic',
|
||||
'l.created_at',
|
||||
])
|
||||
.where((eb) =>
|
||||
eb.or([
|
||||
eb('l.place_id', 'in', idsOrNone(placeIds)),
|
||||
eb.and([
|
||||
eb('l.collection_place_id', 'in', idsOrNone(savedIds)),
|
||||
eb('l.collection_id', '=', eb.ref('cp.collection_id')),
|
||||
]),
|
||||
]),
|
||||
);
|
||||
if (beforeId !== null) query = query.where('l.id', '<', beforeId);
|
||||
return query.orderBy('l.id', 'desc').limit(limit).execute();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,293 @@
|
||||
import type { DB } from '../kysely/db';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
import type { SqlEntityManager } from '@mikro-orm/sql';
|
||||
|
||||
import type { Kysely } from 'kysely';
|
||||
|
||||
type ContextDB = Pick<
|
||||
DB,
|
||||
| 'places'
|
||||
| 'trips'
|
||||
| 'trip_members'
|
||||
| 'users'
|
||||
| 'days'
|
||||
| 'day_assignments'
|
||||
| 'assignment_participants'
|
||||
| 'journeys'
|
||||
| 'journey_entries'
|
||||
| 'journey_entry_photos'
|
||||
| 'journey_photos'
|
||||
| 'trek_photos'
|
||||
| 'trip_files'
|
||||
| 'file_links'
|
||||
>;
|
||||
|
||||
/** Kysely cannot bind an empty IN list and no row has the id 0, so none reads as this. */
|
||||
const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [0]);
|
||||
|
||||
/**
|
||||
* A place planned on a dated day of a trip up to a given day, one row per
|
||||
* assignment: the raw material a visit is derived from.
|
||||
*/
|
||||
export interface PlannedVisitRow {
|
||||
assignment_id: number;
|
||||
place_id: number;
|
||||
name: string;
|
||||
trip_id: number;
|
||||
trip_title: string;
|
||||
day_id: number;
|
||||
day_number: number;
|
||||
date: string;
|
||||
order_index: number | null;
|
||||
assignment_time: string | null;
|
||||
place_time: string | null;
|
||||
}
|
||||
|
||||
/** Someone an assignment names as taking part, or someone with an account on a trip. */
|
||||
export interface VisitPersonRow {
|
||||
id: number;
|
||||
username: string;
|
||||
avatar: string | null;
|
||||
}
|
||||
|
||||
interface VisitAssignmentPersonRow extends VisitPersonRow {
|
||||
assignment_id: number;
|
||||
}
|
||||
|
||||
interface VisitTripPersonRow extends VisitPersonRow {
|
||||
trip_id: number;
|
||||
}
|
||||
|
||||
/** A photo of a journey entry made from one of the places. */
|
||||
interface VisitJourneyPhotoRow {
|
||||
place_id: number;
|
||||
journey_id: number;
|
||||
journey_title: string;
|
||||
entry_id: number;
|
||||
entry_date: string;
|
||||
journey_photo_id: number;
|
||||
photo_id: number;
|
||||
caption: string | null;
|
||||
provider: string;
|
||||
asset_id: string | null;
|
||||
owner_id: number | null;
|
||||
file_path: string | null;
|
||||
thumbnail_path: string | null;
|
||||
width: number | null;
|
||||
height: number | null;
|
||||
media_type: string;
|
||||
taken_at: string | null;
|
||||
}
|
||||
|
||||
/** A trip file attached to one of the places, by a link or by its own place. */
|
||||
interface VisitFileRow {
|
||||
file_id: number;
|
||||
trip_id: number;
|
||||
place_id: number;
|
||||
original_name: string;
|
||||
mime_type: string | null;
|
||||
file_size: number | null;
|
||||
created_at: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the visits of All places (D7, PLC-10, PLC-19, PLC-20, PLC-23) read: the
|
||||
* places planned on the days of trips that have come, the people taking part,
|
||||
* and the journey photos and files that hang on a trip place. Visits are not
|
||||
* stored; they are read from the day plans every time. Not bound to an entity,
|
||||
* like `PlacesLibraryRepository`; the places-library module provides it over
|
||||
* the context-resolving EntityManager. Read only, and it checks no trip
|
||||
* access: every trip and place id it takes is one the caller reaches.
|
||||
*/
|
||||
export class PlaceVisitContextRepository {
|
||||
constructor(private readonly em: EntityManager) {}
|
||||
|
||||
private db(): Kysely<ContextDB> {
|
||||
return (this.em.getContext() as SqlEntityManager).getKysely<ContextDB>();
|
||||
}
|
||||
|
||||
/**
|
||||
* The assignments that count as a visit of `userId`: a place of the trip on
|
||||
* a day with a date up to `today` (YYYY-MM-DD), the assignment naming no one
|
||||
* or naming the user among who takes part. A day without a date never counts.
|
||||
*/
|
||||
private planned(userId: number, today: string) {
|
||||
return this.db()
|
||||
.selectFrom('day_assignments as da')
|
||||
.innerJoin('days as d', 'd.id', 'da.day_id')
|
||||
.innerJoin('places as p', 'p.id', 'da.place_id')
|
||||
.innerJoin('trips as t', 't.id', 'd.trip_id')
|
||||
.select([
|
||||
'da.id as assignment_id',
|
||||
'p.id as place_id',
|
||||
'p.name',
|
||||
't.id as trip_id',
|
||||
't.title as trip_title',
|
||||
'd.id as day_id',
|
||||
'd.day_number',
|
||||
'd.date',
|
||||
'da.order_index',
|
||||
'da.assignment_time',
|
||||
'p.place_time',
|
||||
])
|
||||
.whereRef('p.trip_id', '=', 'd.trip_id')
|
||||
.where('d.date', 'is not', null)
|
||||
.where('d.date', '<=', today)
|
||||
.where((eb) =>
|
||||
eb.or([
|
||||
eb.not(
|
||||
eb.exists(
|
||||
eb.selectFrom('assignment_participants as ap').select('ap.id').whereRef('ap.assignment_id', '=', 'da.id'),
|
||||
),
|
||||
),
|
||||
eb.exists(
|
||||
eb
|
||||
.selectFrom('assignment_participants as ap')
|
||||
.select('ap.id')
|
||||
.whereRef('ap.assignment_id', '=', 'da.id')
|
||||
.where('ap.user_id', '=', userId),
|
||||
),
|
||||
]),
|
||||
)
|
||||
.orderBy('d.date', 'desc')
|
||||
.orderBy('t.id')
|
||||
.orderBy('d.day_number')
|
||||
.orderBy('da.order_index')
|
||||
.orderBy('da.id');
|
||||
}
|
||||
|
||||
/** The visits of `userId` at the trip places `placeIds`, up to `today`. */
|
||||
async plannedAtPlaces(userId: number, today: string, placeIds: number[]): Promise<PlannedVisitRow[]> {
|
||||
const rows = await this.planned(userId, today).where('p.id', 'in', idsOrNone(placeIds)).execute();
|
||||
return rows.flatMap((row) => (row.date === null ? [] : [{ ...row, date: row.date }]));
|
||||
}
|
||||
|
||||
/** The visits of `userId` on the trips `tripIds`, up to `today`. */
|
||||
async plannedOnTrips(userId: number, today: string, tripIds: number[]): Promise<PlannedVisitRow[]> {
|
||||
const rows = await this.planned(userId, today).where('d.trip_id', 'in', idsOrNone(tripIds)).execute();
|
||||
return rows.flatMap((row) => (row.date === null ? [] : [{ ...row, date: row.date }]));
|
||||
}
|
||||
|
||||
/** Who the assignments name as taking part, by assignment. */
|
||||
async assignmentPeople(assignmentIds: number[]): Promise<VisitAssignmentPersonRow[]> {
|
||||
return await this.db()
|
||||
.selectFrom('assignment_participants as ap')
|
||||
.innerJoin('users as u', 'u.id', 'ap.user_id')
|
||||
.select(['ap.assignment_id', 'u.id', 'u.username', 'u.avatar'])
|
||||
.where('ap.assignment_id', 'in', idsOrNone(assignmentIds))
|
||||
.orderBy('ap.assignment_id')
|
||||
.orderBy('ap.id')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** The owner and the members with an account of each trip, the owner first. */
|
||||
async tripPeople(tripIds: number[]): Promise<VisitTripPersonRow[]> {
|
||||
const db = this.db();
|
||||
const owners = await db
|
||||
.selectFrom('trips as t')
|
||||
.innerJoin('users as u', 'u.id', 't.user_id')
|
||||
.select(['t.id as trip_id', 'u.id', 'u.username', 'u.avatar'])
|
||||
.where('t.id', 'in', idsOrNone(tripIds))
|
||||
.where('u.is_guest', '=', 0)
|
||||
.execute();
|
||||
const members = await db
|
||||
.selectFrom('trip_members as m')
|
||||
.innerJoin('users as u', 'u.id', 'm.user_id')
|
||||
.select(['m.trip_id', 'u.id', 'u.username', 'u.avatar'])
|
||||
.where('m.trip_id', 'in', idsOrNone(tripIds))
|
||||
.where('u.is_guest', '=', 0)
|
||||
.orderBy('m.added_at')
|
||||
.orderBy('m.id')
|
||||
.execute();
|
||||
return [...owners, ...members];
|
||||
}
|
||||
|
||||
/** Every place id of the trip. */
|
||||
async tripPlaceIds(tripId: number): Promise<number[]> {
|
||||
const rows = await this.db().selectFrom('places').select('id').where('trip_id', '=', tripId).execute();
|
||||
return rows.map((row) => row.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* The photos of the journey entries made from the trip places, by entry
|
||||
* date and photo order; none of an entry set aside or not filled yet.
|
||||
*/
|
||||
async journeyPhotosOfPlaces(placeIds: number[]): Promise<VisitJourneyPhotoRow[]> {
|
||||
const rows = await this.db()
|
||||
.selectFrom('journey_entries as je')
|
||||
.innerJoin('journeys as j', 'j.id', 'je.journey_id')
|
||||
.innerJoin('journey_entry_photos as jep', 'jep.entry_id', 'je.id')
|
||||
.innerJoin('journey_photos as gp', 'gp.id', 'jep.journey_photo_id')
|
||||
.innerJoin('trek_photos as tp', 'tp.id', 'gp.photo_id')
|
||||
.select([
|
||||
'je.source_place_id as place_id',
|
||||
'j.id as journey_id',
|
||||
'j.title as journey_title',
|
||||
'je.id as entry_id',
|
||||
'je.entry_date',
|
||||
'gp.id as journey_photo_id',
|
||||
'gp.photo_id',
|
||||
'gp.caption',
|
||||
'tp.provider',
|
||||
'tp.asset_id',
|
||||
'tp.owner_id',
|
||||
'tp.file_path',
|
||||
'tp.thumbnail_path',
|
||||
'tp.width',
|
||||
'tp.height',
|
||||
'tp.media_type',
|
||||
'tp.taken_at',
|
||||
])
|
||||
.where('je.source_place_id', 'in', idsOrNone(placeIds))
|
||||
.where('je.dismissed', '=', 0)
|
||||
.where('je.type', '!=', 'skeleton')
|
||||
.orderBy('je.entry_date', 'desc')
|
||||
.orderBy('je.id')
|
||||
.orderBy('jep.sort_order')
|
||||
.orderBy('gp.id')
|
||||
.execute();
|
||||
return rows.flatMap((row) => (row.place_id === null ? [] : [{ ...row, place_id: row.place_id }]));
|
||||
}
|
||||
|
||||
/**
|
||||
* The files not in the trash attached to the trip places: through a link
|
||||
* (`file_links.place_id`) or as the file's own place (`trip_files.place_id`).
|
||||
*/
|
||||
async filesOfPlaces(placeIds: number[]): Promise<VisitFileRow[]> {
|
||||
const db = this.db();
|
||||
const columns = [
|
||||
'f.id as file_id',
|
||||
'f.trip_id',
|
||||
'f.original_name',
|
||||
'f.mime_type',
|
||||
'f.file_size',
|
||||
'f.created_at',
|
||||
] as const;
|
||||
const linked = await db
|
||||
.selectFrom('file_links as l')
|
||||
.innerJoin('trip_files as f', 'f.id', 'l.file_id')
|
||||
.innerJoin('places as p', 'p.id', 'l.place_id')
|
||||
.select([...columns, 'p.id as place_id'])
|
||||
.where('l.place_id', 'in', idsOrNone(placeIds))
|
||||
.whereRef('p.trip_id', '=', 'f.trip_id')
|
||||
.where('f.deleted_at', 'is', null)
|
||||
.execute();
|
||||
const own = await db
|
||||
.selectFrom('trip_files as f')
|
||||
.innerJoin('places as p', 'p.id', 'f.place_id')
|
||||
.select([...columns, 'p.id as place_id'])
|
||||
.where('f.place_id', 'in', idsOrNone(placeIds))
|
||||
.whereRef('p.trip_id', '=', 'f.trip_id')
|
||||
.where('f.deleted_at', 'is', null)
|
||||
.execute();
|
||||
const seen = new Set<string>();
|
||||
return [...linked, ...own]
|
||||
.filter((row) => {
|
||||
const key = `${row.file_id}:${row.place_id}`;
|
||||
if (seen.has(key)) return false;
|
||||
seen.add(key);
|
||||
return true;
|
||||
})
|
||||
.sort((a, b) => a.file_id - b.file_id || a.place_id - b.place_id);
|
||||
}
|
||||
}
|
||||
@@ -27,6 +27,8 @@ type LibraryDB = Pick<
|
||||
| 'days'
|
||||
| 'user_places'
|
||||
| 'user_place_links'
|
||||
| 'tags'
|
||||
| 'personal_place_tags'
|
||||
>;
|
||||
|
||||
/**
|
||||
@@ -38,7 +40,7 @@ const NO_ROW = 0;
|
||||
const idsOrNone = (ids: readonly number[]): number[] => (ids.length > 0 ? [...ids] : [NO_ROW]);
|
||||
|
||||
/** What reading an entry's uses matches: everything. */
|
||||
const NO_MATCH: LibraryMatch = { search: null, categoryId: null, status: null };
|
||||
const NO_MATCH: LibraryMatch = { search: null, categoryId: null, status: null, tags: null };
|
||||
|
||||
/**
|
||||
* The road trip stops that belong to the drive rather than to the places of
|
||||
@@ -79,6 +81,29 @@ export interface LibraryMatch {
|
||||
categoryId: number | null;
|
||||
/** A list's status; only saved places have one. */
|
||||
status: string | null;
|
||||
/** PLC-21: only entries carrying at least one of these personal tags of the user. */
|
||||
tags: LibraryTagMatch | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The personal tags an entry must carry one of (PLC-21). `reach` is every trip
|
||||
* and list the user can open: a tag on any use of an entry counts, also on a
|
||||
* use another filter of the page leaves out.
|
||||
*/
|
||||
interface LibraryTagMatch {
|
||||
tagIds: number[];
|
||||
reach: LibraryArms;
|
||||
}
|
||||
|
||||
/** One personal tag on one target, with the own place a merged one went into. */
|
||||
export interface LibraryEntryTagRow {
|
||||
id: number;
|
||||
name: string;
|
||||
color: string | null;
|
||||
user_place_id: number | null;
|
||||
merged_into_id: number | null;
|
||||
place_id: number | null;
|
||||
collection_place_id: number | null;
|
||||
}
|
||||
|
||||
/** Where an entry stands in the list's order: its sort value and its key. */
|
||||
@@ -145,12 +170,17 @@ export interface LibraryTripPlaceRow extends PlaceFactsRow {
|
||||
trip_start: string | null;
|
||||
trip_end: string | null;
|
||||
trip_owner_id: number;
|
||||
/** The trip's cover picture, for the card that names it. */
|
||||
trip_cover?: string | null;
|
||||
}
|
||||
|
||||
export interface LibraryCollectionPlaceRow extends PlaceFactsRow {
|
||||
id: number;
|
||||
collection_id: number;
|
||||
collection_name: string;
|
||||
/** The list's own colour and symbol, as its rail row shows them. */
|
||||
collection_color?: string | null;
|
||||
collection_icon?: string | null;
|
||||
status: string;
|
||||
}
|
||||
|
||||
@@ -424,11 +454,68 @@ export class PlacesLibraryRepository {
|
||||
.as('u');
|
||||
}
|
||||
|
||||
/** The user's personal tags among `tagIds`, the only tags a statement here matches. */
|
||||
private ownTagIds(db: Kysely<LibraryDB>, userId: number, tagIds: readonly number[]) {
|
||||
return db
|
||||
.selectFrom('tags as tg')
|
||||
.select('tg.id')
|
||||
.where('tg.user_id', '=', userId)
|
||||
.where('tg.trip_id', 'is', null)
|
||||
.where('tg.id', 'in', idsOrNone(tagIds));
|
||||
}
|
||||
|
||||
/**
|
||||
* The entries that carry one of the tags (PLC-21): a tag on one of an
|
||||
* entry's uses, or on its own place or one merged into that.
|
||||
*/
|
||||
private taggedAnchors(db: Kysely<LibraryDB>, tags: LibraryTagMatch) {
|
||||
const onUses = db
|
||||
.selectFrom(this.entries(db, tags.reach, NO_MATCH))
|
||||
.select('u.anchor_key')
|
||||
.where((eb) =>
|
||||
eb.exists(
|
||||
eb
|
||||
.selectFrom('personal_place_tags as pt')
|
||||
.select('pt.id')
|
||||
.where('pt.tag_id', 'in', this.ownTagIds(db, tags.reach.userId, tags.tagIds))
|
||||
.where((inner) =>
|
||||
inner.or([
|
||||
inner.and([inner('u.from_list', '=', 0), inner('pt.place_id', '=', inner.ref('u.use_id'))]),
|
||||
inner.and([inner('u.from_list', '=', 1), inner('pt.collection_place_id', '=', inner.ref('u.use_id'))]),
|
||||
]),
|
||||
),
|
||||
),
|
||||
)
|
||||
.$castTo<{ anchor_key: number }>();
|
||||
const onIdentities = db
|
||||
.selectFrom('personal_place_tags as pi')
|
||||
.innerJoin('user_places as upi', 'upi.id', 'pi.user_place_id')
|
||||
.select((eb) =>
|
||||
eb(
|
||||
eb(eb.fn.coalesce('upi.merged_into_id', 'upi.id'), '*', eb.lit(ANCHOR_SPAN)).$castTo<number>(),
|
||||
'+',
|
||||
eb.lit(ANCHOR_OWN),
|
||||
)
|
||||
.$castTo<number>()
|
||||
.as('anchor_key'),
|
||||
)
|
||||
.where('upi.user_id', '=', tags.reach.userId)
|
||||
.where('pi.tag_id', 'in', this.ownTagIds(db, tags.reach.userId, tags.tagIds))
|
||||
.$castTo<{ anchor_key: number }>();
|
||||
return db.selectFrom(onUses.union(onIdentities).as('tagged')).select('tagged.anchor_key');
|
||||
}
|
||||
|
||||
/** The union of the entries, narrowed to the ones carrying a tag when the match names tags. */
|
||||
private matching(db: Kysely<LibraryDB>, arms: LibraryArms, match: LibraryMatch) {
|
||||
const tags = match.tags;
|
||||
const all = db.selectFrom(this.entries(db, arms, match));
|
||||
return tags === null ? all : all.where('u.anchor_key', 'in', this.taggedAnchors(db, tags));
|
||||
}
|
||||
|
||||
/** How many entries match: all of them, those with a trip place, those with a saved place. */
|
||||
async countEntries(arms: LibraryArms, match: LibraryMatch): Promise<LibraryCounts> {
|
||||
const db = this.db();
|
||||
const row = await db
|
||||
.selectFrom(this.entries(db, arms, match))
|
||||
const row = await this.matching(db, arms, match)
|
||||
.select((eb) => [
|
||||
eb.fn.count<number>('u.anchor_key').distinct().as('all'),
|
||||
eb.fn
|
||||
@@ -455,8 +542,7 @@ export class PlacesLibraryRepository {
|
||||
const db = this.db();
|
||||
const value = after?.value ?? '';
|
||||
const key = after?.key ?? 0;
|
||||
const rows = await db
|
||||
.selectFrom(this.entries(db, arms, match))
|
||||
const rows = await this.matching(db, arms, match)
|
||||
.select(['u.anchor_key', 'u.sort_name', 'u.sort_time'])
|
||||
.distinct()
|
||||
.$if(after !== null && sort === 'name', (qb) =>
|
||||
@@ -525,6 +611,47 @@ export class PlacesLibraryRepository {
|
||||
return row ? Number(row.anchor_key) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The user's personal tags on the targets (PLC-21), by name: on their own
|
||||
* places or ones merged into them, on trip places, on saved places. Only
|
||||
* the user's own personal tags, so nobody reads another person's.
|
||||
*/
|
||||
async entryTags(
|
||||
userId: number,
|
||||
targets: { identityIds: number[]; placeIds: number[]; collectionPlaceIds: number[] },
|
||||
): Promise<LibraryEntryTagRow[]> {
|
||||
const { identityIds, placeIds, collectionPlaceIds } = targets;
|
||||
if (identityIds.length + placeIds.length + collectionPlaceIds.length === 0) return [];
|
||||
return await this.db()
|
||||
.selectFrom('personal_place_tags as pt')
|
||||
.innerJoin('tags as tg', 'tg.id', 'pt.tag_id')
|
||||
.leftJoin('user_places as upt', 'upt.id', 'pt.user_place_id')
|
||||
.select([
|
||||
'tg.id',
|
||||
'tg.name',
|
||||
'tg.color',
|
||||
'pt.user_place_id',
|
||||
'upt.merged_into_id',
|
||||
'pt.place_id',
|
||||
'pt.collection_place_id',
|
||||
])
|
||||
.where('tg.user_id', '=', userId)
|
||||
.where('tg.trip_id', 'is', null)
|
||||
.where((eb) =>
|
||||
eb.or([
|
||||
eb.and([
|
||||
eb('upt.user_id', '=', userId),
|
||||
eb.or([eb('upt.id', 'in', idsOrNone(identityIds)), eb('upt.merged_into_id', 'in', idsOrNone(identityIds))]),
|
||||
]),
|
||||
eb('pt.place_id', 'in', idsOrNone(placeIds)),
|
||||
eb('pt.collection_place_id', 'in', idsOrNone(collectionPlaceIds)),
|
||||
]),
|
||||
)
|
||||
.orderBy('tg.name')
|
||||
.orderBy('tg.id')
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** The trip places with their trip and category, for the entries of a page. */
|
||||
async tripPlaces(placeIds: number[], tripIds: number[]): Promise<LibraryTripPlaceRow[]> {
|
||||
return await this.db()
|
||||
@@ -554,6 +681,7 @@ export class PlacesLibraryRepository {
|
||||
't.start_date as trip_start',
|
||||
't.end_date as trip_end',
|
||||
't.user_id as trip_owner_id',
|
||||
't.cover_image as trip_cover',
|
||||
])
|
||||
.where('p.id', 'in', idsOrNone(placeIds))
|
||||
.where('p.trip_id', 'in', idsOrNone(tripIds))
|
||||
@@ -571,6 +699,8 @@ export class PlacesLibraryRepository {
|
||||
'cp.id',
|
||||
'cp.collection_id',
|
||||
'col.name as collection_name',
|
||||
'col.color as collection_color',
|
||||
'col.icon as collection_icon',
|
||||
'cp.status',
|
||||
'cp.name',
|
||||
'cp.address',
|
||||
|
||||
@@ -76,10 +76,13 @@ import { PaddleObstaclesModule } from './paddle-obstacles/paddle-obstacles.modul
|
||||
import { PaddleRoutingModule } from './paddle-routing/paddle-routing.module';
|
||||
import { PermissionsModule } from './permissions/permissions.module';
|
||||
import { PhotosModule } from './photos/photos.module';
|
||||
import { PlaceActivitiesModule } from './place-activities/place-activities.module';
|
||||
import { PlaceContribModule } from './place-contrib/place-contrib.module';
|
||||
import { PlaceEnrichmentModule } from './place-enrichment/place-enrichment.module';
|
||||
import { PlaceImportModule } from './place-import/place-import.module';
|
||||
import { PlaceShadowModule } from './place-shadow/place-shadow.module';
|
||||
import { PlaceHistoryModule } from './places-library/place-history.module';
|
||||
import { PlaceVisitsModule } from './places-library/place-visits.module';
|
||||
import { PlacesLibraryModule } from './places-library/places-library.module';
|
||||
import { PlacesModule } from './places/places.module';
|
||||
import { PlatformModule } from './platform/platform.module';
|
||||
@@ -205,6 +208,9 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
|
||||
TripJournalLinkModule,
|
||||
CollectionsModule,
|
||||
PlacesLibraryModule,
|
||||
PlaceVisitsModule,
|
||||
PlaceHistoryModule,
|
||||
PlaceActivitiesModule,
|
||||
TripCollectionsModule,
|
||||
ShareModule,
|
||||
TripInviteModule,
|
||||
|
||||
@@ -306,8 +306,16 @@ const CORE_TOOL_GROUPS: ToolGroups = {
|
||||
bookings: {
|
||||
about:
|
||||
"The trip's bookings: flights, trains, stays and every other reservation, the hotels and other " +
|
||||
'accommodation, airports and the live status of a flight.',
|
||||
controllers: ['ReservationsMcp', 'ReservationsReadMcp', 'AccommodationsMcp', 'AirportsMcp', 'FlightLiveMcp'],
|
||||
'accommodation, airports, the live status of a flight, and the bookings and tours a place of the trip is ' +
|
||||
'about (linking them to it).',
|
||||
controllers: [
|
||||
'ReservationsMcp',
|
||||
'ReservationsReadMcp',
|
||||
'AccommodationsMcp',
|
||||
'AirportsMcp',
|
||||
'FlightLiveMcp',
|
||||
'PlaceActivitiesMcp',
|
||||
],
|
||||
tripPart: true,
|
||||
},
|
||||
packing: {
|
||||
@@ -398,9 +406,20 @@ const CORE_TOOL_GROUPS: ToolGroups = {
|
||||
collections: {
|
||||
about:
|
||||
'Collections and all places: saved places across trips, their labels and ratings, every place of the user ' +
|
||||
'in one library, the places that are one and the same (linking, merging and undoing a merge, duplicates) ' +
|
||||
'and the lists linked to this trip.',
|
||||
controllers: ['CollectionsMcp', 'PlacesLibraryMcp', 'PlaceIdentitiesMcp', 'TripCollectionsMcp'],
|
||||
'in one library, the places that are one and the same (linking, merging and undoing a merge, duplicates), ' +
|
||||
'your personal tags on them, the lists linked to this trip and the places visited on past trip days, with ' +
|
||||
'their photos and files, the history of who changed which detail of a place, and the bookings and tours ' +
|
||||
'a saved place or a place of the library is about.',
|
||||
controllers: [
|
||||
'CollectionsMcp',
|
||||
'PlacesLibraryMcp',
|
||||
'PlaceIdentitiesMcp',
|
||||
'PlaceTagsMcp',
|
||||
'TripCollectionsMcp',
|
||||
'PlaceVisitsMcp',
|
||||
'PlaceHistoryMcp',
|
||||
'SavedPlaceActivitiesMcp',
|
||||
],
|
||||
},
|
||||
collab: {
|
||||
about: 'Trip chat: notes, polls, shared links and messages to the people on the trip.',
|
||||
|
||||
@@ -193,3 +193,42 @@ export async function tripTagIdsOf(
|
||||
return [...ids, id];
|
||||
}, Promise.resolve([]));
|
||||
}
|
||||
|
||||
/** A tag as a copy into a trip brings it along: the name and colour a trip tag of that name takes. */
|
||||
interface CarriedTag {
|
||||
name: string;
|
||||
color: string;
|
||||
}
|
||||
|
||||
/** The colour a personal tag stored without one comes along with, the tags' own default. */
|
||||
const DEFAULT_TAG_COLOR = '#10b981';
|
||||
|
||||
/**
|
||||
* D9/PLC-21: the tags each copied saved place brings into the trip, by saved
|
||||
* place id. A saved place's tags and the copier's personal tags stay where they
|
||||
* are unless asked for: `tag_ids` names the list's tags to bring where the
|
||||
* place carries them, `personal_tag_ids` the copier's own personal tags to
|
||||
* share, which come along on every copy (an id that is not one of the
|
||||
* copier's personal tags is ignored). Null when neither is asked for, so no
|
||||
* tag is read or made. Each becomes a tag of the trip, independent of the tag
|
||||
* it came from.
|
||||
*/
|
||||
export async function tagsToCarry(
|
||||
body: { tag_ids?: number[]; personal_tag_ids?: number[] },
|
||||
placeIds: number[],
|
||||
lists: { loadTagsByPlaceIds(ids: number[]): Promise<{ pid: number; id: number; name: string; color: string }[]> },
|
||||
personalTags: () => Promise<{ id: number; name: string; color: string | null; trip_id: number | null }[]>,
|
||||
): Promise<Record<number, CarriedTag[]> | null> {
|
||||
const asked = new Set(body.tag_ids ?? []);
|
||||
const shared = new Set(body.personal_tag_ids ?? []);
|
||||
if (asked.size === 0 && shared.size === 0) return null;
|
||||
const listed = asked.size ? (await lists.loadTagsByPlaceIds(placeIds)).filter((tag) => asked.has(tag.id)) : [];
|
||||
const personal = shared.size
|
||||
? (await personalTags())
|
||||
.filter((tag) => tag.trip_id === null && shared.has(tag.id))
|
||||
// A legacy row can hold a number as its name, so it is read as text.
|
||||
.map((tag) => ({ name: String(tag.name), color: tag.color ?? DEFAULT_TAG_COLOR }))
|
||||
: [];
|
||||
const byPlace = groupByPid(listed, (tag) => ({ name: tag.name, color: tag.color }));
|
||||
return Object.fromEntries(placeIds.map((id) => [id, [...(byPlace[id] ?? []), ...personal]]));
|
||||
}
|
||||
|
||||
@@ -447,7 +447,7 @@ export class CollectionsMcp {
|
||||
@Tool({
|
||||
name: 'copy_collection_places_to_trip',
|
||||
description:
|
||||
"Copy one or more saved collection places into a trip (dedup precheck on the server). Ratings (#1435) travel into the trip; trip members keep voting there. A saved place's notes and tags stay in the list unless asked for: include_notes: true copies the notes, tag_ids names the tags (of those the places carry) to bring, each as a tag of the trip, reusing a trip tag of the same name. Without either field, neither is copied. Requires edit access to the target trip.",
|
||||
"Copy one or more saved collection places into a trip (dedup precheck on the server). Ratings (#1435) travel into the trip; trip members keep voting there. A saved place's notes and tags stay in the list unless asked for: include_notes: true copies the notes, tag_ids names the tags (of those the places carry) to bring, each as a tag of the trip, reusing a trip tag of the same name. Without either field, neither is copied. Your personal tags (list_tags) stay private too: personal_tag_ids names the ones to share, each put on every copied place as a tag of the trip the same way; the trip tag and your personal tag are separate from then on. Requires edit access to the target trip.",
|
||||
inputSchema: collectionCopyToTripRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: collectionsAddonOn,
|
||||
|
||||
@@ -16,6 +16,7 @@ import { AppConfigModule } from '../app-config/app-config.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { NotificationsModule } from '../notifications/notifications.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { PlaceChangesModule } from '../place-changes/place-changes.module';
|
||||
import { PlaceImportModule } from '../place-import/place-import.module';
|
||||
import { PlacesModule } from '../places/places.module';
|
||||
import { buildStorageUploadOptions } from '../storage/storage-upload.factory';
|
||||
@@ -62,6 +63,8 @@ import { MulterModule } from '@nestjs/platform-express';
|
||||
// Copying saved places into a trip runs the places domain's journey hook, and
|
||||
// the copy tool sends its place events the way every MCP tool does.
|
||||
PlacesModule,
|
||||
// PLC-14: every write of a saved place's details keeps its history, in the write's transaction.
|
||||
PlaceChangesModule,
|
||||
McpSharedModule,
|
||||
MikroOrmModule.forFeature([
|
||||
Collections,
|
||||
|
||||
@@ -69,11 +69,12 @@ import type {
|
||||
CollectionImportablesResponse,
|
||||
} from '@trek/shared';
|
||||
import { NotificationsService } from '../notifications/notifications.service';
|
||||
import { PlaceChangesService, savedPlaceTarget } from '../place-changes/place-changes.service';
|
||||
import { PlaceImportService, type ExportedCollectionFile } from '../place-import/place-import.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import {
|
||||
filePlaceOf, groupByPid, listingWriteOf, parseLinks, placeOrderOf, serializeLinks, tagKeyOf, tripDedupSet, tripPlaceFields,
|
||||
tripTagIdsOf,
|
||||
filePlaceOf, groupByPid, listingWriteOf, parseLinks, placeOrderOf, serializeLinks, tagKeyOf, tripDedupSet,
|
||||
tagsToCarry, tripPlaceFields, tripTagIdsOf,
|
||||
} from './collections.helpers';
|
||||
|
||||
// Errors: a DomainError carrying a status; TrekExceptionFilter maps it to that code with an `{ error }` body.
|
||||
@@ -122,6 +123,7 @@ export class CollectionsService {
|
||||
@InjectRepository(Users) private readonly users: UsersRepository,
|
||||
private readonly placeImport: PlaceImportService,
|
||||
private readonly places: PlacesService, // the journey hook of every place copyToTrip adds
|
||||
private readonly changes: PlaceChangesService, // PLC-14: the history of every details write, in its transaction
|
||||
) {}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -861,7 +863,7 @@ export class CollectionsService {
|
||||
// Field update + tag rewrite + label rewrite are one logical write, so one transaction.
|
||||
await this.uow.transactional(async () => {
|
||||
if (movedTo) write.sort_order = await this.nextPlaceOrder(movedTo); // a moved place joins the end of its new list
|
||||
await this.collectionPlaces.updateFields(placeId, write);
|
||||
await this.changes.track(savedPlaceTarget(placeId), userId, () => this.collectionPlaces.updateFields(placeId, write));
|
||||
|
||||
if (body.tag_ids !== undefined) {
|
||||
await this.collectionPlaces.deleteTags(placeId);
|
||||
@@ -883,7 +885,7 @@ export class CollectionsService {
|
||||
async setStatus(userId: number, placeId: number, status: CollectionStatus, socketId?: string): Promise<CollectionPlace> {
|
||||
const collectionId = await this.collectionIdOfPlace(placeId);
|
||||
await this.assertCanEdit(userId, collectionId);
|
||||
await this.collectionPlaces.setStatus(placeId, status);
|
||||
await this.uow.transactional(() => this.changes.track(savedPlaceTarget(placeId), userId, () => this.collectionPlaces.setStatus(placeId, status)));
|
||||
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
|
||||
return this.getPlaceById(placeId);
|
||||
}
|
||||
@@ -957,7 +959,7 @@ export class CollectionsService {
|
||||
let updated = 0;
|
||||
await this.uow.transactional(async () => {
|
||||
for (const id of ids) {
|
||||
updated += await this.collectionPlaces.setStatusIfChanged(id, status);
|
||||
updated += await this.changes.track(savedPlaceTarget(id), userId, () => this.collectionPlaces.setStatusIfChanged(id, status));
|
||||
}
|
||||
});
|
||||
if (updated > 0) for (const cid of touched) await this.notifyCollectionUsers(cid, socketId, 'collections:updated');
|
||||
@@ -1027,7 +1029,7 @@ export class CollectionsService {
|
||||
const collectionId = await this.collectionIdOfPlace(placeId);
|
||||
await this.assertCanEdit(userId, collectionId);
|
||||
const prev = (await this.collectionPlaces.imageUrl(placeId)) ?? null;
|
||||
await this.collectionPlaces.setImageUrl(placeId, imageUrl);
|
||||
await this.uow.transactional(() => this.changes.track(savedPlaceTarget(placeId), userId, () => this.collectionPlaces.setImageUrl(placeId, imageUrl)));
|
||||
await this.release.releaseValues([prev]);
|
||||
await this.notifyCollectionUsers(collectionId, socketId, 'collections:updated');
|
||||
return this.getPlaceById(placeId);
|
||||
@@ -1064,11 +1066,9 @@ export class CollectionsService {
|
||||
}
|
||||
|
||||
const dedup = tripDedupSet(await this.tripPlaces.dedupCandidatesForTrip(body.trip_id));
|
||||
// D9: only the tags asked for, where the saved place carries them, and as tags of the trip, never the person's own.
|
||||
const asked = new Set(body.tag_ids ?? []);
|
||||
const carried = asked.size
|
||||
? groupByPid((await this.collectionsRepo.loadTagsByPlaceIds(sources.map(s => s.id))).filter(t => asked.has(t.id)), t => t)
|
||||
: null;
|
||||
// D9/PLC-21: only the tags asked for (the list's, the caller's own), as tags of the trip.
|
||||
const mine = () => this.tags.listByUser(userId);
|
||||
const carried = await tagsToCarry(body, sources.map(s => s.id), this.collectionsRepo, mine);
|
||||
const tripTags = new Map<string, number>(); // by name, read in the transaction that adds to them
|
||||
let tagsBefore = 0;
|
||||
|
||||
@@ -1079,10 +1079,7 @@ export class CollectionsService {
|
||||
if (carried) for (const t of await this.tags.listByTrip(body.trip_id)) tripTags.set(tagKeyOf(t.name), t.id);
|
||||
tagsBefore = tripTags.size;
|
||||
for (const s of sources) {
|
||||
if (!body.force && isPlaceDuplicate({
|
||||
name: s.name, lat: s.lat, lng: s.lng,
|
||||
google_place_id: s.google_place_id, google_ftid: s.google_ftid, osm_id: s.osm_id,
|
||||
}, dedup)) {
|
||||
if (!body.force && isPlaceDuplicate(s, dedup)) { // by its name, position and provider ids
|
||||
skipped.push({ id: s.id, name: s.name });
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { Places } from '../../db/entities/Places.entity';
|
||||
import { Users } from '../../db/entities/Users.entity';
|
||||
import { AppConfigModule } from '../app-config/app-config.module';
|
||||
import { GoogleQuotaModule } from '../google-quota/google-quota.module';
|
||||
import { PlaceChangesModule } from '../place-changes/place-changes.module';
|
||||
import { PlacePhotosModule } from '../place-photos/place-photos.module';
|
||||
import { StorageModule } from '../storage/storage.module';
|
||||
import { MapsUrlResolver } from './maps-url.resolver';
|
||||
@@ -51,6 +52,7 @@ import { Module } from '@nestjs/common';
|
||||
PlacePhotosModule,
|
||||
StorageModule,
|
||||
GoogleQuotaModule,
|
||||
PlaceChangesModule,
|
||||
MikroOrmModule.forFeature([AppSettings, Users, PlaceDetailsCache, Places]),
|
||||
],
|
||||
controllers: [MapsController],
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
*/
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import type { PlacesRepository } from '../../db/repositories/Places.repository';
|
||||
import { PlaceChangesService } from '../place-changes/place-changes.service';
|
||||
import { AUTOMATIC_CHANGE, tripPlaceTarget } from '../place-changes/place-changes.types';
|
||||
import { PlacePhotoCacheService } from '../place-photos/place-photo-cache.service';
|
||||
import { isGooglePlaceId } from './maps.helpers';
|
||||
import { withPhotoFetchSlot } from './photo-fetch-slot';
|
||||
@@ -27,6 +29,8 @@ export class PlacePhotoResolver {
|
||||
private readonly googlePlaces: GooglePlacesClient,
|
||||
private readonly wiki: WikimediaClient,
|
||||
private readonly selector: PlacesProviderSelector,
|
||||
// PLC-14: the picture filled in here is a change of each place it lands on.
|
||||
private readonly changes: PlaceChangesService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -109,7 +113,11 @@ export class PlacePhotoResolver {
|
||||
|
||||
// Persist stable proxy URL to database
|
||||
try {
|
||||
await this.placesRepo.setImageUrlIfUnset(placeId, cached.photoUrl);
|
||||
await this.changes.track(
|
||||
async () => (await this.changes.tripPlacesWithoutImage(placeId)).map(tripPlaceTarget),
|
||||
AUTOMATIC_CHANGE,
|
||||
() => this.placesRepo.setImageUrlIfUnset(placeId, cached.photoUrl),
|
||||
);
|
||||
} catch (dbErr) {
|
||||
console.error('Failed to persist photo URL to database:', dbErr);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { PlaceActivitiesLibraryService } from './place-activities-library.service';
|
||||
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
|
||||
import { placeLibraryActivitiesResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-18 beside the place detail of All places: the bookings and tours of the
|
||||
* entry over the trips and lists the user reaches, with the origins to link
|
||||
* more through. Read only; behind the Collections addon like the library.
|
||||
*/
|
||||
@Controller('api/addons/collections/library/places')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
|
||||
export class PlaceActivitiesLibraryController {
|
||||
constructor(private readonly activities: PlaceActivitiesLibraryService) {}
|
||||
|
||||
@Get('trip/:id/activities')
|
||||
@ResponseContract(placeLibraryActivitiesResponseSchema)
|
||||
async tripPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) {
|
||||
return this.activities.entry({ id: user.id, role: user.role }, 'trip', id);
|
||||
}
|
||||
|
||||
@Get('list/:id/activities')
|
||||
@ResponseContract(placeLibraryActivitiesResponseSchema)
|
||||
async savedPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) {
|
||||
return this.activities.entry({ id: user.id, role: user.role }, 'list', id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { PlacesLibraryService, placeNotFound, type LibraryUser } from '../places-library/places-library.service';
|
||||
import { oncePerTarget, savedPlaceActivities, tripPlaceActivities } from './place-activities.helpers';
|
||||
import { PlaceActivitiesService } from './place-activities.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type {
|
||||
PlaceActivity,
|
||||
PlaceLibraryActivitiesResponse,
|
||||
PlaceLibraryActivitySource,
|
||||
PlacesLibraryKind,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-18 in All places: the bookings and tours of an entry over every origin
|
||||
* of it the user reaches right now, read with the library's own reach for
|
||||
* every call (a trip place of a trip they can open, a saved place of a list
|
||||
* open to them). An activity of an origin out of reach is left out without
|
||||
* a trace, and one that several origins name is shown once, under the first.
|
||||
* With the entry come its origins and whether the user may link activities
|
||||
* on each, so a link is made through the trip place or saved place it goes to.
|
||||
* Read only.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceActivitiesLibraryService {
|
||||
constructor(
|
||||
private readonly library: PlacesLibraryService,
|
||||
private readonly activities: PlaceActivitiesService,
|
||||
private readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
async entry(user: LibraryUser, kind: PlacesLibraryKind, id: number): Promise<PlaceLibraryActivitiesResponse> {
|
||||
const reach = await this.library.reach(user.id);
|
||||
const anchor = await this.library.anchorOfUse(reach, kind, id);
|
||||
if (anchor === null) throw placeNotFound();
|
||||
const [rows] = await this.library.rows(reach, [anchor]);
|
||||
if (!rows) throw placeNotFound();
|
||||
const access = await this.library.access(user, rows.trips, rows.saved);
|
||||
const toursOn = await this.addons.isAddonEnabled(ADDON_IDS.TOURS);
|
||||
|
||||
const tripRows = await this.activities.tripRows(
|
||||
rows.trips.map((row) => row.id),
|
||||
[...new Set(rows.trips.map((row) => row.trip_id))],
|
||||
);
|
||||
const keptRows = await this.activities.savedRows(rows.saved.map((row) => row.id));
|
||||
|
||||
const activities: PlaceActivity[] = [];
|
||||
const sources: PlaceLibraryActivitySource[] = [];
|
||||
for (const row of rows.trips) {
|
||||
const canLink = access.canEditTrip(row);
|
||||
const source = { kind: 'trip', trip_id: row.trip_id, place_id: row.id } as const;
|
||||
activities.push(...tripPlaceActivities(source, tripRows, canLink));
|
||||
sources.push({
|
||||
source,
|
||||
origin: { kind: 'trip', trip_id: row.trip_id, trip_title: row.trip_title },
|
||||
can_link: canLink,
|
||||
});
|
||||
}
|
||||
for (const row of rows.saved) {
|
||||
const canLink = access.canEditList(row) && toursOn;
|
||||
const source = { kind: 'list', collection_id: row.collection_id, collection_place_id: row.id } as const;
|
||||
activities.push(...savedPlaceActivities(source, keptRows, canLink));
|
||||
sources.push({
|
||||
source,
|
||||
origin: { kind: 'list', collection_id: row.collection_id, collection_name: row.collection_name },
|
||||
can_link: canLink,
|
||||
});
|
||||
}
|
||||
return { activities: oncePerTarget(activities), sources };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
import type { TripAccess } from '../../db/repositories/Trips.repository';
|
||||
import type { User } from '../../types';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { Trip } from '../permissions/trip.decorator';
|
||||
import { TripPlaceActivityLinkDto } from './place-activities.dto';
|
||||
import { PlaceActivitiesService } from './place-activities.service';
|
||||
import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common';
|
||||
import { placeActivitiesResponseSchema, placeActivityCandidatesResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-18 at /api/trips/:tripId/places/:placeId/activities: the bookings and
|
||||
* tours of the trip a place is about. Every member reads them; linking and
|
||||
* unlinking take 'place_edit'. Unlinking takes only the link off, the
|
||||
* booking or tour stays as it is.
|
||||
*/
|
||||
@Controller('api/trips/:tripId/places/:placeId/activities')
|
||||
@UseGuards(JwtAuthGuard, TripAccessGuard)
|
||||
export class PlaceActivitiesController {
|
||||
constructor(private readonly activities: PlaceActivitiesService) {}
|
||||
|
||||
@Get()
|
||||
@ResponseContract(placeActivitiesResponseSchema)
|
||||
async list(
|
||||
@CurrentUser() user: User,
|
||||
@Trip() trip: TripAccess,
|
||||
@Param('placeId', rowId('Place not found')) placeId: number,
|
||||
) {
|
||||
return this.activities.tripPlace(trip.id, placeId, { id: user.id, role: user.role });
|
||||
}
|
||||
|
||||
@Get('candidates')
|
||||
@ResponseContract(placeActivityCandidatesResponseSchema)
|
||||
async candidates(
|
||||
@CurrentUser() user: User,
|
||||
@Trip() trip: TripAccess,
|
||||
@Param('placeId', rowId('Place not found')) placeId: number,
|
||||
) {
|
||||
return this.activities.tripCandidates(trip.id, placeId, { id: user.id, role: user.role });
|
||||
}
|
||||
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
@RequirePermission('place_edit')
|
||||
@ResponseContract(placeActivitiesResponseSchema)
|
||||
async link(
|
||||
@CurrentUser() user: User,
|
||||
@Trip() trip: TripAccess,
|
||||
@Param('placeId', rowId('Place not found')) placeId: number,
|
||||
@Body() body: TripPlaceActivityLinkDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.activities.linkTrip(trip.id, placeId, body, this.activities.restWriter(trip.id, user, socketId));
|
||||
}
|
||||
|
||||
@Delete('reservations/:reservationId')
|
||||
@HttpCode(200)
|
||||
@RequirePermission('place_edit')
|
||||
@ResponseContract(placeActivitiesResponseSchema)
|
||||
async unlinkBooking(
|
||||
@CurrentUser() user: User,
|
||||
@Trip() trip: TripAccess,
|
||||
@Param('placeId', rowId('Place not found')) placeId: number,
|
||||
@Param('reservationId', rowId('This activity is not linked to the place')) reservationId: number,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.activities.unlinkTrip(
|
||||
trip.id,
|
||||
placeId,
|
||||
{ reservation_id: reservationId },
|
||||
this.activities.restWriter(trip.id, user, socketId),
|
||||
);
|
||||
}
|
||||
|
||||
@Delete('tours/:tourId')
|
||||
@HttpCode(200)
|
||||
@RequirePermission('place_edit')
|
||||
@ResponseContract(placeActivitiesResponseSchema)
|
||||
async unlinkTour(
|
||||
@CurrentUser() user: User,
|
||||
@Trip() trip: TripAccess,
|
||||
@Param('placeId', rowId('Place not found')) placeId: number,
|
||||
@Param('tourId', rowId('This activity is not linked to the place')) tourId: number,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.activities.unlinkTrip(
|
||||
trip.id,
|
||||
placeId,
|
||||
{ tour_id: tourId },
|
||||
this.activities.restWriter(trip.id, user, socketId),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
import { savedPlaceActivityLinkRequestSchema, tripPlaceActivityLinkRequestSchema } from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
|
||||
export class TripPlaceActivityLinkDto extends createZodDto(tripPlaceActivityLinkRequestSchema) {}
|
||||
|
||||
export class SavedPlaceActivityLinkDto extends createZodDto(savedPlaceActivityLinkRequestSchema) {}
|
||||
@@ -0,0 +1,192 @@
|
||||
import type {
|
||||
ActivityBookingRow,
|
||||
ActivityKeptTourRow,
|
||||
ActivityTourRow,
|
||||
ImplicitVia,
|
||||
} from '../../db/repositories/PlaceActivityLinks.repository';
|
||||
import { badRequest } from '../common/domain-error';
|
||||
import type { PlaceActivity, PlaceActivityCandidate, PlaceActivitySource } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-18, the pure half of the place activities: rows into the wire shape,
|
||||
* one activity per target and source, and the candidates left to link.
|
||||
*/
|
||||
|
||||
const bookingKey = (reservationId: number) => `reservation:${reservationId}`;
|
||||
const tourKey = (tourId: number) => `tour:${tourId}`;
|
||||
const keptTourKey = (collectionTourId: number) => `collection_tour:${collectionTourId}`;
|
||||
|
||||
export function bookingCandidate(row: ActivityBookingRow): PlaceActivityCandidate {
|
||||
return {
|
||||
key: bookingKey(row.reservation_id),
|
||||
type: 'booking',
|
||||
origin: { kind: 'trip', trip_id: row.trip_id, trip_title: row.trip_title },
|
||||
target: { kind: 'reservation', trip_id: row.trip_id, reservation_id: row.reservation_id },
|
||||
title: row.title,
|
||||
booking_type: row.type,
|
||||
booking_status: row.status,
|
||||
tour_type: null,
|
||||
starts_at: row.reservation_time,
|
||||
ends_at: row.reservation_end_time,
|
||||
date: row.date,
|
||||
day_number: row.day_number,
|
||||
};
|
||||
}
|
||||
|
||||
export function tourCandidate(row: ActivityTourRow): PlaceActivityCandidate {
|
||||
return {
|
||||
key: tourKey(row.tour_id),
|
||||
type: 'tour',
|
||||
origin: { kind: 'trip', trip_id: row.trip_id, trip_title: row.trip_title },
|
||||
target: { kind: 'tour', trip_id: row.trip_id, tour_id: row.tour_id },
|
||||
title: row.title,
|
||||
booking_type: null,
|
||||
booking_status: null,
|
||||
tour_type: row.tour_type,
|
||||
starts_at: null,
|
||||
ends_at: null,
|
||||
date: row.date,
|
||||
day_number: row.day_number,
|
||||
};
|
||||
}
|
||||
|
||||
export function keptTourCandidate(row: ActivityKeptTourRow): PlaceActivityCandidate {
|
||||
return {
|
||||
key: keptTourKey(row.collection_tour_id),
|
||||
type: 'tour',
|
||||
origin: { kind: 'list', collection_id: row.collection_id, collection_name: row.collection_name },
|
||||
target: { kind: 'collection_tour', collection_id: row.collection_id, collection_tour_id: row.collection_tour_id },
|
||||
title: row.title,
|
||||
booking_type: null,
|
||||
booking_status: null,
|
||||
tour_type: row.tour_type,
|
||||
starts_at: null,
|
||||
ends_at: null,
|
||||
date: null,
|
||||
day_number: null,
|
||||
};
|
||||
}
|
||||
|
||||
/** What the trip side read for a set of trip places: links, bookings that belong on their own, and tours. */
|
||||
export interface TripActivityRows {
|
||||
linkedBookings: ActivityBookingRow[];
|
||||
implicitBookings: (ActivityBookingRow & { via: ImplicitVia })[];
|
||||
linkedTours: ActivityTourRow[];
|
||||
/** Tours with a station that stands for the place. */
|
||||
stationTours: ActivityTourRow[];
|
||||
}
|
||||
|
||||
/** The order an implicit reason is named in when a booking belongs for more than one. */
|
||||
const VIA_ORDER: readonly ImplicitVia[] = ['place', 'stay', 'plan'];
|
||||
|
||||
/**
|
||||
* The activities of the trip place `placeId`: every booking linked to it or
|
||||
* belonging to it on its own (once, with both flags), then every tour linked
|
||||
* to it or with a station for it, the same way. `canUnlink` is whether the
|
||||
* reader may change the place's links; only a link can be taken off.
|
||||
*/
|
||||
export function tripPlaceActivities(
|
||||
source: Extract<PlaceActivitySource, { kind: 'trip' }>,
|
||||
rows: TripActivityRows,
|
||||
canUnlink: boolean,
|
||||
): PlaceActivity[] {
|
||||
const ofPlace = <T extends { source_id: number }>(list: T[]) =>
|
||||
list.filter((row) => row.source_id === source.place_id);
|
||||
const bookings = new Map<number, { row: ActivityBookingRow; explicit: boolean; via: ImplicitVia | null }>();
|
||||
for (const row of ofPlace(rows.linkedBookings)) {
|
||||
bookings.set(row.reservation_id, { row, explicit: true, via: null });
|
||||
}
|
||||
for (const row of ofPlace(rows.implicitBookings)) {
|
||||
const known = bookings.get(row.reservation_id);
|
||||
const via = known?.via ?? null;
|
||||
const first = via === null || VIA_ORDER.indexOf(row.via) < VIA_ORDER.indexOf(via) ? row.via : via;
|
||||
bookings.set(row.reservation_id, { row: known?.row ?? row, explicit: known?.explicit ?? false, via: first });
|
||||
}
|
||||
const sorted = [...bookings.values()].sort((a, b) => compareBookings(a.row, b.row));
|
||||
return [
|
||||
...sorted.map(({ row, explicit, via }) => ({
|
||||
...bookingCandidate(row),
|
||||
source,
|
||||
explicit,
|
||||
implicit_via: via,
|
||||
can_unlink: canUnlink && explicit,
|
||||
})),
|
||||
...placeTours(ofPlace(rows.linkedTours), ofPlace(rows.stationTours)).map(({ row, explicit, station }) => ({
|
||||
...tourCandidate(row),
|
||||
source,
|
||||
explicit,
|
||||
implicit_via: station ? ('station' as const) : null,
|
||||
can_unlink: canUnlink && explicit,
|
||||
})),
|
||||
];
|
||||
}
|
||||
|
||||
/** The tours of one place, each once: linked, with a station for the place, or both; by name as read. */
|
||||
function placeTours(linked: ActivityTourRow[], stations: ActivityTourRow[]) {
|
||||
const tours = new Map<number, { row: ActivityTourRow; explicit: boolean; station: boolean }>();
|
||||
for (const row of linked) tours.set(row.tour_id, { row, explicit: true, station: false });
|
||||
for (const row of stations) {
|
||||
const known = tours.get(row.tour_id);
|
||||
tours.set(row.tour_id, { row: known?.row ?? row, explicit: known?.explicit ?? false, station: true });
|
||||
}
|
||||
return [...tours.values()].sort((a, b) => a.row.title.localeCompare(b.row.title) || a.row.tour_id - b.row.tour_id);
|
||||
}
|
||||
|
||||
/** The kept tours linked to the saved place of `source`. */
|
||||
export function savedPlaceActivities(
|
||||
source: Extract<PlaceActivitySource, { kind: 'list' }>,
|
||||
rows: ActivityKeptTourRow[],
|
||||
canUnlink: boolean,
|
||||
): PlaceActivity[] {
|
||||
return rows
|
||||
.filter((row) => row.source_id === source.collection_place_id)
|
||||
.map((row) => ({
|
||||
...keptTourCandidate(row),
|
||||
source,
|
||||
explicit: true,
|
||||
implicit_via: null,
|
||||
can_unlink: canUnlink,
|
||||
}));
|
||||
}
|
||||
|
||||
/** By time as stored (no time last), then by id, the order the repository reads them in. */
|
||||
function compareBookings(a: ActivityBookingRow, b: ActivityBookingRow): number {
|
||||
if (a.reservation_time !== b.reservation_time) {
|
||||
if (a.reservation_time === null) return 1;
|
||||
if (b.reservation_time === null) return -1;
|
||||
return a.reservation_time < b.reservation_time ? -1 : 1;
|
||||
}
|
||||
return a.reservation_id - b.reservation_id;
|
||||
}
|
||||
|
||||
/** The candidates not yet related to the place: everything whose key is not among `taken`. */
|
||||
export function remainingCandidates(
|
||||
candidates: PlaceActivityCandidate[],
|
||||
taken: readonly PlaceActivity[],
|
||||
): PlaceActivityCandidate[] {
|
||||
const keys = new Set(taken.map((activity) => activity.key));
|
||||
return candidates.filter((candidate) => !keys.has(candidate.key));
|
||||
}
|
||||
|
||||
/** Each activity once, under the first source it came with, so an entry of All places names it once. */
|
||||
export function oncePerTarget(activities: PlaceActivity[]): PlaceActivity[] {
|
||||
const seen = new Set<string>();
|
||||
return activities.filter((activity) => {
|
||||
if (seen.has(activity.key)) return false;
|
||||
seen.add(activity.key);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/** What a trip place's link points at: a booking or a tour (the tour's own place) of the trip. */
|
||||
export type TripActivityTarget = { reservation_id: number } | { tour_id: number };
|
||||
|
||||
/** Exactly one of the two ids: the request schema holds it on REST, this on every surface. */
|
||||
export function tripActivityTargetOf(
|
||||
reservationId: number | undefined,
|
||||
tourId: number | undefined,
|
||||
): TripActivityTarget {
|
||||
if (reservationId !== undefined && tourId === undefined) return { reservation_id: reservationId };
|
||||
if (tourId !== undefined && reservationId === undefined) return { tour_id: tourId };
|
||||
throw badRequest('Give either reservation_id or tour_id');
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import { canRead, canWrite } from '../../mcp/scopes';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { tripActivityTargetOf } from './place-activities.helpers';
|
||||
import { PlaceActivitiesService } from './place-activities.service';
|
||||
import { idSchema, tripPlaceActivityLinkRequestSchema } from '@trek/shared';
|
||||
|
||||
/** Reading a place's activities reads its places and its bookings. */
|
||||
const readsActivities = (ctx: McpContext) => canRead(ctx.scopes, 'places') && canRead(ctx.scopes, 'reservations');
|
||||
/** Linking changes the trip's places and names a booking or tour the caller reads. */
|
||||
const linksActivities = (ctx: McpContext) => canWrite(ctx.scopes, 'places') && canRead(ctx.scopes, 'reservations');
|
||||
|
||||
const tripPlaceInput = { tripId: idSchema, placeId: idSchema };
|
||||
const tripLinkInput = { ...tripPlaceInput, ...tripPlaceActivityLinkRequestSchema.shape };
|
||||
|
||||
type TripPlaceInput = { tripId: number; placeId: number };
|
||||
type TripLinkInput = TripPlaceInput & { reservation_id?: number; tour_id?: number };
|
||||
|
||||
/** What every activity carries, shared with the list tools in saved-place-activities.mcp.ts. */
|
||||
export const ACTIVITY_FIELDS =
|
||||
'Each activity has key, type (booking or tour), origin (the trip or list it lives in), target (to open it: trip_id with reservation_id or tour_id, or collection_id with collection_tour_id), title, booking_type and booking_status (bookings), tour_type (tours), starts_at, ends_at, date and day_number, explicit (someone linked it), implicit_via (place, stay or plan for a booking, station for a tour: it belongs to the place by itself, which cannot be undone here) and can_unlink.';
|
||||
|
||||
/**
|
||||
* PLC-18 over MCP, the trip side: the same service and permissions as
|
||||
* `/api/trips/:tripId/places/:placeId/activities`. The assistant loads these
|
||||
* with the bookings; the list and All places tools are SavedPlaceActivitiesMcp.
|
||||
*/
|
||||
@McpController()
|
||||
export class PlaceActivitiesMcp {
|
||||
constructor(
|
||||
private readonly activities: PlaceActivitiesService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'list_place_activities',
|
||||
description: `The bookings and tours of a trip a place of that trip is about: the ones linked to it, the bookings that belong to it by themselves (they name the place, a stay at it or a plan entry of it) and the tours with a station standing for it. Tours only while the trip has Tours on. ${ACTIVITY_FIELDS} can_link says whether you may link more.`,
|
||||
inputSchema: tripPlaceInput,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: readsActivities,
|
||||
})
|
||||
async listPlaceActivities({ tripId, placeId }: TripPlaceInput, ctx: McpContext) {
|
||||
const { role } = await this.guards.tripWriter(tripId, ctx.userId);
|
||||
return ok(await this.activities.tripPlace(tripId, placeId, { id: ctx.userId, role }));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'list_place_activity_candidates',
|
||||
description:
|
||||
'The bookings and tours of the trip not related to the place yet, which link_place_activity can link: same fields as list_place_activities without the link flags. The place itself, when it is a tour, is left out.',
|
||||
inputSchema: tripPlaceInput,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: readsActivities,
|
||||
})
|
||||
async listPlaceActivityCandidates({ tripId, placeId }: TripPlaceInput, ctx: McpContext) {
|
||||
const { role } = await this.guards.tripWriter(tripId, ctx.userId);
|
||||
return ok(await this.activities.tripCandidates(tripId, placeId, { id: ctx.userId, role }));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'link_place_activity',
|
||||
description:
|
||||
'Link a booking (reservation_id) or a tour (tour_id, the id of its place) of the same trip to a place of the trip, exactly one of the two. Changes neither the booking nor the tour. A booking or tour that already belongs to the place by itself is refused. Needs the permission to edit the trip places.',
|
||||
inputSchema: tripLinkInput,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: linksActivities,
|
||||
})
|
||||
async linkPlaceActivity({ tripId, placeId, reservation_id, tour_id }: TripLinkInput, ctx: McpContext) {
|
||||
const writer = await this.guards.tripWriter(tripId, ctx.userId);
|
||||
return ok(await this.activities.linkTrip(tripId, placeId, { reservation_id, tour_id }, writer));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'unlink_place_activity',
|
||||
description:
|
||||
'Take the link of a place to a booking (reservation_id) or a tour (tour_id) off, exactly one of the two. The booking or tour stays as it is; what belongs to the place by itself is changed on the booking or the tour, not here. Needs the permission to edit the trip places.',
|
||||
inputSchema: tripLinkInput,
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
access: linksActivities,
|
||||
})
|
||||
async unlinkPlaceActivity({ tripId, placeId, reservation_id, tour_id }: TripLinkInput, ctx: McpContext) {
|
||||
const writer = await this.guards.tripWriter(tripId, ctx.userId);
|
||||
const target = tripActivityTargetOf(reservation_id, tour_id);
|
||||
return ok(await this.activities.unlinkTrip(tripId, placeId, target, writer));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { PlaceActivityLinks } from '../../db/entities/PlaceActivityLinks.entity';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { CollectionsModule } from '../collections/collections.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { PlacesLibraryModule } from '../places-library/places-library.module';
|
||||
import { RealtimeModule } from '../realtime/realtime.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { PlaceActivitiesLibraryController } from './place-activities-library.controller';
|
||||
import { PlaceActivitiesLibraryService } from './place-activities-library.service';
|
||||
import { PlaceActivitiesController } from './place-activities.controller';
|
||||
import { PlaceActivitiesMcp } from './place-activities.mcp';
|
||||
import { PlaceActivitiesService } from './place-activities.service';
|
||||
import { SavedPlaceActivitiesController } from './saved-place-activities.controller';
|
||||
import { SavedPlaceActivitiesMcp } from './saved-place-activities.mcp';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* PLC-18: the bookings and tours a place is about, linked to a trip place or
|
||||
* a saved place, and read for an entry of All places over the library's
|
||||
* reach (PlacesLibraryModule). Their routes and MCP tools.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
AddonsModule,
|
||||
CollectionsModule,
|
||||
TripMembershipModule,
|
||||
PermissionsModule,
|
||||
RealtimeModule,
|
||||
McpSharedModule,
|
||||
PlacesLibraryModule,
|
||||
MikroOrmModule.forFeature([PlaceActivityLinks]),
|
||||
],
|
||||
controllers: [PlaceActivitiesController, SavedPlaceActivitiesController, PlaceActivitiesLibraryController],
|
||||
providers: [PlaceActivitiesService, PlaceActivitiesLibraryService, PlaceActivitiesMcp, SavedPlaceActivitiesMcp],
|
||||
})
|
||||
export class PlaceActivitiesModule {}
|
||||
@@ -0,0 +1,304 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { PlaceActivityLinks } from '../../db/entities/PlaceActivityLinks.entity';
|
||||
import type {
|
||||
ActivitySavedPlaceRow,
|
||||
PlaceActivityLinksRepository,
|
||||
} from '../../db/repositories/PlaceActivityLinks.repository';
|
||||
import type { User } from '../../types';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { CollectionsService } from '../collections/collections.service';
|
||||
import { badRequest, conflict, forbidden, notFound } from '../common/domain-error';
|
||||
import { requireTripWrite, restTripWriter, tripNotFound, type TripWriter } from '../common/trip-writer';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import {
|
||||
bookingCandidate,
|
||||
keptTourCandidate,
|
||||
remainingCandidates,
|
||||
savedPlaceActivities,
|
||||
tourCandidate,
|
||||
tripActivityTargetOf,
|
||||
tripPlaceActivities,
|
||||
type TripActivityRows,
|
||||
type TripActivityTarget,
|
||||
} from './place-activities.helpers';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type {
|
||||
PlaceActivitiesResponse,
|
||||
PlaceActivity,
|
||||
PlaceActivityCandidatesResponse,
|
||||
PlaceActivitySource,
|
||||
SavedPlaceActivityLinkRequest,
|
||||
TripPlaceActivityLinkRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Who reads: their id and their account role, for the admin bypass of trip permissions. */
|
||||
interface PlaceActivitiesReader {
|
||||
id: number;
|
||||
role: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Linking a booking or a tour to a place changes what the place shows to
|
||||
* everyone on the trip, so it takes the right to change the trip's places.
|
||||
* Seeing the booking or the tour is the trip itself: every member sees every
|
||||
* booking and, while the trip has Tours on, every tour.
|
||||
*/
|
||||
const LINK_PERMISSION = 'place_edit';
|
||||
|
||||
const placeNotFound = () => notFound('Place not found');
|
||||
const bookingNotFound = () => notFound('Booking not found');
|
||||
const tourNotFound = () => notFound('Tour not found', { code: 'tour_not_found' });
|
||||
const notLinked = () => notFound('This activity is not linked to the place');
|
||||
|
||||
/**
|
||||
* PLC-18: the bookings and tours a place is about. A trip place is linked to
|
||||
* bookings and tours of its own trip, a saved place to tours kept in its own
|
||||
* list; a booking that names the place itself (its place, a stay at the
|
||||
* place, a plan entry of the place) and a tour with a station standing for
|
||||
* the place belong to it without a link, are shown as such and cannot be
|
||||
* unlinked here. A link changes neither end and gives no
|
||||
* one access, and unlinking takes only the link: the booking or tour stays.
|
||||
*
|
||||
* Trip side: reading takes the trip; linking and unlinking take
|
||||
* 'place_edit' on it. Tours count only while the trip has the Tours addon on.
|
||||
* List side: reading takes any role on the list, linking and unlinking any
|
||||
* role but viewer, and kept tours count only while Tours is on. A trip or
|
||||
* list out of reach is not found, never hinted at.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceActivitiesService {
|
||||
constructor(
|
||||
@InjectRepository(PlaceActivityLinks) private readonly links: PlaceActivityLinksRepository,
|
||||
private readonly trips: TripAccessService,
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly collections: CollectionsService,
|
||||
private readonly addons: AddonsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
/** The REST caller of a trip-side write: skips the sender's socket. */
|
||||
restWriter(tripId: number, user: User, socketId: string | undefined): TripWriter {
|
||||
return restTripWriter(this.realtime, tripId, user, socketId);
|
||||
}
|
||||
|
||||
// ── Trip places ────────────────────────────────────────────────────────
|
||||
|
||||
/** The activities of the trip place, and whether the reader may link more. */
|
||||
async tripPlace(tripId: number, placeId: number, reader: PlaceActivitiesReader): Promise<PlaceActivitiesResponse> {
|
||||
const canLink = await this.canLinkOnTrip(tripId, reader);
|
||||
await this.requireTripPlace(tripId, placeId);
|
||||
const source = { kind: 'trip', trip_id: tripId, place_id: placeId } as const;
|
||||
return {
|
||||
activities: tripPlaceActivities(source, await this.tripRows([placeId], [tripId]), canLink),
|
||||
can_link: canLink,
|
||||
};
|
||||
}
|
||||
|
||||
/** The bookings and tours of the trip not related to the place yet, the place itself left out. */
|
||||
async tripCandidates(
|
||||
tripId: number,
|
||||
placeId: number,
|
||||
reader: PlaceActivitiesReader,
|
||||
): Promise<PlaceActivityCandidatesResponse> {
|
||||
const { activities } = await this.tripPlace(tripId, placeId, reader);
|
||||
const tours = (await this.addons.isEnabledForTrip(tripId, ADDON_IDS.TOURS))
|
||||
? (await this.links.tripTours(tripId)).filter((row) => row.tour_id !== placeId)
|
||||
: [];
|
||||
const bookings = await this.links.tripBookings(tripId);
|
||||
return {
|
||||
candidates: remainingCandidates([...bookings.map(bookingCandidate), ...tours.map(tourCandidate)], activities),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Links a booking or a tour of the same trip to the place. Linking it again
|
||||
* changes nothing and sends nothing; a booking that already belongs to the
|
||||
* place on its own is refused, since its own place, stay or plan entry says so.
|
||||
*/
|
||||
async linkTrip(
|
||||
tripId: number,
|
||||
placeId: number,
|
||||
body: TripPlaceActivityLinkRequest,
|
||||
writer: TripWriter,
|
||||
): Promise<PlaceActivitiesResponse> {
|
||||
const target = tripActivityTargetOf(body.reservation_id, body.tour_id);
|
||||
await this.requireLinkWrite(tripId, writer);
|
||||
const linked = await this.uow.transactional(async () => {
|
||||
await this.requireTripPlace(tripId, placeId);
|
||||
if ('reservation_id' in target) {
|
||||
if (!(await this.links.bookingInTrip(tripId, target.reservation_id))) throw bookingNotFound();
|
||||
const own = await this.links.implicitBookings([placeId]);
|
||||
if (own.some((row) => row.reservation_id === target.reservation_id)) {
|
||||
throw conflict('This booking already belongs to the place', { code: 'implicit_activity' });
|
||||
}
|
||||
return this.links.link({ place_id: placeId, reservation_id: target.reservation_id }, writer.userId);
|
||||
}
|
||||
if (target.tour_id === placeId) throw badRequest('A tour cannot be linked to itself');
|
||||
if (!(await this.addons.isEnabledForTrip(tripId, ADDON_IDS.TOURS))) throw tourNotFound();
|
||||
if (!(await this.links.tourInTrip(tripId, target.tour_id))) throw tourNotFound();
|
||||
const stations = await this.links.implicitTours([placeId]);
|
||||
if (stations.some((row) => row.tour_id === target.tour_id)) {
|
||||
throw conflict('This tour already belongs to the place', { code: 'implicit_activity' });
|
||||
}
|
||||
return this.links.link({ place_id: placeId, tour_place_id: target.tour_id }, writer.userId);
|
||||
});
|
||||
if (linked) writer.events.emit('placeActivities:changed', { placeId });
|
||||
return this.tripPlace(tripId, placeId, { id: writer.userId, role: writer.role });
|
||||
}
|
||||
|
||||
/** Takes the link of the place to a booking or tour off; the booking or tour stays as it is. */
|
||||
async unlinkTrip(
|
||||
tripId: number,
|
||||
placeId: number,
|
||||
target: TripActivityTarget,
|
||||
writer: TripWriter,
|
||||
): Promise<PlaceActivitiesResponse> {
|
||||
await this.requireLinkWrite(tripId, writer);
|
||||
await this.requireTripPlace(tripId, placeId);
|
||||
const removed = await this.links.unlinkTrip(
|
||||
placeId,
|
||||
'reservation_id' in target ? { reservation_id: target.reservation_id } : { tour_place_id: target.tour_id },
|
||||
);
|
||||
if (!removed) throw notLinked();
|
||||
writer.events.emit('placeActivities:changed', { placeId });
|
||||
return this.tripPlace(tripId, placeId, { id: writer.userId, role: writer.role });
|
||||
}
|
||||
|
||||
/**
|
||||
* The trip-side activity rows of `placeIds`, read once for all of them;
|
||||
* the linked tours only of those of the trips `tripIds` that have Tours on.
|
||||
*/
|
||||
async tripRows(placeIds: number[], tripIds: number[]): Promise<TripActivityRows> {
|
||||
const toursOn = new Set(await this.addons.tripsWithAddon(tripIds, ADDON_IDS.TOURS));
|
||||
const linkedBookings = await this.links.linkedBookings(placeIds);
|
||||
const implicitBookings = await this.links.implicitBookings(placeIds);
|
||||
const linkedTours = toursOn.size > 0 ? await this.links.linkedTours(placeIds) : [];
|
||||
const stationTours = toursOn.size > 0 ? await this.links.implicitTours(placeIds) : [];
|
||||
const shown = (row: { trip_id: number }) => toursOn.has(row.trip_id);
|
||||
return {
|
||||
linkedBookings,
|
||||
implicitBookings,
|
||||
linkedTours: linkedTours.filter(shown),
|
||||
stationTours: stationTours.filter(shown),
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether the reader may change the links of the trip's places; the trip they cannot reach is not found. */
|
||||
private async canLinkOnTrip(tripId: number, reader: PlaceActivitiesReader): Promise<boolean> {
|
||||
const trip = await this.trips.findAccessible(tripId, reader.id);
|
||||
if (!trip) throw tripNotFound();
|
||||
return this.permissions.checkPermission(
|
||||
LINK_PERMISSION,
|
||||
reader.role,
|
||||
trip.user_id,
|
||||
reader.id,
|
||||
trip.user_id !== reader.id,
|
||||
);
|
||||
}
|
||||
|
||||
private async requireTripPlace(tripId: number, placeId: number): Promise<void> {
|
||||
if (!(await this.links.tripPlace(tripId, placeId))) throw placeNotFound();
|
||||
}
|
||||
|
||||
/** The trip with 'place_edit' (404, 403). */
|
||||
private async requireLinkWrite(tripId: number, writer: TripWriter): Promise<void> {
|
||||
await requireTripWrite({ access: this.trips, permissions: this.permissions }, LINK_PERMISSION, tripId, writer);
|
||||
}
|
||||
|
||||
// ── Saved places ───────────────────────────────────────────────────────
|
||||
|
||||
/** The kept tours linked to the saved place, and whether the user may link more. */
|
||||
async savedPlace(userId: number, collectionPlaceId: number): Promise<PlaceActivitiesResponse> {
|
||||
const { place, role } = await this.readableSavedPlace(userId, collectionPlaceId);
|
||||
const canLink = role !== 'viewer' && (await this.toursOn());
|
||||
return {
|
||||
activities: await this.savedActivities(place, canLink),
|
||||
can_link: canLink,
|
||||
};
|
||||
}
|
||||
|
||||
/** The tours kept in the list not linked to the saved place yet; none while Tours is off. */
|
||||
async savedCandidates(userId: number, collectionPlaceId: number): Promise<PlaceActivityCandidatesResponse> {
|
||||
const { place } = await this.readableSavedPlace(userId, collectionPlaceId);
|
||||
if (!(await this.toursOn())) return { candidates: [] };
|
||||
const linked = await this.savedActivities(place, false);
|
||||
const kept = await this.links.keptTours(place.collection_id);
|
||||
return { candidates: remainingCandidates(kept.map(keptTourCandidate), linked) };
|
||||
}
|
||||
|
||||
/** Links a tour kept in the same list to the saved place; linking it again changes nothing and sends nothing. */
|
||||
async linkSaved(
|
||||
userId: number,
|
||||
collectionPlaceId: number,
|
||||
body: SavedPlaceActivityLinkRequest,
|
||||
socketId?: string,
|
||||
): Promise<PlaceActivitiesResponse> {
|
||||
const place = await this.writableSavedPlace(userId, collectionPlaceId);
|
||||
const linked = await this.uow.transactional(async () => {
|
||||
if (!(await this.links.keptTourInList(place.collection_id, body.collection_tour_id))) throw tourNotFound();
|
||||
return this.links.link(
|
||||
{ collection_place_id: collectionPlaceId, collection_tour_id: body.collection_tour_id },
|
||||
userId,
|
||||
);
|
||||
});
|
||||
if (linked) await this.collections.notifyCollectionUsers(place.collection_id, socketId);
|
||||
return this.savedPlace(userId, collectionPlaceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Takes the link of the saved place to a kept tour off; the tour stays in the list. A link the place left
|
||||
* behind in its old list is no link here, as it reads none.
|
||||
*/
|
||||
async unlinkSaved(
|
||||
userId: number,
|
||||
collectionPlaceId: number,
|
||||
collectionTourId: number,
|
||||
socketId?: string,
|
||||
): Promise<PlaceActivitiesResponse> {
|
||||
const place = await this.writableSavedPlace(userId, collectionPlaceId);
|
||||
if (!(await this.links.keptTourInList(place.collection_id, collectionTourId))) throw notLinked();
|
||||
if (!(await this.links.unlinkSaved(collectionPlaceId, collectionTourId))) throw notLinked();
|
||||
await this.collections.notifyCollectionUsers(place.collection_id, socketId);
|
||||
return this.savedPlace(userId, collectionPlaceId);
|
||||
}
|
||||
|
||||
/** The kept tours linked to the saved places of `sources`, none while Tours is off. */
|
||||
async savedRows(collectionPlaceIds: number[]) {
|
||||
return (await this.toursOn()) ? this.links.linkedKeptTours(collectionPlaceIds) : [];
|
||||
}
|
||||
|
||||
private async savedActivities(place: ActivitySavedPlaceRow, canUnlink: boolean): Promise<PlaceActivity[]> {
|
||||
const source: Extract<PlaceActivitySource, { kind: 'list' }> = {
|
||||
kind: 'list',
|
||||
collection_id: place.collection_id,
|
||||
collection_place_id: place.id,
|
||||
};
|
||||
return savedPlaceActivities(source, await this.savedRows([place.id]), canUnlink);
|
||||
}
|
||||
|
||||
/** The saved place with the user's role on its list; one on a list they cannot see is not found. */
|
||||
private async readableSavedPlace(userId: number, collectionPlaceId: number) {
|
||||
const place = await this.links.savedPlace(collectionPlaceId);
|
||||
const role = place ? await this.collections.roleOf(userId, place.collection_id) : null;
|
||||
if (!place || role === null) throw placeNotFound();
|
||||
return { place, role };
|
||||
}
|
||||
|
||||
/** The saved place on a list the user may change (404, 403), with Tours on (404). */
|
||||
private async writableSavedPlace(userId: number, collectionPlaceId: number): Promise<ActivitySavedPlaceRow> {
|
||||
const { place, role } = await this.readableSavedPlace(userId, collectionPlaceId);
|
||||
if (role === 'viewer') throw forbidden('You have read-only access to this list');
|
||||
if (!(await this.toursOn())) throw tourNotFound();
|
||||
return place;
|
||||
}
|
||||
|
||||
/** Kept tours live behind the Tours addon as well as the Collections addon. */
|
||||
private async toursOn(): Promise<boolean> {
|
||||
return this.addons.isAddonEnabled(ADDON_IDS.TOURS);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { SavedPlaceActivityLinkDto } from './place-activities.dto';
|
||||
import { PlaceActivitiesService } from './place-activities.service';
|
||||
import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Post, UseGuards } from '@nestjs/common';
|
||||
import { placeActivitiesResponseSchema, placeActivityCandidatesResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-18 at /api/addons/collections/places/:placeId/activities: the tours
|
||||
* kept in a list that one of its saved places is about. Any role on the list
|
||||
* reads them; linking and unlinking take any role but viewer, and the Tours
|
||||
* addon (without it a list keeps no tours). Behind the Collections addon.
|
||||
*/
|
||||
@Controller('api/addons/collections/places/:placeId/activities')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
|
||||
export class SavedPlaceActivitiesController {
|
||||
constructor(private readonly activities: PlaceActivitiesService) {}
|
||||
|
||||
@Get()
|
||||
@ResponseContract(placeActivitiesResponseSchema)
|
||||
async list(@CurrentUser() user: User, @Param('placeId', rowId('Place not found')) placeId: number) {
|
||||
return this.activities.savedPlace(user.id, placeId);
|
||||
}
|
||||
|
||||
@Get('candidates')
|
||||
@ResponseContract(placeActivityCandidatesResponseSchema)
|
||||
async candidates(@CurrentUser() user: User, @Param('placeId', rowId('Place not found')) placeId: number) {
|
||||
return this.activities.savedCandidates(user.id, placeId);
|
||||
}
|
||||
|
||||
@Post()
|
||||
@HttpCode(200)
|
||||
@ResponseContract(placeActivitiesResponseSchema)
|
||||
async link(
|
||||
@CurrentUser() user: User,
|
||||
@Param('placeId', rowId('Place not found')) placeId: number,
|
||||
@Body() body: SavedPlaceActivityLinkDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.activities.linkSaved(user.id, placeId, body, socketId);
|
||||
}
|
||||
|
||||
@Delete('tours/:tourId')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(placeActivitiesResponseSchema)
|
||||
async unlink(
|
||||
@CurrentUser() user: User,
|
||||
@Param('placeId', rowId('Place not found')) placeId: number,
|
||||
@Param('tourId', rowId('This activity is not linked to the place')) tourId: number,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.activities.unlinkSaved(user.id, placeId, tourId, socketId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { canRead, canReadTrips, canWrite } from '../../mcp/scopes';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_READONLY,
|
||||
TOOL_ANNOTATIONS_WRITE,
|
||||
ok,
|
||||
type McpContext,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { PlaceActivitiesLibraryService } from './place-activities-library.service';
|
||||
import { ACTIVITY_FIELDS } from './place-activities.mcp';
|
||||
import { PlaceActivitiesService } from './place-activities.service';
|
||||
import {
|
||||
idSchema,
|
||||
placeLibraryActivitiesRequestSchema,
|
||||
savedPlaceActivityLinkRequestSchema,
|
||||
type PlaceLibraryActivitiesRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** A saved place's kept tours are the list's. */
|
||||
const readsList = (ctx: McpContext) => canRead(ctx.scopes, 'collections');
|
||||
const writesList = (ctx: McpContext) => canWrite(ctx.scopes, 'collections');
|
||||
/** An entry of All places spans trips (with their bookings) and lists. */
|
||||
const readsEntry = (ctx: McpContext) =>
|
||||
canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes) && canRead(ctx.scopes, 'reservations');
|
||||
|
||||
const savedPlaceInput = { collection_place_id: idSchema };
|
||||
const savedLinkInput = { ...savedPlaceInput, ...savedPlaceActivityLinkRequestSchema.shape };
|
||||
|
||||
/**
|
||||
* PLC-18 over MCP, the list side: the same services, permissions and addon
|
||||
* rules as `/api/addons/collections/places/:placeId/activities` and the All
|
||||
* places reads. The assistant loads these with the collections; the trip
|
||||
* tools are PlaceActivitiesMcp.
|
||||
*/
|
||||
@McpController()
|
||||
export class SavedPlaceActivitiesMcp {
|
||||
constructor(
|
||||
private readonly activities: PlaceActivitiesService,
|
||||
private readonly library: PlaceActivitiesLibraryService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'list_saved_place_activities',
|
||||
description: `The tours kept in a list that one of its saved places is linked to; a place moved in from another list brings none of that list's tours along. ${ACTIVITY_FIELDS} can_link says whether you may link more (any list role but viewer, and Tours on).`,
|
||||
inputSchema: savedPlaceInput,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: readsList,
|
||||
})
|
||||
async listSavedPlaceActivities({ collection_place_id }: { collection_place_id: number }, ctx: McpContext) {
|
||||
return ok(await this.activities.savedPlace(ctx.userId, collection_place_id));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'list_saved_place_activity_candidates',
|
||||
description:
|
||||
'The tours kept in the list of a saved place not linked to it yet, which link_saved_place_tour can link. None while Tours is off.',
|
||||
inputSchema: savedPlaceInput,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: readsList,
|
||||
})
|
||||
async listSavedPlaceActivityCandidates({ collection_place_id }: { collection_place_id: number }, ctx: McpContext) {
|
||||
return ok(await this.activities.savedCandidates(ctx.userId, collection_place_id));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'link_saved_place_tour',
|
||||
description:
|
||||
'Link a tour kept in the same list to a saved place. Changes neither. Needs a list role other than viewer and the Tours addon.',
|
||||
inputSchema: savedLinkInput,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: writesList,
|
||||
})
|
||||
async linkSavedPlaceTour(
|
||||
{ collection_place_id, collection_tour_id }: { collection_place_id: number; collection_tour_id: number },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
return ok(await this.activities.linkSaved(ctx.userId, collection_place_id, { collection_tour_id }));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'unlink_saved_place_tour',
|
||||
description:
|
||||
'Take the link of a saved place to a kept tour off; the tour stays in the list. Needs a list role other than viewer and the Tours addon.',
|
||||
inputSchema: savedLinkInput,
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: writesList,
|
||||
})
|
||||
async unlinkSavedPlaceTour(
|
||||
{ collection_place_id, collection_tour_id }: { collection_place_id: number; collection_tour_id: number },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
return ok(await this.activities.unlinkSaved(ctx.userId, collection_place_id, collection_tour_id));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'get_library_place_activities',
|
||||
description: `The bookings and tours of one entry of All places, opened from a trip place (kind trip, place_id) or a saved place (kind list, collection_place_id), over the trips and lists of the entry you can open; each activity once. ${ACTIVITY_FIELDS} source names the trip place or saved place it belongs to. sources lists the origins of the entry with can_link, to link more with link_place_activity or link_saved_place_tour.`,
|
||||
inputSchema: placeLibraryActivitiesRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: readsEntry,
|
||||
})
|
||||
async getLibraryPlaceActivities(input: PlaceLibraryActivitiesRequest, ctx: McpContext) {
|
||||
const role = (await this.guards.isAdminUser(ctx.userId)) ? 'admin' : 'user';
|
||||
return ok(await this.library.entry({ id: ctx.userId, role }, input.kind, input.id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import type {
|
||||
PlaceChangeClear,
|
||||
PlaceChangeWrite,
|
||||
PlaceDetailsRow,
|
||||
SavedPlaceDetailsRow,
|
||||
TripPlaceDetailsRow,
|
||||
} from '../../db/repositories/PlaceChangeLog.repository';
|
||||
import { AUTOMATIC_CHANGE, type ChangeEditor, type ChangeTarget } from './place-changes.types';
|
||||
import type { PlaceHistoryField } from '@trek/shared';
|
||||
|
||||
/** What a place holds of each field its history follows, null where it holds none. */
|
||||
export type DetailsSnapshot = Partial<Record<PlaceHistoryField, string | null>>;
|
||||
|
||||
/** A stored value as the history keeps it: text, with an empty or blank one read as none. */
|
||||
export function historyValue(value: string | number | null | undefined): string | null {
|
||||
if (value === null || value === undefined) return null;
|
||||
const text = String(value);
|
||||
return text.trim() === '' ? null : text;
|
||||
}
|
||||
|
||||
/** The coordinates as one value, none unless both are there. */
|
||||
export function positionValue(lat: number | null, lng: number | null): string | null {
|
||||
return lat === null || lng === null ? null : `${lat},${lng}`;
|
||||
}
|
||||
|
||||
function commonSnapshot(row: PlaceDetailsRow): DetailsSnapshot {
|
||||
return {
|
||||
name: historyValue(row.name),
|
||||
address: historyValue(row.address),
|
||||
position: positionValue(row.lat, row.lng),
|
||||
category: historyValue(row.category_name),
|
||||
description: historyValue(row.description),
|
||||
notes: historyValue(row.notes),
|
||||
website: historyValue(row.website),
|
||||
phone: historyValue(row.phone),
|
||||
image: historyValue(row.image_url),
|
||||
};
|
||||
}
|
||||
|
||||
export function tripPlaceSnapshot(row: TripPlaceDetailsRow): DetailsSnapshot {
|
||||
return { ...commonSnapshot(row), opening_hours: historyValue(row.opening_hours) };
|
||||
}
|
||||
|
||||
export function savedPlaceSnapshot(row: SavedPlaceDetailsRow): DetailsSnapshot {
|
||||
return { ...commonSnapshot(row), status: historyValue(row.status) };
|
||||
}
|
||||
|
||||
export const targetKey = (target: ChangeTarget): string => `${target.kind}:${target.id}`;
|
||||
|
||||
/** What a write did to one place: the fields it set to a new value, and the ones it cleared. */
|
||||
interface DetailsDiff {
|
||||
changed: Array<{ field: PlaceHistoryField; old_value: string | null; new_value: string }>;
|
||||
cleared: PlaceHistoryField[];
|
||||
}
|
||||
|
||||
export function diffDetails(before: DetailsSnapshot, after: DetailsSnapshot): DetailsDiff {
|
||||
const diff: DetailsDiff = { changed: [], cleared: [] };
|
||||
for (const field of Object.keys(after) as PlaceHistoryField[]) {
|
||||
const old = before[field] ?? null;
|
||||
const now = after[field] ?? null;
|
||||
if (old === now) continue;
|
||||
if (now === null) diff.cleared.push(field);
|
||||
else diff.changed.push({ field, old_value: old, new_value: now });
|
||||
}
|
||||
return diff;
|
||||
}
|
||||
|
||||
/** The rows a diff writes and drops for one place, by who made it. */
|
||||
export function changeRowsOf(
|
||||
target: ChangeTarget,
|
||||
diff: DetailsDiff,
|
||||
editor: ChangeEditor,
|
||||
): { writes: PlaceChangeWrite[]; clear: PlaceChangeClear } {
|
||||
const owner = {
|
||||
place_id: target.kind === 'trip' ? target.id : null,
|
||||
collection_place_id: target.kind === 'list' ? target.id : null,
|
||||
};
|
||||
const automatic = editor === AUTOMATIC_CHANGE;
|
||||
return {
|
||||
writes: diff.changed.map((change) => ({
|
||||
...owner,
|
||||
...change,
|
||||
user_id: automatic ? null : editor,
|
||||
automatic: automatic ? 1 : 0,
|
||||
})),
|
||||
clear: { ...owner, fields: diff.cleared },
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
import { PlaceChangeLog } from '../../db/entities/PlaceChangeLog.entity';
|
||||
import { PlaceChangesService } from './place-changes.service';
|
||||
import { MikroOrmModule } from '@mikro-orm/nestjs';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* PLC-14: the history of the details of trip places and saved places. Below
|
||||
* the places, the collections and the maps, which record through it, and the
|
||||
* places library, which reads it; it imports no domain itself.
|
||||
*/
|
||||
@Module({
|
||||
imports: [MikroOrmModule.forFeature([PlaceChangeLog])],
|
||||
providers: [PlaceChangesService],
|
||||
exports: [PlaceChangesService],
|
||||
})
|
||||
export class PlaceChangesModule {}
|
||||
@@ -0,0 +1,120 @@
|
||||
import { PlaceChangeLog } from '../../db/entities/PlaceChangeLog.entity';
|
||||
import type {
|
||||
PlaceChangeClear,
|
||||
PlaceChangeLogRepository,
|
||||
PlaceChangeRow,
|
||||
PlaceChangeWrite,
|
||||
} from '../../db/repositories/PlaceChangeLog.repository';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import {
|
||||
changeRowsOf,
|
||||
diffDetails,
|
||||
savedPlaceSnapshot,
|
||||
targetKey,
|
||||
tripPlaceSnapshot,
|
||||
type DetailsSnapshot,
|
||||
} from './place-changes.helpers';
|
||||
import type { ChangeEditor, ChangeTarget } from './place-changes.types';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
// The writers name their targets and editors in the same import as the service.
|
||||
export { AUTOMATIC_CHANGE, savedPlaceTarget, tripPlaceTarget, type ChangeEditor } from './place-changes.types';
|
||||
|
||||
/** The places a write may change, or how to find them inside its transaction. */
|
||||
type ChangeTargets = ChangeTarget | readonly ChangeTarget[] | (() => Promise<readonly ChangeTarget[]>);
|
||||
|
||||
/**
|
||||
* PLC-14: the history of the details of trip places and saved places, kept by
|
||||
* every path that writes them (REST, MCP, the plugin RPC, the assistant, the
|
||||
* imports and TREK's own fills) through {@link track}, in the same transaction
|
||||
* as the write: the details before, the write, the details after, and a row
|
||||
* for every field that went from one value to another. A field the write
|
||||
* cleared drops the rows it had instead, so a value deleted on purpose does
|
||||
* not live on here; a field the write left alone, or set to what it held,
|
||||
* records nothing. Who may read which history is the reader's question
|
||||
* (`PlaceHistoryService` in places-library), never this service's.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceChangesService {
|
||||
constructor(
|
||||
@InjectRepository(PlaceChangeLog) private readonly log: PlaceChangeLogRepository,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
/** Runs `write` and records what it changed in the details of `targets`; a write that throws records nothing. */
|
||||
async track<T>(targets: ChangeTargets, editor: ChangeEditor, write: () => Promise<T>): Promise<T> {
|
||||
return this.uow.transactional(async () => {
|
||||
const list = await targetsOf(targets);
|
||||
if (list.length === 0) return write();
|
||||
const before = await this.snapshots(list);
|
||||
const result = await write();
|
||||
await this.record(list, before, await this.snapshots(list), editor);
|
||||
return result;
|
||||
});
|
||||
}
|
||||
|
||||
/** The changes of these places, newest first, before the change `beforeId` when given. */
|
||||
async page(
|
||||
tripPlaceIds: readonly number[],
|
||||
savedPlaceIds: readonly number[],
|
||||
beforeId: number | null,
|
||||
limit: number,
|
||||
): Promise<PlaceChangeRow[]> {
|
||||
return this.log.page(tripPlaceIds, savedPlaceIds, beforeId, limit);
|
||||
}
|
||||
|
||||
/** The trip places with this Google id and no picture: the ones the photo cache's fill reaches. */
|
||||
async tripPlacesWithoutImage(googlePlaceId: string): Promise<number[]> {
|
||||
return this.log.tripPlaceIdsWithoutImage(googlePlaceId);
|
||||
}
|
||||
|
||||
private async snapshots(targets: readonly ChangeTarget[]): Promise<Map<string, DetailsSnapshot>> {
|
||||
const ids = (kind: ChangeTarget['kind']) => targets.filter((target) => target.kind === kind).map((t) => t.id);
|
||||
const tripIds = ids('trip');
|
||||
const savedIds = ids('list');
|
||||
const tripRows = tripIds.length > 0 ? await this.log.tripPlaceDetails(tripIds) : [];
|
||||
const savedRows = savedIds.length > 0 ? await this.log.savedPlaceDetails(savedIds) : [];
|
||||
return new Map<string, DetailsSnapshot>([
|
||||
...tripRows.map((row) => [targetKey({ kind: 'trip', id: row.id }), tripPlaceSnapshot(row)] as const),
|
||||
...savedRows.map((row) => [targetKey({ kind: 'list', id: row.id }), savedPlaceSnapshot(row)] as const),
|
||||
]);
|
||||
}
|
||||
|
||||
/** Runs inside {@link track}'s transaction: the cleared fields' rows go, the new values come in. */
|
||||
private async record(
|
||||
targets: readonly ChangeTarget[],
|
||||
before: Map<string, DetailsSnapshot>,
|
||||
after: Map<string, DetailsSnapshot>,
|
||||
editor: ChangeEditor,
|
||||
): Promise<void> {
|
||||
const writes: PlaceChangeWrite[] = [];
|
||||
const clears: PlaceChangeClear[] = [];
|
||||
for (const target of uniqueTargets(targets)) {
|
||||
const was = before.get(targetKey(target));
|
||||
const now = after.get(targetKey(target));
|
||||
// A place the write deleted (or one that never was) keeps no history.
|
||||
if (!was || !now) continue;
|
||||
const rows = changeRowsOf(target, diffDetails(was, now), editor);
|
||||
writes.push(...rows.writes);
|
||||
clears.push(rows.clear);
|
||||
}
|
||||
await this.log.deleteCleared(clears);
|
||||
await this.log.insertChanges(writes);
|
||||
}
|
||||
}
|
||||
|
||||
function targetsOf(targets: ChangeTargets): Promise<readonly ChangeTarget[]> {
|
||||
if (typeof targets === 'function') return targets();
|
||||
return Promise.resolve(isTargetList(targets) ? targets : [targets]);
|
||||
}
|
||||
|
||||
function isTargetList(targets: ChangeTarget | readonly ChangeTarget[]): targets is readonly ChangeTarget[] {
|
||||
return Array.isArray(targets);
|
||||
}
|
||||
|
||||
function uniqueTargets(targets: readonly ChangeTarget[]): ChangeTarget[] {
|
||||
const seen = new Map<string, ChangeTarget>();
|
||||
for (const target of targets) seen.set(targetKey(target), target);
|
||||
return [...seen.values()];
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/** A place whose details a write may change: a trip place or a saved place. */
|
||||
export interface ChangeTarget {
|
||||
kind: 'trip' | 'list';
|
||||
id: number;
|
||||
}
|
||||
|
||||
export const tripPlaceTarget = (id: number): ChangeTarget => ({ kind: 'trip', id });
|
||||
export const savedPlaceTarget = (id: number): ChangeTarget => ({ kind: 'list', id });
|
||||
|
||||
/** A value TREK filled in itself, which nobody typed. */
|
||||
export const AUTOMATIC_CHANGE = 'automatic' as const;
|
||||
|
||||
/** Who made a change: a user's id, TREK itself, or nobody known. */
|
||||
export type ChangeEditor = number | typeof AUTOMATIC_CHANGE | null;
|
||||
@@ -0,0 +1,45 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { PlaceHistoryQueryDto } from './place-history.dto';
|
||||
import { PlaceHistoryService } from './place-history.service';
|
||||
import { Controller, Get, Param, Query, UseGuards } from '@nestjs/common';
|
||||
import { placeHistoryPageResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-14 beside the place detail of All places: what changed in the details
|
||||
* of the entry, when and by whom, over the trips and lists the user reaches.
|
||||
* Read only; the history is kept by the writes themselves. Behind the
|
||||
* Collections addon like the rest of the library.
|
||||
*/
|
||||
@Controller('api/addons/collections/library/places')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
|
||||
export class PlaceHistoryController {
|
||||
constructor(private readonly history: PlaceHistoryService) {}
|
||||
|
||||
@Get('trip/:id/history')
|
||||
@ResponseContract(placeHistoryPageResponseSchema)
|
||||
async tripPlace(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id', rowId('Place not found')) id: number,
|
||||
@Query() query: PlaceHistoryQueryDto,
|
||||
) {
|
||||
return this.history.history({ id: user.id, role: user.role }, 'trip', id, query);
|
||||
}
|
||||
|
||||
@Get('list/:id/history')
|
||||
@ResponseContract(placeHistoryPageResponseSchema)
|
||||
async savedPlace(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id', rowId('Place not found')) id: number,
|
||||
@Query() query: PlaceHistoryQueryDto,
|
||||
) {
|
||||
return this.history.history({ id: user.id, role: user.role }, 'list', id, query);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
import { placeHistoryQuerySchema } from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
|
||||
export class PlaceHistoryQueryDto extends createZodDto(placeHistoryQuerySchema) {}
|
||||
@@ -0,0 +1,48 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { canRead, canReadTrips } from '../../mcp/scopes';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { PlaceHistoryService } from './place-history.service';
|
||||
import {
|
||||
PLACE_HISTORY_PAGE_DEFAULT,
|
||||
PLACE_HISTORY_PAGE_MAX,
|
||||
placeHistoryRequestSchema,
|
||||
type PlaceHistoryRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** The history spans the entry's trips and lists, so a token needs to read both. */
|
||||
const readsTripsAndLists = (ctx: McpContext) => canRead(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
|
||||
|
||||
/**
|
||||
* PLC-14 over MCP: the same service and the same reach as
|
||||
* `GET /api/addons/collections/library/places/{trip|list}/:id/history`.
|
||||
*/
|
||||
@McpController()
|
||||
export class PlaceHistoryMcp {
|
||||
constructor(
|
||||
private readonly history: PlaceHistoryService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of the tool.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'get_library_place_history',
|
||||
description: `What changed in the details of one entry of All places, opened from a trip place (kind trip, place_id) or a saved place (kind list, collection_place_id): newest first, ${PLACE_HISTORY_PAGE_DEFAULT} at a time unless limit says otherwise (at most ${PLACE_HISTORY_PAGE_MAX}), over the trips and lists of the entry you can open. Each change has its origin (trip with trip_title, or list with collection_name), field (name, address, position as "lat,lng", category by name, description, notes, website, phone, image, opening_hours, status), old_value and new_value, editor (id, username; null when the account is gone or TREK filled the value in itself, then automatic is true) and changed_at (UTC). A value that was cleared leaves no change behind, and its earlier changes are gone too. next_cursor, passed back as cursor, goes on; null on the last page. Changes nothing.`,
|
||||
inputSchema: placeHistoryRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: readsTripsAndLists,
|
||||
})
|
||||
async getLibraryPlaceHistory(input: PlaceHistoryRequest, ctx: McpContext) {
|
||||
const role = (await this.guards.isAdminUser(ctx.userId)) ? 'admin' : 'user';
|
||||
return ok(
|
||||
await this.history.history({ id: ctx.userId, role }, input.kind, input.id, {
|
||||
cursor: input.cursor,
|
||||
limit: input.limit,
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PlaceChangesModule } from '../place-changes/place-changes.module';
|
||||
import { PlaceHistoryController } from './place-history.controller';
|
||||
import { PlaceHistoryMcp } from './place-history.mcp';
|
||||
import { PlaceHistoryService } from './place-history.service';
|
||||
import { PlacesLibraryModule } from './places-library.module';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* PLC-14: the history of the details of an entry of All places, read over
|
||||
* the origins the user reaches. Part of the places-library domain, beside
|
||||
* PlacesLibraryModule, which resolves every entry; the history itself is
|
||||
* kept by PlaceChangesModule, which every write of a place's details goes
|
||||
* through. Read only.
|
||||
*/
|
||||
@Module({
|
||||
imports: [PlacesLibraryModule, PlaceChangesModule, AddonsModule, McpSharedModule],
|
||||
controllers: [PlaceHistoryController],
|
||||
providers: [PlaceHistoryService, PlaceHistoryMcp],
|
||||
})
|
||||
export class PlaceHistoryModule {}
|
||||
@@ -0,0 +1,105 @@
|
||||
import type { PlaceChangeRow } from '../../db/repositories/PlaceChangeLog.repository';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
import { PlaceChangesService } from '../place-changes/place-changes.service';
|
||||
import { PlacesLibraryService, placeNotFound, type LibraryUser } from './places-library.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
PLACE_HISTORY_FIELDS,
|
||||
PLACE_HISTORY_PAGE_DEFAULT,
|
||||
type PlaceHistoryEntry,
|
||||
type PlaceHistoryField,
|
||||
type PlaceHistoryOrigin,
|
||||
type PlaceHistoryPageResponse,
|
||||
type PlaceHistoryQuery,
|
||||
type PlacesLibraryKind,
|
||||
} from '@trek/shared';
|
||||
|
||||
const isHistoryField = (field: string): field is PlaceHistoryField =>
|
||||
(PLACE_HISTORY_FIELDS as readonly string[]).includes(field);
|
||||
|
||||
/**
|
||||
* PLC-14: the history of an entry of All places, newest first, over the
|
||||
* origins of the entry the user reaches right now, read with the library's
|
||||
* own reach for every call: a trip place of a trip they own or are a member
|
||||
* of, a saved place of a list open to them. A change of any other origin is
|
||||
* left out without a trace (no count, no placeholder, no gap in the cursor),
|
||||
* so losing access to a trip or a list takes its changes out of the history
|
||||
* at once, as it takes the origin out of the entry. An entry the user does
|
||||
* not reach at all is not found.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceHistoryService {
|
||||
constructor(
|
||||
private readonly library: PlacesLibraryService,
|
||||
private readonly changes: PlaceChangesService,
|
||||
) {}
|
||||
|
||||
async history(
|
||||
user: LibraryUser,
|
||||
kind: PlacesLibraryKind,
|
||||
id: number,
|
||||
query: PlaceHistoryQuery,
|
||||
): Promise<PlaceHistoryPageResponse> {
|
||||
const reach = await this.library.reach(user.id);
|
||||
const anchor = await this.library.anchorOfUse(reach, kind, id);
|
||||
if (anchor === null) throw placeNotFound();
|
||||
const [rows] = await this.library.rows(reach, [anchor]);
|
||||
if (!rows) throw placeNotFound();
|
||||
|
||||
const trips = new Map(
|
||||
rows.trips.map((row): [number, PlaceHistoryOrigin] => [
|
||||
row.id,
|
||||
{ kind: 'trip', trip_id: row.trip_id, trip_title: row.trip_title, place_id: row.id },
|
||||
]),
|
||||
);
|
||||
const saved = new Map(
|
||||
rows.saved.map((row): [number, PlaceHistoryOrigin] => [
|
||||
row.id,
|
||||
{
|
||||
kind: 'list',
|
||||
collection_id: row.collection_id,
|
||||
collection_name: row.collection_name,
|
||||
collection_place_id: row.id,
|
||||
},
|
||||
]),
|
||||
);
|
||||
const limit = query.limit ?? PLACE_HISTORY_PAGE_DEFAULT;
|
||||
const beforeId = query.cursor === undefined ? null : Number(query.cursor);
|
||||
// One change more than the page holds says whether another page follows.
|
||||
const found = await this.changes.page([...trips.keys()], [...saved.keys()], beforeId, limit + 1);
|
||||
const page = found.slice(0, limit);
|
||||
const last = page[page.length - 1];
|
||||
return {
|
||||
entries: page.flatMap((row) => {
|
||||
const origin = originOf(row, trips, saved);
|
||||
return origin && isHistoryField(row.field) ? [entryOf(row, row.field, origin)] : [];
|
||||
}),
|
||||
next_cursor: found.length > limit && last ? String(last.id) : null,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function originOf(
|
||||
row: PlaceChangeRow,
|
||||
trips: Map<number, PlaceHistoryOrigin>,
|
||||
saved: Map<number, PlaceHistoryOrigin>,
|
||||
): PlaceHistoryOrigin | undefined {
|
||||
if (row.place_id !== null) return trips.get(row.place_id);
|
||||
return row.collection_place_id === null ? undefined : saved.get(row.collection_place_id);
|
||||
}
|
||||
|
||||
function entryOf(row: PlaceChangeRow, field: PlaceHistoryField, origin: PlaceHistoryOrigin): PlaceHistoryEntry {
|
||||
return {
|
||||
id: row.id,
|
||||
origin,
|
||||
field,
|
||||
old_value: row.old_value,
|
||||
new_value: row.new_value,
|
||||
editor:
|
||||
row.user_id === null || row.username === null
|
||||
? null
|
||||
: { id: row.user_id, username: row.username, avatar_url: avatarUrl({ avatar: row.avatar }) },
|
||||
automatic: row.automatic === 1,
|
||||
changed_at: row.created_at,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { rowId } from '../common/row-id.pipe';
|
||||
import { PlaceMediaService } from './place-media.service';
|
||||
import { Controller, Get, Param, UseGuards } from '@nestjs/common';
|
||||
import { placeMediaResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-19/PLC-20 beside the place detail of All places: its pictures, the
|
||||
* journey photos and the trip files that hang on it, each with where it comes
|
||||
* from. Behind the Collections addon like the rest of the library.
|
||||
*/
|
||||
@Controller('api/addons/collections/library/places')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
|
||||
export class PlaceMediaController {
|
||||
constructor(private readonly media: PlaceMediaService) {}
|
||||
|
||||
@Get('trip/:id/media')
|
||||
@ResponseContract(placeMediaResponseSchema)
|
||||
async tripPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) {
|
||||
return this.media.media({ id: user.id, role: user.role }, 'trip', id);
|
||||
}
|
||||
|
||||
@Get('list/:id/media')
|
||||
@ResponseContract(placeMediaResponseSchema)
|
||||
async savedPlace(@CurrentUser() user: User, @Param('id', rowId('Place not found')) id: number) {
|
||||
return this.media.media({ id: user.id, role: user.role }, 'list', id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { PlaceVisitContextRepository } from '../../db/repositories/PlaceVisitContext.repository';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { JourneyDomainService } from '../journey/journey-domain.service';
|
||||
import { uniqueIds } from './place-visits.helpers';
|
||||
import { PlacesLibraryService, placeNotFound, type LibraryUser } from './places-library.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type {
|
||||
PlaceMediaFile,
|
||||
PlaceMediaImage,
|
||||
PlaceMediaJourneyPhoto,
|
||||
PlaceMediaResponse,
|
||||
PlacesLibraryKind,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-19/PLC-20: what an entry of All places shows of its photos and files,
|
||||
* each with where it comes from, read with the rights of where it lives.
|
||||
*
|
||||
* - The general pictures are the ones its trip places and saved places carry
|
||||
* (`image_url`), with the trip or list each comes from.
|
||||
* - The journey photos are those of journey entries made from one of its
|
||||
* trip places, in journeys the user can open (the journey domain's own
|
||||
* check, asked per journey), while the Journey addon is on; an entry the
|
||||
* journey set aside (dismissed) or has not filled yet (skeleton) gives none.
|
||||
* - The files are the trip files not in the trash attached to one of its
|
||||
* trip places, by a link or as the file's own place, with the trip they
|
||||
* open in. A file is there exactly as the trip's file manager has it for a
|
||||
* member: trip access (only trips the user opens contribute places) and
|
||||
* the Documents addon on for the instance; a file attached to a place
|
||||
* stays reachable while one trip turns Documents off, as in the trip.
|
||||
*
|
||||
* A list gives no photo and no file of its own beyond its pictures: being on
|
||||
* a list never opens a journey or a trip.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceMediaService {
|
||||
constructor(
|
||||
private readonly library: PlacesLibraryService,
|
||||
private readonly context: PlaceVisitContextRepository,
|
||||
private readonly journeys: JourneyDomainService,
|
||||
private readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
async media(user: LibraryUser, kind: PlacesLibraryKind, id: number): Promise<PlaceMediaResponse> {
|
||||
const reach = await this.library.reach(user.id);
|
||||
const anchor = await this.library.anchorOfUse(reach, kind, id);
|
||||
if (anchor === null) throw placeNotFound();
|
||||
const [rows] = await this.library.rows(reach, [anchor]);
|
||||
if (!rows) throw placeNotFound();
|
||||
|
||||
const images: PlaceMediaImage[] = [
|
||||
...rows.trips.flatMap((row): PlaceMediaImage[] =>
|
||||
row.image_url
|
||||
? [
|
||||
{
|
||||
kind: 'trip',
|
||||
image_url: row.image_url,
|
||||
trip_id: row.trip_id,
|
||||
trip_title: row.trip_title,
|
||||
place_id: row.id,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
...rows.saved.flatMap((row): PlaceMediaImage[] =>
|
||||
row.image_url
|
||||
? [
|
||||
{
|
||||
kind: 'list',
|
||||
image_url: row.image_url,
|
||||
collection_id: row.collection_id,
|
||||
collection_name: row.collection_name,
|
||||
collection_place_id: row.id,
|
||||
},
|
||||
]
|
||||
: [],
|
||||
),
|
||||
];
|
||||
|
||||
const placeIds = rows.trips.map((row) => row.id);
|
||||
const tripTitles = new Map(rows.trips.map((row) => [row.trip_id, row.trip_title]));
|
||||
|
||||
const journeysOn = placeIds.length > 0 && (await this.addons.isAddonEnabled(ADDON_IDS.JOURNEY));
|
||||
const photos = journeysOn ? await this.context.journeyPhotosOfPlaces(placeIds) : [];
|
||||
const open = await this.openJourneyIds(
|
||||
user.id,
|
||||
photos.map((photo) => photo.journey_id),
|
||||
);
|
||||
const journeyPhotos = photos.flatMap((photo): PlaceMediaJourneyPhoto[] => {
|
||||
if (!open.has(photo.journey_id)) return [];
|
||||
return [
|
||||
{
|
||||
journey_id: photo.journey_id,
|
||||
journey_title: photo.journey_title,
|
||||
entry_id: photo.entry_id,
|
||||
entry_date: photo.entry_date,
|
||||
journey_photo_id: photo.journey_photo_id,
|
||||
photo_id: photo.photo_id,
|
||||
provider: photo.provider,
|
||||
asset_id: photo.asset_id,
|
||||
owner_id: photo.owner_id,
|
||||
file_path: photo.file_path,
|
||||
thumbnail_path: photo.thumbnail_path,
|
||||
width: photo.width,
|
||||
height: photo.height,
|
||||
media_type: photo.media_type,
|
||||
caption: photo.caption,
|
||||
taken_at: photo.taken_at,
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
const documentsOn = placeIds.length > 0 && (await this.addons.isAddonEnabled(ADDON_IDS.DOCUMENTS));
|
||||
const fileRows = documentsOn ? await this.context.filesOfPlaces(placeIds) : [];
|
||||
const files = fileRows.flatMap((file): PlaceMediaFile[] => {
|
||||
const tripTitle = tripTitles.get(file.trip_id);
|
||||
if (tripTitle === undefined) return [];
|
||||
return [
|
||||
{
|
||||
file_id: file.file_id,
|
||||
trip_id: file.trip_id,
|
||||
trip_title: tripTitle,
|
||||
place_id: file.place_id,
|
||||
original_name: file.original_name,
|
||||
mime_type: file.mime_type,
|
||||
file_size: file.file_size,
|
||||
created_at: file.created_at,
|
||||
url: `/api/trips/${file.trip_id}/files/${file.file_id}/download`,
|
||||
},
|
||||
];
|
||||
});
|
||||
|
||||
return { images, journey_photos: journeyPhotos, files };
|
||||
}
|
||||
|
||||
/** Which of the journeys the user can open, asked of the journey domain for each. */
|
||||
private async openJourneyIds(userId: number, journeyIds: readonly number[]): Promise<Set<number>> {
|
||||
const ids = uniqueIds(journeyIds);
|
||||
const answers = await Promise.all(
|
||||
ids.map(async (id) => (await this.journeys.canAccessJourney(id, userId)) !== null),
|
||||
);
|
||||
return new Set(ids.filter((_, index) => answers[index]));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { User } from '../../types';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { PlaceTagsService } from './place-tags.service';
|
||||
import { PlacesLibraryBulkTagsDto, PlacesLibraryEntryTagsDto } from './places-library.dto';
|
||||
import { Body, Controller, HttpCode, Post, Put, UseGuards } from '@nestjs/common';
|
||||
import { placesLibraryBulkTagsResponseSchema, placesLibraryEntryTagsResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-21 under /api/addons/collections/library/places/tags: the user's
|
||||
* personal tags on the entries of "All places", for one entry or for several.
|
||||
* The tags themselves are created, renamed and deleted under /api/tags. Only
|
||||
* the user's own rows change, so nothing is broadcast. Behind the Collections
|
||||
* addon like the rest of the library.
|
||||
*/
|
||||
@Controller('api/addons/collections/library/places/tags')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.COLLECTIONS, 'Collections')
|
||||
export class PlaceTagsController {
|
||||
constructor(private readonly tags: PlaceTagsService) {}
|
||||
|
||||
@Put()
|
||||
@ResponseContract(placesLibraryEntryTagsResponseSchema)
|
||||
async setForEntry(@CurrentUser() user: User, @Body() body: PlacesLibraryEntryTagsDto) {
|
||||
return this.tags.setForEntry({ id: user.id, role: user.role }, body);
|
||||
}
|
||||
|
||||
@Post('bulk')
|
||||
@HttpCode(200)
|
||||
@ResponseContract(placesLibraryBulkTagsResponseSchema)
|
||||
async bulk(@CurrentUser() user: User, @Body() body: PlacesLibraryBulkTagsDto) {
|
||||
return this.tags.bulk({ id: user.id, role: user.role }, body);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import type { PersonalTagAssignment } from '../../db/repositories/PersonalPlaceTags.repository';
|
||||
import type { LibraryEntryTagRow } from '../../db/repositories/PlacesLibrary.repository';
|
||||
import { ANCHOR_LIST, ANCHOR_OWN, ANCHOR_SPAN, ANCHOR_TRIP } from '../../db/repositories/PlacesLibrary.repository';
|
||||
import type { EntryRows } from './places-library.helpers';
|
||||
import type { PlacesLibraryTag } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-21, the pure half of the personal tags on "All places": where an entry's
|
||||
* tags are read from, where a new one is put, and which rows belong to which
|
||||
* entry.
|
||||
*/
|
||||
|
||||
interface TagTargets {
|
||||
identityIds: number[];
|
||||
placeIds: number[];
|
||||
collectionPlaceIds: number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything the entries' tags can sit on: their own places, trip places and
|
||||
* saved places. Read for showing them and for taking one off, so a tag comes
|
||||
* off every copy of it on the entry.
|
||||
*/
|
||||
export function tagTargetsOf(rows: readonly EntryRows[]): TagTargets {
|
||||
return {
|
||||
identityIds: rows.flatMap((row) => (row.identity ? [row.identity.id] : [])),
|
||||
placeIds: rows.flatMap((row) => row.trips.map((trip) => trip.id)),
|
||||
collectionPlaceIds: rows.flatMap((row) => row.saved.map((saved) => saved.id)),
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether a tag row sits on the entry: on its own place (or one merged into it), or on one of its uses. */
|
||||
function belongsTo(row: LibraryEntryTagRow, entry: EntryRows): boolean {
|
||||
const identityId = entry.identity?.id;
|
||||
if (identityId !== undefined && row.user_place_id !== null) {
|
||||
return row.user_place_id === identityId || row.merged_into_id === identityId;
|
||||
}
|
||||
if (row.place_id !== null) return entry.trips.some((trip) => trip.id === row.place_id);
|
||||
if (row.collection_place_id !== null) return entry.saved.some((saved) => saved.id === row.collection_place_id);
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Each entry's tags, once each, in the name order the rows come in. */
|
||||
export function tagsByEntry(entries: readonly EntryRows[], rows: readonly LibraryEntryTagRow[]): PlacesLibraryTag[][] {
|
||||
return entries.map((entry) => {
|
||||
const seen = new Set<number>();
|
||||
return rows.flatMap((row) => {
|
||||
if (seen.has(row.id) || !belongsTo(row, entry)) return [];
|
||||
seen.add(row.id);
|
||||
return [{ id: row.id, name: row.name, color: row.color }];
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** The target a tag of the entry `anchor` is put on: its own place, else the trip place or saved place it is. */
|
||||
export function assignmentOf(anchor: number, tagId: number): PersonalTagAssignment {
|
||||
const id = Math.floor(anchor / ANCHOR_SPAN);
|
||||
const kind = anchor % ANCHOR_SPAN;
|
||||
return {
|
||||
tag_id: tagId,
|
||||
user_place_id: kind === ANCHOR_OWN ? id : null,
|
||||
place_id: kind === ANCHOR_TRIP ? id : null,
|
||||
collection_place_id: kind === ANCHOR_LIST ? id : null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The ids once each, in their first order. */
|
||||
export function uniqueIds(ids: readonly number[]): number[] {
|
||||
return [...new Set(ids)];
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { canReadTrips, canWrite } from '../../mcp/scopes';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_WRITE, ok, type McpContext } from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { PlaceTagsService } from './place-tags.service';
|
||||
import type { LibraryUser } from './places-library.service';
|
||||
import {
|
||||
PLACES_LIBRARY_TAG_KEYS_MAX,
|
||||
PLACES_LIBRARY_TAGS_MAX,
|
||||
placesLibraryBulkTagsRequestSchema,
|
||||
placesLibraryEntryTagsRequestSchema,
|
||||
type PlacesLibraryBulkTagsRequest,
|
||||
type PlacesLibraryEntryTagsRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Tagging writes only the user's own rows, under the lists' write scope, over trips and lists alike. */
|
||||
const writesOwnTags = (ctx: McpContext) => canWrite(ctx.scopes, 'collections') && canReadTrips(ctx.scopes);
|
||||
|
||||
const PRIVATE =
|
||||
'The tags are your personal tags (list_tags, create_tag) and stay private: no trip place and no saved place changes, and no one else sees them. To share some with a trip, copy the place with copy_collection_places_to_trip and personal_tag_ids.';
|
||||
|
||||
/**
|
||||
* PLC-21 over the same service and checks as the REST routes under
|
||||
* /api/addons/collections/library/places/tags: the user's personal tags on
|
||||
* the entries of All places.
|
||||
*/
|
||||
@McpController()
|
||||
export class PlaceTagsMcp {
|
||||
constructor(
|
||||
private readonly tags: PlaceTagsService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of every tool here.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
private async user(userId: number): Promise<LibraryUser> {
|
||||
return { id: userId, role: (await this.guards.isAdminUser(userId)) ? 'admin' : 'user' };
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'set_library_place_tags',
|
||||
description: `Set which of your personal tags an entry of All places carries, by its key from list_all_places (own:<id>, trip:<place id> or list:<saved place id>): exactly tag_ids from now on (at most ${PLACES_LIBRARY_TAGS_MAX}), an empty list takes every tag off. Answers the entry with its tags. ${PRIVATE}`,
|
||||
inputSchema: placesLibraryEntryTagsRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: writesOwnTags,
|
||||
})
|
||||
async setLibraryPlaceTags(input: PlacesLibraryEntryTagsRequest, ctx: McpContext) {
|
||||
return ok(await this.tags.setForEntry(await this.user(ctx.userId), input));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'tag_library_places',
|
||||
description: `Put personal tags on several entries of All places at once (add) and take others off them (remove), by their keys from list_all_places (at most ${PLACES_LIBRARY_TAG_KEYS_MAX} keys); a tag already on an entry stays. Every key must name an entry you reach and every id one of your personal tags, else nothing changes. Answers the entries with their tags. ${PRIVATE}`,
|
||||
inputSchema: placesLibraryBulkTagsRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: writesOwnTags,
|
||||
})
|
||||
async tagLibraryPlaces(input: PlacesLibraryBulkTagsRequest, ctx: McpContext) {
|
||||
return ok(await this.tags.bulk(await this.user(ctx.userId), input));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
import { PersonalPlaceTags } from '../../db/entities/PersonalPlaceTags.entity';
|
||||
import type { PersonalPlaceTagsRepository } from '../../db/repositories/PersonalPlaceTags.repository';
|
||||
import { badRequest, notFound } from '../common/domain-error';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { assignmentOf, tagTargetsOf, uniqueIds } from './place-tags.helpers';
|
||||
import { anchorOfKey, type EntryRows } from './places-library.helpers';
|
||||
import { PlacesLibraryService, placeNotFound, type LibraryReach, type LibraryUser } from './places-library.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type {
|
||||
PlacesLibraryBulkTagsRequest,
|
||||
PlacesLibraryBulkTagsResponse,
|
||||
PlacesLibraryEntryTagsRequest,
|
||||
PlacesLibraryEntryTagsResponse,
|
||||
} from '@trek/shared';
|
||||
|
||||
const tagNotFound = () => notFound('Tag not found');
|
||||
|
||||
/**
|
||||
* PLC-21: the user's personal tags on the entries of "All places", one method
|
||||
* per use case for REST and MCP alike. The tags are the user's personal ones
|
||||
* (`tags` with no trip, managed under /api/tags); a tag of a trip or of
|
||||
* another person names no tag here and is not found.
|
||||
*
|
||||
* Every write changes only the user's own rows: no trip place and no saved
|
||||
* place is written, nobody else sees the tags, so nothing is broadcast. An
|
||||
* entry must be one the user reaches today (the library's checks), else it is
|
||||
* not found; the tags and the entries are read in the transaction that
|
||||
* writes, so a tag or a place deleted in between is not found either.
|
||||
*
|
||||
* A new tag goes on the entry itself: its own place, else the trip place or
|
||||
* saved place it stands for. Taking one off takes it off everything the entry
|
||||
* reads tags from (its own place, the ones merged into that, its uses), so it
|
||||
* is gone from the entry wherever it sat.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceTagsService {
|
||||
constructor(
|
||||
private readonly library: PlacesLibraryService,
|
||||
@InjectRepository(PersonalPlaceTags) private readonly assignments: PersonalPlaceTagsRepository,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
/** The entry `key` carries exactly `tag_ids` from now on. */
|
||||
async setForEntry(
|
||||
user: LibraryUser,
|
||||
request: PlacesLibraryEntryTagsRequest,
|
||||
): Promise<PlacesLibraryEntryTagsResponse> {
|
||||
const anchor = anchorOfKey(request.key);
|
||||
if (anchor === null) throw placeNotFound();
|
||||
const tagIds = uniqueIds(request.tag_ids);
|
||||
const reach = await this.library.reach(user.id);
|
||||
await this.uow.transactional(async () => {
|
||||
await this.requireOwnTags(user.id, tagIds);
|
||||
const rows = await this.requireEntries(reach, [anchor]);
|
||||
await this.assignments.remove(user.id, tagTargetsOf(rows), null);
|
||||
await this.assignments.add(tagIds.map((tagId) => assignmentOf(anchor, tagId)));
|
||||
});
|
||||
return { entry: await this.library.entry(user, anchor) };
|
||||
}
|
||||
|
||||
/** Puts `add` on every entry of `keys` and takes `remove` off them, in one transaction. */
|
||||
async bulk(user: LibraryUser, request: PlacesLibraryBulkTagsRequest): Promise<PlacesLibraryBulkTagsResponse> {
|
||||
const anchors = uniqueIds(
|
||||
request.keys.map((key) => {
|
||||
const anchor = anchorOfKey(key);
|
||||
if (anchor === null) throw placeNotFound();
|
||||
return anchor;
|
||||
}),
|
||||
);
|
||||
const add = uniqueIds(request.add ?? []);
|
||||
const remove = uniqueIds(request.remove ?? []);
|
||||
// The contract refuses both, but an MCP call is checked field by field.
|
||||
if (add.length + remove.length === 0) throw badRequest('Name tags to add or to remove');
|
||||
if (add.some((id) => remove.includes(id))) throw badRequest('A tag cannot be added and removed at once');
|
||||
const reach = await this.library.reach(user.id);
|
||||
await this.uow.transactional(async () => {
|
||||
await this.requireOwnTags(user.id, [...add, ...remove]);
|
||||
const rows = await this.requireEntries(reach, anchors);
|
||||
await this.assignments.remove(user.id, tagTargetsOf(rows), remove);
|
||||
await this.assignments.add(anchors.flatMap((anchor) => add.map((tagId) => assignmentOf(anchor, tagId))));
|
||||
});
|
||||
return { entries: await this.library.entries(user, reach, anchors) };
|
||||
}
|
||||
|
||||
/** Refuses unless every id names a personal tag of the user. */
|
||||
private async requireOwnTags(userId: number, tagIds: readonly number[]): Promise<void> {
|
||||
const wanted = uniqueIds(tagIds);
|
||||
const own = await this.assignments.ownTags(userId, wanted);
|
||||
if (own.length !== wanted.length) throw tagNotFound();
|
||||
}
|
||||
|
||||
/** The rows of every entry, refusing when one of them is out of the user's reach. */
|
||||
private async requireEntries(reach: LibraryReach, anchors: number[]): Promise<EntryRows[]> {
|
||||
const rows = await this.library.rows(reach, anchors);
|
||||
if (rows.length !== anchors.length) throw placeNotFound();
|
||||
return rows;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { PlaceVisitContextRepository, type PlannedVisitRow } from '../../db/repositories/PlaceVisitContext.repository';
|
||||
import { PlaceVisitsClock } from './place-visits.clock';
|
||||
import {
|
||||
collapseVisits,
|
||||
participantsOf,
|
||||
summaryOf,
|
||||
uniqueIds,
|
||||
visitsOfEntry,
|
||||
wireVisit,
|
||||
type DerivedVisit,
|
||||
type VisitSummary,
|
||||
} from './place-visits.helpers';
|
||||
import { groupBy, readInChunks, type EntryRows } from './places-library.helpers';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { PlaceVisit } from '@trek/shared';
|
||||
|
||||
/** The trips a reader reaches, as the library resolved them. */
|
||||
interface VisitReach {
|
||||
userId: number;
|
||||
tripIds: readonly number[];
|
||||
}
|
||||
|
||||
/**
|
||||
* D7: visits are never entered, they are read from the trips. A place counts
|
||||
* as visited by a reader on a day when a trip the reader owns or is a member
|
||||
* of has it planned on a day with a date up to today (UTC), and the stop
|
||||
* names no one or names the reader among who takes part. A day without a
|
||||
* date counts nothing, a coming day neither. Each place counts once per
|
||||
* calendar day, however many stops have it that day. Losing access to a
|
||||
* trip takes its visits with it, since only reached trips are read.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceVisitsReaderService {
|
||||
constructor(
|
||||
private readonly context: PlaceVisitContextRepository,
|
||||
private readonly clock: PlaceVisitsClock,
|
||||
) {}
|
||||
|
||||
/** The planned rows that count for the reader at the trip places `placeIds`, of reached trips only. */
|
||||
async plannedAt(reach: VisitReach, placeIds: readonly number[]): Promise<PlannedVisitRow[]> {
|
||||
const today = this.clock.today();
|
||||
const trips = new Set(reach.tripIds);
|
||||
const rows = await readInChunks(uniqueIds(placeIds), (chunk) =>
|
||||
this.context.plannedAtPlaces(reach.userId, today, chunk),
|
||||
);
|
||||
return rows.filter((row) => trips.has(row.trip_id));
|
||||
}
|
||||
|
||||
/** The planned rows that count for the reader on the trips `tripIds`. */
|
||||
async plannedOn(reach: VisitReach, tripIds: readonly number[]): Promise<PlannedVisitRow[]> {
|
||||
const today = this.clock.today();
|
||||
const reached = new Set(reach.tripIds);
|
||||
const wanted = uniqueIds(tripIds).filter((id) => reached.has(id));
|
||||
return readInChunks(wanted, (chunk) => this.context.plannedOnTrips(reach.userId, today, chunk));
|
||||
}
|
||||
|
||||
/** The visit count and latest visit of each entry, in the entries' order, from one read. */
|
||||
async summaries(reach: VisitReach, entries: readonly EntryRows[]): Promise<VisitSummary[]> {
|
||||
const placeIds = entries.flatMap((rows) => rows.trips.map((row) => row.id));
|
||||
const planned = placeIds.length > 0 ? await this.plannedAt(reach, placeIds) : [];
|
||||
return entries.map((rows) => summaryOf(visitsOfEntry(rows, planned)));
|
||||
}
|
||||
|
||||
/** The visits of one entry of All places, newest first. */
|
||||
async ofEntry(reach: VisitReach, rows: EntryRows): Promise<DerivedVisit[]> {
|
||||
const placeIds = rows.trips.map((row) => row.id);
|
||||
if (placeIds.length === 0) return [];
|
||||
return visitsOfEntry(rows, await this.plannedAt(reach, placeIds));
|
||||
}
|
||||
|
||||
/** The visits on the trips, one per group and day, newest first. */
|
||||
async onTrips(
|
||||
reach: VisitReach,
|
||||
tripIds: readonly number[],
|
||||
groupOf: (row: PlannedVisitRow) => string,
|
||||
): Promise<DerivedVisit[]> {
|
||||
return collapseVisits(await this.plannedOn(reach, tripIds), groupOf);
|
||||
}
|
||||
|
||||
/** The visits as the contract sends them, with who each counts for, read in two blocks of statements. */
|
||||
async wire(visits: readonly DerivedVisit[]): Promise<PlaceVisit[]> {
|
||||
if (visits.length === 0) return [];
|
||||
const assignmentIds = uniqueIds(visits.flatMap((visit) => visit.assignment_ids));
|
||||
const named = await readInChunks(assignmentIds, (chunk) => this.context.assignmentPeople(chunk));
|
||||
const byAssignment = groupBy(named, (row) => row.assignment_id);
|
||||
const tripIds = uniqueIds(
|
||||
visits.filter((visit) => visit.assignment_ids.some((id) => !byAssignment.has(id))).map((visit) => visit.trip_id),
|
||||
);
|
||||
const roster = await readInChunks(tripIds, (chunk) => this.context.tripPeople(chunk));
|
||||
const byTrip = groupBy(roster, (row) => row.trip_id);
|
||||
return visits.map((visit) => wireVisit(visit, participantsOf(visit, byAssignment, byTrip)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import type { TripAccess } from '../../db/repositories/Trips.repository';
|
||||
import type { User } from '../../types';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { Trip } from '../permissions/trip.decorator';
|
||||
import { PlaceVisitsService } from './place-visits.service';
|
||||
import { Controller, Get, UseGuards } from '@nestjs/common';
|
||||
import { placeVisitTripVisitedResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* PLC-23 at /api/trips/:tripId/place-visits: which of the trip's places the
|
||||
* user visited, for the "visited" filter of the trip's list and map. Every
|
||||
* member reads it, each for themselves; nothing here writes.
|
||||
*/
|
||||
@Controller('api/trips/:tripId/place-visits')
|
||||
@UseGuards(JwtAuthGuard, TripAccessGuard)
|
||||
export class PlaceVisitsTripController {
|
||||
constructor(private readonly visits: PlaceVisitsService) {}
|
||||
|
||||
@Get('mine')
|
||||
@ResponseContract(placeVisitTripVisitedResponseSchema)
|
||||
async mine(@CurrentUser() user: User, @Trip() trip: TripAccess) {
|
||||
return this.visits.tripVisited(trip.id, { id: user.id, role: user.role });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { Injectable } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* The calendar day visits are counted up to: today in UTC, the server's own
|
||||
* clock, as YYYY-MM-DD. A provider of its own so a test can name the day.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceVisitsClock {
|
||||
today(): string {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import type { User } from '../../types';
|
||||
import { CurrentUser } from '../auth-core/current-user.decorator';
|
||||
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
|
||||
import { ResponseContract } from '../common/response-contract';
|
||||
import { PlaceVisitsForPlaceQueryDto, PlaceVisitsListQueryDto } from './place-visits.dto';
|
||||
import { PlaceVisitsService } from './place-visits.service';
|
||||
import { Controller, Get, Query, UseGuards } from '@nestjs/common';
|
||||
import { placeVisitsForPlaceResponseSchema, placeVisitsListResponseSchema } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* D7/PLC-10 at /api/place-visits: the user's visits and the visits at one
|
||||
* place of All places, read from the trips they reach. Read only: a visit
|
||||
* comes from the trip's plan, never from here. Not behind an addon: a visit
|
||||
* belongs to its trip as much as to Places.
|
||||
*/
|
||||
@Controller('api/place-visits')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class PlaceVisitsController {
|
||||
constructor(private readonly visits: PlaceVisitsService) {}
|
||||
|
||||
@Get()
|
||||
@ResponseContract(placeVisitsListResponseSchema)
|
||||
async list(@CurrentUser() user: User, @Query() query: PlaceVisitsListQueryDto) {
|
||||
return this.visits.list({ id: user.id, role: user.role }, query);
|
||||
}
|
||||
|
||||
@Get('place')
|
||||
@ResponseContract(placeVisitsForPlaceResponseSchema)
|
||||
async forPlace(@CurrentUser() user: User, @Query() query: PlaceVisitsForPlaceQueryDto) {
|
||||
return this.visits.forPlace({ id: user.id, role: user.role }, query.kind, query.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
import { placeVisitsForPlaceQuerySchema, placeVisitsListQuerySchema } from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
|
||||
export class PlaceVisitsForPlaceQueryDto extends createZodDto(placeVisitsForPlaceQuerySchema) {}
|
||||
export class PlaceVisitsListQueryDto extends createZodDto(placeVisitsListQuerySchema) {}
|
||||
@@ -0,0 +1,163 @@
|
||||
import type { PlannedVisitRow, VisitPersonRow } from '../../db/repositories/PlaceVisitContext.repository';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
import type { EntryRows } from './places-library.helpers';
|
||||
import type { PlaceVisit, PlaceVisitPerson } from '@trek/shared';
|
||||
|
||||
/** The visit count and latest day of some visits, as "All places" shows them. */
|
||||
export interface VisitSummary {
|
||||
visit_count: number;
|
||||
last_visit: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One visit, derived from the plan: a place on one calendar day, read from
|
||||
* the first trip day that has it, with every assignment of the place on that
|
||||
* trip day behind it (their participants are the visit's).
|
||||
*/
|
||||
export interface DerivedVisit {
|
||||
visited_on: string;
|
||||
visited_time: string | null;
|
||||
trip_id: number;
|
||||
trip_title: string;
|
||||
place_id: number;
|
||||
day_id: number;
|
||||
day_number: number;
|
||||
name: string;
|
||||
assignment_ids: number[];
|
||||
}
|
||||
|
||||
/** The order the plan reads in: day first, then the trip, the day number and the stop order. */
|
||||
function planOrder(a: PlannedVisitRow, b: PlannedVisitRow): number {
|
||||
return (
|
||||
(a.date < b.date ? 1 : a.date > b.date ? -1 : 0) ||
|
||||
a.trip_id - b.trip_id ||
|
||||
a.day_number - b.day_number ||
|
||||
(a.order_index ?? 0) - (b.order_index ?? 0) ||
|
||||
a.assignment_id - b.assignment_id
|
||||
);
|
||||
}
|
||||
|
||||
/** The earlier of two clock times, a known one before none. */
|
||||
function earlier(a: string | null, b: string | null): string | null {
|
||||
if (a === null) return b;
|
||||
if (b === null) return a;
|
||||
return a <= b ? a : b;
|
||||
}
|
||||
|
||||
/** Newest day first, the later time first, a visit without a time after the timed ones of its day. */
|
||||
function newestFirst(a: DerivedVisit, b: DerivedVisit): number {
|
||||
if (a.visited_on !== b.visited_on) return a.visited_on < b.visited_on ? 1 : -1;
|
||||
if (a.visited_time !== b.visited_time) {
|
||||
if (a.visited_time === null) return 1;
|
||||
if (b.visited_time === null) return -1;
|
||||
return a.visited_time < b.visited_time ? 1 : -1;
|
||||
}
|
||||
return a.trip_id - b.trip_id || a.day_id - b.day_id || a.place_id - b.place_id;
|
||||
}
|
||||
|
||||
/**
|
||||
* The visits of planned rows: one per group (what counts as one place) and
|
||||
* calendar day, however many assignments, trip places or trips name it that
|
||||
* day. The first trip day in plan order stands for the visit; the time is the
|
||||
* earliest set on that day (the stop's own time, else the place's).
|
||||
*/
|
||||
export function collapseVisits(
|
||||
rows: readonly PlannedVisitRow[],
|
||||
groupOf: (row: PlannedVisitRow) => string,
|
||||
): DerivedVisit[] {
|
||||
const visits = new Map<string, DerivedVisit>();
|
||||
for (const row of [...rows].sort(planOrder)) {
|
||||
const key = `${groupOf(row)}|${row.date}`;
|
||||
const time = row.assignment_time ?? row.place_time;
|
||||
const visit = visits.get(key);
|
||||
if (!visit) {
|
||||
visits.set(key, {
|
||||
visited_on: row.date,
|
||||
visited_time: time,
|
||||
trip_id: row.trip_id,
|
||||
trip_title: row.trip_title,
|
||||
place_id: row.place_id,
|
||||
day_id: row.day_id,
|
||||
day_number: row.day_number,
|
||||
name: row.name,
|
||||
assignment_ids: [row.assignment_id],
|
||||
});
|
||||
} else if (visit.day_id === row.day_id) {
|
||||
visit.visited_time = earlier(visit.visited_time, time);
|
||||
if (!visit.assignment_ids.includes(row.assignment_id)) visit.assignment_ids.push(row.assignment_id);
|
||||
}
|
||||
}
|
||||
return [...visits.values()].sort(newestFirst);
|
||||
}
|
||||
|
||||
/**
|
||||
* The visits that belong to one entry of "All places": those at one of its
|
||||
* trip places, which are only the trip places of trips the user reaches.
|
||||
* A saved place or an own place adds no visit of its own; an own place
|
||||
* gathers the trip places it groups, and those count once per day.
|
||||
*/
|
||||
export function visitsOfEntry(rows: EntryRows, planned: readonly PlannedVisitRow[]): DerivedVisit[] {
|
||||
const places = new Set(rows.trips.map((row) => row.id));
|
||||
return collapseVisits(
|
||||
planned.filter((row) => places.has(row.place_id)),
|
||||
() => 'entry',
|
||||
);
|
||||
}
|
||||
|
||||
/** How many visits there are and the latest day among them. */
|
||||
export function summaryOf(visits: readonly DerivedVisit[]): VisitSummary {
|
||||
const last = visits.reduce<string | null>(
|
||||
(latest, visit) => (latest === null || visit.visited_on > latest ? visit.visited_on : latest),
|
||||
null,
|
||||
);
|
||||
return { visit_count: visits.length, last_visit: last };
|
||||
}
|
||||
|
||||
/** People once each, in the order first given. */
|
||||
export function uniquePeople<T extends { id: number }>(people: readonly T[]): T[] {
|
||||
const seen = new Set<number>();
|
||||
return people.filter((person) => {
|
||||
if (seen.has(person.id)) return false;
|
||||
seen.add(person.id);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Who a visit counts for: the people its assignments name, or, for an
|
||||
* assignment naming no one, everyone with an account on the trip.
|
||||
*/
|
||||
export function participantsOf(
|
||||
visit: DerivedVisit,
|
||||
byAssignment: ReadonlyMap<number, readonly VisitPersonRow[]>,
|
||||
byTrip: ReadonlyMap<number, readonly VisitPersonRow[]>,
|
||||
): PlaceVisitPerson[] {
|
||||
const people = visit.assignment_ids.flatMap((id) => {
|
||||
const named = byAssignment.get(id) ?? [];
|
||||
return named.length > 0 ? named : (byTrip.get(visit.trip_id) ?? []);
|
||||
});
|
||||
return uniquePeople(people).map((person) => ({
|
||||
id: person.id,
|
||||
username: person.username,
|
||||
avatar_url: avatarUrl(person),
|
||||
}));
|
||||
}
|
||||
|
||||
/** A derived visit as the contract sends it. */
|
||||
export function wireVisit(visit: DerivedVisit, participants: PlaceVisitPerson[]): PlaceVisit {
|
||||
return {
|
||||
visited_on: visit.visited_on,
|
||||
visited_time: visit.visited_time,
|
||||
trip: { id: visit.trip_id, title: visit.trip_title },
|
||||
place_id: visit.place_id,
|
||||
day_id: visit.day_id,
|
||||
day_number: visit.day_number,
|
||||
name: visit.name,
|
||||
participants,
|
||||
};
|
||||
}
|
||||
|
||||
/** The ids once each, in the order first given. */
|
||||
export function uniqueIds(ids: readonly number[]): number[] {
|
||||
return [...new Set(ids)];
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { McpController, Tool, TOOL_ANNOTATIONS_READONLY, ok, type McpContext } from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { PlaceMediaService } from './place-media.service';
|
||||
import { PlaceVisitsService } from './place-visits.service';
|
||||
import type { LibraryUser } from './places-library.service';
|
||||
import {
|
||||
idSchema,
|
||||
placesLibraryDetailRequestSchema,
|
||||
placeVisitsForPlaceQuerySchema,
|
||||
placeVisitsListQuerySchema,
|
||||
type PlaceVisitsForPlaceQuery,
|
||||
type PlaceVisitsListQuery,
|
||||
type PlacesLibraryDetailRequest,
|
||||
} from '@trek/shared';
|
||||
|
||||
const DERIVED =
|
||||
'Visits are read from the trips, never entered: a place counts as visited on a dated day up to today it is planned on, in a trip you own or are a member of, when the stop names no one or names you. Each place counts once per day.';
|
||||
|
||||
const tripInput = { tripId: idSchema };
|
||||
|
||||
/**
|
||||
* D7/PLC-10, PLC-19, PLC-20, PLC-23 over the same services and checks as
|
||||
* /api/place-visits, /api/trips/:tripId/place-visits and the media route of
|
||||
* All places. Read only, like the routes. The visits answer to the places
|
||||
* scope; the media of an entry of All places sits behind the Collections
|
||||
* addon like the rest of the library.
|
||||
*/
|
||||
@McpController()
|
||||
export class PlaceVisitsMcp {
|
||||
constructor(
|
||||
private readonly visits: PlaceVisitsService,
|
||||
private readonly media: PlaceMediaService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
// Read by the addon gate of the media tool.
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
private async user(userId: number): Promise<LibraryUser> {
|
||||
return { id: userId, role: (await this.guards.isAdminUser(userId)) ? 'admin' : 'user' };
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'list_place_visits',
|
||||
description: `Your visits, newest day first, of one trip (trip_id) or of all, paged with limit and offset, each with its day, time, trip, trip place, day and who it counts for. ${DERIVED}`,
|
||||
inputSchema: placeVisitsListQuerySchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'places', mode: 'read' },
|
||||
})
|
||||
async listPlaceVisits(input: PlaceVisitsListQuery, ctx: McpContext) {
|
||||
return ok(await this.visits.list(await this.user(ctx.userId), input));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'get_place_visit_history',
|
||||
description: `Your visits at one place of All places, opened from a trip place (kind trip) or a saved place (kind list), newest first, plus visit_count and last_visit. A day counts once however many trips or lists hold the place. ${DERIVED}`,
|
||||
inputSchema: placeVisitsForPlaceQuerySchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'places', mode: 'read' },
|
||||
})
|
||||
async getPlaceVisitHistory(input: PlaceVisitsForPlaceQuery, ctx: McpContext) {
|
||||
return ok(await this.visits.forPlace(await this.user(ctx.userId), input.kind, input.id));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'list_my_visited_trip_places',
|
||||
description: `The trip's places you visited (place_ids), counting the days at each trip place and at the same place on your other trips, with visit_count and last_visit. ${DERIVED}`,
|
||||
inputSchema: tripInput,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'places', mode: 'read' },
|
||||
})
|
||||
async listMyVisitedTripPlaces({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
return ok(await this.visits.tripVisited(tripId, await this.user(ctx.userId)));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'get_library_place_media',
|
||||
description:
|
||||
'The pictures, journey photos and trip files of one entry of All places, opened from a trip place or a saved place, each with the trip, list or journey it comes from. Only journeys and trips you can open contribute.',
|
||||
inputSchema: placesLibraryDetailRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
access: { group: 'collections', mode: 'read' },
|
||||
})
|
||||
async getLibraryPlaceMedia(input: PlacesLibraryDetailRequest, ctx: McpContext) {
|
||||
return ok(await this.media.media(await this.user(ctx.userId), input.kind, input.id));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { JourneyDomainModule } from '../journey/journey-domain.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
|
||||
import { PlaceMediaController } from './place-media.controller';
|
||||
import { PlaceMediaService } from './place-media.service';
|
||||
import { PlaceVisitsTripController } from './place-visits-trip.controller';
|
||||
import { PlaceVisitsController } from './place-visits.controller';
|
||||
import { PlaceVisitsMcp } from './place-visits.mcp';
|
||||
import { PlaceVisitsService } from './place-visits.service';
|
||||
import { PlacesLibraryModule } from './places-library.module';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* D7/PLC-10, PLC-19, PLC-20, PLC-23: the visits read from the trips, their
|
||||
* history at a place of All places, the trip places visited, and the photos
|
||||
* and files of an entry of All places. Part of the places-library domain,
|
||||
* beside PlacesLibraryModule, which resolves every place and provides the
|
||||
* visit reader and its context repository. Read only.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
PlacesLibraryModule,
|
||||
AddonsModule,
|
||||
PermissionsModule,
|
||||
JourneyDomainModule,
|
||||
TripMembershipModule,
|
||||
McpSharedModule,
|
||||
],
|
||||
controllers: [PlaceVisitsController, PlaceVisitsTripController, PlaceMediaController],
|
||||
providers: [PlaceVisitsService, PlaceMediaService, PlaceVisitsMcp],
|
||||
})
|
||||
export class PlaceVisitsModule {}
|
||||
@@ -0,0 +1,121 @@
|
||||
import { PlaceVisitContextRepository } from '../../db/repositories/PlaceVisitContext.repository';
|
||||
import { tripNotFound } from '../common/trip-writer';
|
||||
import { TripAccessService } from '../trip-membership/trip-access.service';
|
||||
import { PlaceVisitsReaderService } from './place-visits-reader.service';
|
||||
import { collapseVisits, uniqueIds, visitsOfEntry } from './place-visits.helpers';
|
||||
import { entryKey, type EntryRows } from './places-library.helpers';
|
||||
import { PlacesLibraryService, placeNotFound, type LibraryReach, type LibraryUser } from './places-library.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
PLACE_VISITS_PAGE_DEFAULT,
|
||||
type PlaceVisitsForPlaceResponse,
|
||||
type PlaceVisitsListQuery,
|
||||
type PlaceVisitsListResponse,
|
||||
type PlaceVisitTripVisitedResponse,
|
||||
type PlacesLibraryKind,
|
||||
} from '@trek/shared';
|
||||
|
||||
/**
|
||||
* D7/PLC-10, PLC-23: the visits of a reader, read from the trips they reach
|
||||
* (`PlaceVisitsReaderService` has the rule). Nothing here writes: a visit
|
||||
* comes from planning a place on a day and goes with that plan or with the
|
||||
* access to its trip. What counts as one place is what All places shows as
|
||||
* one entry, so a place grouped with others or on several trips counts once
|
||||
* per day.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceVisitsService {
|
||||
constructor(
|
||||
private readonly library: PlacesLibraryService,
|
||||
private readonly reader: PlaceVisitsReaderService,
|
||||
private readonly context: PlaceVisitContextRepository,
|
||||
private readonly trips: TripAccessService,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The reader's visits at one place of All places, opened from a trip place
|
||||
* or a saved place: every day at one of the entry's trip places, newest
|
||||
* first, the same ones the entry counts.
|
||||
*/
|
||||
async forPlace(user: LibraryUser, kind: PlacesLibraryKind, id: number): Promise<PlaceVisitsForPlaceResponse> {
|
||||
const reach = await this.library.reach(user.id);
|
||||
const anchor = await this.library.anchorOfUse(reach, kind, id);
|
||||
if (anchor === null) throw placeNotFound();
|
||||
const [rows] = await this.library.rows(reach, [anchor]);
|
||||
if (!rows) throw placeNotFound();
|
||||
const visits = await this.reader.ofEntry(reach, rows);
|
||||
return {
|
||||
visits: await this.reader.wire(visits),
|
||||
visit_count: visits.length,
|
||||
last_visit: visits[0]?.visited_on ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
/** The reader's visits, newest day first, of one trip or of all, paged. */
|
||||
async list(user: LibraryUser, query: PlaceVisitsListQuery): Promise<PlaceVisitsListResponse> {
|
||||
const reach = await this.library.reach(user.id);
|
||||
const tripIds = query.trip_id === undefined ? reach.tripIds : [query.trip_id];
|
||||
const entryOf = await this.entryKeys(reach);
|
||||
const visits = await this.reader.onTrips(
|
||||
reach,
|
||||
tripIds,
|
||||
(row) => entryOf.get(row.place_id) ?? `trip:${row.place_id}`,
|
||||
);
|
||||
const offset = query.offset ?? 0;
|
||||
const page = visits.slice(offset, offset + (query.limit ?? PLACE_VISITS_PAGE_DEFAULT));
|
||||
return { visits: await this.reader.wire(page), total: visits.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* The trip's places the reader visited, for the filter of the trip's list
|
||||
* and map: every place with a visit at it or at the same place elsewhere
|
||||
* (the same entry of All places), with how many days and the latest.
|
||||
*/
|
||||
async tripVisited(tripId: number, user: LibraryUser): Promise<PlaceVisitTripVisitedResponse> {
|
||||
if (!(await this.trips.findAccessible(tripId, user.id))) throw tripNotFound();
|
||||
const placeIds = await this.context.tripPlaceIds(tripId);
|
||||
if (placeIds.length === 0) return { place_ids: [], places: [] };
|
||||
const reach = await this.library.reach(user.id);
|
||||
const entries = await this.entriesOfPlaces(reach, placeIds);
|
||||
const entryPlaces = uniqueIds([
|
||||
...placeIds,
|
||||
...[...entries.values()].flatMap((rows) => rows.trips.map((row) => row.id)),
|
||||
]);
|
||||
const planned = await this.reader.plannedAt(reach, entryPlaces);
|
||||
if (planned.length === 0) return { place_ids: [], places: [] };
|
||||
const places = placeIds.flatMap((placeId) => {
|
||||
const rows = entries.get(placeId);
|
||||
const visits = rows
|
||||
? visitsOfEntry(rows, planned)
|
||||
: collapseVisits(
|
||||
planned.filter((row) => row.place_id === placeId),
|
||||
() => 'place',
|
||||
);
|
||||
const last = visits[0]?.visited_on;
|
||||
return last === undefined ? [] : [{ place_id: placeId, visit_count: visits.length, last_visit: last }];
|
||||
});
|
||||
return { place_ids: places.map((place) => place.place_id), places };
|
||||
}
|
||||
|
||||
/** The entry of All places each trip place the reader reaches stands for, by its key. */
|
||||
private async entryKeys(reach: LibraryReach): Promise<Map<number, string>> {
|
||||
const uses = await this.library.usesOf(reach, null);
|
||||
return new Map(uses.filter((use) => use.from_list === 0).map((use) => [use.use_id, entryKey(use.anchor_key)]));
|
||||
}
|
||||
|
||||
/** The entry of All places each trip place stands for, by trip place id. */
|
||||
private async entriesOfPlaces(reach: LibraryReach, placeIds: readonly number[]): Promise<Map<number, EntryRows>> {
|
||||
const wanted = new Set(placeIds);
|
||||
const uses = (await this.library.usesOf(reach, null)).filter(
|
||||
(use) => use.from_list === 0 && wanted.has(use.use_id),
|
||||
);
|
||||
const anchors = uniqueIds(uses.map((use) => use.anchor_key));
|
||||
const rows = new Map((await this.library.rows(reach, anchors)).map((row) => [row.anchor, row]));
|
||||
const byPlace = new Map<number, EntryRows>();
|
||||
for (const use of uses) {
|
||||
const row = rows.get(use.anchor_key);
|
||||
if (row) byPlace.set(use.use_id, row);
|
||||
}
|
||||
return byPlace;
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,7 @@
|
||||
import {
|
||||
placesLibraryBulkTagsRequestSchema,
|
||||
placesLibraryDuplicatesQuerySchema,
|
||||
placesLibraryEntryTagsRequestSchema,
|
||||
placesLibraryQuerySchema,
|
||||
placesLibraryLinkRequestSchema,
|
||||
placesLibraryMergeRequestSchema,
|
||||
@@ -16,3 +18,7 @@ export class PlacesLibraryUnlinkDto extends createZodDto(placesLibraryUnlinkRequ
|
||||
export class PlacesLibraryDuplicatesQueryDto extends createZodDto(placesLibraryDuplicatesQuerySchema) {}
|
||||
export class PlacesLibraryPairDto extends createZodDto(placesLibraryPairRequestSchema) {}
|
||||
export class PlacesLibraryMergeDto extends createZodDto(placesLibraryMergeRequestSchema) {}
|
||||
|
||||
/** PLC-21: the personal tags of one entry, and of several at once. */
|
||||
export class PlacesLibraryEntryTagsDto extends createZodDto(placesLibraryEntryTagsRequestSchema) {}
|
||||
export class PlacesLibraryBulkTagsDto extends createZodDto(placesLibraryBulkTagsRequestSchema) {}
|
||||
|
||||
@@ -142,6 +142,7 @@ function tripOriginOf(row: LibraryTripPlaceRow, canEdit: boolean, linked: boolea
|
||||
trip_title: row.trip_title,
|
||||
trip_start: row.trip_start,
|
||||
trip_end: row.trip_end,
|
||||
trip_cover: row.trip_cover ?? null,
|
||||
place_id: row.id,
|
||||
can_edit: canEdit,
|
||||
read_only: !canEdit,
|
||||
@@ -154,6 +155,8 @@ function listOriginOf(row: LibraryCollectionPlaceRow, canEdit: boolean, linked:
|
||||
kind: 'list',
|
||||
collection_id: row.collection_id,
|
||||
collection_name: row.collection_name,
|
||||
collection_color: row.collection_color ?? null,
|
||||
collection_icon: row.collection_icon ?? null,
|
||||
collection_place_id: row.id,
|
||||
status: collectionStatusSchema.parse(row.status),
|
||||
can_edit: canEdit,
|
||||
|
||||
@@ -43,7 +43,7 @@ export class PlacesLibraryMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'list_all_places',
|
||||
description: `Page through every place the user has: the saved places of every list they can open and the places of every trip they can open, by name (sort: name, the default) or last changed first (sort: updated), ${PLACES_LIBRARY_PAGE_DEFAULT} at a time unless limit says otherwise (at most ${PLACES_LIBRARY_PAGE_MAX}). Tours, tracks and road trip stops of the drive are left out; lodging counts as a place. A saved place and a trip place are one entry only when the saved place came from that trip place and both agree (the same provider id, or the same name at the same spot); otherwise they are separate entries, unless the user put them together as an own place of theirs (link_library_places, merge_library_places). Each entry has a key (trip:<place id>, list:<saved place id>, or own:<id> for an own place), identity_id (the own place's id, null for any other entry), name, address, lat, lng, category, image_url and its origins: kind trip (trip_id, trip_title, trip_start, trip_end, place_id, can_edit, read_only) or kind list (collection_id, collection_name, collection_place_id, status, can_edit). No notes; get_library_place reads one entry in full. Filter by q (name or address), category_id, kind, collection_id, trip_id or status (a list status); a list filter and a trip filter do not go together. Next to the page: total (what every filter matches), counts (all, trip, list for q and category_id alone) and next_cursor, passed back as cursor for the next page, null on the last. A page can end before limit, so always go on at next_cursor.`,
|
||||
description: `Page through every place the user has: the saved places of every list they can open and the places of every trip they can open, by name (sort: name, the default) or last changed first (sort: updated), ${PLACES_LIBRARY_PAGE_DEFAULT} at a time unless limit says otherwise (at most ${PLACES_LIBRARY_PAGE_MAX}). Tours, tracks and road trip stops of the drive are left out; lodging counts as a place. A saved place and a trip place are one entry only when the saved place came from that trip place and both agree (the same provider id, or the same name at the same spot); otherwise they are separate entries, unless the user put them together as an own place of theirs (link_library_places, merge_library_places). Each entry has a key (trip:<place id>, list:<saved place id>, or own:<id> for an own place), identity_id (the own place's id, null for any other entry), name, address, lat, lng, category, image_url and its origins: kind trip (trip_id, trip_title, trip_start, trip_end, trip_cover, place_id, can_edit, read_only) or kind list (collection_id, collection_name, collection_color, collection_icon, collection_place_id, status, can_edit). Each entry also carries tags, your own personal tags on it (private, set with set_library_place_tags or tag_library_places). No notes; get_library_place reads one entry in full. Filter by q (name or address), category_id, kind, collection_id, trip_id, status (a list status) or tag_ids (entries with at least one of these personal tags); a list filter and a trip filter do not go together. Next to the page: total (what every filter matches), counts (all, trip, list for q, category_id and tag_ids alone) and next_cursor, passed back as cursor for the next page, null on the last. A page can end before limit, so always go on at next_cursor.`,
|
||||
inputSchema: placesLibraryQuerySchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
import { PersonalPlaceTags } from '../../db/entities/PersonalPlaceTags.entity';
|
||||
import { UserPlaceLinks } from '../../db/entities/UserPlaceLinks.entity';
|
||||
import { UserPlaceMergeDismissals } from '../../db/entities/UserPlaceMergeDismissals.entity';
|
||||
import { UserPlaceMerges } from '../../db/entities/UserPlaceMerges.entity';
|
||||
import { UserPlaces } from '../../db/entities/UserPlaces.entity';
|
||||
import { PlaceVisitContextRepository } from '../../db/repositories/PlaceVisitContext.repository';
|
||||
import { PlacesLibraryRepository } from '../../db/repositories/PlacesLibrary.repository';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { CollectionsModule } from '../collections/collections.module';
|
||||
@@ -14,6 +16,11 @@ import { PlaceIdentitiesPruneJob } from './place-identities-prune.job';
|
||||
import { PlaceIdentitiesController } from './place-identities.controller';
|
||||
import { PlaceIdentitiesMcp } from './place-identities.mcp';
|
||||
import { PlaceIdentitiesService } from './place-identities.service';
|
||||
import { PlaceTagsController } from './place-tags.controller';
|
||||
import { PlaceTagsMcp } from './place-tags.mcp';
|
||||
import { PlaceTagsService } from './place-tags.service';
|
||||
import { PlaceVisitsReaderService } from './place-visits-reader.service';
|
||||
import { PlaceVisitsClock } from './place-visits.clock';
|
||||
import { PlacesLibraryController } from './places-library.controller';
|
||||
import { PlacesLibraryMcp } from './places-library.mcp';
|
||||
import { PlacesLibraryService } from './places-library.service';
|
||||
@@ -25,9 +32,10 @@ import { Module } from '@nestjs/common';
|
||||
* PLC-07/PLC-08 "All places" under the Collections addon: the saved places of
|
||||
* every list and the places of every trip the user can open, read only, plus
|
||||
* (D5/PLC-13) the user's own places that group them, the duplicate
|
||||
* suggestions and merges. The library repository reads across trips and
|
||||
* lists, so it backs no entity and is built here over the context-resolving
|
||||
* EntityManager, the way MaintenanceModule builds its own.
|
||||
* suggestions and merges, and (D7) the visits every entry carries, read from
|
||||
* the trips' day plans, and (PLC-21) the user's personal tags on them. The library repository and the visit context read
|
||||
* across trips and lists, so they back no entity and are built here over the
|
||||
* context-resolving EntityManager, the way MaintenanceModule builds its own.
|
||||
*/
|
||||
@Module({
|
||||
imports: [
|
||||
@@ -37,21 +45,38 @@ import { Module } from '@nestjs/common';
|
||||
PermissionsModule,
|
||||
McpSharedModule,
|
||||
SchedulingModule,
|
||||
MikroOrmModule.forFeature([UserPlaces, UserPlaceLinks, UserPlaceMerges, UserPlaceMergeDismissals]),
|
||||
MikroOrmModule.forFeature([
|
||||
UserPlaces,
|
||||
UserPlaceLinks,
|
||||
UserPlaceMerges,
|
||||
UserPlaceMergeDismissals,
|
||||
PersonalPlaceTags,
|
||||
]),
|
||||
],
|
||||
controllers: [PlacesLibraryController, PlaceIdentitiesController],
|
||||
controllers: [PlacesLibraryController, PlaceIdentitiesController, PlaceTagsController],
|
||||
providers: [
|
||||
{
|
||||
provide: PlacesLibraryRepository,
|
||||
useFactory: (em: EntityManager) => new PlacesLibraryRepository(em),
|
||||
inject: [EntityManager],
|
||||
},
|
||||
{
|
||||
provide: PlaceVisitContextRepository,
|
||||
useFactory: (em: EntityManager) => new PlaceVisitContextRepository(em),
|
||||
inject: [EntityManager],
|
||||
},
|
||||
PlaceVisitsClock,
|
||||
PlaceVisitsReaderService,
|
||||
PlacesLibraryService,
|
||||
PlacesLibraryMcp,
|
||||
PlaceIdentitiesService,
|
||||
PlaceDuplicatesService,
|
||||
PlaceIdentitiesMcp,
|
||||
PlaceIdentitiesPruneJob,
|
||||
PlaceTagsService,
|
||||
PlaceTagsMcp,
|
||||
],
|
||||
// The visits and media of All places (PlaceVisitsModule, same domain) read through these.
|
||||
exports: [PlacesLibraryService, PlaceVisitsReaderService, PlaceVisitContextRepository],
|
||||
})
|
||||
export class PlacesLibraryModule {}
|
||||
|
||||
@@ -11,6 +11,8 @@ import { CollectionsService } from '../collections/collections.service';
|
||||
import { badRequest, notFound } from '../common/domain-error';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { TripMembershipService } from '../trip-membership/trip-membership.service';
|
||||
import { tagsByEntry, tagTargetsOf } from './place-tags.helpers';
|
||||
import { PlaceVisitsReaderService } from './place-visits-reader.service';
|
||||
import {
|
||||
decodeLibraryCursor,
|
||||
encodeLibraryCursor,
|
||||
@@ -35,6 +37,7 @@ import {
|
||||
type PlacesLibraryKind,
|
||||
type PlacesLibraryPageResponse,
|
||||
type PlacesLibraryQuery,
|
||||
type PlacesLibraryTag,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Who asks, as the permission check reads them. */
|
||||
@@ -80,6 +83,10 @@ function armsOfReach(reach: LibraryReach): LibraryArms {
|
||||
* Uses the user put together as one place of their own (D5) are one entry,
|
||||
* named and placed as that own place; only the uses the user reaches today
|
||||
* belong to it.
|
||||
*
|
||||
* Every entry carries the user's visits to it (D7/PLC-10), read from the
|
||||
* plans of the trips they reach (`PlaceVisitsReaderService`): each day once
|
||||
* per entry, the same ones the visit history of the place lists.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlacesLibraryService {
|
||||
@@ -88,6 +95,7 @@ export class PlacesLibraryService {
|
||||
private readonly collections: CollectionsService,
|
||||
private readonly membership: TripMembershipService,
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly visits: PlaceVisitsReaderService,
|
||||
) {}
|
||||
|
||||
async list(
|
||||
@@ -106,6 +114,8 @@ export class PlacesLibraryService {
|
||||
search: query.q ? query.q : null,
|
||||
categoryId: query.category_id ?? null,
|
||||
status: query.status ?? null,
|
||||
// PLC-21: a tag on any use the user reaches counts, whatever the page's other filters leave out.
|
||||
tags: query.tag_ids === undefined ? null : { tagIds: query.tag_ids, reach: armsOfReach(reach) },
|
||||
};
|
||||
|
||||
const counts = await this.repo.countEntries(armsOfReach(reach), { ...match, status: null });
|
||||
@@ -151,7 +161,12 @@ export class PlacesLibraryService {
|
||||
const rows = (await this.rows(reach, [anchor]))[0];
|
||||
if (!rows) throw placeNotFound();
|
||||
const entry = entryOf(rows, await this.access(user, rows.trips, rows.saved));
|
||||
return { entry, details: await this.details(user.id, rows) };
|
||||
const [summary] = await this.visits.summaries(reach, [rows]);
|
||||
const [tags] = await this.tagsOf(user.id, [rows]);
|
||||
return {
|
||||
entry: { ...entry, ...summary, tags: tags ?? [] },
|
||||
details: await this.details(user.id, rows),
|
||||
};
|
||||
}
|
||||
|
||||
/** The trips and lists the user reaches right now. */
|
||||
@@ -205,7 +220,15 @@ export class PlacesLibraryService {
|
||||
rows.flatMap((row) => row.trips),
|
||||
rows.flatMap((row) => row.saved),
|
||||
);
|
||||
return rows.map((row) => entryOf(row, access));
|
||||
const summaries = await this.visits.summaries(reach, rows);
|
||||
const tags = await this.tagsOf(user.id, rows);
|
||||
return rows.map((row, index) => ({ ...entryOf(row, access), ...summaries[index], tags: tags[index] ?? [] }));
|
||||
}
|
||||
|
||||
/** PLC-21: the user's own personal tags of each entry, in the entries' order. */
|
||||
private async tagsOf(userId: number, rows: readonly EntryRows[]): Promise<PlacesLibraryTag[][]> {
|
||||
const tagRows = await readInChunks(rows, (chunk) => this.repo.entryTags(userId, tagTargetsOf(chunk)));
|
||||
return tagsByEntry(rows, tagRows);
|
||||
}
|
||||
|
||||
/** One entry, or null when it has no use the user reaches. */
|
||||
|
||||
@@ -426,7 +426,12 @@ export class PlacesController {
|
||||
if (!('category_id' in body)) {
|
||||
throw new HttpException({ error: 'Provide at least one field to update' }, 400);
|
||||
}
|
||||
const updated = await this.places.updateMany(tripId, ids, { category_id: body.category_id as number | null });
|
||||
const updated = await this.places.updateMany(
|
||||
tripId,
|
||||
ids,
|
||||
{ category_id: body.category_id as number | null },
|
||||
user.id,
|
||||
);
|
||||
for (const place of updated) {
|
||||
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
|
||||
await this.places.onUpdated(place.id);
|
||||
@@ -470,7 +475,13 @@ export class PlacesController {
|
||||
await this.storage.put('places', file.filename, { tmpPath: file.path });
|
||||
// Reuse the existing image_url slot (the top-precedence thumbnail source); the
|
||||
// update path reclaims any previously uploaded file it replaces.
|
||||
const result = await this.places.update(tripId, id, { image_url: placeImageUrl(file.filename) } as never);
|
||||
const result = await this.places.update(
|
||||
tripId,
|
||||
id,
|
||||
{ image_url: placeImageUrl(file.filename) } as never,
|
||||
undefined,
|
||||
user.id,
|
||||
);
|
||||
if (!result || isUpdateConflict(result)) {
|
||||
throw new HttpException({ error: 'Place not found' }, 404);
|
||||
}
|
||||
@@ -494,7 +505,7 @@ export class PlacesController {
|
||||
if (isDemoWriteBlocked(this.env, user.email)) {
|
||||
throw new HttpException(DEMO_WRITE_ERROR, 403);
|
||||
}
|
||||
const result = await this.places.setImageFromFile(tripId, id, body.file_id);
|
||||
const result = await this.places.setImageFromFile(tripId, id, body.file_id, user.id);
|
||||
if (result === 'not_found') throw new HttpException({ error: 'File not found' }, 404);
|
||||
if (result === 'not_image') throw new HttpException({ error: 'Only jpg, png, gif, webp images allowed' }, 400);
|
||||
if (result === 'too_large') throw new HttpException({ error: 'Image too large' }, 400);
|
||||
@@ -567,7 +578,7 @@ export class PlacesController {
|
||||
validateRouteColor(body);
|
||||
validateUrlFields(body);
|
||||
await this.requireEdit(trip, user);
|
||||
const result = await this.places.update(tripId, id, body as never, ifMatch);
|
||||
const result = await this.places.update(tripId, id, body as never, ifMatch, user.id);
|
||||
if (!result) {
|
||||
throw new HttpException({ error: 'Place not found' }, 404);
|
||||
}
|
||||
|
||||
@@ -233,7 +233,7 @@ export class PlacesMcp {
|
||||
if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const before = await this.origins.valuesBefore(placeId);
|
||||
const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours: opening_hours === undefined ? undefined : hoursText(opening_hours), image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent, tags });
|
||||
const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours: opening_hours === undefined ? undefined : hoursText(opening_hours), image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent, tags }, undefined, ctx.userId);
|
||||
// No base version is sent, so the update never answers a conflict; the guard only narrows the type.
|
||||
if (!place || isUpdateConflict(place)) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
|
||||
this.guards.safeBroadcast(tripId, 'place:updated', { place });
|
||||
@@ -261,7 +261,7 @@ export class PlacesMcp {
|
||||
if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const before = await this.origins.valuesBefore(placeId);
|
||||
const result = await this.places.setImageFromFile(String(tripId), String(placeId), fileId);
|
||||
const result = await this.places.setImageFromFile(String(tripId), String(placeId), fileId, ctx.userId);
|
||||
if (result === 'not_found') return errorResult('File not found.');
|
||||
if (result === 'not_image') return errorResult('That file is not a jpg, png, gif or webp image.');
|
||||
if (result === 'too_large') return errorResult('That image is too large.');
|
||||
@@ -561,7 +561,7 @@ export class PlacesMcp {
|
||||
const before = new Map(
|
||||
await Promise.all(placeIds.map(async (id) => [id, await this.origins.valuesBefore(id)] as const)),
|
||||
);
|
||||
const updated = await this.places.updateMany(String(tripId), placeIds, fields);
|
||||
const updated = await this.places.updateMany(String(tripId), placeIds, fields, ctx.userId);
|
||||
// Per place, the event and then the journey hook, in the order POST /places/bulk-update keeps.
|
||||
await inOrder(updated, async (place) => {
|
||||
this.guards.safeBroadcast(tripId, 'place:updated', { place });
|
||||
|
||||
@@ -17,6 +17,7 @@ import { JourneyDomainModule } from '../journey/journey-domain.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { PlaceChangesModule } from '../place-changes/place-changes.module';
|
||||
import { PlaceContribModule } from '../place-contrib/place-contrib.module';
|
||||
import { PlaceImportModule } from '../place-import/place-import.module';
|
||||
import { PlacePhotosModule } from '../place-photos/place-photos.module';
|
||||
@@ -79,6 +80,8 @@ import { MulterModule } from '@nestjs/platform-express';
|
||||
// Every place write records where its shareable details came from, and the
|
||||
// user's values go to the community enrichment's queue there.
|
||||
PlaceContribModule,
|
||||
// PLC-14: every write of a place's details keeps its history, in the write's transaction.
|
||||
PlaceChangesModule,
|
||||
// Plan 3c Task 4: `PlacesService`'s and `PlacesMcp`'s own `@InjectRepository`
|
||||
// constructor params (`PlacesRepository`, `TagsRepository`,
|
||||
// `PlaceRatingsRepository`, `TripMembersRepository`,
|
||||
|
||||
@@ -97,7 +97,13 @@ export class PlacesRpc {
|
||||
// null-refusal check compares against the resolved place, not an always-truthy
|
||||
// Promise, and the broadcast below carries the actual place.
|
||||
const before = await this.origins.valuesBefore(placeId);
|
||||
const place = await this.places.update(String(tripId), String(placeId), parsed.data as PlaceUpdateInput);
|
||||
const place = await this.places.update(
|
||||
String(tripId),
|
||||
String(placeId),
|
||||
parsed.data as PlaceUpdateInput,
|
||||
undefined,
|
||||
actor,
|
||||
);
|
||||
if (place === null) throw new ForbiddenResource(`no place ${placeId} on trip ${tripId}`);
|
||||
this.realtime.broadcast(tripId, 'place:updated', { place });
|
||||
if ('id' in place) await this.origins.record(place.id, before, PLUGIN);
|
||||
|
||||
@@ -27,6 +27,7 @@ import { JourneyDomainService } from '../journey/journey-domain.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { StorageReleaseService } from '../storage/storage-release.service';
|
||||
import { AccommodationsService } from '../accommodations/accommodations.service';
|
||||
import { AUTOMATIC_CHANGE, PlaceChangesService, tripPlaceTarget, type ChangeEditor } from '../place-changes/place-changes.service';
|
||||
import { Places } from '../../db/entities/Places.entity';
|
||||
import { Tags } from '../../db/entities/Tags.entity';
|
||||
import { PlaceRatings } from '../../db/entities/PlaceRatings.entity';
|
||||
@@ -164,6 +165,7 @@ export class PlacesService {
|
||||
private readonly release: StorageReleaseService, // the images a change or a delete left unnamed (#2924)
|
||||
// Reading files and shared lists; this service only persists what it reads.
|
||||
private readonly placeImport: PlaceImportService,
|
||||
private readonly changes: PlaceChangesService, // PLC-14: the history of every details write, in its transaction
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -283,7 +285,7 @@ export class PlacesService {
|
||||
* and the storage reclaim job takes the copy like any other uploaded image. Returns a reason
|
||||
* string when the file cannot serve, the updated place otherwise.
|
||||
*/
|
||||
async setImageFromFile(tripId: string, placeId: string, fileId: number): Promise<'not_found' | 'not_image' | 'too_large' | Awaited<ReturnType<PlacesService['update']>>> {
|
||||
async setImageFromFile(tripId: string, placeId: string, fileId: number, editor: ChangeEditor = null): Promise<'not_found' | 'not_image' | 'too_large' | Awaited<ReturnType<PlacesService['update']>>> {
|
||||
const tid = toRowId(tripId);
|
||||
// PL53 — the trip's own, not-trashed attachment.
|
||||
const file = tid === null ? undefined : await this.placesRepo.findActiveTripFile(fileId, tid);
|
||||
@@ -295,7 +297,7 @@ export class PlacesService {
|
||||
const name = `${randomUUID()}${ext}`;
|
||||
const { stream } = await this.storage.getStream('files', path.basename(file.filename));
|
||||
await this.storage.put('places', name, stream, { contentType: mime });
|
||||
const updated = await this.update(tripId, placeId, { image_url: placeImageUrl(name) } as never);
|
||||
const updated = await this.update(tripId, placeId, { image_url: placeImageUrl(name) } as never, undefined, editor);
|
||||
// The copy is this request's own until the update names it, so a failed update drops it here.
|
||||
if (!updated || isUpdateConflict(updated)) await this.storage.delete('places', name).catch(() => undefined);
|
||||
return updated;
|
||||
@@ -408,8 +410,9 @@ export class PlacesService {
|
||||
placeId: string,
|
||||
body: PlaceUpdateInput,
|
||||
ifMatch?: string,
|
||||
editor: ChangeEditor = null, // who the history names (PLC-14)
|
||||
): Promise<PlaceWithTags | UpdateConflict | null> {
|
||||
const { result, previousImage } = await this.uow.transactional(() => this.applyUpdate(tripId, placeId, body, ifMatch));
|
||||
const { result, previousImage } = await this.uow.transactional(() => this.applyUpdate(tripId, placeId, body, ifMatch, editor));
|
||||
await this.release.releaseValues([previousImage]); // after the commit: kept while a copy or a cover names it
|
||||
return result;
|
||||
}
|
||||
@@ -422,7 +425,8 @@ export class PlacesService {
|
||||
tripId: string,
|
||||
placeId: string,
|
||||
body: PlaceUpdateInput,
|
||||
ifMatch?: string,
|
||||
ifMatch: string | undefined,
|
||||
editor: ChangeEditor,
|
||||
): Promise<{ result: PlaceWithTags | UpdateConflict | null; previousImage?: string | null }> {
|
||||
// PL9 — the pre-image read every `!== undefined` fallback below needs.
|
||||
// `toRowId` first (Task 3 review H1, absorbed here): every write in
|
||||
@@ -468,7 +472,7 @@ export class PlacesService {
|
||||
// `!== undefined ? x : existing.x` pre-image fallbacks are resolved to
|
||||
// their final value HERE, in the service — the repository writes
|
||||
// exactly what it is handed.
|
||||
await this.placesRepo.updatePlace(id, {
|
||||
await this.changes.track(tripPlaceTarget(id), editor, () => this.placesRepo.updatePlace(id, {
|
||||
// COALESCE(?, name): the bound value is `name || null` (falsy clears
|
||||
// to null), and `?? existingPlace.name` is the COALESCE half itself —
|
||||
// a `nativeUpdate` writes a literal value, it does not evaluate SQL
|
||||
@@ -509,7 +513,7 @@ export class PlacesService {
|
||||
stop_type: stop_type !== undefined ? stop_type : existingPlace.stop_type,
|
||||
// And how a stop that had its own fill amount goes back to following the setting.
|
||||
fill_percent: fill_percent !== undefined ? fill_percent : existingPlace.fill_percent,
|
||||
});
|
||||
}));
|
||||
|
||||
if (tags !== undefined) {
|
||||
await this.tagsRepo.deleteForPlace(id); // PL12
|
||||
@@ -680,7 +684,7 @@ export class PlacesService {
|
||||
* fields change and everything else is preserved. IDs that don't belong to the
|
||||
* trip are skipped. Returns the updated places.
|
||||
*/
|
||||
async updateMany(tripId: string, ids: number[], body: PlaceUpdateInput): Promise<PlaceWithTags[]> {
|
||||
async updateMany(tripId: string, ids: number[], body: PlaceUpdateInput, editor: ChangeEditor = null): Promise<PlaceWithTags[]> {
|
||||
if (ids.length === 0) return [];
|
||||
const updated: PlaceWithTags[] = [];
|
||||
const previousImages: (string | null | undefined)[] = [];
|
||||
@@ -688,7 +692,7 @@ export class PlacesService {
|
||||
for (const id of ids) {
|
||||
// Bulk update sends no If-Match, so applyUpdate() never returns a
|
||||
// conflict here; the guard keeps the types honest.
|
||||
const { result: place, previousImage } = await this.applyUpdate(tripId, String(id), body);
|
||||
const { result: place, previousImage } = await this.applyUpdate(tripId, String(id), body, undefined, editor);
|
||||
if (place && !isUpdateConflict(place)) updated.push(place);
|
||||
previousImages.push(previousImage);
|
||||
}
|
||||
@@ -1302,14 +1306,8 @@ export class PlacesService {
|
||||
if (place.google_place_id) return;
|
||||
if (typeof place.lat !== 'number' || typeof place.lng !== 'number') return;
|
||||
|
||||
// Rule 21 / M1 (Task 9 fix wave): non-null asserted — this whole path
|
||||
// only ever runs right after this service's own import, downstream of
|
||||
// the controller's `requireTrip` gate, which already `toRowId`-parsed
|
||||
// this same `tripId` once. Deliberately NOT applied to
|
||||
// `this.realtime.broadcast` below: every broadcast call in this domain,
|
||||
// controller included, keys the room by the raw route string, and
|
||||
// changing this one call's room shape alone would desync it from what
|
||||
// the client actually joined.
|
||||
// Rule 21 / M1: asserted, this only runs after this service's own import behind `requireTrip`, which parsed
|
||||
// this `tripId`. The broadcast below keeps the raw route string: that is the room the client joined.
|
||||
const tid = toRowId(tripId)!;
|
||||
|
||||
// Asked for a Google identity rather than for the best answer: the whole
|
||||
@@ -1331,10 +1329,8 @@ export class PlacesService {
|
||||
if (!gpid) return;
|
||||
const gftid = trimOrNull(match.google_ftid);
|
||||
|
||||
// PL43 — `fillIfEmpty`, COALESCE-per-column so enrichment only fills
|
||||
// empty columns — never overwrites data the import already captured
|
||||
// (e.g. Naver's address) or anything the user edited.
|
||||
await this.placesRepo.fillIfEmpty(place.id, tid, {
|
||||
// PL43: only the empty columns, never what the import captured (e.g. Naver's address) or the user edited.
|
||||
await this.fillTracked(place.id, tid, {
|
||||
google_place_id: gpid,
|
||||
google_ftid: gftid,
|
||||
address: trimOrNull(match.address),
|
||||
@@ -1342,26 +1338,29 @@ export class PlacesService {
|
||||
phone: trimOrNull(match.phone),
|
||||
});
|
||||
|
||||
// Photo is best-effort: Google often has none, in which case getPlacePhoto
|
||||
// resolves with photoUrl: null. A missing photo (or a provider outage, which
|
||||
// still throws) must never abort the rest of the enrichment.
|
||||
// Best-effort: Google often has no photo (photoUrl: null), and a missing one or a provider outage (which still
|
||||
// throws) must never abort the rest of the enrichment.
|
||||
try {
|
||||
const photo = await this.maps.getPlacePhoto(userId, gpid, place.lat, place.lng, place.name);
|
||||
if (photo?.photoUrl) {
|
||||
// PL44 — `fillIfEmpty`, the `image_url`-only shape.
|
||||
await this.placesRepo.fillIfEmpty(place.id, tid, { image_url: photo.photoUrl });
|
||||
}
|
||||
if (photo?.photoUrl) await this.fillTracked(place.id, tid, { image_url: photo.photoUrl }); // PL44
|
||||
} catch {
|
||||
/* no photo — leave image_url as-is */
|
||||
}
|
||||
|
||||
// PL45 — push the enriched row to every connected client (no socket
|
||||
// exclusion: the importer's own client should also receive the late
|
||||
// update — `socketId: undefined`, no `X-Socket-Id` to exclude).
|
||||
// PL45: every connected client gets the late enriched row, the importer's own included (`socketId: undefined`,
|
||||
// no `X-Socket-Id` to exclude).
|
||||
const updated = await this.placesRepo.findWithTagsAndRatings(place.id);
|
||||
if (updated) this.realtime.broadcast(tripId, 'place:updated', { place: updated }, undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
* PL43/PL44/PL46: TREK's own fill of a trip place's empty columns (COALESCE per column), and its
|
||||
* history (PLC-14), in one transaction. Each fill stands alone: network lookups sit between them.
|
||||
*/
|
||||
private fillTracked(id: number, tid: number, fill: Parameters<PlacesRepository['fillIfEmpty']>[2]): Promise<unknown> {
|
||||
return this.uow.transactional(() => this.changes.track(tripPlaceTarget(id), AUTOMATIC_CHANGE, () => this.placesRepo.fillIfEmpty(id, tid, fill)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Enrich a batch of just-imported places in the background. Never throws —
|
||||
* any per-place failure is swallowed so one bad lookup can't take down the
|
||||
@@ -1438,10 +1437,8 @@ export class PlacesService {
|
||||
timeoutMs: 10000,
|
||||
});
|
||||
if (!address) continue;
|
||||
// PL46 — `fillIfEmpty`, the `address`-only shape.
|
||||
await this.placesRepo.fillIfEmpty(place.id, tid, { address });
|
||||
// PL47 — same broadcast shape as PL45: `socketId: undefined`, no
|
||||
// exclusion.
|
||||
await this.fillTracked(place.id, tid, { address }); // PL46
|
||||
// PL47 — same broadcast shape as PL45: `socketId: undefined`, no exclusion.
|
||||
const updated = await this.placesRepo.findWithTagsAndRatings(place.id);
|
||||
if (updated) this.realtime.broadcast(tripId, 'place:updated', { place: updated }, undefined);
|
||||
} catch (err) {
|
||||
|
||||
@@ -9,7 +9,9 @@ import type { Tag } from '@trek/shared';
|
||||
* A ping rather than the tag: a delete has nothing left to send.
|
||||
*
|
||||
* `socketId` is REST's requesting tab, which updated its own list and is left
|
||||
* out; MCP passes none. The callers keep their ownership checks.
|
||||
* out; MCP passes none. The callers keep their ownership checks. A create that
|
||||
* answers a tag the user had already (one name per person, PLC-21) changed
|
||||
* nothing, so it sends nothing.
|
||||
*/
|
||||
@Injectable()
|
||||
export class TagWritesService {
|
||||
@@ -19,8 +21,8 @@ export class TagWritesService {
|
||||
) {}
|
||||
|
||||
async create(userId: number, name: string, color: string | undefined, socketId: string | undefined): Promise<Tag> {
|
||||
const tag = await this.tags.create(userId, name, color);
|
||||
this.announce(userId, socketId);
|
||||
const { tag, created } = await this.tags.ensure(userId, name, color);
|
||||
if (created) this.announce(userId, socketId);
|
||||
return tag;
|
||||
}
|
||||
|
||||
|
||||
@@ -43,7 +43,8 @@ export class TagsMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'create_tag',
|
||||
description: 'Create a new tag (user-scoped label for places).',
|
||||
description:
|
||||
'Create a personal tag (user-scoped label for places). A name stands once per person, whatever its case: when you have a tag of that name already, that tag is returned as it is (its color unchanged) and nothing new is made.',
|
||||
inputSchema: {
|
||||
name: z.string().min(1).max(100),
|
||||
color: z.string().optional().describe('Hex color string e.g. #6366f1'),
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { Tags } from '../../db/entities/Tags.entity';
|
||||
import type { TagsRepository } from '../../db/repositories/Tags.repository';
|
||||
import type { TagRow, TagsRepository } from '../../db/repositories/Tags.repository';
|
||||
import { conflict } from '../common/domain-error';
|
||||
import { toRowId } from '../common/row-id';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import type { Tag } from '@trek/shared';
|
||||
@@ -20,7 +22,10 @@ import type { Tag } from '@trek/shared';
|
||||
*/
|
||||
@Injectable()
|
||||
export class TagsService {
|
||||
constructor(@InjectRepository(Tags) private readonly tags: TagsRepository) {}
|
||||
constructor(
|
||||
@InjectRepository(Tags) private readonly tags: TagsRepository,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
// `TagRow`'s `color`/`created_at` are nullable (the DB columns carry no NOT
|
||||
// NULL constraint); the `@trek/shared` `Tag` contract narrows them to
|
||||
@@ -49,13 +54,35 @@ export class TagsService {
|
||||
return tag as unknown as Tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* A personal tag of that name, the user's own when they have one already
|
||||
* (PLC-21: a name stands once per person, whatever its case), else a new one.
|
||||
*/
|
||||
async create(userId: number, name: string, color?: string): Promise<Tag> {
|
||||
const tag = await this.tags.createTag({
|
||||
user_id: userId,
|
||||
name,
|
||||
color: color || '#10b981',
|
||||
return (await this.ensure(userId, name, color)).tag;
|
||||
}
|
||||
|
||||
/**
|
||||
* {@link create}, saying whether the tag is new. An existing one is answered
|
||||
* as it is: the color asked for is the new tag's, never a recolor of the old.
|
||||
*/
|
||||
async ensure(userId: number, name: string, color?: string): Promise<{ tag: Tag; created: boolean }> {
|
||||
return this.uow.transactional(async () => {
|
||||
const existing = await this.namesake(userId, name, null);
|
||||
if (existing) return { tag: existing as unknown as Tag, created: false };
|
||||
const tag = await this.tags.createTag({ user_id: userId, name, color: color || '#10b981' });
|
||||
return { tag: tag as unknown as Tag, created: true };
|
||||
});
|
||||
return tag as unknown as Tag;
|
||||
}
|
||||
|
||||
/** The user's other personal tag named `name` (trimmed, case ignored), or undefined. */
|
||||
private async namesake(userId: number, name: unknown, exceptId: number | null): Promise<TagRow | undefined> {
|
||||
if (typeof name !== 'string') return undefined;
|
||||
const key = name.trim().toLowerCase();
|
||||
return (await this.tags.listByUser(userId)).find(
|
||||
// A legacy row can hold a number as its name, so it is read as text.
|
||||
(tag) => tag.trip_id === null && tag.id !== exceptId && String(tag.name).trim().toLowerCase() === key,
|
||||
);
|
||||
}
|
||||
|
||||
async update(id: string | number, name?: string, color?: string): Promise<Tag> {
|
||||
@@ -79,7 +106,15 @@ export class TagsService {
|
||||
// fold into the same `?? undefined` parity the legacy re-select had.
|
||||
const rowId = toRowId(id);
|
||||
if (rowId === null) return undefined as unknown as Tag;
|
||||
return ((await this.tags.patch(rowId, changes)) ?? undefined) as unknown as Tag;
|
||||
const patched = await this.uow.transactional(async () => {
|
||||
// PLC-21: a personal tag is not renamed onto another of the same person's names.
|
||||
const [current] = await this.tags.findByIds([rowId]);
|
||||
if (changes.name && current?.trip_id === null && (await this.namesake(current.user_id, changes.name, rowId))) {
|
||||
throw conflict('A tag with this name already exists');
|
||||
}
|
||||
return await this.tags.patch(rowId, changes);
|
||||
});
|
||||
return (patched ?? undefined) as unknown as Tag;
|
||||
}
|
||||
|
||||
async remove(id: string | number): Promise<void> {
|
||||
|
||||
@@ -0,0 +1,197 @@
|
||||
/**
|
||||
* The bookings and tours a place is about (PLC-18) through the real
|
||||
* AddonGuard, JwtAuthGuard and TripAccessGuard against a migrated and seeded
|
||||
* temp SQLite db, every answer checked against its response contract.
|
||||
*/
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { PlaceActivitiesModule } from '../../src/nest/place-activities/place-activities.module';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { addTripMember } from '../helpers/factories/trips';
|
||||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
import { oneByOne } from '../helpers/one-by-one';
|
||||
import { seedPlaceActivities, type PlaceActivitiesFixture } from '../helpers/place-activities-fixture';
|
||||
import { resetTestDb } from '../helpers/test-db';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const realtime = new FakeRealtimeService();
|
||||
|
||||
let app: INestApplication;
|
||||
let server: Server;
|
||||
let orm: TestOrm;
|
||||
let f: PlaceActivitiesFixture;
|
||||
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
const tripBase = (tripId: number, placeId: number) => `/api/trips/${tripId}/places/${placeId}/activities`;
|
||||
const savedBase = (id: number | string) => `/api/addons/collections/places/${id}/activities`;
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
await TestUnitOfWorkModule.forRoot(db),
|
||||
await createTestMikroOrmModule(db),
|
||||
RealtimeModule,
|
||||
PlaceActivitiesModule,
|
||||
],
|
||||
})
|
||||
.overrideProvider(RealtimeService)
|
||||
.useValue(realtime)
|
||||
.compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.use(cookieParser());
|
||||
app.useGlobalPipes(new ZodValidationPipe());
|
||||
app.useGlobalFilters(new TrekExceptionFilter());
|
||||
await app.init();
|
||||
server = app.getHttpServer() as Server;
|
||||
orm = await createTestOrm(db);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
resetTestDb(db);
|
||||
orm.clear();
|
||||
realtime.reset();
|
||||
f = await seedPlaceActivities(orm);
|
||||
await setAddonEnabled(orm, 'collections', true);
|
||||
await setAddonEnabled(orm, 'tours', true);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
describe('Place activities e2e (real guards + temp SQLite)', () => {
|
||||
it('answers 401 without a session and 404 for a trip out of reach or a place of another trip', async () => {
|
||||
expect((await request(server).get(tripBase(f.alps.id, f.places.cafe.id))).status).toBe(401);
|
||||
const hidden = await request(server).get(tripBase(f.elsewhere.id, f.places.hidden.id)).set(as(f.me.id));
|
||||
expect(hidden.status).toBe(404);
|
||||
expect(hidden.body).toEqual({ error: 'Trip not found' });
|
||||
const foreign = await request(server).get(tripBase(f.alps.id, f.places.forum.id)).set(as(f.me.id));
|
||||
expect(foreign.status).toBe(404);
|
||||
expect(foreign.body).toEqual({ error: 'Place not found' });
|
||||
});
|
||||
|
||||
it('links a booking and a tour to a trip place, lists them with the candidates, and unlinks them', async () => {
|
||||
const cafe = f.places.cafe.id;
|
||||
const candidates = await request(server)
|
||||
.get(`${tripBase(f.alps.id, cafe)}/candidates`)
|
||||
.set(as(f.me.id));
|
||||
expect(candidates.status).toBe(200);
|
||||
expect(candidates.body.candidates.map((c: { title: string }) => c.title)).toEqual(
|
||||
expect.arrayContaining(['Guided tour', 'Old town walk', 'Ridge walk']),
|
||||
);
|
||||
|
||||
const link = await request(server)
|
||||
.post(tripBase(f.alps.id, cafe))
|
||||
.set(as(f.me.id))
|
||||
.set('X-Socket-Id', '42')
|
||||
.send({ reservation_id: f.bookings.guided.id });
|
||||
expect(link.status).toBe(200);
|
||||
expect(realtime.broadcastMock).toHaveBeenCalledWith(f.alps.id, 'placeActivities:changed', { placeId: cafe }, '42');
|
||||
await request(server).post(tripBase(f.alps.id, cafe)).set(as(f.me.id)).send({ tour_id: f.tours.walk.id });
|
||||
|
||||
const list = await request(server).get(tripBase(f.alps.id, cafe)).set(as(f.me.id));
|
||||
expect(list.status).toBe(200);
|
||||
expect(list.body.can_link).toBe(true);
|
||||
expect(list.body.activities.map((a: { key: string; explicit: boolean }) => [a.key, a.explicit])).toEqual([
|
||||
[`reservation:${f.bookings.guided.id}`, true],
|
||||
[`reservation:${f.bookings.dinner.id}`, false],
|
||||
[`tour:${f.tours.walk.id}`, true],
|
||||
]);
|
||||
|
||||
const booking = await request(server)
|
||||
.delete(`${tripBase(f.alps.id, cafe)}/reservations/${f.bookings.guided.id}`)
|
||||
.set(as(f.me.id));
|
||||
expect(booking.status).toBe(200);
|
||||
const tour = await request(server)
|
||||
.delete(`${tripBase(f.alps.id, cafe)}/tours/${f.tours.walk.id}`)
|
||||
.set(as(f.me.id));
|
||||
expect(tour.status).toBe(200);
|
||||
expect(tour.body.activities.map((a: { title: string }) => a.title)).toEqual(['Dinner']);
|
||||
});
|
||||
|
||||
it('refuses a body it does not take, a booking that belongs already and a bad id', async () => {
|
||||
const cafe = f.places.cafe.id;
|
||||
const refused = await oneByOne(
|
||||
[{}, { reservation_id: 1, tour_id: 2 }, { reservation_id: '0x5' }, { tour_id: 1.5 }, { tour_id: 1, x: 1 }],
|
||||
(body) => request(server).post(tripBase(f.alps.id, cafe)).set(as(f.me.id)).send(body),
|
||||
);
|
||||
expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400, 400]);
|
||||
const own = await request(server)
|
||||
.post(tripBase(f.alps.id, cafe))
|
||||
.set(as(f.me.id))
|
||||
.send({ reservation_id: f.bookings.dinner.id });
|
||||
expect(own.status).toBe(409);
|
||||
expect(own.body).toMatchObject({ error: 'This booking already belongs to the place' });
|
||||
const missing = await oneByOne(['abc', '0x5'], (id) =>
|
||||
request(server)
|
||||
.delete(`${tripBase(f.alps.id, cafe)}/reservations/${id}`)
|
||||
.set(as(f.me.id)),
|
||||
);
|
||||
for (const res of missing) {
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'This activity is not linked to the place' });
|
||||
}
|
||||
});
|
||||
|
||||
it('lets a member read what a place is about', async () => {
|
||||
await addTripMember(orm, f.alps.id, f.friend.id);
|
||||
const res = await request(server).get(tripBase(f.alps.id, f.places.hotel.id)).set(as(f.friend.id));
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.activities).toEqual([expect.objectContaining({ title: 'Hotel Sonne', implicit_via: 'place' })]);
|
||||
});
|
||||
|
||||
it('links a kept tour to a saved place behind the Collections addon, and reads an entry of All places', async () => {
|
||||
await setAddonEnabled(orm, 'collections', false);
|
||||
expect((await request(server).get(savedBase(f.saved.savedCafe.id)).set(as(f.me.id))).status).toBe(404);
|
||||
await setAddonEnabled(orm, 'collections', true);
|
||||
|
||||
const link = await request(server)
|
||||
.post(savedBase(f.saved.savedCafe.id))
|
||||
.set(as(f.me.id))
|
||||
.send({ collection_tour_id: f.kept.keptRidge.id });
|
||||
expect(link.status).toBe(200);
|
||||
expect(link.body.activities).toEqual([expect.objectContaining({ title: 'Kept ridge', can_unlink: true })]);
|
||||
const candidates = await request(server)
|
||||
.get(`${savedBase(f.saved.savedCafe.id)}/candidates`)
|
||||
.set(as(f.me.id));
|
||||
expect(candidates.body.candidates.map((c: { title: string }) => c.title)).toEqual(['Kept lake loop']);
|
||||
|
||||
const entry = await request(server)
|
||||
.get(`/api/addons/collections/library/places/list/${f.saved.savedCafe.id}/activities`)
|
||||
.set(as(f.me.id));
|
||||
expect(entry.status).toBe(200);
|
||||
expect(entry.body.activities.map((a: { title: string }) => a.title).sort()).toEqual(['Dinner', 'Kept ridge']);
|
||||
expect(entry.body.sources).toHaveLength(2);
|
||||
|
||||
const unlink = await request(server)
|
||||
.delete(`${savedBase(f.saved.savedCafe.id)}/tours/${f.kept.keptRidge.id}`)
|
||||
.set(as(f.me.id));
|
||||
expect(unlink.status).toBe(200);
|
||||
expect(unlink.body).toEqual({ activities: [], can_link: true });
|
||||
|
||||
const viewer = await request(server)
|
||||
.post(savedBase(f.saved.pantheon.id))
|
||||
.set(as(f.me.id))
|
||||
.send({ collection_tour_id: f.kept.keptRome.id });
|
||||
expect(viewer.status).toBe(403);
|
||||
const secret = await request(server).get(savedBase(f.saved.secret.id)).set(as(f.me.id));
|
||||
expect(secret.status).toBe(404);
|
||||
expect(secret.body).toEqual({ error: 'Place not found' });
|
||||
const bad = await request(server).get(savedBase('0x5')).set(as(f.me.id));
|
||||
expect(bad.status).toBe(404);
|
||||
expect(bad.body).toEqual({ error: 'Place not found' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,242 @@
|
||||
/**
|
||||
* PLC-14 end to end on the whole app (buildApp, the real guards, services,
|
||||
* MCP registry and a migrated temp database): the history of a place's
|
||||
* details is written by the routes and tools that change them, in their own
|
||||
* transaction, and read over the origins of an entry of All places the
|
||||
* reader reaches today. A change of a trip or list the reader cannot open
|
||||
* leaves no trace, a cleared value takes its earlier changes along, a deleted
|
||||
* place takes its history along, and the pages go on by their cursor.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { CollectionMembers } from '../../src/db/entities/CollectionMembers.entity';
|
||||
import { PlaceChangeLog } from '../../src/db/entities/PlaceChangeLog.entity';
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { addCollectionMember } from '../helpers/factories/collections';
|
||||
import { countRows, deleteRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture';
|
||||
import { resetRateLimits } from '../helpers/test-db';
|
||||
import { sessionCookie } from './harness';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index';
|
||||
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import type { PlaceHistoryPageResponse } from '@trek/shared';
|
||||
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const LIBRARY = '/api/addons/collections/library/places';
|
||||
|
||||
let app: INestApplication;
|
||||
let orm: MikroORM;
|
||||
let f: LibraryFixture;
|
||||
|
||||
const http = () => request(app.getHttpServer());
|
||||
|
||||
async function history(userId: number, kind: 'trip' | 'list', id: number, query: Record<string, string> = {}) {
|
||||
return http().get(`${LIBRARY}/${kind}/${id}/history`).query(query).set('Cookie', sessionCookie(userId));
|
||||
}
|
||||
|
||||
async function changes(userId: number, kind: 'trip' | 'list', id: number): Promise<PlaceHistoryPageResponse> {
|
||||
const res = await history(userId, kind, id);
|
||||
expect(res.status).toBe(200);
|
||||
return res.body as PlaceHistoryPageResponse;
|
||||
}
|
||||
|
||||
const fieldsOf = (page: PlaceHistoryPageResponse) => page.entries.map((entry) => entry.field);
|
||||
|
||||
async function editTripPlace(userId: number, tripId: number, placeId: number, body: object) {
|
||||
const res = await http()
|
||||
.put(`/api/trips/${tripId}/places/${placeId}`)
|
||||
.set('Cookie', sessionCookie(userId))
|
||||
.send(body);
|
||||
expect(res.status).toBe(200);
|
||||
}
|
||||
|
||||
async function editSavedPlace(userId: number, savedId: number, body: object) {
|
||||
const res = await http()
|
||||
.patch(`/api/addons/collections/places/${savedId}`)
|
||||
.set('Cookie', sessionCookie(userId))
|
||||
.send(body);
|
||||
expect(res.status).toBe(200);
|
||||
}
|
||||
|
||||
/** One tool call through a real MCP session as `userId`: its JSON answer, or its error text. */
|
||||
async function callTool(userId: number, name: string, args: Record<string, unknown>) {
|
||||
const server = createLocalMcpServer('TREK place history e2e');
|
||||
const around = (_info: unknown, call: () => unknown): unknown => withRequestContext(orm, call);
|
||||
await withRequestContext(orm, () =>
|
||||
app
|
||||
.get(McpRegistryService)
|
||||
.attach(server, { userId, scopes: null, isStaticToken: false }, { include: (kind) => kind === 'tool', around }),
|
||||
);
|
||||
const [clientTransport, serverTransport] = InMemoryTransport.createLinkedPair();
|
||||
const client = new Client({ name: 'place-history-e2e', version: '1.0.0' });
|
||||
await server.connect(serverTransport);
|
||||
await client.connect(clientTransport);
|
||||
try {
|
||||
const result = await client.callTool({ name, arguments: args });
|
||||
const content = Array.isArray(result.content) ? (result.content as Array<{ text?: string }>) : [];
|
||||
const text = content[0]?.text ?? '';
|
||||
return result.isError === true
|
||||
? { error: text, answer: null }
|
||||
: { error: null, answer: JSON.parse(text) as unknown };
|
||||
} finally {
|
||||
await client.close();
|
||||
await server.close();
|
||||
}
|
||||
}
|
||||
|
||||
beforeAll(async () => {
|
||||
app = await buildApp();
|
||||
orm = app.get(MikroORM);
|
||||
await setAddonEnabled(orm, 'collections', true);
|
||||
}, 60_000);
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetRateLimits(app);
|
||||
f = await seedLibrary(orm);
|
||||
});
|
||||
|
||||
afterAll(async () => {
|
||||
await app?.close();
|
||||
});
|
||||
|
||||
describe('the history of a place', () => {
|
||||
it('PHIST-E2E-001: records each changed field of a trip place with who changed it, newest first', async () => {
|
||||
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, {
|
||||
name: 'Café Central Wien',
|
||||
address: 'Herrengasse 14, 1010 Wien',
|
||||
// Unchanged: no row for it.
|
||||
description: 'A coffee house',
|
||||
});
|
||||
const page = await changes(f.me.id, 'trip', f.places.cafe.id);
|
||||
expect(page.next_cursor).toBeNull();
|
||||
expect(page.entries).toEqual([
|
||||
expect.objectContaining({
|
||||
field: 'address',
|
||||
old_value: 'Herrengasse 14, Wien',
|
||||
new_value: 'Herrengasse 14, 1010 Wien',
|
||||
automatic: false,
|
||||
editor: expect.objectContaining({ id: f.me.id }),
|
||||
origin: { kind: 'trip', trip_id: f.alps.id, trip_title: 'Alps', place_id: f.places.cafe.id },
|
||||
}),
|
||||
expect.objectContaining({ field: 'name', old_value: 'Café Central', new_value: 'Café Central Wien' }),
|
||||
]);
|
||||
expect(page.entries[0]?.changed_at).toMatch(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}$/);
|
||||
});
|
||||
|
||||
it('PHIST-E2E-002: one entry reads the changes of all its origins, the list ones with their list', async () => {
|
||||
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { phone: '+43 1 533' });
|
||||
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'Try the strudel' });
|
||||
const status = await http()
|
||||
.post(`/api/addons/collections/places/${f.saved.savedCafe.id}/status`)
|
||||
.set('Cookie', sessionCookie(f.me.id))
|
||||
.send({ status: 'visited' });
|
||||
expect(status.status).toBe(200);
|
||||
|
||||
const fromTrip = await changes(f.me.id, 'trip', f.places.cafe.id);
|
||||
expect(fieldsOf(fromTrip)).toEqual(['status', 'notes', 'phone']);
|
||||
expect(fromTrip.entries[0]).toEqual(
|
||||
expect.objectContaining({
|
||||
old_value: 'want',
|
||||
new_value: 'visited',
|
||||
origin: {
|
||||
kind: 'list',
|
||||
collection_id: f.lists.food.id,
|
||||
collection_name: 'Food',
|
||||
collection_place_id: f.saved.savedCafe.id,
|
||||
},
|
||||
}),
|
||||
);
|
||||
// Opened from the saved place, the same entry reads the same history.
|
||||
expect(await changes(f.me.id, 'list', f.saved.savedCafe.id)).toEqual(fromTrip);
|
||||
});
|
||||
|
||||
it('PHIST-E2E-003: shows only the changes of the origins the reader reaches, and none after access ends', async () => {
|
||||
await addCollectionMember(orm, f.lists.food.id, f.friend.id, { role: 'viewer' });
|
||||
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { notes: 'Window seat' });
|
||||
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { description: 'Viennese coffee house' });
|
||||
|
||||
// The friend reaches the list but not the trip: the trip's change is not there, nor counted anywhere.
|
||||
const friendPage = await changes(f.friend.id, 'list', f.saved.savedCafe.id);
|
||||
expect(fieldsOf(friendPage)).toEqual(['description']);
|
||||
expect(friendPage.next_cursor).toBeNull();
|
||||
expect(JSON.stringify(friendPage)).not.toContain('Window seat');
|
||||
expect((await history(f.friend.id, 'trip', f.places.cafe.id)).status).toBe(404);
|
||||
|
||||
// The stranger reaches neither; their own list's copy has a history of its own.
|
||||
expect((await history(f.stranger.id, 'list', f.saved.savedCafe.id)).status).toBe(404);
|
||||
await editSavedPlace(f.stranger.id, f.saved.secret.id, { notes: 'Secret note' });
|
||||
expect(JSON.stringify(await changes(f.me.id, 'trip', f.places.cafe.id))).not.toContain('Secret note');
|
||||
|
||||
await deleteRows(orm, CollectionMembers, { collection: f.lists.food.id, user: f.friend.id });
|
||||
expect((await history(f.friend.id, 'list', f.saved.savedCafe.id)).status).toBe(404);
|
||||
});
|
||||
|
||||
it('PHIST-E2E-004: a cleared value takes the earlier changes of its field along, and is no change itself', async () => {
|
||||
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'First' });
|
||||
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: 'Second', address: 'Herrengasse 14' });
|
||||
expect(fieldsOf(await changes(f.me.id, 'list', f.saved.savedCafe.id))).toEqual(['notes', 'address', 'notes']);
|
||||
|
||||
await editSavedPlace(f.me.id, f.saved.savedCafe.id, { notes: null });
|
||||
const page = await changes(f.me.id, 'list', f.saved.savedCafe.id);
|
||||
expect(fieldsOf(page)).toEqual(['address']);
|
||||
expect(JSON.stringify(page)).not.toContain('First');
|
||||
expect(JSON.stringify(page)).not.toContain('Try the cake');
|
||||
|
||||
// A trip place's text cleared to empty counts as cleared too.
|
||||
await editTripPlace(f.me.id, f.alps.id, f.places.museum.id, { address: 'Museumstraße 15' });
|
||||
await editTripPlace(f.me.id, f.alps.id, f.places.museum.id, { address: '' });
|
||||
expect((await changes(f.me.id, 'trip', f.places.museum.id)).entries).toEqual([]);
|
||||
});
|
||||
|
||||
it('PHIST-E2E-005: pages newest first by its cursor and refuses a cursor it never gave', async () => {
|
||||
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://a.example' });
|
||||
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://b.example' });
|
||||
await editTripPlace(f.me.id, f.alps.id, f.places.cafe.id, { website: 'https://c.example' });
|
||||
|
||||
const first = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '2' });
|
||||
expect(first.status).toBe(200);
|
||||
const one = first.body as PlaceHistoryPageResponse;
|
||||
expect(one.entries.map((entry) => entry.new_value)).toEqual(['https://c.example', 'https://b.example']);
|
||||
expect(one.next_cursor).not.toBeNull();
|
||||
|
||||
const second = await history(f.me.id, 'trip', f.places.cafe.id, { limit: '2', cursor: one.next_cursor ?? '' });
|
||||
const two = second.body as PlaceHistoryPageResponse;
|
||||
expect(two.entries.map((entry) => entry.new_value)).toEqual(['https://a.example']);
|
||||
expect(two.next_cursor).toBeNull();
|
||||
|
||||
expect((await history(f.me.id, 'trip', f.places.cafe.id, { cursor: 'abc' })).status).toBe(400);
|
||||
});
|
||||
|
||||
it('PHIST-E2E-006: a deleted place takes its history along', async () => {
|
||||
await editTripPlace(f.me.id, f.alps.id, f.places.museum.id, { name: 'Landesmuseum' });
|
||||
expect(await countRows(orm, PlaceChangeLog, { place: f.places.museum.id })).toBe(1);
|
||||
await deleteRows(orm, Places, { id: f.places.museum.id });
|
||||
expect(await countRows(orm, PlaceChangeLog, { place: f.places.museum.id })).toBe(0);
|
||||
});
|
||||
|
||||
it('PHIST-E2E-007: the MCP tools write and read the same history with the same reach', async () => {
|
||||
const updated = await callTool(f.me.id, 'update_place', {
|
||||
tripId: f.alps.id,
|
||||
placeId: f.places.cafe.id,
|
||||
address: 'Herrengasse 14, 1010 Wien',
|
||||
});
|
||||
expect(updated.error).toBeNull();
|
||||
|
||||
const read = await callTool(f.me.id, 'get_library_place_history', { kind: 'trip', id: f.places.cafe.id });
|
||||
expect(read.error).toBeNull();
|
||||
const page = read.answer as PlaceHistoryPageResponse;
|
||||
expect(page.entries).toEqual([
|
||||
expect.objectContaining({ field: 'address', editor: expect.objectContaining({ id: f.me.id }) }),
|
||||
]);
|
||||
|
||||
const refused = await callTool(f.friend.id, 'get_library_place_history', { kind: 'trip', id: f.places.cafe.id });
|
||||
expect(refused.answer).toBeNull();
|
||||
expect(refused.error).toMatch(/not found/i);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,201 @@
|
||||
/**
|
||||
* Personal tags on "All places" (PLC-21) through the real AddonGuard and
|
||||
* JwtAuthGuard against a migrated and seeded temp SQLite db, every answer
|
||||
* checked against its response contract: tagging one entry and several, the
|
||||
* tag filter in the query string, and sharing chosen personal tags with a trip
|
||||
* when a saved place is copied into it.
|
||||
*/
|
||||
import { Places } from '../../src/db/entities/Places.entity';
|
||||
import { Tags } from '../../src/db/entities/Tags.entity';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { PlacesLibraryModule } from '../../src/nest/places-library/places-library.module';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { makeTag } from '../helpers/factories/places';
|
||||
import { findRow, findRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
import { oneByOne } from '../helpers/one-by-one';
|
||||
import { seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture';
|
||||
import { resetTestDb } from '../helpers/test-db';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
|
||||
LOG_LEVEL: 'error',
|
||||
logInfo: vi.fn(),
|
||||
logDebug: vi.fn(),
|
||||
logError: vi.fn(),
|
||||
logWarn: vi.fn(),
|
||||
}));
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const LIBRARY = '/api/addons/collections/library/places';
|
||||
const TAGS = `${LIBRARY}/tags`;
|
||||
|
||||
let app: INestApplication;
|
||||
let server: Server;
|
||||
let orm: TestOrm;
|
||||
let f: LibraryFixture;
|
||||
let wine: number;
|
||||
let view: number;
|
||||
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
const keysOf = (body: { entries: { key: string }[] }) => body.entries.map((entry) => entry.key);
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
await TestUnitOfWorkModule.forRoot(db),
|
||||
await createTestMikroOrmModule(db),
|
||||
RealtimeModule,
|
||||
PlacesLibraryModule,
|
||||
],
|
||||
})
|
||||
.overrideProvider(RealtimeService)
|
||||
.useValue(new FakeRealtimeService())
|
||||
.compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.use(cookieParser());
|
||||
app.useGlobalPipes(new ZodValidationPipe());
|
||||
app.useGlobalFilters(new TrekExceptionFilter());
|
||||
await app.init();
|
||||
server = app.getHttpServer() as Server;
|
||||
orm = await createTestOrm(db);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
resetTestDb(db);
|
||||
orm.clear();
|
||||
f = await seedLibrary(orm);
|
||||
await setAddonEnabled(orm, 'collections', true);
|
||||
wine = (await makeTag(orm, f.me.id, { name: 'Wine', color: '#aa0000' })).id;
|
||||
view = (await makeTag(orm, f.me.id, { name: 'View', color: '#00aa00' })).id;
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
describe('Personal place tags e2e (real guards + temp SQLite)', () => {
|
||||
it('answers 404 while Collections is off, before any sign-in check, and 401 without a session', async () => {
|
||||
await setAddonEnabled(orm, 'collections', false);
|
||||
expect((await request(server).put(TAGS).send({ key: 'trip:1', tag_ids: [] })).status).toBe(404);
|
||||
await setAddonEnabled(orm, 'collections', true);
|
||||
expect((await request(server).put(TAGS).send({ key: 'trip:1', tag_ids: [] })).status).toBe(401);
|
||||
expect(
|
||||
(
|
||||
await request(server)
|
||||
.post(`${TAGS}/bulk`)
|
||||
.send({ keys: ['trip:1'], add: [1] })
|
||||
).status,
|
||||
).toBe(401);
|
||||
});
|
||||
|
||||
it('tags one entry and several, and filters the list by the tags in the query string', async () => {
|
||||
const cafe = `trip:${f.places.cafe.id}`;
|
||||
const pantheon = `list:${f.saved.pantheon.id}`;
|
||||
const set = await request(server)
|
||||
.put(TAGS)
|
||||
.set(as(f.me.id))
|
||||
.send({ key: cafe, tag_ids: [wine] });
|
||||
expect(set.status).toBe(200);
|
||||
expect(set.body.entry.tags).toEqual([{ id: wine, name: 'Wine', color: '#aa0000' }]);
|
||||
|
||||
const bulk = await request(server)
|
||||
.post(`${TAGS}/bulk`)
|
||||
.set(as(f.me.id))
|
||||
.send({ keys: [pantheon, cafe], add: [view] });
|
||||
expect(bulk.status).toBe(200);
|
||||
expect(keysOf(bulk.body)).toEqual([pantheon, cafe]);
|
||||
expect(bulk.body.entries[1].tags.map((tag: { name: string }) => tag.name)).toEqual(['View', 'Wine']);
|
||||
|
||||
const filtered = await request(server)
|
||||
.get(LIBRARY)
|
||||
.query({ tag_ids: String(wine) })
|
||||
.set(as(f.me.id));
|
||||
expect(filtered.status).toBe(200);
|
||||
expect(keysOf(filtered.body)).toEqual([cafe]);
|
||||
expect(filtered.body.counts).toEqual({ all: 1, trip: 1, list: 1 });
|
||||
const both = await request(server)
|
||||
.get(LIBRARY)
|
||||
.query({ tag_ids: `${wine},${view}` })
|
||||
.set(as(f.me.id));
|
||||
expect(both.body.total).toBe(2);
|
||||
const detail = await request(server).get(`${LIBRARY}/list/${f.saved.pantheon.id}`).set(as(f.me.id));
|
||||
expect(detail.body.entry.tags).toEqual([{ id: view, name: 'View', color: '#00aa00' }]);
|
||||
const friends = await request(server)
|
||||
.get(LIBRARY)
|
||||
.query({ tag_ids: String(wine) })
|
||||
.set(as(f.friend.id));
|
||||
expect(friends.body.total).toBe(0);
|
||||
});
|
||||
|
||||
it('refuses malformed bodies and filters, foreign tags and entries out of reach', async () => {
|
||||
const theirs = (await makeTag(orm, f.friend.id, { name: 'Theirs' })).id;
|
||||
const bad = await oneByOne(
|
||||
[
|
||||
{ key: 'trip:abc', tag_ids: [] },
|
||||
{ key: 'trip:1', tag_ids: [1.5] },
|
||||
{ key: 'trip:1', tag_ids: [], extra: true },
|
||||
],
|
||||
(body) => request(server).put(TAGS).set(as(f.me.id)).send(body),
|
||||
);
|
||||
expect(bad.map((res) => res.status)).toEqual([400, 400, 400]);
|
||||
const badBulk = await oneByOne(
|
||||
[{ keys: ['trip:1'] }, { keys: [], add: [1] }, { keys: ['trip:1'], add: [1], remove: [1] }],
|
||||
(body) => request(server).post(`${TAGS}/bulk`).set(as(f.me.id)).send(body),
|
||||
);
|
||||
expect(badBulk.map((res) => res.status)).toEqual([400, 400, 400]);
|
||||
const badQuery = await oneByOne(['0x5', '1,,2', '1.5', ''], (tagIds) =>
|
||||
request(server).get(LIBRARY).query({ tag_ids: tagIds }).set(as(f.me.id)),
|
||||
);
|
||||
expect(badQuery.map((res) => res.status)).toEqual([400, 400, 400, 400]);
|
||||
|
||||
const foreign = await request(server)
|
||||
.put(TAGS)
|
||||
.set(as(f.me.id))
|
||||
.send({ key: `trip:${f.places.cafe.id}`, tag_ids: [theirs] });
|
||||
expect(foreign.status).toBe(404);
|
||||
expect(foreign.body).toEqual({ error: 'Tag not found' });
|
||||
const hidden = await request(server)
|
||||
.post(`${TAGS}/bulk`)
|
||||
.set(as(f.me.id))
|
||||
.send({ keys: [`list:${f.saved.secret.id}`], add: [wine] });
|
||||
expect(hidden.status).toBe(404);
|
||||
expect(hidden.body).toEqual({ error: 'Place not found' });
|
||||
});
|
||||
|
||||
it('shares only the chosen personal tags with a trip when a saved place is copied into it', async () => {
|
||||
await makeTag(orm, f.me.id, { name: 'wine', trip: f.alps.id, color: '#111111' });
|
||||
const res = await request(server)
|
||||
.post('/api/addons/collections/copy-to-trip')
|
||||
.set(as(f.me.id))
|
||||
.send({ trip_id: f.alps.id, place_ids: [f.saved.pantheon.id], personal_tag_ids: [wine, view, 999999] });
|
||||
expect(res.status).toBe(200);
|
||||
const placeId = res.body.created[0].id as number;
|
||||
expect(await findRow(orm, Places, { id: placeId })).not.toBeNull();
|
||||
const tripTags = await findRows(orm, Tags, { trip: f.alps.id }, { name: 'asc' });
|
||||
// The trip's own "wine" is reused, whatever its case; "View" becomes a new trip tag.
|
||||
expect(tripTags.map((tag) => tag.name)).toEqual(['View', 'wine']);
|
||||
const personal = await findRows(orm, Tags, { user: f.me.id, trip: null });
|
||||
expect(personal.map((tag) => tag.id).sort((a, b) => a - b)).toEqual([wine, view].sort((a, b) => a - b));
|
||||
|
||||
const none = await request(server)
|
||||
.post('/api/addons/collections/copy-to-trip')
|
||||
.set(as(f.me.id))
|
||||
.send({ trip_id: f.alps.id, place_ids: [f.saved.lunch.id], force: true });
|
||||
expect(none.status).toBe(200);
|
||||
expect(await findRows(orm, Tags, { trip: f.alps.id })).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* Visits read from the trips (D7/PLC-10 to PLC-23) through the real
|
||||
* JwtAuthGuard, TripAccessGuard and AddonGuard against a migrated and seeded
|
||||
* temp SQLite db, the visit clock pinned on the second day of the fixture's
|
||||
* trip Alps: the history and the counts on All places, the trip's visited
|
||||
* places, the list, the stop's participants, losing access, the refused
|
||||
* queries, that nothing can be written, and the media of an entry.
|
||||
*/
|
||||
import { AssignmentParticipants } from '../../src/db/entities/AssignmentParticipants.entity';
|
||||
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
|
||||
import { TripMembers } from '../../src/db/entities/TripMembers.entity';
|
||||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||||
import { PlaceVisitsClock } from '../../src/nest/places-library/place-visits.clock';
|
||||
import { PlaceVisitsModule } from '../../src/nest/places-library/place-visits.module';
|
||||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||||
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
|
||||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||||
import { makeDayAssignment } from '../helpers/factories/itinerary';
|
||||
import { createRow, deleteRows, findRow } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||||
import { addTripMember, makeDay, readTripDays } from '../helpers/factories/trips';
|
||||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||||
import { oneByOne } from '../helpers/one-by-one';
|
||||
import { seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture';
|
||||
import { resetTestDb } from '../helpers/test-db';
|
||||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||||
import { sessionCookie } from './harness';
|
||||
import type { INestApplication } from '@nestjs/common';
|
||||
import { Test } from '@nestjs/testing';
|
||||
|
||||
import cookieParser from 'cookie-parser';
|
||||
import type { Server } from 'http';
|
||||
import request from 'supertest';
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const db = createSnapshotTestDb();
|
||||
const realtime = new FakeRealtimeService();
|
||||
|
||||
let app: INestApplication;
|
||||
let server: Server;
|
||||
let orm: TestOrm;
|
||||
let f: LibraryFixture;
|
||||
|
||||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||||
const VISITS = '/api/place-visits';
|
||||
const LIBRARY = '/api/addons/collections/library/places';
|
||||
const TODAY = '2026-07-02';
|
||||
|
||||
beforeAll(async () => {
|
||||
const moduleRef = await Test.createTestingModule({
|
||||
imports: [
|
||||
await TestUnitOfWorkModule.forRoot(db),
|
||||
await createTestMikroOrmModule(db),
|
||||
RealtimeModule,
|
||||
PlaceVisitsModule,
|
||||
],
|
||||
})
|
||||
.overrideProvider(RealtimeService)
|
||||
.useValue(realtime)
|
||||
.compile();
|
||||
app = moduleRef.createNestApplication();
|
||||
app.use(cookieParser());
|
||||
app.useGlobalPipes(new ZodValidationPipe());
|
||||
app.useGlobalFilters(new TrekExceptionFilter());
|
||||
await app.init();
|
||||
server = app.getHttpServer() as Server;
|
||||
orm = await createTestOrm(db);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
resetTestDb(db);
|
||||
orm.clear();
|
||||
realtime.reset();
|
||||
vi.restoreAllMocks();
|
||||
vi.spyOn(app.get(PlaceVisitsClock), 'today').mockReturnValue(TODAY);
|
||||
f = await seedLibrary(orm);
|
||||
await setAddonEnabled(orm, 'collections', true);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await app.close();
|
||||
await orm.close();
|
||||
db.close();
|
||||
});
|
||||
|
||||
async function entryOf(userId: number, key: string) {
|
||||
const res = await request(server).get(LIBRARY).set(as(userId));
|
||||
expect(res.status).toBe(200);
|
||||
return res.body.entries.find((row: { key: string }) => row.key === key);
|
||||
}
|
||||
|
||||
describe('Place visits e2e (real guards + temp SQLite)', () => {
|
||||
it('answers 401 without a session and refuses queries it does not take', async () => {
|
||||
expect((await request(server).get(VISITS)).status).toBe(401);
|
||||
expect((await request(server).get(`/api/trips/${f.alps.id}/place-visits/mine`)).status).toBe(401);
|
||||
const refused = await oneByOne(
|
||||
[{ kind: 'own', id: '1' }, { kind: 'trip', id: '0x5' }, { kind: 'trip' }, { kind: 'trip', id: '1', extra: '1' }],
|
||||
(query) => request(server).get(`${VISITS}/place`).query(query).set(as(f.me.id)),
|
||||
);
|
||||
expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400]);
|
||||
const list = await oneByOne([{ limit: '0' }, { limit: '201' }, { trip_id: 'abc' }], (query) =>
|
||||
request(server).get(VISITS).query(query).set(as(f.me.id)),
|
||||
);
|
||||
expect(list.map((res) => res.status)).toEqual([400, 400, 400]);
|
||||
});
|
||||
|
||||
it('has nothing to write: confirming, correcting and deleting a visit are gone', async () => {
|
||||
const tries = await oneByOne(
|
||||
[
|
||||
() =>
|
||||
request(server).post(VISITS).set(as(f.me.id)).send({ visited_on: '2026-07-01', place_id: f.places.cafe.id }),
|
||||
() => request(server).patch(`${VISITS}/1`).set(as(f.me.id)).send({ note: 'x' }),
|
||||
() => request(server).delete(`${VISITS}/1`).set(as(f.me.id)),
|
||||
() => request(server).get(`${VISITS}/candidates`).set(as(f.me.id)),
|
||||
() => request(server).get(`/api/trips/${f.alps.id}/place-visits/suggestions`).set(as(f.me.id)),
|
||||
],
|
||||
(call) => call(),
|
||||
);
|
||||
expect(tries.map((res) => res.status)).toEqual([404, 404, 404, 404, 404]);
|
||||
});
|
||||
|
||||
it('reads the history and the counts of All places from the dated days that have come', async () => {
|
||||
const [, day2, day3] = await readTripDays(orm, f.alps.id);
|
||||
if (!day2 || !day3) throw new Error('Alps has three days');
|
||||
await makeDayAssignment(orm, day2.id, f.places.cafe.id, { assignment_time: '12:00' });
|
||||
await makeDayAssignment(orm, day2.id, f.places.cafe.id, { assignment_time: '10:00' });
|
||||
await makeDayAssignment(orm, day3.id, f.places.cafe.id);
|
||||
const undated = await makeDay(orm, f.alps.id, { date: null });
|
||||
await makeDayAssignment(orm, undated.id, f.places.museum.id);
|
||||
|
||||
const history = await request(server)
|
||||
.get(`${VISITS}/place`)
|
||||
.query({ kind: 'list', id: f.saved.savedCafe.id })
|
||||
.set(as(f.me.id));
|
||||
expect(history.status).toBe(200);
|
||||
expect(history.body).toMatchObject({ visit_count: 2, last_visit: TODAY });
|
||||
expect(
|
||||
history.body.visits.map((v: { visited_on: string; visited_time: string }) => [v.visited_on, v.visited_time]),
|
||||
).toEqual([
|
||||
[TODAY, '10:00'],
|
||||
['2026-07-01', '09:00'],
|
||||
]);
|
||||
expect(await entryOf(f.me.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 2, last_visit: TODAY });
|
||||
expect(await entryOf(f.me.id, `trip:${f.places.museum.id}`)).toMatchObject({ visit_count: 0, last_visit: null });
|
||||
|
||||
const mine = await request(server).get(`/api/trips/${f.alps.id}/place-visits/mine`).set(as(f.me.id));
|
||||
expect(mine.body).toEqual({
|
||||
place_ids: [f.places.cafe.id],
|
||||
places: [{ place_id: f.places.cafe.id, visit_count: 2, last_visit: TODAY }],
|
||||
});
|
||||
const list = await request(server).get(VISITS).query({ limit: '1' }).set(as(f.me.id));
|
||||
expect(list.body).toMatchObject({ total: 2, visits: [{ visited_on: TODAY, trip: { id: f.alps.id } }] });
|
||||
});
|
||||
|
||||
it('counts a stop for its participants only, and nothing once the trip is out of reach', async () => {
|
||||
await addTripMember(orm, f.alps.id, f.friend.id);
|
||||
await createRow(orm, AssignmentParticipants, { assignment: (await firstCafeStop()).id, user: f.friend.id });
|
||||
expect(await entryOf(f.me.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 0 });
|
||||
expect(await entryOf(f.friend.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 1 });
|
||||
|
||||
await deleteRows(orm, TripMembers, { trip: f.alps.id, user: f.friend.id });
|
||||
expect((await request(server).get(VISITS).set(as(f.friend.id))).body).toEqual({ visits: [], total: 0 });
|
||||
expect((await request(server).get(`/api/trips/${f.alps.id}/place-visits/mine`).set(as(f.friend.id))).status).toBe(
|
||||
404,
|
||||
);
|
||||
});
|
||||
|
||||
it('reads the media of an entry behind the Collections addon; the visits are no addon’s', async () => {
|
||||
const media = await request(server).get(`${LIBRARY}/trip/${f.places.cafe.id}/media`).set(as(f.me.id));
|
||||
expect(media.status).toBe(200);
|
||||
expect(media.body).toEqual({ images: [], journey_photos: [], files: [] });
|
||||
await setAddonEnabled(orm, 'collections', false);
|
||||
expect((await request(server).get(`${LIBRARY}/trip/${f.places.cafe.id}/media`).set(as(f.me.id))).status).toBe(404);
|
||||
expect((await request(server).get(VISITS).set(as(f.me.id))).status).toBe(200);
|
||||
});
|
||||
});
|
||||
|
||||
/** The stop that plans Café Central on the first day of Alps in the fixture. */
|
||||
async function firstCafeStop() {
|
||||
const stop = await findRow(orm, DayAssignments, { day: f.day1.id, place: f.places.cafe.id });
|
||||
if (!stop) throw new Error('the fixture plans Café Central on day 1');
|
||||
return stop;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
/**
|
||||
* PLC-18: the bookings and tours a place names, and the tours a list keeps
|
||||
* for a saved place to name, seeded through the ORM like the app writes them.
|
||||
*/
|
||||
import { CollectionTours } from '../../../src/db/entities/CollectionTours.entity';
|
||||
import { PlaceActivityLinks } from '../../../src/db/entities/PlaceActivityLinks.entity';
|
||||
import type { FactoryOrm } from './context';
|
||||
import { createRow } from './rows';
|
||||
import type { EntityDTO, EntityData } from '@mikro-orm/core';
|
||||
|
||||
export type KeptTourRow = EntityDTO<CollectionTours>;
|
||||
export type PlaceActivityLinkRow = EntityDTO<PlaceActivityLinks>;
|
||||
|
||||
/** A hike kept in the list `collectionId`, with no line and no points. */
|
||||
export function makeKeptTour(
|
||||
orm: FactoryOrm,
|
||||
collectionId: number,
|
||||
overrides: EntityData<CollectionTours> = {},
|
||||
): Promise<KeptTourRow> {
|
||||
return createRow(
|
||||
orm,
|
||||
CollectionTours,
|
||||
{
|
||||
collection: collectionId,
|
||||
name: 'Kept ridge',
|
||||
waypoints: '[]',
|
||||
tourTypeRef: 'hike',
|
||||
origin: 'trek',
|
||||
source_trip_title: 'Alps',
|
||||
source_tour_name: 'Ridge',
|
||||
},
|
||||
overrides,
|
||||
);
|
||||
}
|
||||
|
||||
/** A link of a trip place to a booking or a tour (its place), or of a saved place to a kept tour. */
|
||||
export function linkPlaceActivity(
|
||||
orm: FactoryOrm,
|
||||
link:
|
||||
| { place: number; reservation: number }
|
||||
| { place: number; tourPlace: number }
|
||||
| { collectionPlace: number; collectionTour: number },
|
||||
linkedBy: number | null = null,
|
||||
): Promise<PlaceActivityLinkRow> {
|
||||
return createRow(orm, PlaceActivityLinks, { ...link, linkedByRef: linkedBy });
|
||||
}
|
||||
@@ -15,6 +15,7 @@ import { WikimediaClient } from '../../src/nest/maps/providers/wikimedia.client'
|
||||
import type { PlacePhotoCacheService } from '../../src/nest/place-photos/place-photo-cache.service';
|
||||
import { noGoogleQuota } from './google-quota';
|
||||
import { photonOff } from './photon';
|
||||
import { passThroughPlaceChanges } from './place-changes';
|
||||
|
||||
/** MapsService and the outbound clients it was wired with, for tests that reach a client directly. */
|
||||
export interface MapsParts {
|
||||
@@ -43,7 +44,7 @@ export function buildMapsParts(
|
||||
const osm = new OsmClient(photonOff());
|
||||
const wiki = new WikimediaClient();
|
||||
const selector = new PlacesProviderSelector(appSettings, users, googleQuota);
|
||||
const photos = new PlacePhotoResolver(photoCache, places, google, wiki, selector);
|
||||
const photos = new PlacePhotoResolver(photoCache, places, google, wiki, selector, passThroughPlaceChanges());
|
||||
const links = new MapsUrlResolver(osm);
|
||||
const details = new PlaceDetailsResolver(placeDetailsCache, google, osm, selector);
|
||||
const along = new PoisAlongResolver(osm);
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* The bookings and tours the place activity suites (PLC-18) read, on top of
|
||||
* the All places fixture (`seedLibrary`): in Alps, a guided tour booking on
|
||||
* no place and a dinner booked against Café Central's plan entry; a lake
|
||||
* cabin booking against the stay at Camp Lake; the tour Ridge walk with a
|
||||
* station standing for Museum, and a second tour, Old town walk, on no place.
|
||||
* Food keeps two tours. Hotel Sonne's own booking names the place already.
|
||||
*/
|
||||
import { DayAccommodations } from '../../src/db/entities/DayAccommodations.entity';
|
||||
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
|
||||
import type { FactoryOrm } from './factories/context';
|
||||
import { makeKeptTour } from './factories/place-activities';
|
||||
import { makePlace } from './factories/places';
|
||||
import { makeReservation } from './factories/reservations';
|
||||
import { findRow } from './factories/rows';
|
||||
import { addTourWaypoints, makeTour } from './factories/tours';
|
||||
import { seedLibrary } from './places-library-fixture';
|
||||
|
||||
export async function seedPlaceActivities(orm: FactoryOrm) {
|
||||
const f = await seedLibrary(orm);
|
||||
const { alps, places, lists, day1 } = f;
|
||||
const guided = await makeReservation(orm, alps.id, {
|
||||
title: 'Guided tour',
|
||||
type: 'tour',
|
||||
status: 'confirmed',
|
||||
reservation_time: '2026-07-01T10:00',
|
||||
day: day1.id,
|
||||
});
|
||||
const plan = await findRow(orm, DayAssignments, { place: places.cafe.id });
|
||||
if (!plan) throw new Error('seedPlaceActivities: Café Central has no plan entry');
|
||||
const dinner = await makeReservation(orm, alps.id, { title: 'Dinner', type: 'restaurant', assignment: plan.id });
|
||||
const stay = await findRow(orm, DayAccommodations, { place: places.camp.id });
|
||||
if (!stay) throw new Error('seedPlaceActivities: Camp Lake has no stay');
|
||||
const cabin = await makeReservation(orm, alps.id, {
|
||||
title: 'Lake cabin',
|
||||
type: 'hotel',
|
||||
accommodation_id: `${stay.id}.0`,
|
||||
});
|
||||
await addTourWaypoints(orm, places.ridge.id, [
|
||||
{ lat: 47.26, lng: 11.39 },
|
||||
{ lat: 47.2681, lng: 11.3933, linkedPlace: places.museum.id },
|
||||
{ lat: 47.27, lng: 11.4 },
|
||||
]);
|
||||
const walk = await makePlace(orm, alps.id, { name: 'Old town walk' });
|
||||
await makeTour(orm, walk.id, { tourTypeRef: 'walk' });
|
||||
const keptRidge = await makeKeptTour(orm, lists.food.id, { name: 'Kept ridge' });
|
||||
const keptLake = await makeKeptTour(orm, lists.food.id, { name: 'Kept lake loop' });
|
||||
const keptRome = await makeKeptTour(orm, lists.sights.id, { name: 'Rome by night' });
|
||||
return { ...f, bookings: { guided, dinner, cabin }, tours: { walk }, kept: { keptRidge, keptLake, keptRome } };
|
||||
}
|
||||
|
||||
export type PlaceActivitiesFixture = Awaited<ReturnType<typeof seedPlaceActivities>>;
|
||||
@@ -0,0 +1,13 @@
|
||||
import type { PlaceChangesService } from '../../src/nest/place-changes/place-changes.service';
|
||||
|
||||
/**
|
||||
* A PlaceChangesService for the suites that build a places or collections
|
||||
* service by hand and are about something else: it runs every write and
|
||||
* records no history. The history itself is tested in
|
||||
* tests/unit/nest/place-changes/ and tests/e2e/place-history.e2e.test.ts.
|
||||
*/
|
||||
export function passThroughPlaceChanges(): PlaceChangesService {
|
||||
return {
|
||||
track: <T>(_targets: unknown, _editor: unknown, write: () => Promise<T>) => write(),
|
||||
} as unknown as PlaceChangesService;
|
||||
}
|
||||
@@ -134,6 +134,7 @@ import {
|
||||
createTestPackingTemplateCategoriesRepo,
|
||||
createTestPackingTemplateItemsRepo,
|
||||
} from './packing-repos';
|
||||
import { passThroughPlaceChanges } from './place-changes';
|
||||
import { buildPlaceImportService } from './place-import';
|
||||
import { createTestVacayHolidayCalendarsRepo, createTestSchoolHolidayRegionsRepo } from './school-holidays-repos';
|
||||
import { createTestShareTokensRepo, createTestPluginsRepo, createTestPluginUserErasureQueueRepo } from './share-repos';
|
||||
@@ -465,6 +466,7 @@ export async function createPluginRpcHostParts(
|
||||
await createTestBudgetItemsRepo(db),
|
||||
{ releaseValues: async () => [] } as never, // StorageReleaseService
|
||||
buildPlaceImportService(),
|
||||
passThroughPlaceChanges(),
|
||||
);
|
||||
// After places: copying saved places into a trip runs the places journey hook.
|
||||
const collections = new CollectionsService(
|
||||
@@ -494,6 +496,7 @@ export async function createPluginRpcHostParts(
|
||||
usersRepo,
|
||||
buildPlaceImportService(),
|
||||
places,
|
||||
passThroughPlaceChanges(),
|
||||
);
|
||||
// After accommodations: a hotel booking writes the stay's day stop through it.
|
||||
const reservations = new ReservationsService(
|
||||
@@ -576,7 +579,7 @@ export async function createPluginRpcHostParts(
|
||||
const guards = new PluginGuards(await createTestTripsRepo(db), permissions, addons, usersRepo);
|
||||
|
||||
const controllers: object[] = [
|
||||
new TagsRpc(new TagsService(await createTestTagsRepo(db))),
|
||||
new TagsRpc(new TagsService(await createTestTagsRepo(db), await createTestUnitOfWork(db))),
|
||||
new CategoriesRpc(new CategoriesService(await createTestCategoriesRepo(db))),
|
||||
new WeatherRpc(new WeatherService()),
|
||||
new ExchangeRatesRpc(exchangeRates),
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { ListImportResult } from '../../../src/nest/places/places.helpers';
|
||||
import { PlacesService } from '../../../src/nest/places/places.service';
|
||||
import { StorageService } from '../../../src/nest/storage/storage.service';
|
||||
import { makeDayAssignment } from '../../helpers/factories/itinerary';
|
||||
import { linkPlaceActivity } from '../../helpers/factories/place-activities';
|
||||
import { makeTag } from '../../helpers/factories/places';
|
||||
import { insertRow, updateRows } from '../../helpers/factories/rows';
|
||||
import { linkTripCollection } from '../../helpers/factories/user-places';
|
||||
@@ -403,6 +404,31 @@ export const plan: CaseGroup = {
|
||||
rest: { method: 'delete', path: (s) => `/api/trips/${s.trip.id}/collections/${s.collection.id}` },
|
||||
expect: ['tripCollections:changed'],
|
||||
},
|
||||
{
|
||||
// PLC-18: the members' place detail reads the place's activities again.
|
||||
tool: 'link_place_activity',
|
||||
needs: ['place', 'transport'],
|
||||
args: (s) => ({ tripId: s.trip.id, placeId: s.place.id, reservation_id: s.transport.id }),
|
||||
rest: {
|
||||
method: 'post',
|
||||
path: (s) => `/api/trips/${s.trip.id}/places/${s.place.id}/activities`,
|
||||
body: (s) => ({ reservation_id: s.transport.id }),
|
||||
},
|
||||
expect: ['placeActivities:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'unlink_place_activity',
|
||||
needs: ['place', 'tour'],
|
||||
setup: async (s, app) => {
|
||||
await linkPlaceActivity(app.get(MikroORM), { place: s.place.id, tourPlace: s.tourPlace.id });
|
||||
},
|
||||
args: (s) => ({ tripId: s.trip.id, placeId: s.place.id, tour_id: s.tourPlace.id }),
|
||||
rest: {
|
||||
method: 'delete',
|
||||
path: (s) => `/api/trips/${s.trip.id}/places/${s.place.id}/activities/tours/${s.tourPlace.id}`,
|
||||
},
|
||||
expect: ['placeActivities:changed'],
|
||||
},
|
||||
{
|
||||
tool: 'create_day_note',
|
||||
args: (s) => ({ tripId: s.trip.id, dayId: s.days[0].id, text: 'Bring the museum pass' }),
|
||||
|
||||
@@ -19,6 +19,8 @@ import { PlaceIdentitiesService } from '../../../src/nest/places-library/place-i
|
||||
import { addCollectionMember } from '../../helpers/factories/collections';
|
||||
import { inContext } from '../../helpers/factories/context';
|
||||
import { addJourneyContributor, linkTripToJourney, makeJourneyEntry } from '../../helpers/factories/journeys';
|
||||
import { linkPlaceActivity, makeKeptTour } from '../../helpers/factories/place-activities';
|
||||
import { makeTag } from '../../helpers/factories/places';
|
||||
import { createRow, insertRow, updateRows } from '../../helpers/factories/rows';
|
||||
import { linkUserPlace, makeUserPlace } from '../../helpers/factories/user-places';
|
||||
import { addVacayPlanMember } from '../../helpers/factories/vacay';
|
||||
@@ -56,6 +58,13 @@ async function mergedPlaces(s: Scene, app: INestApplication): Promise<void> {
|
||||
);
|
||||
keep(s, 'merge', merged.merge_id);
|
||||
}
|
||||
const PERSONAL_TAGS =
|
||||
"puts the caller's own personal tags on entries of All places (PLC-21): no trip place or saved place is written and nobody else sees them, so there is nothing to send";
|
||||
|
||||
/** A personal tag of the owner, for tagging the scene's places. */
|
||||
async function personalTag(s: Scene, app: INestApplication): Promise<void> {
|
||||
keep(s, 'tag', (await makeTag(ormOf(app), s.owner.id, { name: `Personal ${s.n}` })).id);
|
||||
}
|
||||
const TOKEN_ONLY = 'manages a public link token: nothing on any screen follows it live, so there is nothing to send';
|
||||
const onJourney = (s: Scene) => ({ journeyId: s.journey.id });
|
||||
const WINTER = { name: 'Winter', startDate: '2027-02-01', endDate: '2027-02-12' };
|
||||
@@ -1068,6 +1077,36 @@ const collectionCases: ParityCase[] = [
|
||||
{ event: 'collections:removed', user: 'actor' },
|
||||
],
|
||||
},
|
||||
{
|
||||
// PLC-18: the list's members read the saved place's kept tours again.
|
||||
tool: 'link_saved_place_tour',
|
||||
needs: ['collection'],
|
||||
setup: async (s, app) => {
|
||||
keep(s, 'keptTour', (await makeKeptTour(ormOf(app), s.collection.id, { name: `Kept ridge ${s.n}` })).id);
|
||||
},
|
||||
args: (s) => ({ collection_place_id: s.collectionPlace.id, collection_tour_id: kept(s, 'keptTour') }),
|
||||
rest: {
|
||||
method: 'post',
|
||||
path: (s) => `${COLLECTIONS}/places/${s.collectionPlace.id}/activities`,
|
||||
body: (s) => ({ collection_tour_id: kept(s, 'keptTour') }),
|
||||
},
|
||||
expect: [{ event: 'collections:updated', user: 'actor' }],
|
||||
},
|
||||
{
|
||||
tool: 'unlink_saved_place_tour',
|
||||
needs: ['collection'],
|
||||
setup: async (s, app) => {
|
||||
const tour = await makeKeptTour(ormOf(app), s.collection.id, { name: `Kept ridge ${s.n}` });
|
||||
await linkPlaceActivity(ormOf(app), { collectionPlace: s.collectionPlace.id, collectionTour: tour.id });
|
||||
keep(s, 'keptTour', tour.id);
|
||||
},
|
||||
args: (s) => ({ collection_place_id: s.collectionPlace.id, collection_tour_id: kept(s, 'keptTour') }),
|
||||
rest: {
|
||||
method: 'delete',
|
||||
path: (s) => `${COLLECTIONS}/places/${s.collectionPlace.id}/activities/tours/${kept(s, 'keptTour')}`,
|
||||
},
|
||||
expect: [{ event: 'collections:updated', user: 'actor' }],
|
||||
},
|
||||
];
|
||||
|
||||
/** The page ids of the scenes' books, in page order, so the tools can name them. */
|
||||
@@ -1358,6 +1397,20 @@ export const user: CaseGroup = {
|
||||
setup: mergedPlaces,
|
||||
args: (s) => ({ merge_id: kept(s, 'merge') }),
|
||||
},
|
||||
{
|
||||
tool: 'set_library_place_tags',
|
||||
reason: PERSONAL_TAGS,
|
||||
needs: ['place'],
|
||||
setup: personalTag,
|
||||
args: (s) => ({ key: `trip:${s.place.id}`, tag_ids: [kept(s, 'tag')] }),
|
||||
},
|
||||
{
|
||||
tool: 'tag_library_places',
|
||||
reason: PERSONAL_TAGS,
|
||||
needs: ['place', 'place2'],
|
||||
setup: personalTag,
|
||||
args: (s) => ({ keys: [`trip:${s.place.id}`, `trip:${s.place2.id}`], add: [kept(s, 'tag')] }),
|
||||
},
|
||||
{
|
||||
tool: 'create_manual_school_holiday_country',
|
||||
reason: HOLIDAY_CATALOG,
|
||||
|
||||
@@ -63,14 +63,17 @@ describe('ALL_ENTITIES', () => {
|
||||
* + trip_addon_overrides, the owner's per-trip on or off for a trip addon
|
||||
* + user_places, user_place_links, user_place_merges and user_place_merge_dismissals,
|
||||
* a user's own place identities, the uses they group, the merges and the dismissed pairs
|
||||
* + trip_collection_links, the lists a trip links)
|
||||
* + trip_collection_links, the lists a trip links
|
||||
* + place_change_log, what changed in the details of a trip place or a saved place
|
||||
* + place_activity_links, the bookings and tours a trip place or a saved place names
|
||||
* + personal_place_tags, the personal tags a user put on the entries of All places)
|
||||
* is registered, and no two share a class name (a silent duplicate would
|
||||
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
|
||||
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
|
||||
* which de-duplicates by class name).
|
||||
*/
|
||||
it('ENT-003: exactly 179 entities, every class name unique', () => {
|
||||
expect(ALL_ENTITIES.length).toBe(179);
|
||||
it('ENT-003: exactly 182 entities, every class name unique', () => {
|
||||
expect(ALL_ENTITIES.length).toBe(182);
|
||||
const names = ALL_ENTITIES.map((s) => s.meta.className);
|
||||
expect(new Set(names).size).toBe(names.length);
|
||||
});
|
||||
|
||||
@@ -70,7 +70,10 @@ import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
// + user_places: id, user_id, name; user_place_links: id, user_place_id, user_id; user_place_merges: id, user_id,
|
||||
// leading_id, merged_id, moved_link_ids; user_place_merge_dismissals: id, user_id, key_a, key_b;
|
||||
// trip_collection_links: id, trip_id, collection_id (each row is written whole by the places library or the trip).
|
||||
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 653;
|
||||
// + place_change_log: id, field (a change is only ever written whole, by the history of a place's details).
|
||||
// + place_activity_links: id (a link is only ever written whole, by the place it names an activity for).
|
||||
// + personal_place_tags: id, tag_id (a tag on an entry is only ever written whole, by the places library).
|
||||
const KNOWN_UNINITIALISED_NOT_NULL_SCALARS = 658;
|
||||
|
||||
describe('entity class fields never carry a NaN initialiser (task-4-review-shape.md, Important 1)', () => {
|
||||
it('CLASSFIELD-001: new X() has no own property whose value is NaN, across all 133 entities', () => {
|
||||
|
||||
@@ -121,6 +121,9 @@ const UNNUMBERED = [
|
||||
'Migration20200101046520_a_reset_link_belongs_to_the_address_it_was_sent_to',
|
||||
'Migration20200101046530_a_user_keeps_their_own_place_identities',
|
||||
'Migration20200101046540_a_trip_links_its_collections',
|
||||
'Migration20200101046550_a_place_keeps_the_history_of_its_details',
|
||||
'Migration20200101046570_a_place_links_the_tours_and_bookings_it_is_about',
|
||||
'Migration20200101046580_a_person_tags_the_places_they_keep',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
/**
|
||||
* PlaceActivityLinksRepository and the table under it (PLC-18): the checks a
|
||||
* link relies on, the links it writes and takes off, the bookings and tours
|
||||
* it reads for trip places (linked, by their own place, stay or plan entry,
|
||||
* by a station), the kept tours of saved places, and the shape the CHECK,
|
||||
* the UNIQUE pairs and the cascades hold.
|
||||
*/
|
||||
import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity';
|
||||
import { PlaceActivityLinks } from '../../../../src/db/entities/PlaceActivityLinks.entity';
|
||||
import { Places } from '../../../../src/db/entities/Places.entity';
|
||||
import { Reservations } from '../../../../src/db/entities/Reservations.entity';
|
||||
import { Users } from '../../../../src/db/entities/Users.entity';
|
||||
import type { PlaceActivityLinksRepository } from '../../../../src/db/repositories/PlaceActivityLinks.repository';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { linkPlaceActivity } from '../../../helpers/factories/place-activities';
|
||||
import { countRows, deleteRows, findRow, updateRows } from '../../../helpers/factories/rows';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { seedPlaceActivities, type PlaceActivitiesFixture } from '../../../helpers/place-activities-fixture';
|
||||
import { resetTestDb } from '../../../helpers/test-db';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repo: PlaceActivityLinksRepository;
|
||||
let f: PlaceActivitiesFixture;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repo = t.repo(PlaceActivityLinks);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
resetTestDb(testDb);
|
||||
t.clear();
|
||||
f = await seedPlaceActivities(t);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
describe('PlaceActivityLinksRepository', () => {
|
||||
it('PAL-REPO-001: finds the places and activities a link names only where they belong', async () => {
|
||||
const { alps, rome, places, saved, bookings, kept, lists } = f;
|
||||
expect(await repo.tripPlace(alps.id, places.cafe.id)).toEqual({ id: places.cafe.id, trip_id: alps.id });
|
||||
expect(await repo.tripPlace(rome.id, places.cafe.id)).toBeUndefined();
|
||||
expect(await repo.savedPlace(saved.savedCafe.id)).toEqual({ id: saved.savedCafe.id, collection_id: lists.food.id });
|
||||
expect(await repo.savedPlace(999999)).toBeUndefined();
|
||||
expect(await repo.bookingInTrip(alps.id, bookings.guided.id)).toBe(true);
|
||||
expect(await repo.bookingInTrip(rome.id, bookings.guided.id)).toBe(false);
|
||||
expect(await repo.tourInTrip(alps.id, places.ridge.id)).toBe(true);
|
||||
expect(await repo.tourInTrip(alps.id, places.cafe.id)).toBe(false);
|
||||
expect(await repo.tourInTrip(rome.id, places.ridge.id)).toBe(false);
|
||||
expect(await repo.keptTourInList(lists.food.id, kept.keptRidge.id)).toBe(true);
|
||||
expect(await repo.keptTourInList(lists.food.id, kept.keptRome.id)).toBe(false);
|
||||
});
|
||||
|
||||
it('PAL-REPO-002: links once, unlinks once, and reads the linked bookings, tours and kept tours', async () => {
|
||||
const { me, places, saved, bookings, kept } = f;
|
||||
expect(await repo.link({ place_id: places.cafe.id, reservation_id: bookings.guided.id }, me.id)).toBe(true);
|
||||
expect(await repo.link({ place_id: places.cafe.id, reservation_id: bookings.guided.id }, me.id)).toBe(false);
|
||||
expect(await repo.link({ place_id: places.cafe.id, tour_place_id: places.ridge.id }, me.id)).toBe(true);
|
||||
expect(
|
||||
await repo.link({ collection_place_id: saved.savedCafe.id, collection_tour_id: kept.keptRidge.id }, me.id),
|
||||
).toBe(true);
|
||||
|
||||
const [booking] = await repo.linkedBookings([places.cafe.id]);
|
||||
expect(booking).toMatchObject({
|
||||
source_id: places.cafe.id,
|
||||
trip_id: f.alps.id,
|
||||
trip_title: 'Alps',
|
||||
reservation_id: bookings.guided.id,
|
||||
title: 'Guided tour',
|
||||
type: 'tour',
|
||||
status: 'confirmed',
|
||||
reservation_time: '2026-07-01T10:00',
|
||||
date: '2026-07-01',
|
||||
day_number: 1,
|
||||
});
|
||||
expect(await repo.linkedTours([places.cafe.id])).toEqual([
|
||||
expect.objectContaining({
|
||||
source_id: places.cafe.id,
|
||||
tour_id: places.ridge.id,
|
||||
title: 'Ridge walk',
|
||||
tour_type: 'hike',
|
||||
}),
|
||||
]);
|
||||
expect(await repo.linkedKeptTours([saved.savedCafe.id])).toEqual([
|
||||
expect.objectContaining({
|
||||
source_id: saved.savedCafe.id,
|
||||
collection_id: f.lists.food.id,
|
||||
collection_name: 'Food',
|
||||
collection_tour_id: kept.keptRidge.id,
|
||||
title: 'Kept ridge',
|
||||
}),
|
||||
]);
|
||||
expect(await repo.linkedBookings([])).toEqual([]);
|
||||
|
||||
expect(await repo.unlinkTrip(places.cafe.id, { reservation_id: bookings.guided.id })).toBe(true);
|
||||
expect(await repo.unlinkTrip(places.cafe.id, { reservation_id: bookings.guided.id })).toBe(false);
|
||||
expect(await repo.unlinkTrip(places.cafe.id, { tour_place_id: places.ridge.id })).toBe(true);
|
||||
expect(await repo.unlinkSaved(saved.savedCafe.id, kept.keptRidge.id)).toBe(true);
|
||||
expect(await repo.unlinkSaved(saved.savedCafe.id, kept.keptRidge.id)).toBe(false);
|
||||
expect(await countRows(t, PlaceActivityLinks, {})).toBe(0);
|
||||
});
|
||||
|
||||
it('PAL-REPO-003: reads the bookings that belong to a place by its own place, stay or plan entry, and the station tours', async () => {
|
||||
const { places, bookings } = f;
|
||||
const own = await repo.implicitBookings([places.hotel.id, places.camp.id, places.cafe.id]);
|
||||
expect(own.map((row) => [row.source_id, row.title, row.via]).sort()).toEqual(
|
||||
[
|
||||
[places.hotel.id, 'Hotel Sonne', 'place'],
|
||||
[places.camp.id, 'Lake cabin', 'stay'],
|
||||
[places.cafe.id, 'Dinner', 'plan'],
|
||||
].sort(),
|
||||
);
|
||||
expect(own.find((row) => row.via === 'stay')?.reservation_id).toBe(bookings.cabin.id);
|
||||
expect(await repo.implicitTours([places.museum.id])).toEqual([
|
||||
expect.objectContaining({ source_id: places.museum.id, tour_id: places.ridge.id }),
|
||||
]);
|
||||
expect(await repo.implicitTours([places.cafe.id])).toEqual([]);
|
||||
});
|
||||
|
||||
it('PAL-REPO-004: lists the candidates of a trip and a list', async () => {
|
||||
const bookings = await repo.tripBookings(f.alps.id);
|
||||
expect(bookings.map((row) => row.title).sort()).toEqual(['Dinner', 'Guided tour', 'Hotel Sonne', 'Lake cabin']);
|
||||
expect(bookings.every((row) => row.source_id === 0)).toBe(true);
|
||||
const tours = await repo.tripTours(f.alps.id);
|
||||
expect(tours.map((row) => row.title)).toEqual(['Old town walk', 'Ridge walk']);
|
||||
expect(tours.find((row) => row.title === 'Old town walk')?.tour_type).toBe('walk');
|
||||
const kept = await repo.keptTours(f.lists.food.id);
|
||||
expect(kept.map((row) => row.title)).toEqual(['Kept lake loop', 'Kept ridge']);
|
||||
});
|
||||
|
||||
it('PAL-REPO-005: the CHECK refuses a mixed or empty link, the UNIQUE a second one, and an account that goes leaves its links', async () => {
|
||||
const { me, places, saved, bookings } = f;
|
||||
await expect(
|
||||
linkPlaceActivity(t, {
|
||||
place: places.cafe.id,
|
||||
reservation: bookings.guided.id,
|
||||
tourPlace: places.ridge.id,
|
||||
} as never),
|
||||
).rejects.toThrow();
|
||||
await expect(
|
||||
linkPlaceActivity(t, { place: places.cafe.id, collectionTour: f.kept.keptRidge.id } as never),
|
||||
).rejects.toThrow();
|
||||
await expect(linkPlaceActivity(t, { collectionPlace: saved.savedCafe.id } as never)).rejects.toThrow();
|
||||
await linkPlaceActivity(t, { place: places.cafe.id, reservation: bookings.guided.id }, me.id);
|
||||
await expect(linkPlaceActivity(t, { place: places.cafe.id, reservation: bookings.guided.id })).rejects.toThrow();
|
||||
// Who linked it is kept as unknown when that account goes; the link stays.
|
||||
const { user: helper } = await makeUser(t);
|
||||
await linkPlaceActivity(t, { place: places.museum.id, reservation: bookings.guided.id }, helper.id);
|
||||
await deleteRows(t, Users, { id: helper.id });
|
||||
const kept = await findRow(t, PlaceActivityLinks, { place: places.museum.id, reservation: bookings.guided.id });
|
||||
expect(kept?.linked_by).toBeNull();
|
||||
expect(await countRows(t, PlaceActivityLinks, {})).toBe(2);
|
||||
});
|
||||
|
||||
it('PAL-REPO-006: deleting the booking, the tour or the place takes only its links', async () => {
|
||||
const { places, bookings } = f;
|
||||
await linkPlaceActivity(t, { place: places.cafe.id, reservation: bookings.guided.id });
|
||||
await linkPlaceActivity(t, { place: places.museum.id, reservation: bookings.guided.id });
|
||||
await linkPlaceActivity(t, { place: places.cafe.id, tourPlace: places.ridge.id });
|
||||
await deleteRows(t, Reservations, { id: bookings.guided.id });
|
||||
expect(await countRows(t, PlaceActivityLinks, {})).toBe(1);
|
||||
await deleteRows(t, Places, { id: places.ridge.id });
|
||||
expect(await countRows(t, PlaceActivityLinks, {})).toBe(0);
|
||||
expect(await findRow(t, Places, { id: places.cafe.id })).not.toBeNull();
|
||||
});
|
||||
|
||||
it('PAL-REPO-007: a saved place moved to another list reads none of the tours of its old list, and has them back on its return', async () => {
|
||||
const { me, saved, kept, lists } = f;
|
||||
await repo.link({ collection_place_id: saved.savedCafe.id, collection_tour_id: kept.keptRidge.id }, me.id);
|
||||
await updateRows(t, CollectionPlaces, { id: saved.savedCafe.id }, { collection: lists.sights.id });
|
||||
expect(await repo.linkedKeptTours([saved.savedCafe.id])).toEqual([]);
|
||||
// The link itself stays: it belongs to the old list, which may get the place back.
|
||||
expect(await countRows(t, PlaceActivityLinks, { collectionPlace: saved.savedCafe.id })).toBe(1);
|
||||
await updateRows(t, CollectionPlaces, { id: saved.savedCafe.id }, { collection: lists.food.id });
|
||||
const back = await repo.linkedKeptTours([saved.savedCafe.id]);
|
||||
expect(back.map((row) => [row.title, row.collection_id])).toEqual([['Kept ridge', lists.food.id]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,179 @@
|
||||
/**
|
||||
* PlaceChangeLogRepository and the table under it (PLC-14): the details it
|
||||
* reads of trip places and saved places, the trip places a photo fill
|
||||
* reaches, the changes it writes and drops, the page it reads with who made
|
||||
* each change, the list a saved place's change was made in, the CHECK on
|
||||
* its owner, and the rows that go with their place, list or account.
|
||||
*/
|
||||
import { CollectionPlaces } from '../../../../src/db/entities/CollectionPlaces.entity';
|
||||
import { Collections } from '../../../../src/db/entities/Collections.entity';
|
||||
import { PlaceChangeLog } from '../../../../src/db/entities/PlaceChangeLog.entity';
|
||||
import { Places } from '../../../../src/db/entities/Places.entity';
|
||||
import { Users } from '../../../../src/db/entities/Users.entity';
|
||||
import type { PlaceChangeLogRepository } from '../../../../src/db/repositories/PlaceChangeLog.repository';
|
||||
import { createSnapshotTestDb } from '../../../helpers/db-mock';
|
||||
import { makeCollection, makeCollectionPlace } from '../../../helpers/factories/collections';
|
||||
import { makeCategory, makePlace } from '../../../helpers/factories/places';
|
||||
import { countRows, deleteRows, insertRow, updateRows } from '../../../helpers/factories/rows';
|
||||
import { makeTour } from '../../../helpers/factories/tours';
|
||||
import { makeTrip } from '../../../helpers/factories/trips';
|
||||
import { makeUser } from '../../../helpers/factories/users';
|
||||
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let repo: PlaceChangeLogRepository;
|
||||
|
||||
beforeAll(async () => {
|
||||
t = await createTestOrm(testDb);
|
||||
repo = t.repo(PlaceChangeLog);
|
||||
});
|
||||
beforeEach(async () => {
|
||||
t.clear();
|
||||
await deleteRows(t, PlaceChangeLog);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await t.close();
|
||||
testDb.close();
|
||||
});
|
||||
|
||||
const change = (over: Partial<Parameters<PlaceChangeLogRepository['insertChanges']>[0][number]>) => ({
|
||||
place_id: null,
|
||||
collection_place_id: null,
|
||||
field: 'name',
|
||||
old_value: 'A',
|
||||
new_value: 'B',
|
||||
user_id: null,
|
||||
automatic: 0,
|
||||
...over,
|
||||
});
|
||||
|
||||
async function seed() {
|
||||
const { user } = await makeUser(t);
|
||||
const category = await makeCategory(t);
|
||||
const trip = await makeTrip(t, user.id);
|
||||
const place = await makePlace(t, trip.id, {
|
||||
name: 'Café',
|
||||
address: 'Herrengasse 14',
|
||||
lat: 48.2,
|
||||
lng: 16.3,
|
||||
category: category.id,
|
||||
opening_hours: 'Mo-Fr 8-18',
|
||||
google_place_id: 'g-cafe',
|
||||
});
|
||||
const list = await makeCollection(t, user.id);
|
||||
const saved = await makeCollectionPlace(t, list.id, user.id, { name: 'Saved café', status: 'want', notes: 'Cake' });
|
||||
return { user, category, trip, place, list, saved };
|
||||
}
|
||||
|
||||
describe('PlaceChangeLogRepository', () => {
|
||||
it('PCLREPO-001: reads the details of trip places and saved places with their category names', async () => {
|
||||
const s = await seed();
|
||||
expect(await repo.tripPlaceDetails([s.place.id, 999_999])).toEqual([
|
||||
expect.objectContaining({
|
||||
id: s.place.id,
|
||||
name: 'Café',
|
||||
address: 'Herrengasse 14',
|
||||
lat: 48.2,
|
||||
lng: 16.3,
|
||||
category_name: s.category.name,
|
||||
opening_hours: 'Mo-Fr 8-18',
|
||||
}),
|
||||
]);
|
||||
expect(await repo.savedPlaceDetails([s.saved.id])).toEqual([
|
||||
expect.objectContaining({ id: s.saved.id, name: 'Saved café', status: 'want', notes: 'Cake' }),
|
||||
]);
|
||||
expect(await repo.tripPlaceDetails([])).toEqual([]);
|
||||
});
|
||||
|
||||
it('PCLREPO-002: finds the trip places of a Google id that have no picture yet', async () => {
|
||||
const s = await seed();
|
||||
const pictured = await makePlace(t, s.trip.id, { google_place_id: 'g-cafe', image_url: '/uploads/places/a.jpg' });
|
||||
const blank = await makePlace(t, s.trip.id, { google_place_id: 'g-cafe', image_url: '' });
|
||||
const ids = await repo.tripPlaceIdsWithoutImage('g-cafe');
|
||||
expect([...ids].sort((a, b) => a - b)).toEqual([s.place.id, blank.id].sort((a, b) => a - b));
|
||||
expect(ids).not.toContain(pictured.id);
|
||||
});
|
||||
|
||||
it('PCLREPO-003: writes changes, pages them newest first with their editor, and drops a cleared field', async () => {
|
||||
const s = await seed();
|
||||
await repo.insertChanges([
|
||||
change({ place_id: s.place.id, field: 'name', user_id: s.user.id }),
|
||||
change({ place_id: s.place.id, field: 'notes', old_value: null, new_value: 'x', automatic: 1 }),
|
||||
change({ collection_place_id: s.saved.id, field: 'status', old_value: 'idea', new_value: 'want' }),
|
||||
]);
|
||||
await repo.insertChanges([]);
|
||||
|
||||
const page = await repo.page([s.place.id], [s.saved.id], null, 10);
|
||||
expect(page.map((row) => row.field)).toEqual(['status', 'notes', 'name']);
|
||||
expect(page[2]).toEqual(expect.objectContaining({ user_id: s.user.id, username: s.user.username, automatic: 0 }));
|
||||
expect(page[1]).toEqual(expect.objectContaining({ user_id: null, username: null, automatic: 1 }));
|
||||
|
||||
const after = page[1]?.id ?? 0;
|
||||
expect((await repo.page([s.place.id], [s.saved.id], after, 10)).map((row) => row.field)).toEqual(['name']);
|
||||
expect((await repo.page([s.place.id], [], null, 1)).map((row) => row.field)).toEqual(['notes']);
|
||||
expect(await repo.page([], [], null, 10)).toEqual([]);
|
||||
|
||||
await repo.deleteCleared([
|
||||
{ place_id: s.place.id, collection_place_id: null, fields: ['notes'] },
|
||||
{ place_id: null, collection_place_id: s.saved.id, fields: ['status'] },
|
||||
{ place_id: s.place.id, collection_place_id: null, fields: [] },
|
||||
]);
|
||||
await repo.deleteCleared([]);
|
||||
expect((await repo.page([s.place.id], [s.saved.id], null, 10)).map((row) => row.field)).toEqual(['name']);
|
||||
});
|
||||
|
||||
it('PCLREPO-004: the changes go with their place, and name nobody once the account is gone', async () => {
|
||||
const s = await seed();
|
||||
const { user: other } = await makeUser(t);
|
||||
await repo.insertChanges([
|
||||
change({ place_id: s.place.id, user_id: other.id }),
|
||||
change({ collection_place_id: s.saved.id, user_id: other.id }),
|
||||
]);
|
||||
await deleteRows(t, Users, { id: other.id });
|
||||
expect(await countRows(t, PlaceChangeLog, { collectionPlace: s.saved.id, user: null })).toBe(1);
|
||||
await deleteRows(t, Places, { id: s.place.id });
|
||||
expect(await countRows(t, PlaceChangeLog, { place: s.place.id })).toBe(0);
|
||||
expect(await countRows(t, PlaceChangeLog)).toBe(1);
|
||||
});
|
||||
|
||||
it('PCLREPO-005: a saved place moved to another list shows only the changes made there, the old ones again on its return', async () => {
|
||||
const s = await seed();
|
||||
await repo.insertChanges([change({ collection_place_id: s.saved.id, field: 'notes', user_id: s.user.id })]);
|
||||
expect(await countRows(t, PlaceChangeLog, { collectionPlace: s.saved.id, collection: s.list.id })).toBe(1);
|
||||
const other = await makeCollection(t, s.user.id);
|
||||
await updateRows(t, CollectionPlaces, { id: s.saved.id }, { collection: other.id });
|
||||
expect(await repo.page([], [s.saved.id], null, 10)).toEqual([]);
|
||||
await repo.insertChanges([change({ collection_place_id: s.saved.id, field: 'name' })]);
|
||||
expect((await repo.page([], [s.saved.id], null, 10)).map((row) => row.field)).toEqual(['name']);
|
||||
await updateRows(t, CollectionPlaces, { id: s.saved.id }, { collection: s.list.id });
|
||||
expect((await repo.page([], [s.saved.id], null, 10)).map((row) => row.field)).toEqual(['notes']);
|
||||
// A deleted list takes the changes made in it; the place lives on in the other one.
|
||||
await updateRows(t, CollectionPlaces, { id: s.saved.id }, { collection: other.id });
|
||||
await deleteRows(t, Collections, { id: s.list.id });
|
||||
expect(await countRows(t, PlaceChangeLog, { collectionPlace: s.saved.id })).toBe(1);
|
||||
});
|
||||
|
||||
it('PCLREPO-006: the CHECK holds exactly one owner, and a list beside a saved place only', async () => {
|
||||
const s = await seed();
|
||||
const row = { field: 'name', old_value: 'A', new_value: 'B' };
|
||||
await expect(insertRow(t, PlaceChangeLog, { ...row })).rejects.toThrow();
|
||||
await expect(
|
||||
insertRow(t, PlaceChangeLog, { ...row, place: s.place.id, collectionPlace: s.saved.id, collection: s.list.id }),
|
||||
).rejects.toThrow();
|
||||
await expect(insertRow(t, PlaceChangeLog, { ...row, collectionPlace: s.saved.id })).rejects.toThrow();
|
||||
await expect(insertRow(t, PlaceChangeLog, { ...row, place: s.place.id, collection: s.list.id })).rejects.toThrow();
|
||||
await insertRow(t, PlaceChangeLog, { ...row, place: s.place.id });
|
||||
await insertRow(t, PlaceChangeLog, { ...row, collectionPlace: s.saved.id, collection: s.list.id });
|
||||
expect(await countRows(t, PlaceChangeLog)).toBe(2);
|
||||
});
|
||||
|
||||
it('PCLREPO-007: a tour has no details to follow, so no write records a change of it', async () => {
|
||||
const s = await seed();
|
||||
const tour = await makePlace(t, s.trip.id, { name: 'Ridge loop' });
|
||||
await makeTour(t, tour.id);
|
||||
expect((await repo.tripPlaceDetails([s.place.id, tour.id])).map((row) => row.id)).toEqual([s.place.id]);
|
||||
});
|
||||
});
|
||||
@@ -56,6 +56,7 @@ import { Places } from '../../../src/db/entities/Places.entity';
|
||||
import { Tags } from '../../../src/db/entities/Tags.entity';
|
||||
import { Users } from '../../../src/db/entities/Users.entity';
|
||||
import { FakeRealtimeService } from '../../helpers/fake-realtime';
|
||||
import { passThroughPlaceChanges } from '../../helpers/place-changes';
|
||||
|
||||
const realtime = new FakeRealtimeService();
|
||||
const broadcastToUser = realtime.broadcastToUserMock;
|
||||
@@ -132,9 +133,8 @@ beforeAll(async () => {
|
||||
await createTestCollectionPlacesRepo(testDb), await createTestCollectionPlaceRatingsRepo(testDb),
|
||||
tripsRepoForSpy, await createTestTripMembersRepo(testDb),
|
||||
await createTestPlacesRepo(testDb), await createTestPlaceRatingsRepo(testDb),
|
||||
await createTestTagsRepo(testDb), await createTestUsersRepo(testDb),
|
||||
buildPlaceImportService(),
|
||||
placesHooks as never,
|
||||
await createTestTagsRepo(testDb), await createTestUsersRepo(testDb), buildPlaceImportService(),
|
||||
placesHooks as never, passThroughPlaceChanges(),
|
||||
);
|
||||
photoCache = new PlacePhotoCacheService(
|
||||
makeStorageFixture('photos/google/').storage,
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* tagsToCarry (D9/PLC-21): which tags a copy into a trip brings along per
|
||||
* saved place: the list's tags asked for where the place carries them, and
|
||||
* the copier's personal tags asked for on every copy, nothing unasked.
|
||||
*/
|
||||
import { tagsToCarry } from '../../../src/nest/collections/collections.helpers';
|
||||
|
||||
import { describe, expect, it, vi } from 'vitest';
|
||||
|
||||
const listTags = [
|
||||
{ pid: 1, id: 10, name: 'Must', color: '#ff0000' },
|
||||
{ pid: 2, id: 11, name: 'Later', color: '#00ff00' },
|
||||
];
|
||||
const personal = [
|
||||
{ id: 20, name: 'Wine', color: '#aa0000', trip_id: null },
|
||||
{ id: 21, name: 'Old', color: null, trip_id: null },
|
||||
{ id: 22, name: 'Trip tag', color: '#000000', trip_id: 5 },
|
||||
];
|
||||
|
||||
describe('tagsToCarry', () => {
|
||||
it('COLL-CARRY-001: reads and brings nothing when nothing is asked for', async () => {
|
||||
const lists = { loadTagsByPlaceIds: vi.fn() };
|
||||
const mine = vi.fn();
|
||||
expect(await tagsToCarry({}, [1, 2], lists, mine)).toBeNull();
|
||||
expect(await tagsToCarry({ tag_ids: [], personal_tag_ids: [] }, [1], lists, mine)).toBeNull();
|
||||
expect(lists.loadTagsByPlaceIds).not.toHaveBeenCalled();
|
||||
expect(mine).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('COLL-CARRY-002: the list tags asked for where a place carries them, the personal ones on every copy', async () => {
|
||||
const lists = { loadTagsByPlaceIds: vi.fn().mockResolvedValue(listTags) };
|
||||
const mine = vi.fn().mockResolvedValue(personal);
|
||||
expect(await tagsToCarry({ tag_ids: [10], personal_tag_ids: [20, 21, 22, 99] }, [1, 2], lists, mine)).toEqual({
|
||||
1: [
|
||||
{ name: 'Must', color: '#ff0000' },
|
||||
{ name: 'Wine', color: '#aa0000' },
|
||||
{ name: 'Old', color: '#10b981' },
|
||||
],
|
||||
2: [
|
||||
{ name: 'Wine', color: '#aa0000' },
|
||||
{ name: 'Old', color: '#10b981' },
|
||||
],
|
||||
});
|
||||
expect(lists.loadTagsByPlaceIds).toHaveBeenCalledWith([1, 2]);
|
||||
});
|
||||
|
||||
it('COLL-CARRY-003: personal tags alone read no list tags', async () => {
|
||||
const lists = { loadTagsByPlaceIds: vi.fn() };
|
||||
const mine = vi.fn().mockResolvedValue(personal);
|
||||
expect(await tagsToCarry({ personal_tag_ids: [20] }, [3], lists, mine)).toEqual({
|
||||
3: [{ name: 'Wine', color: '#aa0000' }],
|
||||
});
|
||||
expect(lists.loadTagsByPlaceIds).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user