feat(server): let a trip owner switch trip addons for one trip

A trip can now turn a trip addon (lists, costs, documents, collab, road
trip, tours) on or off for itself, whatever the instance switch says. No
row in the new trip_addon_overrides table means the trip follows the
instance; a row is the owner's choice. Going back to the instance setting
deletes the row, and no addon data is touched either way.

- GET/PUT /api/trips/:tripId/addons[/:addonId] (every member reads, the
  owner writes) and the MCP tools get_trip_addons and set_trip_addon, on
  the shared tripAddons contract; tripAddons:changed tells the members.
- Every trip-scoped addon surface asks the trip: REST through
  TripAddonGuard, MCP through a per-call gate on the named or pinned trip,
  plugin RPC and events, the share link, the offline bundle, reminders,
  doc sync, the assistant (tools, keep_attached_file), booking costs, the
  trip summary prompt, and the cross-trip tour reads (library, Atlas
  stats, collection save).
- Routes without a trip open while the addon is on in any of the user's
  trips. Switching an addon on that the instance has off ends the members'
  MCP sessions so they reconnect with its tools.
- A copied trip takes its owner's choices along.

Behaviour changes: an anonymous call to an addon route that is off now
gets 401 instead of 404, and with an instance switch off the packing,
todo and files plugin RPC methods, the files MCP tools, todo reminder
mails, core plugin events, plugin view contributions, the share link's
lists, costs and chat sections and the offline bundle's lists follow it.
This commit is contained in:
Maurice
2026-11-21 13:23:02 +01:00
parent 2f7b8357ce
commit 3f38621024
203 changed files with 3710 additions and 498 deletions
+4 -1
View File
@@ -1,6 +1,7 @@
import { EntityRepositoryType, type Opt, defineEntity, p } from '@mikro-orm/core';
import { Collection, EntityRepositoryType, type Opt, defineEntity, p } from '@mikro-orm/core';
import { AddonsRepository } from '../repositories/Addons.repository';
import { IntegerFlagType } from '../types';
import { TripAddonOverrides } from './TripAddonOverrides.entity';
export interface AddonConfig {
[key: string]: unknown;
@@ -16,6 +17,7 @@ export class Addons {
enabled?: boolean | null;
config?: AddonConfig | null;
sort_order?: number | null = 0;
trip_addon_overrides_collection = new Collection<TripAddonOverrides>(this);
}
export const AddonsSchema = defineEntity({
@@ -30,5 +32,6 @@ export const AddonsSchema = defineEntity({
enabled: p.type(IntegerFlagType).nullable().default(false),
config: p.json<AddonConfig>().nullable().default('{}'),
sort_order: p.integer().nullable(),
trip_addon_overrides_collection: () => p.oneToMany(TripAddonOverrides).mappedBy('addon').hidden(),
},
});
@@ -0,0 +1,30 @@
import { EntityRepositoryType, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TripAddonOverridesRepository } from '../repositories/TripAddonOverrides.repository';
import { DbTimestampType } from '../types';
import { Addons } from './Addons.entity';
import { Trips } from './Trips.entity';
export class TripAddonOverrides {
[EntityRepositoryType]?: TripAddonOverridesRepository;
[PrimaryKeyProp]?: ['trip', 'addon'];
trip!: Ref<Trips>;
trip_id!: number;
addon!: Ref<Addons>;
addon_id!: string;
enabled!: number;
updated_at?: string | null;
}
export const TripAddonOverridesSchema = defineEntity({
class: TripAddonOverrides,
repository: () => TripAddonOverridesRepository,
uniques: [{ properties: ['trip', 'addon'] }],
properties: {
trip: () => p.manyToOne(Trips).primary().ref().hidden(),
trip_id: p.integer().persist(false),
addon: () => p.manyToOne(Addons).primary().ref().hidden().index('idx_trip_addon_overrides_addon_id'),
addon_id: p.text().persist(false).index('idx_trip_addon_overrides_addon_id'),
enabled: p.integer(),
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
},
});
+3
View File
@@ -35,6 +35,7 @@ import { Tags } from './Tags.entity';
import { TodoCategoryAssignees } from './TodoCategoryAssignees.entity';
import { TodoItems } from './TodoItems.entity';
import { TourDrafts } from './TourDrafts.entity';
import { TripAddonOverrides } from './TripAddonOverrides.entity';
import { TripAlbumLinks } from './TripAlbumLinks.entity';
import { TripDocumentLinks } from './TripDocumentLinks.entity';
import { TripFiles } from './TripFiles.entity';
@@ -98,6 +99,7 @@ export class Trips {
todo_category_assignees_collection = new Collection<TodoCategoryAssignees>(this);
todo_items_collection = new Collection<TodoItems>(this);
tour_drafts_collection = new Collection<TourDrafts>(this);
trip_addon_overrides_collection = new Collection<TripAddonOverrides>(this);
trip_album_links_collection = new Collection<TripAlbumLinks>(this);
trip_document_links_collection = new Collection<TripDocumentLinks>(this);
trip_files_collection = new Collection<TripFiles>(this);
@@ -177,6 +179,7 @@ export const TripsSchema = defineEntity({
todo_category_assignees_collection: () => p.oneToMany(TodoCategoryAssignees).mappedBy('trip').hidden(),
todo_items_collection: () => p.oneToMany(TodoItems).mappedBy('trip').hidden(),
tour_drafts_collection: () => p.oneToMany(TourDrafts).mappedBy('trip').hidden(),
trip_addon_overrides_collection: () => p.oneToMany(TripAddonOverrides).mappedBy('trip').hidden(),
trip_album_links_collection: () => p.oneToMany(TripAlbumLinks).mappedBy('trip').hidden(),
trip_document_links_collection: () => p.oneToMany(TripDocumentLinks).mappedBy('trip').hidden(),
trip_files_collection: () => p.oneToMany(TripFiles).mappedBy('trip').hidden(),
+2
View File
@@ -144,6 +144,7 @@ import { ToursSchema } from './Tours.entity';
import { TrekPhotoCacheMetaSchema } from './TrekPhotoCacheMeta.entity';
import { TrekPhotoSignalsSchema } from './TrekPhotoSignals.entity';
import { TrekPhotosSchema } from './TrekPhotos.entity';
import { TripAddonOverridesSchema } from './TripAddonOverrides.entity';
import { TripAlbumLinksSchema } from './TripAlbumLinks.entity';
import { TripDocumentLinksSchema } from './TripDocumentLinks.entity';
import { TripFilesSchema } from './TripFiles.entity';
@@ -319,6 +320,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TrekPhotoCacheMetaSchema,
TrekPhotoSignalsSchema,
TrekPhotosSchema,
TripAddonOverridesSchema,
TripAlbumLinksSchema,
TripDocumentLinksSchema,
TripFilesSchema,
@@ -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 TripAddonOverridesTable {
trip_id: number;
addon_id: string;
enabled: number;
updated_at: InsertOptional<string | null>;
}
+2
View File
@@ -150,6 +150,7 @@ import type { ToursTable } from './Tours.table';
import type { TrekPhotoCacheMetaTable } from './TrekPhotoCacheMeta.table';
import type { TrekPhotoSignalsTable } from './TrekPhotoSignals.table';
import type { TrekPhotosTable } from './TrekPhotos.table';
import type { TripAddonOverridesTable } from './TripAddonOverrides.table';
import type { TripAlbumLinksTable } from './TripAlbumLinks.table';
import type { TripDocumentLinksTable } from './TripDocumentLinks.table';
import type { TripFilesTable } from './TripFiles.table';
@@ -331,6 +332,7 @@ export interface DB {
trek_photo_cache_meta: TrekPhotoCacheMetaTable;
trek_photo_signals: TrekPhotoSignalsTable;
trek_photos: TrekPhotosTable;
trip_addon_overrides: TripAddonOverridesTable;
trip_album_links: TripAlbumLinksTable;
trip_document_links: TripDocumentLinksTable;
trip_files: TripFilesTable;
@@ -0,0 +1,42 @@
import { engineDdl } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* A trip can switch a trip addon (lists, costs, files, collab, road trip,
* tours) on or off for itself, whatever the instance says.
*
* No row means the trip follows the instance switch in `addons.enabled`. A row
* is the owner's explicit choice in either direction: `enabled` 1 turns the
* addon on for this trip although the admin switched it off, 0 hides it here
* although it is on everywhere else. Going back to the instance setting
* deletes the row. Nothing of the addon's data is touched either way.
*
* The rows go with their trip, and with their addon should an addon row ever
* be removed. The primary key leads with `trip_id`, which covers the trip's
* foreign key; `addon_id` gets an index of its own for the addon's.
*/
export class Migration20200101046490_a_trip_can_switch_its_own_addons extends Migration {
override name = 'Migration20200101046490_a_trip_can_switch_its_own_addons';
override up(): void {
engineDdl(this, {
sqlite: [
`CREATE TABLE trip_addon_overrides (
trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE,
addon_id TEXT NOT NULL REFERENCES addons(id) ON DELETE CASCADE,
enabled INTEGER NOT NULL,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (trip_id, addon_id)
)`,
'CREATE INDEX idx_trip_addon_overrides_addon_id ON trip_addon_overrides(addon_id)',
],
postgres: [
'create table "trip_addon_overrides" ("trip_id" bigint not null, "addon_id" text not null, "enabled" bigint not null, "updated_at" text null default to_char((CURRENT_TIMESTAMP AT TIME ZONE \'UTC\'), \'YYYY-MM-DD HH24:MI:SS\'), primary key ("trip_id", "addon_id"))',
'create index "idx_trip_addon_overrides_addon_id" on "trip_addon_overrides" ("addon_id")',
'alter table "trip_addon_overrides" add constraint "trip_addon_overrides_trip_id_addon_id_unique" unique ("trip_id", "addon_id")',
'alter table "trip_addon_overrides" add constraint "trip_addon_overrides_trip_id_foreign" foreign key ("trip_id") references "trips" ("id") on update cascade on delete cascade',
'alter table "trip_addon_overrides" add constraint "trip_addon_overrides_addon_id_foreign" foreign key ("addon_id") references "addons" ("id") on update cascade on delete cascade',
],
});
}
}
@@ -0,0 +1,116 @@
import type { TripAddonOverrides } from '../entities/TripAddonOverrides.entity';
import type { DB } from '../kysely/db';
import { dbNow } from '../types';
import { TrekRepository } from './_shared/trek-repository';
/** One trip's explicit choice for one addon: on or off, whatever the instance says. */
interface TripAddonOverrideRow {
addon_id: string;
enabled: boolean;
}
type OverridesKyselyDB = Pick<DB, 'trip_addon_overrides'>;
type OverridesAccessKyselyDB = Pick<DB, 'trip_addon_overrides' | 'trips' | 'trip_members'>;
/**
* `trip_addon_overrides`: a sparse, trip-scoped override of the instance's addon
* switch. No row means the trip follows `addons.enabled`; a row is the owner's
* explicit on (1) or off (0). Resetting to the instance setting deletes the row,
* so a trip never holds a row that merely repeats the default it inherits.
*/
export class TripAddonOverridesRepository extends TrekRepository<TripAddonOverrides> {
/** Every override the trip holds, in addon id order. */
async listForTrip(trip_id: number): Promise<TripAddonOverrideRow[]> {
const rows = await this.kysely<OverridesKyselyDB>()
.selectFrom('trip_addon_overrides')
.select(['addon_id', 'enabled'])
.where('trip_id', '=', trip_id)
.orderBy('addon_id')
.execute();
return rows.map((row) => ({ addon_id: row.addon_id, enabled: row.enabled === 1 }));
}
/** The trip's override for one addon: true or false, or null when it follows the instance. */
async findForTrip(trip_id: number, addon_id: string): Promise<boolean | null> {
const row = await this.kysely<OverridesKyselyDB>()
.selectFrom('trip_addon_overrides')
.select('enabled')
.where('trip_id', '=', trip_id)
.where('addon_id', '=', addon_id)
.executeTakeFirst();
return row ? row.enabled === 1 : null;
}
/** The choices these trips made for one addon; a trip that follows the instance has no row. */
async listForTrips(
trip_ids: readonly number[],
addon_id: string,
): Promise<Array<{ trip_id: number; enabled: boolean }>> {
if (trip_ids.length === 0) return [];
const rows = await this.kysely<OverridesKyselyDB>()
.selectFrom('trip_addon_overrides')
.select(['trip_id', 'enabled'])
.where('addon_id', '=', addon_id)
.where('trip_id', 'in', [...trip_ids])
.execute();
return rows.map((row) => ({ trip_id: row.trip_id, enabled: row.enabled === 1 }));
}
/** Sets the trip's choice for one addon, replacing an earlier one, and stamps when. */
async upsertOverride(trip_id: number, addon_id: string, enabled: boolean): Promise<void> {
const value = enabled ? 1 : 0;
const at = dbNow();
await this.kysely<OverridesKyselyDB>()
.insertInto('trip_addon_overrides')
.values({ trip_id, addon_id, enabled: value, updated_at: at })
.onConflict((oc) => oc.columns(['trip_id', 'addon_id']).doUpdateSet({ enabled: value, updated_at: at }))
.execute();
}
/** Drops the trip's choice for one addon, so the instance setting applies again. */
async deleteOverride(trip_id: number, addon_id: string): Promise<void> {
await this.kysely<OverridesKyselyDB>()
.deleteFrom('trip_addon_overrides')
.where('trip_id', '=', trip_id)
.where('addon_id', '=', addon_id)
.execute();
}
/**
* Gives a copied trip the choices of the trip it was copied from, in one
* statement. The new trip holds no rows yet, so the conflict target only
* keeps a repeated copy from failing.
*/
async copyForTrip(from_trip_id: number, to_trip_id: number): Promise<void> {
await this.kysely<OverridesKyselyDB>()
.insertInto('trip_addon_overrides')
.columns(['trip_id', 'addon_id', 'enabled', 'updated_at'])
.expression((eb) =>
eb
.selectFrom('trip_addon_overrides as o')
.select([eb.val(to_trip_id).as('trip_id'), 'o.addon_id', 'o.enabled', eb.val(dbNow()).as('updated_at')])
.where('o.trip_id', '=', from_trip_id),
)
.onConflict((oc) => oc.columns(['trip_id', 'addon_id']).doNothing())
.execute();
}
/**
* Whether any trip the user owns or is a member of switched the addon on for
* itself. Routes without a trip (a library, a search across trips) open on
* that when the instance switch is off.
*/
async anyEnabledForUser(user_id: number, addon_id: string): Promise<boolean> {
const row = await this.kysely<OverridesAccessKyselyDB>()
.selectFrom('trip_addon_overrides as o')
.innerJoin('trips as t', 't.id', 'o.trip_id')
.leftJoin('trip_members as m', (join) => join.onRef('m.trip_id', '=', 't.id').on('m.user_id', '=', user_id))
.select('o.trip_id')
.where('o.addon_id', '=', addon_id)
.where('o.enabled', '=', 1)
.where((eb) => eb.or([eb('t.user_id', '=', user_id), eb('m.user_id', 'is not', null)]))
.limit(1)
.executeTakeFirst();
return row !== undefined;
}
}