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);
}
}