feat(journey): a trip can link a journal and open it to the members it picks

A trip can now show one journal from the Journey addon as its own: any
journal its owner picks, and one journal on as many trips as they like.
The trip members chosen for the link get into the journal as viewers or
editors, see it in their own journal list and follow it live, for as long
as the link holds them and they stay on the trip.

That access is never copied into journey_contributors. It is read where
journal access is read: the contributor repository answers with the
stronger of a direct role and a link role, the journal list and the live
update recipients take the link members in, and the photo access check
goes the same way. Every one of those reads starts from linkReach, which
only counts members still on the linking trip, so unlinking, deselecting
someone and their leaving the trip all end exactly what the link gave.
A member who leaves is also taken off the link, so coming back later does
not quietly reopen the journal.

Linking or changing the members takes the journal's owner and the new
journal_link trip permission (trip owner by default); unlinking takes
either. /api/trips/:tripId/journal answers the link as each member may see
it, /candidates says who a journal would be opened to for the first time,
and four MCP tools do the same over the same service. A trip:journal:changed
event tells the trip to look again.
This commit is contained in:
Maurice
2026-10-18 15:59:31 +02:00
parent e725d4f0a9
commit 80b6739362
61 changed files with 1405 additions and 33 deletions
@@ -6,6 +6,7 @@ import { JourneyEntries } from './JourneyEntries.entity';
import { JourneyPhotos } from './JourneyPhotos.entity';
import { JourneyShareTokens } from './JourneyShareTokens.entity';
import { JourneyTrips } from './JourneyTrips.entity';
import { TripJournalLinks } from './TripJournalLinks.entity';
import { Users } from './Users.entity';
export class Journeys {
@@ -32,6 +33,7 @@ export class Journeys {
journey_photos_collection = new Collection<JourneyPhotos>(this);
journey_share_tokens: Ref<JourneyShareTokens> | null = null;
journey_trips_collection = new Collection<JourneyTrips>(this);
trip_journal_links_collection = new Collection<TripJournalLinks>(this);
}
export const JourneysSchema = defineEntity({
@@ -60,5 +62,6 @@ export const JourneysSchema = defineEntity({
journey_photos_collection: () => p.oneToMany(JourneyPhotos).mappedBy('journey').hidden(),
journey_share_tokens: () => p.oneToOne(JourneyShareTokens).ref().mappedBy('journey').hidden(),
journey_trips_collection: () => p.oneToMany(JourneyTrips).mappedBy('journey').hidden(),
trip_journal_links_collection: () => p.oneToMany(TripJournalLinks).mappedBy('journey').hidden(),
},
});
@@ -0,0 +1,38 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TripJournalLinkMembersRepository } from '../repositories/TripJournalLinkMembers.repository';
import { TripJournalLinks } from './TripJournalLinks.entity';
import { Users } from './Users.entity';
export class TripJournalLinkMembers {
[EntityRepositoryType]?: TripJournalLinkMembersRepository;
[PrimaryKeyProp]?: ['trip', 'user'];
trip!: Ref<TripJournalLinks>;
trip_id!: number;
user!: Ref<Users>;
user_id!: number;
role: TTripJournalLinkMembersRole & Opt = TripJournalLinkMembersRole.VIEWER;
hide_skeletons: number & Opt = 0;
added_at!: number;
}
export const TripJournalLinkMembersRole = {
VIEWER: 'viewer',
EDITOR: 'editor',
} as const;
export type TTripJournalLinkMembersRole = (typeof TripJournalLinkMembersRole)[keyof typeof TripJournalLinkMembersRole];
export const TripJournalLinkMembersSchema = defineEntity({
class: TripJournalLinkMembers,
repository: () => TripJournalLinkMembersRepository,
uniques: [{ properties: ['trip', 'user'] }],
properties: {
trip: () => p.manyToOne(TripJournalLinks).primary().ref().name('trip_id').hidden(),
trip_id: p.integer().persist(false),
user: () => p.manyToOne(Users).primary().ref().hidden().index('idx_trip_journal_link_members_user'),
user_id: p.integer().persist(false).index('idx_trip_journal_link_members_user'),
role: p.enum(() => TripJournalLinkMembersRole).default('viewer'),
hide_skeletons: p.integer().default(0),
added_at: p.integer(),
},
});
@@ -0,0 +1,34 @@
import { Collection, EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TripJournalLinksRepository } from '../repositories/TripJournalLinks.repository';
import { Journeys } from './Journeys.entity';
import { TripJournalLinkMembers } from './TripJournalLinkMembers.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class TripJournalLinks {
[EntityRepositoryType]?: TripJournalLinksRepository;
[PrimaryKeyProp]?: 'trip';
trip?: Ref<Trips> | null;
trip_id?: number | null;
journey!: Ref<Journeys>;
journey_id!: number;
linked_by?: number | null;
created_at!: number;
linkedByRef?: Ref<Users> | null;
trip_journal_link_members_collection = new Collection<TripJournalLinkMembers>(this);
}
export const TripJournalLinksSchema = defineEntity({
class: TripJournalLinks,
repository: () => TripJournalLinksRepository,
properties: {
trip: () => p.oneToOne(Trips).primary().ref().deleteRule('cascade').nullable().hidden(),
trip_id: p.integer().nullable().persist(false),
journey: () => p.manyToOne(Journeys).ref().deleteRule('cascade').hidden().index('idx_trip_journal_links_journey'),
journey_id: p.integer().persist(false).index('idx_trip_journal_links_journey'),
linked_by: p.integer().nullable().persist(false).index('idx_trip_journal_links_linked_by'),
created_at: p.integer(),
linkedByRef: () => p.manyToOne(Users).ref().joinColumn('linked_by').nullable().hidden().index('idx_trip_journal_links_linked_by'),
trip_journal_link_members_collection: () => p.oneToMany(TripJournalLinkMembers).mappedBy('trip').hidden(),
},
});
+3
View File
@@ -32,6 +32,7 @@ import { TripAlbumLinks } from './TripAlbumLinks.entity';
import { TripDocumentLinks } from './TripDocumentLinks.entity';
import { TripFiles } from './TripFiles.entity';
import { TripInviteTokens } from './TripInviteTokens.entity';
import { TripJournalLinks } from './TripJournalLinks.entity';
import { TripMembers } from './TripMembers.entity';
import { TripPhotos } from './TripPhotos.entity';
import { Users } from './Users.entity';
@@ -84,6 +85,7 @@ export class Trips {
trip_document_links_collection = new Collection<TripDocumentLinks>(this);
trip_files_collection = new Collection<TripFiles>(this);
trip_invite_tokens_collection = new Collection<TripInviteTokens>(this);
trip_journal_links: Ref<TripJournalLinks> | null = null;
trip_members_collection = new Collection<TripMembers>(this);
trip_photos_collection = new Collection<TripPhotos>(this);
}
@@ -145,6 +147,7 @@ export const TripsSchema = defineEntity({
trip_document_links_collection: () => p.oneToMany(TripDocumentLinks).mappedBy('trip').hidden(),
trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('trip').hidden(),
trip_invite_tokens_collection: () => p.oneToMany(TripInviteTokens).mappedBy('trip').hidden(),
trip_journal_links: () => p.oneToOne(TripJournalLinks).ref().mappedBy('trip').hidden(),
trip_members_collection: () => p.oneToMany(TripMembers).mappedBy('trip').hidden(),
trip_photos_collection: () => p.oneToMany(TripPhotos).mappedBy('trip').hidden(),
},
+6
View File
@@ -57,6 +57,8 @@ import { TripAlbumLinks } from './TripAlbumLinks.entity';
import { TripDocumentLinks } from './TripDocumentLinks.entity';
import { TripFiles } from './TripFiles.entity';
import { TripInviteTokens } from './TripInviteTokens.entity';
import { TripJournalLinkMembers } from './TripJournalLinkMembers.entity';
import { TripJournalLinks } from './TripJournalLinks.entity';
import { TripMembers } from './TripMembers.entity';
import { TripPhotos } from './TripPhotos.entity';
import { Trips } from './Trips.entity';
@@ -182,6 +184,8 @@ export class Users {
trip_document_links_collection = new Collection<TripDocumentLinks>(this);
trip_files_collection = new Collection<TripFiles>(this);
trip_invite_tokens_collection = new Collection<TripInviteTokens>(this);
trip_journal_link_members_collection = new Collection<TripJournalLinkMembers>(this);
trip_journal_links_collection = new Collection<TripJournalLinks>(this);
trip_members_collection = new Collection<TripMembers>(this);
trip_members_collection1 = new Collection<TripMembers>(this);
trip_photos_collection = new Collection<TripPhotos>(this);
@@ -325,6 +329,8 @@ export const UsersSchema = defineEntity({
trip_document_links_collection: () => p.oneToMany(TripDocumentLinks).mappedBy('createdByRef').hidden(),
trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('uploadedByRef').hidden(),
trip_invite_tokens_collection: () => p.oneToMany(TripInviteTokens).mappedBy('createdByRef').hidden(),
trip_journal_link_members_collection: () => p.oneToMany(TripJournalLinkMembers).mappedBy('user').hidden(),
trip_journal_links_collection: () => p.oneToMany(TripJournalLinks).mappedBy('linkedByRef').hidden(),
trip_members_collection: () => p.oneToMany(TripMembers).mappedBy('user').hidden(),
trip_members_collection1: () => p.oneToMany(TripMembers).mappedBy('invitedByRef').hidden(),
trip_photos_collection: () => p.oneToMany(TripPhotos).mappedBy('user').hidden(),
+4
View File
@@ -116,6 +116,8 @@ import { TripAlbumLinksSchema } from './TripAlbumLinks.entity';
import { TripDocumentLinksSchema } from './TripDocumentLinks.entity';
import { TripFilesSchema } from './TripFiles.entity';
import { TripInviteTokensSchema } from './TripInviteTokens.entity';
import { TripJournalLinkMembersSchema } from './TripJournalLinkMembers.entity';
import { TripJournalLinksSchema } from './TripJournalLinks.entity';
import { TripMembersSchema } from './TripMembers.entity';
import { TripPhotosSchema } from './TripPhotos.entity';
import { TripsSchema } from './Trips.entity';
@@ -256,6 +258,8 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TripDocumentLinksSchema,
TripFilesSchema,
TripInviteTokensSchema,
TripJournalLinkMembersSchema,
TripJournalLinksSchema,
TripMembersSchema,
TripPhotosSchema,
TripsSchema,
@@ -0,0 +1,11 @@
// Generated by scripts/generate-db-types.ts from the migrated schema. Do not edit by hand:
// change the migration, then run `npm run gen:db-types`.
import type { InsertOptional } from './columns';
export interface TripJournalLinkMembersTable {
trip_id: number;
user_id: number;
role: InsertOptional<string>;
hide_skeletons: InsertOptional<number>;
added_at: number;
}
@@ -0,0 +1,10 @@
// 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 TripJournalLinksTable {
trip_id: InsertOptional<number>;
journey_id: number;
linked_by: InsertOptional<number | null>;
created_at: number;
}
+4
View File
@@ -122,6 +122,8 @@ import type { TripAlbumLinksTable } from './TripAlbumLinks.table';
import type { TripDocumentLinksTable } from './TripDocumentLinks.table';
import type { TripFilesTable } from './TripFiles.table';
import type { TripInviteTokensTable } from './TripInviteTokens.table';
import type { TripJournalLinkMembersTable } from './TripJournalLinkMembers.table';
import type { TripJournalLinksTable } from './TripJournalLinks.table';
import type { TripMembersTable } from './TripMembers.table';
import type { TripPhotosTable } from './TripPhotos.table';
import type { TripsTable } from './Trips.table';
@@ -268,6 +270,8 @@ export interface DB {
trip_document_links: TripDocumentLinksTable;
trip_files: TripFilesTable;
trip_invite_tokens: TripInviteTokensTable;
trip_journal_link_members: TripJournalLinkMembersTable;
trip_journal_links: TripJournalLinksTable;
trip_members: TripMembersTable;
trip_photos: TripPhotosTable;
trips: TripsTable;
@@ -0,0 +1,43 @@
import { Migration } from '@mikro-orm/migrations';
/**
* A trip can show one journal from the Journey addon as its own. The link
* belongs to the trip, not to the journal's own trips (`journey_trips`): any
* journal its owner chooses, and one journal may hang off several trips.
* `linked_by` names who linked it, kept when that account goes as unknown.
*
* `trip_journal_link_members` lists the trip members the link lets into the
* journal, as viewer or editor, apart from `journey_contributors` so that
* unlinking, deselecting someone or their leaving the trip takes away exactly
* the access the link gave and nothing the journal's owner granted directly.
* `hide_skeletons` is that member's own journal preference, which for a direct
* contributor sits on the contributor row. A member's rows go with the link,
* with the trip and with the account.
*/
export class Migration20200101044300_a_trip_links_a_journal extends Migration {
override name = 'Migration20200101044300_a_trip_links_a_journal';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS trip_journal_links (
trip_id INTEGER PRIMARY KEY REFERENCES trips(id) ON DELETE CASCADE,
journey_id INTEGER NOT NULL REFERENCES journeys(id) ON DELETE CASCADE,
linked_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
created_at INTEGER NOT NULL
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_trip_journal_links_journey ON trip_journal_links(journey_id)');
this.addSql('CREATE INDEX IF NOT EXISTS idx_trip_journal_links_linked_by ON trip_journal_links(linked_by)');
this.addSql(`
CREATE TABLE IF NOT EXISTS trip_journal_link_members (
trip_id INTEGER NOT NULL REFERENCES trip_journal_links(trip_id) ON DELETE CASCADE,
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
role TEXT NOT NULL DEFAULT 'viewer' CHECK (role IN ('viewer', 'editor')),
hide_skeletons INTEGER NOT NULL DEFAULT 0,
added_at INTEGER NOT NULL,
PRIMARY KEY (trip_id, user_id)
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_trip_journal_link_members_user ON trip_journal_link_members(user_id)');
}
}
@@ -1,5 +1,6 @@
import type { JourneyContributors } from '../entities/JourneyContributors.entity';
import type { DB } from '../kysely/db';
import { readLinkHideSkeletons, readLinkRole, type TripJournalLinkKyselyDB } from './TripJournalLinks.repository';
import { TrekRepository } from './_shared/trek-repository';
/** JG18's contributor-list row (`getJourneyFull`) — the junction plus the joined username/avatar. */
@@ -15,6 +16,9 @@ export interface JourneyContributorListRow {
/** The `journey_contributors`/`users` tables {@link JourneyContributorsRepository.listForJourney} reads. */
type JourneyContributorListKyselyDB = Pick<DB, 'journey_contributors' | 'users'>;
/** The table the access reads below take a person's own contributor row from. */
type JourneyContributorRowKyselyDB = Pick<DB, 'journey_contributors'>;
/**
* `journey_contributors` — a genuine TWO-column composite primary key
* (`journey` + `user`, both `.primary()`, R3 — pinned against
@@ -26,36 +30,53 @@ type JourneyContributorListKyselyDB = Pick<DB, 'journey_contributors' | 'users'>
* pinned in `task-1-report.md`.
*/
export class JourneyContributorsRepository extends TrekRepository<JourneyContributors> {
/** JG4 — `canAccessJourney`'s contributor-match primitive: `SELECT 1 FROM journey_contributors WHERE journey_id = ? AND user_id = ?`. */
async existsForUser(journeyId: number, userId: number): Promise<boolean> {
const row = await this.qb('jc')
.select(['jc.journey'])
.where({ journey: journeyId, user: userId })
.execute<unknown>('get', false);
return !!row;
/** The person's own contributor row on the journal, if they have one. */
private async directRow(journeyId: number, userId: number) {
return await this.kysely<JourneyContributorRowKyselyDB>()
.selectFrom('journey_contributors')
.select(['role', 'hide_skeletons'])
.where('journey_id', '=', journeyId)
.where('user_id', '=', userId)
.executeTakeFirst();
}
/** JG7/JG21 — `canEdit`'s edit-access primitive and `getJourneyFull`'s `myRole` resolution: `SELECT role FROM journey_contributors WHERE journey_id = ? AND user_id = ?`. */
async findRole(journeyId: number, userId: number): Promise<string | undefined> {
const row = await this.qb('jc')
.select(['jc.role'])
.where({ journey: journeyId, user: userId })
.execute<{ role: string } | undefined>('get', false);
return row?.role;
/** JG4 — whether a person may open the journal: as a contributor, or through a trip's link. */
async hasAccess(journeyId: number, userId: number): Promise<boolean> {
return (await this.findAccessRole(journeyId, userId)) !== undefined;
}
/** JG20/JG27 — `getJourneyFull`'s `hide_skeletons` preference read and `updateJourneyPreferences`'s re-read, one statement text. */
/**
* JG7/JG21 — the role a person acts with on the journal, for `canEdit` and
* `my_role`: their contributor role, or the role a trip's link gives them
* when that is the stronger one. Undefined with neither.
*/
async findAccessRole(journeyId: number, userId: number): Promise<string | undefined> {
const direct = await this.directRow(journeyId, userId);
if (direct?.role === 'owner' || direct?.role === 'editor') return direct.role;
const linked = await readLinkRole(this.kysely<TripJournalLinkKyselyDB>(), journeyId, userId);
return linked ?? direct?.role;
}
/** JG20/JG27 — the person's "hide skeletons" choice, from their contributor row or else from their link. */
async getHideSkeletons(journeyId: number, userId: number): Promise<boolean> {
const row = await this.qb('jc')
.select(['jc.hide_skeletons'])
.where({ journey: journeyId, user: userId })
.execute<{ hide_skeletons: number } | undefined>('get', false);
return !!row?.hide_skeletons;
const direct = await this.directRow(journeyId, userId);
if (direct) return !!direct.hide_skeletons;
return !!(await readLinkHideSkeletons(this.kysely<TripJournalLinkKyselyDB>(), journeyId, userId));
}
/** JG26 — `updateJourneyPreferences`'s write: `UPDATE journey_contributors SET hide_skeletons = ? WHERE journey_id = ? AND user_id = ?`. */
/** JG26 — stores that choice where `getHideSkeletons` reads it: the contributor row, or else the person's links. */
async setHideSkeletons(journeyId: number, userId: number, value: number): Promise<void> {
await this.nativeUpdate({ journey: journeyId, user: userId }, { hide_skeletons: value });
if (await this.directRow(journeyId, userId)) {
await this.nativeUpdate({ journey: journeyId, user: userId }, { hide_skeletons: value });
return;
}
const db = this.kysely<TripJournalLinkKyselyDB>();
await db
.updateTable('trip_journal_link_members')
.set({ hide_skeletons: value })
.where('user_id', '=', userId)
.where('trip_id', 'in', db.selectFrom('trip_journal_links').select('trip_id').where('journey_id', '=', journeyId))
.execute();
}
/** JG18 — `getJourneyFull`'s contributor list, joined to `users` for `username`/`avatar` (`avatar_url` is computed in the SERVICE, unchanged). */
@@ -1,5 +1,6 @@
import type { Journeys } from '../entities/Journeys.entity';
import type { DB } from '../kysely/db';
import { linkReach, type TripJournalLinkKyselyDB } from './TripJournalLinks.repository';
import { TrekRepository } from './_shared/trek-repository';
/**
@@ -114,6 +115,12 @@ export class JourneysRepository extends TrekRepository<Journeys> {
.where('journey_id', '=', id)
.execute();
const ids = new Set(contributors.map((c) => c.user_id));
// The trip members a trip's link lets in follow the journal live as well.
const linked = await linkReach(this.kysely<TripJournalLinkKyselyDB>())
.select('m.user_id')
.where('l.journey_id', '=', id)
.execute();
for (const l of linked) ids.add(l.user_id);
const ownerId = await this.findOwnerId(id);
if (ownerId !== undefined) ids.add(ownerId);
return [...ids];
@@ -169,7 +176,18 @@ export class JourneysRepository extends TrekRepository<Journeys> {
.whereRef('jt2.journey_id', '=', 'j.id')
.as('trip_date_max'),
])
.where((eb) => eb.or([eb('j.user_id', '=', user_id), eb('jc.user_id', '=', user_id)]))
// A journal a trip's link lets this person into is theirs to open here too.
.where((eb) =>
eb.or([
eb('j.user_id', '=', user_id),
eb('jc.user_id', '=', user_id),
eb(
'j.id',
'in',
linkReach(this.kysely<TripJournalLinkKyselyDB>()).select('l.journey_id').where('m.user_id', '=', user_id),
),
]),
)
.orderBy('j.updated_at', 'desc')
.execute();
return rows as JourneyListRow[];
@@ -0,0 +1,4 @@
import type { TripJournalLinkMembers } from '../entities/TripJournalLinkMembers.entity';
import { TrekRepository } from './_shared/trek-repository';
export class TripJournalLinkMembersRepository extends TrekRepository<TripJournalLinkMembers> {}
@@ -0,0 +1,227 @@
import type { TripJournalLinks } from '../entities/TripJournalLinks.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
import type { Kysely } from 'kysely';
/** The tables a link's reach is read from. */
export type TripJournalLinkKyselyDB = Pick<
DB,
'trip_journal_links' | 'trip_journal_link_members' | 'trips' | 'trip_members' | 'journeys' | 'users'
>;
export type TripJournalLinkRole = 'viewer' | 'editor';
/** A trip's link with the journal it shows, as the settings dialog reads it. */
export interface TripJournalLinkRow {
trip_id: number;
journey_id: number;
linked_by: number | null;
created_at: number;
journey_title: string;
journey_subtitle: string | null;
journey_cover_image: string | null;
journey_owner_id: number;
}
/** Someone on the trip, as the member picker lists them. */
export interface TripPersonRow {
user_id: number;
username: string;
avatar: string | null;
is_guest: boolean;
is_trip_owner: boolean;
}
/** One person the link lets into its journal. */
export interface TripJournalLinkMemberRow {
user_id: number;
role: TripJournalLinkRole;
username: string;
avatar: string | null;
}
/**
* The link members who still belong to the linking trip, as its owner or on its
* roster, with the link they hold. Every read of link access starts here, so
* leaving a trip ends what its link gave in the same instant, whether or not
* anything cleaned up after it. A caller narrows it by journal or by person and
* picks its own columns.
*/
export function linkReach(db: Kysely<TripJournalLinkKyselyDB>) {
return db
.selectFrom('trip_journal_links as l')
.innerJoin('trip_journal_link_members as m', 'm.trip_id', 'l.trip_id')
.innerJoin('trips as t', 't.id', 'l.trip_id')
.where((eb) =>
eb.or([
eb('t.user_id', '=', eb.ref('m.user_id')),
eb.exists(
eb
.selectFrom('trip_members as tm')
.select('tm.id')
.whereRef('tm.trip_id', '=', 'l.trip_id')
.whereRef('tm.user_id', '=', 'm.user_id'),
),
]),
);
}
/** The stronger of two link roles; a person linked through two trips gets the better one. */
function strongest(roles: string[]): TripJournalLinkRole | null {
if (roles.includes('editor')) return 'editor';
return roles.length > 0 ? 'viewer' : null;
}
/** The role a person holds on a journal through any trip's link, or null when none lets them in. */
export async function readLinkRole(
db: Kysely<TripJournalLinkKyselyDB>,
journeyId: number,
userId: number,
): Promise<TripJournalLinkRole | null> {
const rows = await linkReach(db)
.select('m.role')
.where('l.journey_id', '=', journeyId)
.where('m.user_id', '=', userId)
.execute();
return strongest(rows.map((r) => r.role));
}
/** A link member's own "hide skeletons" choice on the journal, or null when no link lets them in. */
export async function readLinkHideSkeletons(
db: Kysely<TripJournalLinkKyselyDB>,
journeyId: number,
userId: number,
): Promise<number | null> {
const row = await linkReach(db)
.select('m.hide_skeletons')
.where('l.journey_id', '=', journeyId)
.where('m.user_id', '=', userId)
.executeTakeFirst();
return row?.hide_skeletons ?? null;
}
/**
* `trip_journal_links` and its members: which journal a trip shows, and who
* of the trip may read or write it through that link. The access this table
* gives is read through {@link linkReach} everywhere, never copied into
* `journey_contributors`, so a direct contributor's role is never overwritten
* and undoing a link takes away exactly what it gave.
*/
export class TripJournalLinksRepository extends TrekRepository<TripJournalLinks> {
/** The trip's link with its journal's title and cover, or null without one. */
async findForTrip(tripId: number): Promise<TripJournalLinkRow | null> {
const row = await this.kysely<TripJournalLinkKyselyDB>()
.selectFrom('trip_journal_links as l')
.innerJoin('journeys as j', 'j.id', 'l.journey_id')
.select([
'l.trip_id',
'l.journey_id',
'l.linked_by',
'l.created_at',
'j.title as journey_title',
'j.subtitle as journey_subtitle',
'j.cover_image as journey_cover_image',
'j.user_id as journey_owner_id',
])
.where('l.trip_id', '=', tripId)
.executeTakeFirst();
return row ?? null;
}
/** The people the trip's link lets in, still on the trip or not, with their name for the list. */
async listMembers(tripId: number): Promise<TripJournalLinkMemberRow[]> {
const rows = await this.kysely<TripJournalLinkKyselyDB>()
.selectFrom('trip_journal_link_members as m')
.innerJoin('users as u', 'u.id', 'm.user_id')
.select(['m.user_id', 'm.role', 'u.username', 'u.avatar'])
.where('m.trip_id', '=', tripId)
.orderBy('u.username', 'asc')
.execute();
return rows.map((r) => ({ ...r, role: r.role === 'editor' ? 'editor' : 'viewer' }));
}
/** Everyone on the trip, its owner first, with what the member picker shows of them. */
async listTripPeople(tripId: number): Promise<TripPersonRow[]> {
const db = this.kysely<TripJournalLinkKyselyDB>();
const owner = await db
.selectFrom('trips as t')
.innerJoin('users as u', 'u.id', 't.user_id')
.select(['u.id as user_id', 'u.username', 'u.avatar', 'u.is_guest'])
.where('t.id', '=', tripId)
.executeTakeFirst();
const members = await db
.selectFrom('trip_members as tm')
.innerJoin('users as u', 'u.id', 'tm.user_id')
.select(['u.id as user_id', 'u.username', 'u.avatar', 'u.is_guest'])
.where('tm.trip_id', '=', tripId)
.orderBy('u.username', 'asc')
.execute();
const people = owner ? [{ ...owner, is_trip_owner: true }] : [];
for (const m of members) if (m.user_id !== owner?.user_id) people.push({ ...m, is_trip_owner: false });
return people.map((p) => ({ ...p, is_guest: p.is_guest === 1 }));
}
/** Points the trip at a journal, replacing the one it showed. */
async upsertLink(tripId: number, journeyId: number, linkedBy: number, now: number): Promise<void> {
await this.kysely<TripJournalLinkKyselyDB>()
.insertInto('trip_journal_links')
.values({ trip_id: tripId, journey_id: journeyId, linked_by: linkedBy, created_at: now })
.onConflict((oc) =>
oc.column('trip_id').doUpdateSet({ journey_id: journeyId, linked_by: linkedBy, created_at: now }),
)
.execute();
}
/** Sets who the trip's link lets in, replacing the list it had. */
async replaceMembers(
tripId: number,
members: { user_id: number; role: TripJournalLinkRole }[],
now: number,
): Promise<void> {
const db = this.kysely<TripJournalLinkKyselyDB>();
await db.deleteFrom('trip_journal_link_members').where('trip_id', '=', tripId).execute();
if (members.length === 0) return;
await db
.insertInto('trip_journal_link_members')
.values(members.map((m) => ({ trip_id: tripId, user_id: m.user_id, role: m.role, added_at: now })))
.execute();
}
/** Removes the trip's link; its members go with it. */
async deleteForTrip(tripId: number): Promise<void> {
await this.kysely<TripJournalLinkKyselyDB>()
.deleteFrom('trip_journal_links')
.where('trip_id', '=', tripId)
.execute();
}
/** Takes one person off the trip's link, as when they leave the trip. */
async deleteMember(tripId: number, userId: number): Promise<void> {
await this.kysely<TripJournalLinkKyselyDB>()
.deleteFrom('trip_journal_link_members')
.where('trip_id', '=', tripId)
.where('user_id', '=', userId)
.execute();
}
/** Everyone a journal's links let in, for its live updates. */
async linkRecipientUserIds(journeyId: number): Promise<number[]> {
const rows = await linkReach(this.kysely<TripJournalLinkKyselyDB>())
.select('m.user_id')
.distinct()
.where('l.journey_id', '=', journeyId)
.execute();
return rows.map((r) => r.user_id);
}
/** The trips that show this journal, for telling their members when it changes hands. */
async listTripIdsForJourney(journeyId: number): Promise<number[]> {
const rows = await this.kysely<TripJournalLinkKyselyDB>()
.selectFrom('trip_journal_links')
.select('trip_id')
.where('journey_id', '=', journeyId)
.execute();
return rows.map((r) => r.trip_id);
}
}
+2
View File
@@ -52,6 +52,7 @@ import { AirtrailModule } from './integrations/airtrail.module';
import { DawarichModule } from './integrations/dawarich.module';
import { JourneyAccessModule } from './journey/journey-access.module';
import { JourneyModule } from './journey/journey.module';
import { TripJournalLinkModule } from './journey/trip-journal-link.module';
import { LlmParseModule } from './llm-parse/llm-parse.module';
import { ManagedExtModule } from './managed/managed-ext.module';
import { MapsModule } from './maps/maps.module';
@@ -166,6 +167,7 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
AirtrailModule,
DawarichModule,
JourneyModule,
TripJournalLinkModule,
CollectionsModule,
ShareModule,
TripInviteModule,
@@ -178,7 +178,7 @@ export class JourneyDomainService {
// `SELECT *` read this repository now serves.
const own = await this.journeysRepo.findOwnedByUser(journeyId, userId);
if (own) return own as Journey;
const isContributor = await this.contributorsRepo.existsForUser(journeyId, userId);
const isContributor = await this.contributorsRepo.hasAccess(journeyId, userId);
if (isContributor) return ((await this.journeysRepo.findById(journeyId)) as Journey) || null;
return null;
}
@@ -189,7 +189,7 @@ export class JourneyDomainService {
async canEdit(journeyId: number, userId: number): Promise<boolean> {
if (await this.isOwner(journeyId, userId)) return true;
const role = await this.contributorsRepo.findRole(journeyId, userId);
const role = await this.contributorsRepo.findAccessRole(journeyId, userId);
return role === 'editor' || role === 'owner';
}
@@ -293,7 +293,7 @@ export class JourneyDomainService {
myRole = 'owner';
} else {
// JG21 — same text as JG7 (`findRole`).
const role = await this.contributorsRepo.findRole(journeyId, userId);
const role = await this.contributorsRepo.findAccessRole(journeyId, userId);
myRole = (role as 'editor' | 'viewer' | undefined) ?? null;
}
@@ -0,0 +1,70 @@
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 { TripAccessGuard } from '../permissions/trip-access.guard';
import { TripJournalCandidatesQueryDto, TripJournalLinkDto, TripJournalLinkMembersDto } from './trip-journal-link.dto';
import { TripJournalLinkService } from './trip-journal-link.service';
import { Body, Controller, Delete, Get, Headers, HttpCode, Param, Patch, Put, Query, UseGuards } from '@nestjs/common';
import { tripJournalCandidatesResponseSchema, tripJournalLinkResponseSchema } from '@trek/shared';
/**
* The journal a trip shows, at `/api/trips/:tripId/journal`. Every member of
* the trip may read the link as it concerns them; changing it is decided in the
* service, because it turns on who owns the journal as well as on the trip
* permission. Behind the Journey addon: with it off the routes answer 404.
*/
@Controller('api/trips/:tripId/journal')
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.JOURNEY, 'Journey')
export class TripJournalLinkController {
constructor(private readonly links: TripJournalLinkService) {}
@Get()
@ResponseContract(tripJournalLinkResponseSchema)
async get(@Param('tripId') tripId: string, @CurrentUser() user: User) {
return this.links.get(Number(tripId), user);
}
@Get('candidates')
@ResponseContract(tripJournalCandidatesResponseSchema)
async candidates(
@Param('tripId') tripId: string,
@CurrentUser() user: User,
@Query() query: TripJournalCandidatesQueryDto,
) {
return { candidates: await this.links.candidates(Number(tripId), user, query.journey_id) };
}
@Put()
@ResponseContract(tripJournalLinkResponseSchema)
async link(
@Param('tripId') tripId: string,
@CurrentUser() user: User,
@Body() body: TripJournalLinkDto,
@Headers('x-socket-id') socketId?: string,
) {
return this.links.link(Number(tripId), user, body.journey_id, body.members, socketId);
}
@Patch('members')
@ResponseContract(tripJournalLinkResponseSchema)
async setMembers(
@Param('tripId') tripId: string,
@CurrentUser() user: User,
@Body() body: TripJournalLinkMembersDto,
@Headers('x-socket-id') socketId?: string,
) {
return this.links.setMembers(Number(tripId), user, body.members, socketId);
}
@Delete()
@HttpCode(200)
@ResponseContract(tripJournalLinkResponseSchema)
async unlink(@Param('tripId') tripId: string, @CurrentUser() user: User, @Headers('x-socket-id') socketId?: string) {
return this.links.unlink(Number(tripId), user, socketId);
}
}
@@ -0,0 +1,11 @@
import {
tripJournalCandidatesQuerySchema,
tripJournalLinkMembersRequestSchema,
tripJournalLinkRequestSchema,
} from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class TripJournalLinkDto extends createZodDto(tripJournalLinkRequestSchema) {}
export class TripJournalLinkMembersDto extends createZodDto(tripJournalLinkMembersRequestSchema) {}
export class TripJournalCandidatesQueryDto extends createZodDto(tripJournalCandidatesQuerySchema) {}
@@ -0,0 +1,97 @@
import { ADDON_IDS } from '../../addons';
import {
McpController,
TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_WRITE,
Tool,
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 { TripJournalLinkService, type TripJournalActor } from './trip-journal-link.service';
import { idSchema, tripJournalLinkRequestSchema } from '@trek/shared';
const journeyAddonOn = addonGate(ADDON_IDS.JOURNEY);
/**
* The trip's linked journal over MCP: the same service, the same permission and
* journal-owner rules as `/api/trips/:tripId/journal`, behind the Journey addon.
*/
@McpController()
export class TripJournalLinkMcp {
constructor(
private readonly links: TripJournalLinkService,
private readonly guards: McpToolGuardsService,
readonly addons: AddonsService,
) {}
private async actor(tripId: number, userId: number): Promise<TripJournalActor> {
const { role } = await this.guards.tripWriter(tripId, userId);
return { id: userId, role };
}
@Tool({
name: 'get_trip_journal',
description:
'The journal from the Journey addon a trip shows as its own, if any: its id and title, your access to it, and whether you may link, unlink or change who it is open to. Open the journal itself with get_journey.',
inputSchema: { tripId: idSchema },
annotations: TOOL_ANNOTATIONS_READONLY,
when: journeyAddonOn,
access: { group: 'journey', mode: 'read' },
})
async getTripJournal({ tripId }: { tripId: number }, ctx: McpContext) {
return ok(await this.links.get(tripId, await this.actor(tripId, ctx.userId)));
}
@Tool({
name: 'link_trip_journal',
description:
'Show one of your own journals in a trip, replacing the journal it showed. The trip members listed get into the journal as viewers or editors and see it in their own journal list; members left out do not. Needs the journal to be yours and the trip permission to link journals.',
inputSchema: { tripId: idSchema, journey_id: idSchema, members: tripJournalLinkRequestSchema.shape.members },
annotations: TOOL_ANNOTATIONS_WRITE,
when: journeyAddonOn,
access: { group: 'journey', mode: 'write' },
})
async linkTripJournal(
{
tripId,
journey_id,
members,
}: { tripId: number; journey_id: number; members: { user_id: number; role: 'viewer' | 'editor' }[] },
ctx: McpContext,
) {
return ok(await this.links.link(tripId, await this.actor(tripId, ctx.userId), journey_id, members));
}
@Tool({
name: 'set_trip_journal_members',
description:
"Change which trip members the trip's linked journal is open to, and as viewer or editor. The list replaces the one before; anyone left out loses the access the link gave them. Only the journal's owner can do this.",
inputSchema: { tripId: idSchema, members: tripJournalLinkRequestSchema.shape.members },
annotations: TOOL_ANNOTATIONS_WRITE,
when: journeyAddonOn,
access: { group: 'journey', mode: 'write' },
})
async setTripJournalMembers(
{ tripId, members }: { tripId: number; members: { user_id: number; role: 'viewer' | 'editor' }[] },
ctx: McpContext,
) {
return ok(await this.links.setMembers(tripId, await this.actor(tripId, ctx.userId), members));
}
@Tool({
name: 'unlink_trip_journal',
description:
'Take the linked journal off a trip. The journal itself stays; the members the link let in lose that access, while its owner and direct contributors keep theirs.',
inputSchema: { tripId: idSchema },
annotations: TOOL_ANNOTATIONS_DELETE,
when: journeyAddonOn,
access: { group: 'journey', mode: 'write' },
})
async unlinkTripJournal({ tripId }: { tripId: number }, ctx: McpContext) {
return ok(await this.links.unlink(tripId, await this.actor(tripId, ctx.userId)));
}
}
@@ -0,0 +1,37 @@
import { JourneyContributors } from '../../db/entities/JourneyContributors.entity';
import { TripJournalLinks } from '../../db/entities/TripJournalLinks.entity';
import { AddonsModule } from '../addons/addons.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { JourneyDomainModule } from './journey-domain.module';
import { TripJournalLinkController } from './trip-journal-link.controller';
import { TripJournalLinkMcp } from './trip-journal-link.mcp';
import { TripJournalLinkService } from './trip-journal-link.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
/**
* A trip showing one journal from the Journey addon: the link, its routes and
* its MCP tools. Its own module rather than part of JourneyModule, because the
* trip roster needs `TripJournalLinkService.dropMember` when someone leaves,
* and TripMembersModule must not pull in the whole journey surface (uploads,
* memories, both photo providers) for that. It imports nothing from the trip
* roster in return, so the edge runs one way.
*/
@Module({
imports: [
JourneyDomainModule,
TripMembershipModule,
PermissionsModule,
RealtimeModule,
AddonsModule,
McpSharedModule,
MikroOrmModule.forFeature([TripJournalLinks, JourneyContributors]),
],
controllers: [TripJournalLinkController],
providers: [TripJournalLinkService, TripJournalLinkMcp],
exports: [TripJournalLinkService],
})
export class TripJournalLinkModule {}
@@ -0,0 +1,218 @@
import { JourneyContributors } from '../../db/entities/JourneyContributors.entity';
import { TripJournalLinks } from '../../db/entities/TripJournalLinks.entity';
import type { JourneyContributorsRepository } from '../../db/repositories/JourneyContributors.repository';
import type { TripJournalLinksRepository, TripPersonRow } from '../../db/repositories/TripJournalLinks.repository';
import { avatarUrl } from '../common/avatarUrl';
import { forbidden, notFound } from '../common/domain-error';
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 { JourneyDomainService } from './journey-domain.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type {
TripJournalAccessRole,
TripJournalCandidate,
TripJournalLinkMemberRequest,
TripJournalLinkResponse,
} from '@trek/shared';
/** Who is acting: their id, and their account role for the admin bypass of trip permissions. */
export interface TripJournalActor {
id: number;
role: string;
}
const NOT_LINKED = 'No journal is linked to this trip';
/**
* A trip that shows one journal from the Journey addon as its own.
*
* Linking opens the journal to the trip members chosen for it, as viewers or
* editors, for as long as the link holds them and they stay on the trip. That
* access is read wherever journal access is read (`JourneyContributorsRepository`
* folds it in), so the journal's own screens, its live updates and its MCP tools
* serve linked members without knowing about trips.
*
* Linking a journal, or changing who it is open to, hands someone else's access
* to it, so it takes the journal's owner, and on the trip the `journal_link`
* permission. Taking the link down only takes access away, so the permission
* alone or the journal's owner alone is enough.
*/
@Injectable()
export class TripJournalLinkService {
constructor(
@InjectRepository(TripJournalLinks) private readonly links: TripJournalLinksRepository,
@InjectRepository(JourneyContributors) private readonly contributors: JourneyContributorsRepository,
private readonly journeys: JourneyDomainService,
private readonly tripAccess: TripAccessService,
private readonly permissions: PermissionsService,
private readonly realtime: RealtimeService,
private readonly uow: UnitOfWork,
) {}
/** The trip, or a 404 for someone who is not on it. */
private async requireTrip(tripId: number, actor: TripJournalActor) {
const trip = await this.tripAccess.findAccessible(tripId, actor.id);
if (!trip) throw notFound('Trip not found');
return trip;
}
private async mayLink(trip: { user_id: number }, actor: TripJournalActor): Promise<boolean> {
return this.permissions.checkPermission(
'journal_link',
actor.role,
trip.user_id,
actor.id,
trip.user_id !== actor.id,
);
}
/** The access someone holds on a journal today, as owner, contributor or through a link. */
private async accessOf(journeyId: number, ownerId: number, userId: number): Promise<TripJournalAccessRole | null> {
if (userId === ownerId) return 'owner';
const role = await this.contributors.findAccessRole(journeyId, userId);
return role === 'owner' || role === 'editor' || role === 'viewer' ? role : null;
}
/** The trip's journal as this person sees it, and what they may do with it. */
async get(tripId: number, actor: TripJournalActor): Promise<TripJournalLinkResponse> {
const trip = await this.requireTrip(tripId, actor);
const canLink = await this.mayLink(trip, actor);
const row = await this.links.findForTrip(tripId);
if (!row) return { link: null, can_link: canLink, can_unlink: false, can_edit_members: false };
const isJournalOwner = row.journey_owner_id === actor.id;
const myRole = await this.accessOf(row.journey_id, row.journey_owner_id, actor.id);
const canEditMembers = canLink && isJournalOwner;
const canUnlink = canLink || isJournalOwner;
// Someone the journal is closed to, and who can do nothing about the link,
// does not see that the trip has one.
if (!myRole && !canLink) return { link: null, can_link: false, can_unlink: false, can_edit_members: false };
const members = canLink || isJournalOwner ? await this.links.listMembers(tripId) : null;
return {
link: {
journey_id: row.journey_id,
title: row.journey_title,
subtitle: row.journey_subtitle,
cover_image: row.journey_cover_image,
owner_id: row.journey_owner_id,
linked_by: row.linked_by,
created_at: row.created_at,
my_role: myRole,
members:
members?.map((m) => ({ user_id: m.user_id, username: m.username, avatar_url: avatarUrl(m), role: m.role })) ??
null,
},
can_link: canLink,
can_unlink: canUnlink,
can_edit_members: canEditMembers,
};
}
/**
* The people of the trip who could be let into a journal, with the access they
* hold there today. A null `access` is someone the link would let in for the
* first time, the person the dialog warns about. Only for the journal's owner.
*/
async candidates(tripId: number, actor: TripJournalActor, journeyId: number): Promise<TripJournalCandidate[]> {
await this.requireTrip(tripId, actor);
if (!(await this.journeys.isOwner(journeyId, actor.id))) throw forbidden('Only the journal owner can link it');
const people = (await this.links.listTripPeople(tripId)).filter((p) => !p.is_guest && p.user_id !== actor.id);
return await Promise.all(
people.map(async (p) => ({
user_id: p.user_id,
username: p.username,
avatar_url: avatarUrl(p),
is_trip_owner: p.is_trip_owner,
access: await this.accessOf(journeyId, actor.id, p.user_id),
})),
);
}
/**
* The members a link may hold: people on the trip, never a guest (who cannot
* sign in) and never the journal's owner (who has it anyway). A repeated id
* keeps its last role.
*/
private allowedMembers(
people: TripPersonRow[],
ownerId: number,
members: TripJournalLinkMemberRequest[],
): TripJournalLinkMemberRequest[] {
const onTrip = new Set(people.filter((p) => !p.is_guest).map((p) => p.user_id));
const byUser = new Map<number, TripJournalLinkMemberRequest>();
for (const m of members) {
if (m.user_id === ownerId) continue;
if (!onTrip.has(m.user_id)) throw forbidden('Only members of this trip can be given the journal');
byUser.set(m.user_id, m);
}
return [...byUser.values()];
}
/** Shows a journal in the trip, to these members, replacing the one it showed. */
async link(
tripId: number,
actor: TripJournalActor,
journeyId: number,
members: TripJournalLinkMemberRequest[],
socketId?: string,
): Promise<TripJournalLinkResponse> {
const trip = await this.requireTrip(tripId, actor);
if (!(await this.mayLink(trip, actor))) throw forbidden('No permission to link a journal');
if (!(await this.journeys.isOwner(journeyId, actor.id))) throw forbidden('Only the journal owner can link it');
const allowed = this.allowedMembers(await this.links.listTripPeople(tripId), actor.id, members);
const now = Date.now();
await this.uow.transactional(async () => {
await this.links.upsertLink(tripId, journeyId, actor.id, now);
await this.links.replaceMembers(tripId, allowed, now);
});
this.realtime.broadcast(tripId, 'trip:journal:changed', {}, socketId);
return this.get(tripId, actor);
}
/** Changes who the linked journal is open to. */
async setMembers(
tripId: number,
actor: TripJournalActor,
members: TripJournalLinkMemberRequest[],
socketId?: string,
): Promise<TripJournalLinkResponse> {
const trip = await this.requireTrip(tripId, actor);
const row = await this.links.findForTrip(tripId);
if (!row) throw notFound(NOT_LINKED);
if (!(await this.mayLink(trip, actor)) || row.journey_owner_id !== actor.id) {
throw forbidden('Only the journal owner can change who it is open to');
}
const allowed = this.allowedMembers(await this.links.listTripPeople(tripId), row.journey_owner_id, members);
await this.uow.transactional(async () => {
await this.links.replaceMembers(tripId, allowed, Date.now());
});
this.realtime.broadcast(tripId, 'trip:journal:changed', {}, socketId);
return this.get(tripId, actor);
}
/** Takes the journal off the trip; everyone it let in loses that access. */
async unlink(tripId: number, actor: TripJournalActor, socketId?: string): Promise<TripJournalLinkResponse> {
const trip = await this.requireTrip(tripId, actor);
const row = await this.links.findForTrip(tripId);
if (!row) throw notFound(NOT_LINKED);
if (!(await this.mayLink(trip, actor)) && row.journey_owner_id !== actor.id) {
throw forbidden('No permission to unlink the journal');
}
await this.links.deleteForTrip(tripId);
this.realtime.broadcast(tripId, 'trip:journal:changed', {}, socketId);
return this.get(tripId, actor);
}
/**
* Someone left the trip: their place on its link goes too, so coming back
* later does not quietly reopen the journal. Their access already ended with
* the membership; this only tidies the row. Runs in the caller's transaction.
*/
async dropMember(tripId: number, userId: number): Promise<void> {
await this.links.deleteMember(tripId, userId);
}
}
@@ -57,7 +57,7 @@ export class MemoriesAccessService {
/** MA2's owner-OR-contributor check, shared by MA2 and MA6's per-journey loop — the same two-branch `journeys`/`journey_contributors` logic `canAccessJourney` uses, re-implemented here (see the class docstring on why it isn't a call to `JourneyDomainService`). */
private async ownerOrContributor(journeyId: number, userId: number): Promise<boolean> {
if (await this.journeys.isOwnedByUser(journeyId, userId)) return true;
return await this.journeyContributors.existsForUser(journeyId, userId);
return await this.journeyContributors.hasAccess(journeyId, userId);
}
async canAccessUserPhoto(
@@ -4,6 +4,7 @@ import { Users } from '../../db/entities/Users.entity';
import { AuditModule } from '../audit/audit.module';
import { AuthModule } from '../auth/auth.module';
import { BudgetModule } from '../budget/budget.module';
import { TripJournalLinkModule } from '../journey/trip-journal-link.module';
import { NotificationsModule } from '../notifications/notifications.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { RealtimeModule } from '../realtime/realtime.module';
@@ -34,6 +35,7 @@ import { Module } from '@nestjs/common';
AuditModule,
AuthModule,
BudgetModule,
TripJournalLinkModule,
MikroOrmModule.forFeature([Trips, TripMembers, Users]),
],
controllers: [TripMembersController],
@@ -11,6 +11,7 @@ import { BudgetService } from '../budget/budget.service';
import { avatarUrl } from '../common/avatarUrl';
import { NotFoundError, ValidationError } from '../common/domain-errors';
import { UnitOfWork } from '../database/unit-of-work';
import { TripJournalLinkService } from '../journey/trip-journal-link.service';
import { NotificationsService } from '../notifications/notifications.service';
import { PermissionsService } from '../permissions/permissions.service';
import { RealtimeService } from '../realtime/realtime.service';
@@ -79,6 +80,7 @@ export class TripMembersService {
private readonly permissions: PermissionsService,
private readonly realtime: RealtimeService,
private readonly notifications: NotificationsService,
private readonly journalLinks: TripJournalLinkService,
private readonly uow: UnitOfWork,
@InjectRepository(Trips) private readonly tripsRepo: TripsRepository,
@InjectRepository(TripMembers) private readonly tripMembersRepo: TripMembersRepository,
@@ -197,7 +199,12 @@ export class TripMembersService {
* the route's one remaining raw-string caller).
*/
async removeMember(tripId: number, targetUserId: number): Promise<void> {
await this.tripMembersRepo.remove(tripId, targetUserId);
// A linked journal stops being open to someone who left; coming back later
// must not quietly reopen it.
await this.uow.transactional(async () => {
await this.tripMembersRepo.remove(tripId, targetUserId);
await this.journalLinks.dropMember(tripId, targetUserId);
});
}
/**