mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
fix(places): undo, unlink and dismissals that hold after a key or access change
Review findings on the place identities and trip list links: - The assistant offers PlacesLibraryMcp, PlaceIdentitiesMcp and TripCollectionsMcp with the collections group (done with the CI fix). - Undoing a merge restores the entries as they were: the merge logs, in its moved_link_ids JSON, each link it moved and each link it made with the use that link names, and whether the merged side became an own place only for the merge. The undo deletes what the merge made and moves the rest back, and only touches a link still in the leading place naming the same use, so a link id SQLite hands out again never moves someone else's link. The sweep counts a merge as spent by the same rule. Same unreleased migration, no schema change. - A use can be taken out of an own place by the user's own link row also once its trip or list is out of reach; the answer then holds no entry, and the place left can be merged again. - A dismissed duplicate is kept by one use of each side (an own place by its first link) and matched by the uses each entry holds, so it stays out when an entry becomes an own place or a merge is undone. - link() checks the named uses with one targeted read instead of reading every use of the user, and the library reads its rows in blocks of 500 ids. - Saved place reorders and the trip tags of a copy run one statement after the other again; a copy takes the first spelling of a tag name, as before. - Unlinking a list from a trip takes place_edit alone, so a link to a list the writer cannot open can be taken off; a member leaving or taken off the trip takes the links whose list nobody left on it can open. - The linked lists and their map places sort by lower(name), then by id, the same on both engines. - list_all_places names the own:<id> keys and identity_id (MCP and wiki); the undo, unlink and trip unlink descriptions say what they do now; README counts 451 tools.
This commit is contained in:
@@ -617,9 +617,31 @@ export const MAIL_INGEST_ATTACHMENTS: JsonColumn<MailIngestAttachment[]> = {
|
||||
fallback: () => [],
|
||||
};
|
||||
|
||||
/** The links a merge of two own places moved (D6), for its undo. A broken row moves nothing back. */
|
||||
export const USER_PLACE_MERGE_MOVED_LINKS: JsonColumn<number[]> = {
|
||||
/**
|
||||
* A link a merge wrote or moved, with the use it named then: the undo only
|
||||
* acts on a link that still names that use, so an id SQLite handed out again
|
||||
* never moves someone else's link.
|
||||
*/
|
||||
const mergedLinkSchema = z.object({
|
||||
link: z.number().int().positive(),
|
||||
kind: z.enum(['trip', 'list']),
|
||||
id: z.number().int().positive(),
|
||||
});
|
||||
export type MergedLink = z.infer<typeof mergedLinkSchema>;
|
||||
|
||||
const userPlaceMergeLogSchema = z.object({
|
||||
/** The links that moved from the merged own place to the leading one. */
|
||||
moved: z.array(mergedLinkSchema),
|
||||
/** The links the merge made for the leading entry when it was no own place yet. */
|
||||
made: z.array(mergedLinkSchema),
|
||||
/** Whether the merged entry became an own place only for the merge. */
|
||||
merged_made: z.boolean(),
|
||||
});
|
||||
export type UserPlaceMergeLog = z.infer<typeof userPlaceMergeLogSchema>;
|
||||
|
||||
/** What a merge of two own places moved and made (D6), for its undo. A broken row moves nothing back. */
|
||||
export const USER_PLACE_MERGE_MOVED_LINKS: JsonColumn<UserPlaceMergeLog> = {
|
||||
column: 'user_place_merges.moved_link_ids',
|
||||
schema: idList,
|
||||
fallback: () => [],
|
||||
schema: userPlaceMergeLogSchema,
|
||||
fallback: () => ({ moved: [], made: [], merged_made: false }),
|
||||
};
|
||||
|
||||
+3
-3
@@ -16,9 +16,9 @@ import { Migration } from '@mikro-orm/migrations';
|
||||
* The links go with the use, so a deleted place or list drops them; an identity
|
||||
* left without links is removed by the service, not here.
|
||||
*
|
||||
* `user_place_merges` keeps what a merge moved (the link ids, JSON) so it can
|
||||
* be undone, and `user_place_merge_dismissals` the duplicate suggestions the
|
||||
* user turned down, by the two entry keys in order.
|
||||
* `user_place_merges` keeps what a merge moved and made (each link id with the
|
||||
* use it names, JSON) so it can be undone, and `user_place_merge_dismissals`
|
||||
* the duplicate suggestions the user turned down, by one use of each side in order.
|
||||
*/
|
||||
export class Migration20200101046530_a_user_keeps_their_own_place_identities extends Migration {
|
||||
override name = 'Migration20200101046530_a_user_keeps_their_own_place_identities';
|
||||
|
||||
@@ -151,16 +151,16 @@ export class CollectionPlacesRepository extends TrekRepository<CollectionPlaces>
|
||||
|
||||
/** `UPDATE collection_places SET sort_order=? WHERE id=? AND collection_id=?`, per place, inside the caller's transaction. */
|
||||
async setSortOrders(collectionId: number, orderedIds: number[]): Promise<void> {
|
||||
await Promise.all(
|
||||
orderedIds.map((id, position) =>
|
||||
this.db_()
|
||||
.updateTable('collection_places')
|
||||
.set({ sort_order: position })
|
||||
.where('id', '=', id)
|
||||
.where('collection_id', '=', collectionId)
|
||||
.execute(),
|
||||
),
|
||||
);
|
||||
// One statement after the other on the transaction's connection, so a failure stops the rest before the rollback.
|
||||
await orderedIds.reduce(async (previous, id, position) => {
|
||||
await previous;
|
||||
await this.db_()
|
||||
.updateTable('collection_places')
|
||||
.set({ sort_order: position })
|
||||
.where('id', '=', id)
|
||||
.where('collection_id', '=', collectionId)
|
||||
.execute();
|
||||
}, Promise.resolve());
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------
|
||||
|
||||
@@ -494,12 +494,23 @@ export class PlacesLibraryRepository {
|
||||
.orderBy('u.from_list')
|
||||
.orderBy('u.use_id')
|
||||
.execute();
|
||||
return rows.map((row) => ({
|
||||
anchor_key: Number(row.anchor_key),
|
||||
from_list: Number(row.from_list),
|
||||
use_id: Number(row.use_id),
|
||||
linked: Number(row.linked) === 1,
|
||||
}));
|
||||
return rows.map(useRowOf);
|
||||
}
|
||||
|
||||
/** Which of the uses (from_list 0: a trip place, 1: a saved place) the user reaches, each with its entry. */
|
||||
async reachedUses(arms: LibraryArms, uses: readonly { fromList: number; useId: number }[]): Promise<LibraryUseRow[]> {
|
||||
if (uses.length === 0) return [];
|
||||
const db = this.db();
|
||||
const rows = await db
|
||||
.selectFrom(this.entries(db, arms, NO_MATCH))
|
||||
.select(['u.anchor_key', 'u.from_list', 'u.use_id', 'u.linked'])
|
||||
.where((eb) =>
|
||||
eb.or(uses.map((use) => eb.and([eb('u.from_list', '=', use.fromList), eb('u.use_id', '=', use.useId)]))),
|
||||
)
|
||||
.orderBy('u.from_list')
|
||||
.orderBy('u.use_id')
|
||||
.execute();
|
||||
return rows.map(useRowOf);
|
||||
}
|
||||
|
||||
/** The entry the use stands for (from_list 0: a trip place, 1: a saved place), when the user reaches it. */
|
||||
@@ -720,3 +731,13 @@ export class PlacesLibraryRepository {
|
||||
return { stays: present(stays), bookings: present(bookings) };
|
||||
}
|
||||
}
|
||||
|
||||
/** A use as the union reads it, its numbers as numbers whatever the engine hands back. */
|
||||
function useRowOf(row: { anchor_key: unknown; from_list: unknown; use_id: unknown; linked: unknown }): LibraryUseRow {
|
||||
return {
|
||||
anchor_key: Number(row.anchor_key),
|
||||
from_list: Number(row.from_list),
|
||||
use_id: Number(row.use_id),
|
||||
linked: Number(row.linked) === 1,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ export class TripCollectionLinksRepository extends TrekRepository<TripCollection
|
||||
return this.kysely<TripCollectionLinksDB>();
|
||||
}
|
||||
|
||||
/** The lists linked to the trip, by list name. */
|
||||
/** The lists linked to the trip, by list name (case ignored, the same on both engines), then by id. */
|
||||
async listForTrip(tripId: number): Promise<TripCollectionLinkRow[]> {
|
||||
const rows = await this.db()
|
||||
.selectFrom('trip_collection_links as l')
|
||||
@@ -66,7 +66,7 @@ export class TripCollectionLinksRepository extends TrekRepository<TripCollection
|
||||
.as('place_count'),
|
||||
])
|
||||
.where('l.trip_id', '=', tripId)
|
||||
.orderBy('c.name')
|
||||
.orderBy((eb) => eb.fn<string>('lower', ['c.name']))
|
||||
.orderBy('l.collection_id')
|
||||
.execute();
|
||||
return rows.map((row) => ({ ...row, place_count: Number(row.place_count ?? 0) }));
|
||||
@@ -97,7 +97,7 @@ export class TripCollectionLinksRepository extends TrekRepository<TripCollection
|
||||
* with the trip place it came from: the same provider id, or the same name
|
||||
* (trimmed, case ignored) within `COORD_DEDUP_TOLERANCE` and no provider id
|
||||
* that differs. The stored source alone proves nothing, since any editor of
|
||||
* the list may have written it. By list, then by name.
|
||||
* the list may have written it. By list, then by name (case ignored), then by id.
|
||||
*/
|
||||
async layerPlaces(tripId: number, collectionIds: number[]): Promise<TripCollectionLayerRow[]> {
|
||||
const rows = await this.db()
|
||||
@@ -154,7 +154,7 @@ export class TripCollectionLinksRepository extends TrekRepository<TripCollection
|
||||
.where('cp.lat', 'is not', null)
|
||||
.where('cp.lng', 'is not', null)
|
||||
.orderBy('cp.collection_id')
|
||||
.orderBy('cp.name')
|
||||
.orderBy((eb) => eb.fn<string>('lower', ['cp.name']))
|
||||
.orderBy('cp.id')
|
||||
.execute();
|
||||
return rows.flatMap((row) =>
|
||||
|
||||
@@ -322,6 +322,71 @@ export class TripMembersRepository extends TrekRepository<TripMembers> {
|
||||
.execute();
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the trip's list links (PLC-15) whose list no one left on the trip,
|
||||
* its owner or a member, can open: such a link shows to nobody, and would
|
||||
* come back unasked once the list is shared with one of them again. Runs
|
||||
* inside the caller's transaction, after the member is gone.
|
||||
*/
|
||||
async dropUnseenCollectionLinks(tripId: number): Promise<void> {
|
||||
const db =
|
||||
this.kysely<
|
||||
Pick<DB, 'trip_collection_links' | 'collections' | 'collection_members' | 'trips' | 'trip_members'>
|
||||
>();
|
||||
await db
|
||||
.deleteFrom('trip_collection_links')
|
||||
.where('trip_id', '=', tripId)
|
||||
.where((eb) =>
|
||||
eb.not(
|
||||
eb.exists(
|
||||
eb
|
||||
.selectFrom('collections as c')
|
||||
.select('c.id')
|
||||
.whereRef('c.id', '=', 'trip_collection_links.collection_id')
|
||||
.where((seen) =>
|
||||
seen.or([
|
||||
seen(
|
||||
'c.owner_id',
|
||||
'in',
|
||||
seen.selectFrom('trips as t').select('t.user_id').where('t.id', '=', tripId),
|
||||
),
|
||||
seen(
|
||||
'c.owner_id',
|
||||
'in',
|
||||
seen.selectFrom('trip_members as tm').select('tm.user_id').where('tm.trip_id', '=', tripId),
|
||||
),
|
||||
seen.exists(
|
||||
seen
|
||||
.selectFrom('collection_members as cm')
|
||||
.select('cm.id')
|
||||
.whereRef('cm.collection_id', '=', 'c.id')
|
||||
.where('cm.status', '=', 'accepted')
|
||||
.where((member) =>
|
||||
member.or([
|
||||
member(
|
||||
'cm.user_id',
|
||||
'in',
|
||||
member.selectFrom('trips as t2').select('t2.user_id').where('t2.id', '=', tripId),
|
||||
),
|
||||
member(
|
||||
'cm.user_id',
|
||||
'in',
|
||||
member
|
||||
.selectFrom('trip_members as tm2')
|
||||
.select('tm2.user_id')
|
||||
.where('tm2.trip_id', '=', tripId),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
]),
|
||||
),
|
||||
),
|
||||
),
|
||||
)
|
||||
.execute();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Plan 3c Task 7 (`trips.rpc.ts::members`) — additive: no other repository
|
||||
// is rooted at `trip_members` joined to `users`, and RP3's shape is
|
||||
|
||||
@@ -16,6 +16,12 @@ interface UserPlaceLinkRef {
|
||||
user_place_id: number;
|
||||
}
|
||||
|
||||
/** A link with the own place it is in and the use it names. */
|
||||
export interface UserPlaceLinkUse extends LinkedUse {
|
||||
link: number;
|
||||
user_place_id: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* `user_place_links`: which use belongs to which own place of a person (D5).
|
||||
* A use belongs to one own place per person at most, which the unique keys on
|
||||
@@ -81,16 +87,28 @@ export class UserPlaceLinksRepository extends TrekRepository<UserPlaceLinks> {
|
||||
await this.db().deleteFrom('user_place_links').where('id', '=', id).where('user_id', '=', userId).execute();
|
||||
}
|
||||
|
||||
/** The ids of the links the own place holds. */
|
||||
async idsOf(userId: number, userPlaceId: number): Promise<number[]> {
|
||||
/** The links the own place holds, each with the use it names, in id order. */
|
||||
async linksOf(userId: number, userPlaceId: number): Promise<UserPlaceLinkUse[]> {
|
||||
const rows = await this.db()
|
||||
.selectFrom('user_place_links')
|
||||
.select('id')
|
||||
.select(['id', 'user_place_id', 'place_id', 'collection_place_id'])
|
||||
.where('user_id', '=', userId)
|
||||
.where('user_place_id', '=', userPlaceId)
|
||||
.orderBy('id')
|
||||
.execute();
|
||||
return rows.map((row) => row.id);
|
||||
return rows.map(linkUseOf);
|
||||
}
|
||||
|
||||
/** The links `ids` that still exist, each with the own place it is in and the use it names. */
|
||||
async byIds(ids: number[]): Promise<UserPlaceLinkUse[]> {
|
||||
if (ids.length === 0) return [];
|
||||
const rows = await this.db()
|
||||
.selectFrom('user_place_links')
|
||||
.select(['id', 'user_place_id', 'place_id', 'collection_place_id'])
|
||||
.where('id', 'in', ids)
|
||||
.orderBy('id')
|
||||
.execute();
|
||||
return rows.map(linkUseOf);
|
||||
}
|
||||
|
||||
/** Moves the user's links `ids` to the own place `userPlaceId`; a link gone by now is skipped. */
|
||||
@@ -104,10 +122,24 @@ export class UserPlaceLinksRepository extends TrekRepository<UserPlaceLinks> {
|
||||
.execute();
|
||||
}
|
||||
|
||||
/** Which of the links `ids` still exist. */
|
||||
async existing(ids: number[]): Promise<number[]> {
|
||||
if (ids.length === 0) return [];
|
||||
const rows = await this.db().selectFrom('user_place_links').select('id').where('id', 'in', ids).execute();
|
||||
return rows.map((row) => row.id);
|
||||
/** Deletes the user's links `ids`; a link gone by now is skipped. */
|
||||
async deleteIds(userId: number, ids: number[]): Promise<void> {
|
||||
if (ids.length === 0) return;
|
||||
await this.db().deleteFrom('user_place_links').where('user_id', '=', userId).where('id', 'in', ids).execute();
|
||||
}
|
||||
}
|
||||
|
||||
/** A link row as `UserPlaceLinkUse`: the use it names, a trip place or a saved place. */
|
||||
function linkUseOf(row: {
|
||||
id: number;
|
||||
user_place_id: number;
|
||||
place_id: number | null;
|
||||
collection_place_id: number | null;
|
||||
}): UserPlaceLinkUse {
|
||||
return {
|
||||
link: row.id,
|
||||
user_place_id: row.user_place_id,
|
||||
kind: row.place_id === null ? 'list' : 'trip',
|
||||
id: row.place_id ?? row.collection_place_id ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { TrekRepository } from './_shared/trek-repository';
|
||||
|
||||
type DismissalsDB = Pick<DB, 'user_place_merge_dismissals'>;
|
||||
|
||||
/** A turned-down suggestion by its two entry keys, the smaller first. */
|
||||
/** A turned-down suggestion by one use of each side (`trip:<id>`, `list:<id>`), the smaller first. */
|
||||
interface DismissedPair {
|
||||
key_a: string;
|
||||
key_b: string;
|
||||
|
||||
@@ -176,21 +176,20 @@ export function tagKeyOf(name: string): string {
|
||||
|
||||
/**
|
||||
* The trip's own tag of each name, in the order of `tags`: the one `known`
|
||||
* holds, or one `makeTag` makes now (once per name). `known` keeps the new
|
||||
* ones, so the next place of the same copy reuses them.
|
||||
* holds, or one `makeTag` makes now, from the first entry of that name. The
|
||||
* tags are made one after the other, and `known` keeps the new ones, so the
|
||||
* next place of the same copy reuses them.
|
||||
*/
|
||||
export async function tripTagIdsOf(
|
||||
tags: { name: string; color: string }[],
|
||||
known: Map<string, number>,
|
||||
makeTag: (name: string, color: string) => Promise<number>,
|
||||
): Promise<number[]> {
|
||||
const missing = new Map(tags.filter((t) => !known.has(tagKeyOf(t.name))).map((t) => [tagKeyOf(t.name), t]));
|
||||
const made = await Promise.all(
|
||||
[...missing.entries()].map(async ([key, { name, color }]) => [key, await makeTag(name.trim(), color)] as const),
|
||||
);
|
||||
for (const [key, id] of made) known.set(key, id);
|
||||
return tags.flatMap(({ name }): number[] => {
|
||||
const id = known.get(tagKeyOf(name));
|
||||
return id === undefined ? [] : [id];
|
||||
});
|
||||
return tags.reduce<Promise<number[]>>(async (previous, { name, color }) => {
|
||||
const ids = await previous;
|
||||
const key = tagKeyOf(name);
|
||||
const id = known.get(key) ?? (await makeTag(name.trim(), color));
|
||||
known.set(key, id);
|
||||
return [...ids, id];
|
||||
}, Promise.resolve([]));
|
||||
}
|
||||
|
||||
@@ -8,7 +8,15 @@ import {
|
||||
type DuplicateCandidate,
|
||||
} from './place-duplicates.helpers';
|
||||
import { PlaceIdentitiesService } from './place-identities.service';
|
||||
import { categoryOf, entryKey, leadOf, originsOf, type EntryRows, type OriginAccess } from './places-library.helpers';
|
||||
import {
|
||||
categoryOf,
|
||||
entryKey,
|
||||
leadOf,
|
||||
originsOf,
|
||||
useKey,
|
||||
type EntryRows,
|
||||
type OriginAccess,
|
||||
} from './places-library.helpers';
|
||||
import { PlacesLibraryService, type LibraryUser } from './places-library.service';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import {
|
||||
@@ -44,6 +52,18 @@ function candidateOf(rows: EntryRows): DuplicateCandidate {
|
||||
};
|
||||
}
|
||||
|
||||
/** The uses of an entry by `useKey`, which a turned-down pair is kept by. */
|
||||
function useKeysOf(rows: EntryRows): string[] {
|
||||
return [...rows.trips.map((row) => useKey(0, row.id)), ...rows.saved.map((row) => useKey(1, row.id))];
|
||||
}
|
||||
|
||||
/** Whether the user turned the pair down: a dismissal names one use of each side. */
|
||||
function isDismissed(dismissed: ReadonlySet<string>, a: EntryRows | undefined, b: EntryRows | undefined): boolean {
|
||||
if (!a || !b || dismissed.size === 0) return false;
|
||||
const usesOfB = useKeysOf(b);
|
||||
return useKeysOf(a).some((x) => usesOfB.some((y) => dismissed.has(pairKey(x, y))));
|
||||
}
|
||||
|
||||
function sideOf(rows: EntryRows, candidate: DuplicateCandidate, access: OriginAccess): PlacesLibraryDuplicateSide {
|
||||
return {
|
||||
key: candidate.key,
|
||||
@@ -65,7 +85,8 @@ function sideOf(rows: EntryRows, candidate: DuplicateCandidate, access: OriginAc
|
||||
* on request over the entries they reach today and paged: two entries that
|
||||
* share a provider id, or carry the same name (trimmed, case ignored) within
|
||||
* `COORD_DEDUP_TOLERANCE`. Entries are bucketed first (`findDuplicates`), so
|
||||
* no entry is compared with every other. Pairs the user turned down stay out.
|
||||
* no entry is compared with every other. Pairs the user turned down stay out,
|
||||
* matched by the uses each side holds, so a dismissal outlives a key change.
|
||||
*/
|
||||
@Injectable()
|
||||
export class PlaceDuplicatesService {
|
||||
@@ -87,7 +108,9 @@ export class PlaceDuplicatesService {
|
||||
const dismissed = await this.identities.dismissedPairs(user.id);
|
||||
const pairs = findDuplicates(rows.map(candidateOf)).filter((pair) => {
|
||||
const key = pairKey(pair.a.key, pair.b.key);
|
||||
return !dismissed.has(key) && (after === null || key > after);
|
||||
return (
|
||||
!isDismissed(dismissed, rowsByKey.get(pair.a.key), rowsByKey.get(pair.b.key)) && (after === null || key > after)
|
||||
);
|
||||
});
|
||||
const page = pairs.slice(0, limit);
|
||||
|
||||
|
||||
@@ -73,7 +73,7 @@ export class PlaceIdentitiesMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'unlink_library_place',
|
||||
description: `Take one trip place (kind trip) or saved place (kind list) out of the own place of yours it is part of; it is an entry of its own again. Answers the entry it belongs to now. ${OWN_ONLY}`,
|
||||
description: `Take one trip place (kind trip) or saved place (kind list) out of the own place of yours it is part of; it is an entry of its own again. Works also for a place in a trip or list you can no longer open; the answer then holds no entry. Answers the entry it belongs to now. ${OWN_ONLY}`,
|
||||
inputSchema: placesLibraryUnlinkRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
@@ -123,7 +123,7 @@ export class PlaceIdentitiesMcp {
|
||||
@Tool({
|
||||
name: 'undo_library_merge',
|
||||
description:
|
||||
'Take a merge of merge_library_places back by its merge_id: the places the merged entry brought along are an own place of their own again.',
|
||||
'Take a merge of merge_library_places back by its merge_id: both entries are as they were before it. The places the merged entry brought along are its own again, and an own place the merge made for an entry that was none goes again; a place moved since stays where it is now.',
|
||||
inputSchema: placesLibraryUndoMergeRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
|
||||
@@ -2,8 +2,12 @@ import { UserPlaceLinks } from '../../db/entities/UserPlaceLinks.entity';
|
||||
import { UserPlaceMergeDismissals } from '../../db/entities/UserPlaceMergeDismissals.entity';
|
||||
import { UserPlaceMerges } from '../../db/entities/UserPlaceMerges.entity';
|
||||
import { UserPlaces } from '../../db/entities/UserPlaces.entity';
|
||||
import { USER_PLACE_MERGE_MOVED_LINKS } from '../../db/json-columns';
|
||||
import type { LinkedUse, UserPlaceLinksRepository } from '../../db/repositories/UserPlaceLinks.repository';
|
||||
import { USER_PLACE_MERGE_MOVED_LINKS, type MergedLink, type UserPlaceMergeLog } from '../../db/json-columns';
|
||||
import type {
|
||||
LinkedUse,
|
||||
UserPlaceLinksRepository,
|
||||
UserPlaceLinkUse,
|
||||
} from '../../db/repositories/UserPlaceLinks.repository';
|
||||
import type { UserPlaceMergeDismissalsRepository } from '../../db/repositories/UserPlaceMergeDismissals.repository';
|
||||
import type { UserPlaceMergesRepository } from '../../db/repositories/UserPlaceMerges.repository';
|
||||
import type { UserPlaceFacts, UserPlacesRepository } from '../../db/repositories/UserPlaces.repository';
|
||||
@@ -11,7 +15,16 @@ import { decodeJson, encodeJson } from '../../utils/json-column';
|
||||
import { badRequest, forbidden, notFound } from '../common/domain-error';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { pairKey } from './place-duplicates.helpers';
|
||||
import { anchorOfIdentity, anchorOfKey, firstUseOf, useKey, type EntryRows } from './places-library.helpers';
|
||||
import {
|
||||
anchorOfIdentity,
|
||||
anchorOfKey,
|
||||
firstUseOf,
|
||||
fromListOf,
|
||||
identityOfAnchor,
|
||||
readInChunks,
|
||||
useKey,
|
||||
type EntryRows,
|
||||
} from './places-library.helpers';
|
||||
import { PlacesLibraryService, placeNotFound, type LibraryReach, type LibraryUser } from './places-library.service';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
@@ -40,7 +53,8 @@ function usesOfRows(rows: EntryRows): LinkedUse[] {
|
||||
* (`user_places`, `user_place_links`, `user_place_merges`); no trip place and
|
||||
* no saved place is written, so nothing reaches anyone else and nothing needs
|
||||
* a realtime event. Every use named must be one the user reaches today
|
||||
* (the library's checks), else it is not found.
|
||||
* (the library's checks), else it is not found; only taking a use out works
|
||||
* on the user's own link alone, so a use out of reach can still leave.
|
||||
*
|
||||
* An own place left without a link is removed in the same transaction as the
|
||||
* write that emptied it; one emptied by a deleted trip, place or list goes at
|
||||
@@ -70,8 +84,9 @@ export class PlaceIdentitiesService {
|
||||
async link(user: LibraryUser, request: PlacesLibraryLinkRequest): Promise<PlacesLibraryEntryResponse> {
|
||||
const uses = uniqueUses(request.uses);
|
||||
const reach = await this.library.reach(user.id);
|
||||
const reachable = new Set((await this.library.usesOf(reach, null)).map((use) => useKey(use.from_list, use.use_id)));
|
||||
if (uses.some((use) => !reachable.has(useKey(use.kind === 'trip' ? 0 : 1, use.id)))) throw placeNotFound();
|
||||
const reached = await this.library.reachedUses(reach, uses);
|
||||
const reachable = new Set(reached.map((use) => useKey(use.from_list, use.use_id)));
|
||||
if (uses.some((use) => !reachable.has(useKey(fromListOf(use.kind), use.id)))) throw placeNotFound();
|
||||
if (request.identity_id !== undefined) {
|
||||
const own = await this.identities.findOwn(user.id, request.identity_id);
|
||||
if (!own || own.merged_into_id !== null) throw placeNotFound();
|
||||
@@ -90,12 +105,18 @@ export class PlaceIdentitiesService {
|
||||
return { entry: await this.library.entry(user, anchorOfIdentity(identityId)) };
|
||||
}
|
||||
|
||||
/** Takes one use out of the own place it is in; it is an entry of its own (or of its source) again. */
|
||||
/**
|
||||
* Takes one use out of the own place it is in; it is an entry of its own (or
|
||||
* of its source) again. The link is the user's own row, so it can be taken
|
||||
* out also once its trip or list is out of reach; the answer then holds no entry.
|
||||
*/
|
||||
async unlink(user: LibraryUser, use: PlacesLibraryUse): Promise<PlacesLibraryEntryResponse> {
|
||||
const reach = await this.library.reach(user.id);
|
||||
if ((await this.library.anchorOfUse(reach, use.kind, use.id)) === null) throw placeNotFound();
|
||||
const link = await this.links.findForUse(user.id, use);
|
||||
if (!link) throw notAssigned();
|
||||
if (!link) {
|
||||
if ((await this.library.anchorOfUse(reach, use.kind, use.id)) === null) throw placeNotFound();
|
||||
throw notAssigned();
|
||||
}
|
||||
await this.uow.transactional(async () => {
|
||||
await this.links.deleteOwn(user.id, link.id);
|
||||
await this.identities.touch(user.id, link.user_place_id);
|
||||
@@ -110,7 +131,8 @@ export class PlaceIdentitiesService {
|
||||
* to the leading one, and the other is marked merged into it. The merged
|
||||
* place keeps the leading entry's name and position; neither is written into
|
||||
* a trip or a list. Refused while either side holds a use the user cannot
|
||||
* open any more, since they could not see what they merge.
|
||||
* open any more, since they could not see what they merge. The merge logs
|
||||
* what it moved and what it made, each link with the use it names, for its undo.
|
||||
*/
|
||||
async merge(user: LibraryUser, leadingKey: string, otherKey: string): Promise<PlacesLibraryMergeResponse> {
|
||||
const leading = anchorOfKey(leadingKey);
|
||||
@@ -125,29 +147,45 @@ export class PlaceIdentitiesService {
|
||||
}
|
||||
const { mergeId, leadId } = await this.uow.transactional(async () => {
|
||||
const leadId = await this.materialize(user.id, lead);
|
||||
const made = lead.identity ? [] : await this.links.linksOf(user.id, leadId);
|
||||
const restId = await this.materialize(user.id, rest);
|
||||
const moved = await this.links.idsOf(user.id, restId);
|
||||
await this.links.moveTo(user.id, moved, leadId);
|
||||
const moved = await this.links.linksOf(user.id, restId);
|
||||
await this.links.moveTo(
|
||||
user.id,
|
||||
moved.map((link) => link.link),
|
||||
leadId,
|
||||
);
|
||||
await this.identities.setMergedInto(user.id, restId, leadId);
|
||||
await this.identities.touch(user.id, leadId);
|
||||
const mergeId = await this.merges.record(
|
||||
user.id,
|
||||
leadId,
|
||||
restId,
|
||||
encodeJson(USER_PLACE_MERGE_MOVED_LINKS, moved),
|
||||
);
|
||||
const log: UserPlaceMergeLog = {
|
||||
moved: moved.map(loggedLink),
|
||||
made: made.map(loggedLink),
|
||||
merged_made: rest.identity === null,
|
||||
};
|
||||
const mergeId = await this.merges.record(user.id, leadId, restId, encodeJson(USER_PLACE_MERGE_MOVED_LINKS, log));
|
||||
return { mergeId, leadId };
|
||||
});
|
||||
return { merge_id: mergeId, entry: await this.library.entry(user, anchorOfIdentity(leadId)) };
|
||||
}
|
||||
|
||||
/** Takes a merge back: the moved links return to the merged place, which stands on its own again. */
|
||||
/**
|
||||
* Takes a merge back to how the entries were before it: the moved links
|
||||
* return to the merged place, which stands on its own again, and what the
|
||||
* merge made only for itself (an own place for an entry that was none, with
|
||||
* its links) goes again. Only a link still in the leading place and still
|
||||
* naming the use it named then is touched; one changed since stays as it is.
|
||||
*/
|
||||
async undoMerge(user: LibraryUser, mergeId: number): Promise<SuccessResponse> {
|
||||
const merge = await this.merges.findOwn(user.id, mergeId);
|
||||
if (!merge) throw mergeNotFound();
|
||||
const moved = decodeJson(USER_PLACE_MERGE_MOVED_LINKS, merge.moved_link_ids, `user_place_merges ${merge.id}`);
|
||||
const log = decodeJson(USER_PLACE_MERGE_MOVED_LINKS, merge.moved_link_ids, `user_place_merges ${merge.id}`);
|
||||
await this.uow.transactional(async () => {
|
||||
await this.links.moveTo(user.id, moved, merge.merged_id);
|
||||
const unchanged = await this.unchangedLinks(merge.leading_id, [...log.moved, ...log.made]);
|
||||
const moved = log.moved.filter((link) => unchanged.has(link.link)).map((link) => link.link);
|
||||
const made = log.made.filter((link) => unchanged.has(link.link)).map((link) => link.link);
|
||||
if (log.merged_made) await this.links.deleteIds(user.id, moved);
|
||||
else await this.links.moveTo(user.id, moved, merge.merged_id);
|
||||
await this.links.deleteIds(user.id, made);
|
||||
await this.identities.setMergedInto(user.id, merge.merged_id, null);
|
||||
await this.identities.touch(user.id, merge.leading_id);
|
||||
await this.merges.deleteIds([merge.id]);
|
||||
@@ -156,16 +194,26 @@ export class PlaceIdentitiesService {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/** Turns a duplicate suggestion down, so it is not suggested again. */
|
||||
/**
|
||||
* Turns a duplicate suggestion down, so it is not suggested again. The pair
|
||||
* is kept by one use of each side (an own place by its first link) rather
|
||||
* than by the entry keys, which change when an entry becomes an own place or
|
||||
* a merge is undone; the suggestion stays out while each side holds that use.
|
||||
*/
|
||||
async dismiss(userId: number, a: string, b: string): Promise<SuccessResponse> {
|
||||
if (anchorOfKey(a) === null || anchorOfKey(b) === null) throw placeNotFound();
|
||||
const anchorA = anchorOfKey(a);
|
||||
const anchorB = anchorOfKey(b);
|
||||
if (anchorA === null || anchorB === null) throw placeNotFound();
|
||||
if (a === b) throw badRequest('Pick two different places');
|
||||
const [keyA, keyB] = pairKey(a, b).split('|') as [string, string];
|
||||
const useA = await this.useKeyOf(userId, a, anchorA);
|
||||
const useB = await this.useKeyOf(userId, b, anchorB);
|
||||
if (useA === useB) throw badRequest('Pick two different places');
|
||||
const [keyA, keyB] = pairKey(useA, useB).split('|') as [string, string];
|
||||
await this.dismissals.dismiss(userId, { key_a: keyA, key_b: keyB });
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
/** The suggestions the user turned down, by pair key. */
|
||||
/** The suggestions the user turned down, by the pair key of one use of each side. */
|
||||
async dismissedPairs(userId: number): Promise<Set<string>> {
|
||||
return new Set((await this.dismissals.listForUser(userId)).map((row) => pairKey(row.key_a, row.key_b)));
|
||||
}
|
||||
@@ -189,6 +237,32 @@ export class PlaceIdentitiesService {
|
||||
return (await this.wholeIdentitiesOf(userId, rows)).every(Boolean);
|
||||
}
|
||||
|
||||
/** The use an entry key is kept by: the key itself for a trip or saved place, an own place's first link. */
|
||||
private async useKeyOf(userId: number, key: string, anchor: number): Promise<string> {
|
||||
const identityId = identityOfAnchor(anchor);
|
||||
if (identityId === null) return key;
|
||||
const [first] = await this.links.linksOf(userId, identityId);
|
||||
if (!first) throw placeNotFound();
|
||||
return `${first.kind}:${first.id}`;
|
||||
}
|
||||
|
||||
/** The logged links still in the own place `leadingId` that name the use they named then, by id. */
|
||||
private async unchangedLinks(leadingId: number, logged: readonly MergedLink[]): Promise<Set<number>> {
|
||||
const byId = await this.linksById(logged.map((link) => link.link));
|
||||
return new Set(
|
||||
logged.flatMap((link) => {
|
||||
const now = byId.get(link.link);
|
||||
return now && sameLink(now, link, leadingId) ? [link.link] : [];
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/** The links `ids` that still exist, by id. */
|
||||
private async linksById(ids: number[]): Promise<Map<number, UserPlaceLinkUse>> {
|
||||
const rows = await readInChunks([...new Set(ids)], (chunk) => this.links.byIds(chunk));
|
||||
return new Map(rows.map((row) => [row.link, row]));
|
||||
}
|
||||
|
||||
/** Moves the uses into the own place `id`, out of any other of the user's. Runs inside the caller's transaction. */
|
||||
private async attach(
|
||||
userId: number,
|
||||
@@ -240,25 +314,40 @@ export class PlaceIdentitiesService {
|
||||
}
|
||||
|
||||
/**
|
||||
* Drops the merges none of whose moved links is left, then the own places of
|
||||
* the user (of everyone when null) that hold no link and no merge names.
|
||||
* Drops the merges none of whose moved links is left as the merge left it
|
||||
* (in the leading place, naming the same use), then the own places of the
|
||||
* user (of everyone when null) that hold no link and no merge names.
|
||||
* Runs inside the caller's transaction.
|
||||
*/
|
||||
private async prune(userId: number | null): Promise<number> {
|
||||
const merges = await this.merges.list(userId);
|
||||
const moved = new Map(
|
||||
merges.map((merge) => [
|
||||
merge.id,
|
||||
decodeJson(USER_PLACE_MERGE_MOVED_LINKS, merge.moved_link_ids, `user_place_merges ${merge.id}`),
|
||||
]),
|
||||
const merges = (await this.merges.list(userId)).map((merge) => ({
|
||||
id: merge.id,
|
||||
leadingId: merge.leading_id,
|
||||
moved: decodeJson(USER_PLACE_MERGE_MOVED_LINKS, merge.moved_link_ids, `user_place_merges ${merge.id}`).moved,
|
||||
}));
|
||||
const byId = await this.linksById(merges.flatMap((merge) => merge.moved.map((link) => link.link)));
|
||||
const spent = merges.filter(
|
||||
(merge) =>
|
||||
!merge.moved.some((link) => {
|
||||
const now = byId.get(link.link);
|
||||
return now !== undefined && sameLink(now, link, merge.leadingId);
|
||||
}),
|
||||
);
|
||||
const alive = new Set(await this.links.existing([...new Set([...moved.values()].flat())]));
|
||||
const spent = merges.filter((merge) => !(moved.get(merge.id) ?? []).some((id) => alive.has(id)));
|
||||
await this.merges.deleteIds(spent.map((merge) => merge.id));
|
||||
return this.identities.pruneEmpty(userId);
|
||||
}
|
||||
}
|
||||
|
||||
/** A link as a merge logs it: its id with the use it names. */
|
||||
function loggedLink(link: UserPlaceLinkUse): MergedLink {
|
||||
return { link: link.link, kind: link.kind, id: link.id };
|
||||
}
|
||||
|
||||
/** Whether a link as it is now is the logged one, still in the own place `userPlaceId`. */
|
||||
function sameLink(now: UserPlaceLinkUse, logged: MergedLink, userPlaceId: number): boolean {
|
||||
return now.user_place_id === userPlaceId && now.kind === logged.kind && now.id === logged.id;
|
||||
}
|
||||
|
||||
/** The uses once each, in the order given. */
|
||||
function uniqueUses(uses: readonly PlacesLibraryUse[]): LinkedUse[] {
|
||||
const seen = new Set<string>();
|
||||
|
||||
@@ -62,6 +62,21 @@ export function useKey(fromList: number, id: number): string {
|
||||
return `${fromList === 0 ? 'trip' : 'list'}:${id}`;
|
||||
}
|
||||
|
||||
/** How many ids one `IN (...)` of the library binds at most. */
|
||||
export const IN_LIST_CHUNK = 500;
|
||||
|
||||
/**
|
||||
* Reads `items` in blocks of `IN_LIST_CHUNK` and joins what each block
|
||||
* answered, in the blocks' order; nothing is read for no items. Keeps a large
|
||||
* library under SQLite's and Postgres' limits on bound parameters.
|
||||
*/
|
||||
export async function readInChunks<T, R>(items: readonly T[], read: (chunk: T[]) => Promise<R[]>): Promise<R[]> {
|
||||
const chunks = Array.from({ length: Math.ceil(items.length / IN_LIST_CHUNK) }, (_, index) =>
|
||||
items.slice(index * IN_LIST_CHUNK, (index + 1) * IN_LIST_CHUNK),
|
||||
);
|
||||
return (await Promise.all(chunks.map(read))).flat();
|
||||
}
|
||||
|
||||
/** The `from_list` of a use kind. */
|
||||
export function fromListOf(kind: PlacesLibraryKind): number {
|
||||
return kind === 'trip' ? 0 : 1;
|
||||
|
||||
@@ -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. Each entry has a key, 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, 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.`,
|
||||
inputSchema: placesLibraryQuerySchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
entryKey,
|
||||
entryOf,
|
||||
fromListOf,
|
||||
readInChunks,
|
||||
groupBy,
|
||||
identityOfAnchor,
|
||||
infoOf,
|
||||
@@ -165,6 +166,15 @@ export class PlacesLibraryService {
|
||||
return this.repo.anchorOfUse(armsOfReach(reach), fromListOf(kind), id);
|
||||
}
|
||||
|
||||
/** Which of `uses` the user reaches, each with the entry it stands for. */
|
||||
async reachedUses(
|
||||
reach: LibraryReach,
|
||||
uses: readonly { kind: PlacesLibraryKind; id: number }[],
|
||||
): Promise<LibraryUseRow[]> {
|
||||
const wanted = uses.map((use) => ({ fromList: fromListOf(use.kind), useId: use.id }));
|
||||
return readInChunks(wanted, (chunk) => this.repo.reachedUses(armsOfReach(reach), chunk));
|
||||
}
|
||||
|
||||
/** The uses the user reaches, of the entries `anchors` or of all of them. */
|
||||
async usesOf(reach: LibraryReach, anchors: number[] | null): Promise<LibraryUseRow[]> {
|
||||
return this.repo.usesOf(armsOfReach(reach), anchors);
|
||||
@@ -180,9 +190,10 @@ export class PlacesLibraryService {
|
||||
const id = identityOfAnchor(anchor);
|
||||
return id === null ? [] : [id];
|
||||
});
|
||||
const trips = tripPlaceIds.length > 0 ? await this.repo.tripPlaces(tripPlaceIds, reach.tripIds) : [];
|
||||
const saved = savedIds.length > 0 ? await this.repo.savedPlaces(reach.collectionIds, savedIds) : [];
|
||||
const identities = identityIds.length > 0 ? await this.repo.identities(reach.userId, identityIds) : [];
|
||||
// In blocks, so a large library stays under the engines' limits on bound parameters.
|
||||
const trips = await readInChunks(tripPlaceIds, (chunk) => this.repo.tripPlaces(chunk, reach.tripIds));
|
||||
const saved = await readInChunks(savedIds, (chunk) => this.repo.savedPlaces(reach.collectionIds, chunk));
|
||||
const identities = await readInChunks(identityIds, (chunk) => this.repo.identities(reach.userId, chunk));
|
||||
return rowsByAnchor(anchors, own, trips, saved, identities);
|
||||
}
|
||||
|
||||
|
||||
@@ -81,7 +81,7 @@ export class TripCollectionsMcp {
|
||||
@Tool({
|
||||
name: 'unlink_collection_from_trip',
|
||||
description:
|
||||
'Unlink a list of saved places from a trip. The list and its places stay as they are. Needs the permission to edit the trip places and the list to be open to you.',
|
||||
'Unlink a list of saved places from a trip. The list and its places stay as they are. Needs the permission to edit the trip places; the list need not be open to you, so a link nobody on the trip can open any more can still be taken off.',
|
||||
inputSchema: linkInput,
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
when: addonGate(ADDON_IDS.COLLECTIONS),
|
||||
|
||||
@@ -38,9 +38,11 @@ const collectionNotFound = () => notFound('Collection not found');
|
||||
* PLC-15/PLC-16: the lists of saved places a trip draws on. A link gives no
|
||||
* one access: each member sees a linked list, its count included, only while
|
||||
* the list is open to them on their own (owner or accepted member), and
|
||||
* nothing of a list that is not. Linking and unlinking take 'place_edit' on
|
||||
* the trip and a list the caller can see; a list they cannot see is not
|
||||
* found. A trip or list deleted takes its links along (ON DELETE CASCADE).
|
||||
* nothing of a list that is not. Linking takes 'place_edit' on the trip and
|
||||
* a list the caller can see (a list they cannot see is not found); unlinking
|
||||
* takes 'place_edit' alone. A trip or list deleted takes its links along
|
||||
* (ON DELETE CASCADE), and a member leaving or taken off the trip takes the
|
||||
* links nobody left on it can open (`TripMembersRepository.dropUnseenCollectionLinks`).
|
||||
* Nothing here writes a trip place or a saved place.
|
||||
*/
|
||||
@Injectable()
|
||||
@@ -110,9 +112,14 @@ export class TripCollectionsService {
|
||||
return this.list(tripId, { id: writer.userId, role: writer.role });
|
||||
}
|
||||
|
||||
/** Unlinks a list the writer can open from the trip; the list itself stays as it is. */
|
||||
/**
|
||||
* Unlinks a list from the trip; the list itself stays as it is. 'place_edit'
|
||||
* on the trip is enough, so a link to a list the writer cannot open (its
|
||||
* owner left the trip, the list was unshared) can still be taken off; a list
|
||||
* not linked answers the same whether the writer could open it or not.
|
||||
*/
|
||||
async unlink(tripId: number, collectionId: number, writer: TripWriter): Promise<TripCollectionLinksResponse> {
|
||||
await this.gate(tripId, collectionId, writer);
|
||||
await this.requireLinkWrite(tripId, writer);
|
||||
if (!(await this.links.unlink(tripId, collectionId))) throw notFound('This list is not linked to the trip');
|
||||
writer.events.emit('tripCollections:changed', {});
|
||||
return this.list(tripId, { id: writer.userId, role: writer.role });
|
||||
@@ -149,7 +156,12 @@ export class TripCollectionsService {
|
||||
|
||||
/** The trip with 'place_edit' (404, 403) and a list the writer can see (404). */
|
||||
private async gate(tripId: number, collectionId: number, writer: TripWriter): Promise<void> {
|
||||
await requireTripWrite({ access: this.trips, permissions: this.permissions }, LINK_PERMISSION, tripId, writer);
|
||||
await this.requireLinkWrite(tripId, writer);
|
||||
if ((await this.collections.roleOf(writer.userId, collectionId)) === null) throw collectionNotFound();
|
||||
}
|
||||
|
||||
/** 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,6 +218,8 @@ export class TripMembersService {
|
||||
const wasMember = await this.tripMembersRepo.exists(tripId, targetUserId);
|
||||
await this.tripMembersRepo.remove(tripId, targetUserId);
|
||||
await this.tripMembersRepo.leaveJournalLink(tripId, targetUserId);
|
||||
// A list only they could open would stay linked unseen and come back once it is shared again.
|
||||
await this.tripMembersRepo.dropUnseenCollectionLinks(tripId);
|
||||
// Taken off by somebody else, they must not walk back in through the
|
||||
// trip's invite link (GHSA-wr4c-964p-39jg). Leaving yourself leaves no note.
|
||||
if (wasMember && removedBy !== targetUserId) await this.tripMembersRepo.recordRemoval(tripId, targetUserId);
|
||||
|
||||
Reference in New Issue
Block a user