feat(tours): point a tour at its trip's packing list

A tour can now point at the packing list of its trip, as a whole or at one
of its categories (say "Hiking gear" for a hike), and shows it in its detail.
The new Packing list section reads the list live as the user may see it: the
backpack tile with the item count on its corner and the category's own
colour, how many are packed with a thin progress bar, the first items ticked
off or not with their quantity, how many more there are, and a button that
opens the trip's Lists tab. Who may change the tour links one, changes it or
lets go through a dialog that lists the whole list and every category with
its colour and item count, and writes only on its confirm.

It is a reference, never a copy: the items stay in Packing, are ticked off
and edited there, and each traveller sees in the tour only the items Packing
shows them, so an item kept to oneself never shows through a tour. A
category that is renamed, cleared or only holds items of others reads as
missing, an empty one as empty, a link that could not be read says so with a
retry, and while Lists are switched off the link stays, dimmed, and can
still be let go. Removing the link, or the tour, leaves the list and every
item as they are. Nothing suggests or changes an item by itself.

On the server the link is a row of its own in the tours domain
(tour_packing_links, migration 046110), one per tour and gone with it.
GET, PUT and DELETE /api/trips/:tripId/tours/:placeId/packing-link read it
with the trip and change it with place_edit; linking needs the Lists addon
and, for a category, an item of it the user can see. The writes answer the
tour with its link and tell the trip through tours:changed, so the offline
client queues them as writes of the tour and replays them like one. A copied
trip keeps its tours' links, a tour saved as new or taken over does not.
The MCP tools get_tour_packing, link_tour_packing and unlink_tour_packing run
over the same service and checks; the read also hands the tour's facts as
context for suggesting what to pack, which only becomes an item through the
packing tools. The empty category placeholder now lives in @trek/shared so
both sides leave it out alike. All 27 locales carry the new strings, and
the wiki describes the link and the tools.
This commit is contained in:
Maurice
2026-10-20 13:56:42 +02:00
parent 65fe8cd6e5
commit f833a05461
106 changed files with 3661 additions and 22 deletions
+1
View File
@@ -114,6 +114,7 @@
"TourChangeSteps": "tours",
"TourObstacleReviews": "tours",
"TourStationVisits": "tours",
"TourPackingLinks": "tours",
"TourSources": "tours",
"TourTypes": "tours",
"TourWaypoints": "tours",
@@ -0,0 +1,29 @@
import { EntityRepositoryType, type Opt, PrimaryKeyProp, type Ref, defineEntity, p } from '@mikro-orm/core';
import { TourPackingLinksRepository } from '../repositories/TourPackingLinks.repository';
import { DbTimestampType } from '../types';
import { Tours } from './Tours.entity';
import { Users } from './Users.entity';
export class TourPackingLinks {
[EntityRepositoryType]?: TourPackingLinksRepository;
[PrimaryKeyProp]?: 'place';
place?: Ref<Tours> | null;
place_id?: number | null;
category?: string | null;
linked_by?: number | null;
linked_at!: string & Opt;
linkedByRef?: Ref<Users> | null;
}
export const TourPackingLinksSchema = defineEntity({
class: TourPackingLinks,
repository: () => TourPackingLinksRepository,
properties: {
place: () => p.oneToOne(Tours).primary().ref().name('place_id').deleteRule('cascade').nullable().hidden(),
place_id: p.integer().nullable().persist(false),
category: p.text().nullable(),
linked_by: p.integer().nullable().persist(false).index('idx_tour_packing_links_linked_by'),
linked_at: p.type(DbTimestampType).defaultRaw(`CURRENT_TIMESTAMP`),
linkedByRef: () => p.manyToOne(Users).ref().joinColumn('linked_by').nullable().hidden().index('idx_tour_packing_links_linked_by'),
},
});
+3
View File
@@ -6,6 +6,7 @@ import { TourActivities } from './TourActivities.entity';
import { TourActivityExclusions } from './TourActivityExclusions.entity';
import { TourChangeSteps } from './TourChangeSteps.entity';
import { TourObstacleReviews } from './TourObstacleReviews.entity';
import { TourPackingLinks } from './TourPackingLinks.entity';
import { TourSources } from './TourSources.entity';
import { TourTypes } from './TourTypes.entity';
import { TourWaypoints } from './TourWaypoints.entity';
@@ -56,6 +57,7 @@ export class Tours {
tour_activity_exclusions_collection = new Collection<TourActivityExclusions>(this);
tour_change_steps_collection = new Collection<TourChangeSteps>(this);
tour_obstacle_reviews_collection = new Collection<TourObstacleReviews>(this);
tour_packing_links: Ref<TourPackingLinks> | null = null;
tour_sources: Ref<TourSources> | null = null;
tour_waypoints_collection = new Collection<TourWaypoints>(this);
}
@@ -192,6 +194,7 @@ export const ToursSchema = defineEntity({
tour_activity_exclusions_collection: () => p.oneToMany(TourActivityExclusions).mappedBy('place').hidden(),
tour_change_steps_collection: () => p.oneToMany(TourChangeSteps).mappedBy('place').hidden(),
tour_obstacle_reviews_collection: () => p.oneToMany(TourObstacleReviews).mappedBy('place').hidden(),
tour_packing_links: () => p.oneToOne(TourPackingLinks).ref().mappedBy('place').hidden(),
tour_sources: () => p.oneToOne(TourSources).ref().mappedBy('place').hidden(),
tour_waypoints_collection: () => p.oneToMany(TourWaypoints).mappedBy('place').hidden(),
},
+3
View File
@@ -54,6 +54,7 @@ import { TodoCategoryAssignees } from './TodoCategoryAssignees.entity';
import { TodoItems } from './TodoItems.entity';
import { TourActivities } from './TourActivities.entity';
import { TourActivityExclusions } from './TourActivityExclusions.entity';
import { TourPackingLinks } from './TourPackingLinks.entity';
import { TourSources } from './TourSources.entity';
import { TrekPhotos } from './TrekPhotos.entity';
import { TripAlbumLinks } from './TripAlbumLinks.entity';
@@ -184,6 +185,7 @@ export class Users {
todo_items_collection = new Collection<TodoItems>(this);
tour_activities_collection = new Collection<TourActivities>(this);
tour_activity_exclusions_collection = new Collection<TourActivityExclusions>(this);
tour_packing_links_collection = new Collection<TourPackingLinks>(this);
tour_sources_collection = new Collection<TourSources>(this);
trek_photos_collection = new Collection<TrekPhotos>(this);
trip_album_links_collection = new Collection<TripAlbumLinks>(this);
@@ -332,6 +334,7 @@ export const UsersSchema = defineEntity({
todo_items_collection: () => p.oneToMany(TodoItems).mappedBy('assignedUser').hidden(),
tour_activities_collection: () => p.oneToMany(TourActivities).mappedBy('assignedByRef').hidden(),
tour_activity_exclusions_collection: () => p.oneToMany(TourActivityExclusions).mappedBy('user').hidden(),
tour_packing_links_collection: () => p.oneToMany(TourPackingLinks).mappedBy('linkedByRef').hidden(),
tour_sources_collection: () => p.oneToMany(TourSources).mappedBy('importedByRef').hidden(),
trek_photos_collection: () => p.oneToMany(TrekPhotos).mappedBy('owner').hidden(),
trip_album_links_collection: () => p.oneToMany(TripAlbumLinks).mappedBy('user').hidden(),
+2
View File
@@ -112,6 +112,7 @@ import { TourActivitiesSchema } from './TourActivities.entity';
import { TourActivityExclusionsSchema } from './TourActivityExclusions.entity';
import { TourChangeStepsSchema } from './TourChangeSteps.entity';
import { TourObstacleReviewsSchema } from './TourObstacleReviews.entity';
import { TourPackingLinksSchema } from './TourPackingLinks.entity';
import { TourSourcesSchema } from './TourSources.entity';
import { TourStationVisitsSchema } from './TourStationVisits.entity';
import { TourTypesSchema } from './TourTypes.entity';
@@ -261,6 +262,7 @@ export const ALL_ENTITIES: readonly EntitySchema[] = [
TourActivityExclusionsSchema,
TourChangeStepsSchema,
TourObstacleReviewsSchema,
TourPackingLinksSchema,
TourSourcesSchema,
TourStationVisitsSchema,
TourTypesSchema,
@@ -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 TourPackingLinksTable {
place_id: InsertOptional<number>;
category: InsertOptional<string | null>;
linked_by: InsertOptional<number | null>;
linked_at: InsertOptional<string>;
}
+2
View File
@@ -118,6 +118,7 @@ import type { TourActivitiesTable } from './TourActivities.table';
import type { TourActivityExclusionsTable } from './TourActivityExclusions.table';
import type { TourChangeStepsTable } from './TourChangeSteps.table';
import type { TourObstacleReviewsTable } from './TourObstacleReviews.table';
import type { TourPackingLinksTable } from './TourPackingLinks.table';
import type { TourSourcesTable } from './TourSources.table';
import type { TourStationVisitsTable } from './TourStationVisits.table';
import type { TourTypesTable } from './TourTypes.table';
@@ -273,6 +274,7 @@ export interface DB {
tour_activity_exclusions: TourActivityExclusionsTable;
tour_change_steps: TourChangeStepsTable;
tour_obstacle_reviews: TourObstacleReviewsTable;
tour_packing_links: TourPackingLinksTable;
tour_sources: TourSourcesTable;
tour_station_visits: TourStationVisitsTable;
tour_types: TourTypesTable;
@@ -0,0 +1,25 @@
import { Migration } from '@mikro-orm/migrations';
/**
* P2D-XD-01: a tour points at the packing list of its trip, as a whole or at
* one of its categories. The row only names what it points at: `category` is
* NULL for the whole list, otherwise the category as its items carry it. The
* items stay Packing's, so nothing here copies, owns or deletes one, and
* removing the row leaves the list as it was. One link per tour, gone with
* the tour; `linked_by` turns unknown when that account goes.
*/
export class Migration20200101046110_a_tour_points_at_its_packing_list extends Migration {
override name = 'Migration20200101046110_a_tour_points_at_its_packing_list';
override up(): void {
this.addSql(`
CREATE TABLE IF NOT EXISTS tour_packing_links (
place_id INTEGER PRIMARY KEY REFERENCES tours(place_id) ON DELETE CASCADE,
category TEXT,
linked_by INTEGER REFERENCES users(id) ON DELETE SET NULL,
linked_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP
)
`);
this.addSql('CREATE INDEX IF NOT EXISTS idx_tour_packing_links_linked_by ON tour_packing_links(linked_by)');
}
}
@@ -0,0 +1,55 @@
import { currentTimestampKysely } from '../dialect/kysely-functions';
import type { TourPackingLinks } from '../entities/TourPackingLinks.entity';
import type { DB } from '../kysely/db';
import { TrekRepository } from './_shared/trek-repository';
type LinksDB = Pick<DB, 'tour_packing_links'>;
/** What a tour points at in its trip's packing list: null for the whole list, otherwise one category. */
interface TourPackingLinkRow {
category: string | null;
linked_at: string;
}
/**
* `tour_packing_links` (P2D-XD-01): the packing list, or the category of it,
* a tour points at. One row per tour, gone with the tour. It names what it
* points at and nothing else, so no statement here reaches a packing item.
*/
export class TourPackingLinksRepository extends TrekRepository<TourPackingLinks> {
private db() {
return this.kysely<LinksDB>();
}
/** The tour's link; undefined while it points at nothing. */
async findForTour(place_id: number): Promise<TourPackingLinkRow | undefined> {
return await this.db()
.selectFrom('tour_packing_links')
.select(['category', 'linked_at'])
.where('place_id', '=', place_id)
.executeTakeFirst();
}
/** Points the tour at the list or a category, replacing what it pointed at before; the time is the new link's. */
async put(place_id: number, category: string | null, linked_by: number): Promise<void> {
const platform = this.getEntityManager().getPlatform();
await this.db()
.insertInto('tour_packing_links')
.values({ place_id, category, linked_by })
.onConflict((oc) =>
oc.column('place_id').doUpdateSet((eb) => ({
category: eb.ref('excluded.category'),
linked_by: eb.ref('excluded.linked_by'),
// The clock in the spelling of the live database: CURRENT_TIMESTAMP is no function call.
linked_at: currentTimestampKysely(platform),
})),
)
.execute();
}
/** Lets go of what the tour points at; false when it pointed at nothing. */
async remove(place_id: number): Promise<boolean> {
const result = await this.db().deleteFrom('tour_packing_links').where('place_id', '=', place_id).executeTakeFirst();
return Number(result.numDeletedRows ?? 0) > 0;
}
}
@@ -215,6 +215,7 @@ type ToursKyselyDB = Pick<
| 'tour_sources'
| 'days'
| 'tour_obstacle_reviews'
| 'tour_packing_links'
| 'trips'
>;
@@ -569,6 +570,35 @@ export class ToursRepository extends TrekRepository<Tours> {
.execute();
}
/**
* P2D-XD-01: the packing list or category a copied tour pointed at, onto its
* copy in the copied trip, whose packing list is copied too. Nothing for a
* tour that pointed at nothing.
*/
async copyPackingLink(source_place_id: number, place_id: number): Promise<void> {
await this.db()
.insertInto('tour_packing_links')
.columns(['place_id', 'category', 'linked_by', 'linked_at'])
.expression((eb) =>
eb
.selectFrom('tour_packing_links')
.select((inner) => [inner.val(place_id).as('place_id'), 'category', 'linked_by', 'linked_at'])
.where('place_id', '=', source_place_id),
)
.execute();
}
/**
* What a copied trip's tour keeps besides its facet and its points: its
* import record, its obstacle decisions and its packing link, onto its copy.
* Called inside the trip copy's transaction.
*/
async copyTourRelations(source_place_id: number, place_id: number): Promise<void> {
await this.copySource(source_place_id, place_id);
await this.copyObstacleReviews(source_place_id, place_id);
await this.copyPackingLink(source_place_id, place_id);
}
/** The days every tour of a trip sits on, each tour and day once, in day order, with the stage a day holds (MDT-02). */
async listTourDays(trip_id: number): Promise<TourDayRow[]> {
return await this.db()
@@ -0,0 +1,5 @@
import { tourPackingLinkRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
export class TourPackingLinkDto extends createZodDto(tourPackingLinkRequestSchema) {}
@@ -0,0 +1,56 @@
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 { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { TourPackingLinkDto } from './dto/tour-packing-link.dto';
import { TourPackingLinkService } from './tour-packing-link.service';
import { Body, Controller, Delete, Get, Headers, Param, Put, UseGuards } from '@nestjs/common';
import { tourDetailResponseSchema, tourPackingLinkResponseSchema } from '@trek/shared';
/**
* P2D-XD-01 /api/trips/:tripId/tours/:placeId/packing-link: the packing list,
* or the category of it, a tour points at. Reading it needs the trip; pointing
* the tour somewhere else or letting go needs 'place_edit', as every other
* change of a tour does. The writes answer the tour with its link, so a write
* replayed from the offline queue lands like any other tour write.
*/
@Controller('api/trips/:tripId/tours')
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
@RequireAddon(ADDON_IDS.TOURS, 'Tours')
export class TourPackingLinkController {
constructor(private readonly packingLinks: TourPackingLinkService) {}
@Get(':placeId/packing-link')
@ResponseContract(tourPackingLinkResponseSchema)
async read(@Param('tripId') tripId: string, @Param('placeId') placeId: string) {
return await this.packingLinks.read(tripId, placeId);
}
@RequirePermission('place_edit')
@Put(':placeId/packing-link')
@ResponseContract(tourDetailResponseSchema)
async link(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('placeId') placeId: string,
@Body() body: TourPackingLinkDto,
@Headers('x-socket-id') socketId?: string,
) {
return await this.packingLinks.link(tripId, placeId, body, user.id, socketId);
}
@RequirePermission('place_edit')
@Delete(':placeId/packing-link')
@ResponseContract(tourDetailResponseSchema)
async unlink(
@Param('tripId') tripId: string,
@Param('placeId') placeId: string,
@Headers('x-socket-id') socketId?: string,
) {
return await this.packingLinks.unlink(tripId, placeId, socketId);
}
}
@@ -0,0 +1,193 @@
import { ADDON_IDS } from '../../addons';
import { TourPackingLinks } from '../../db/entities/TourPackingLinks.entity';
import { Tours } from '../../db/entities/Tours.entity';
import type { TourPackingLinksRepository } from '../../db/repositories/TourPackingLinks.repository';
import type { TourListRow, ToursRepository } from '../../db/repositories/Tours.repository';
import { AddonsService } from '../addons/addons.service';
import { DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { PackingService } from '../packing/packing.service';
import { ToursService } from './tours.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import {
linkedPackingItems,
type TourDetailResponse,
type TourPackingLink,
type TourPackingLinkRequest,
type TourPackingLinkResponse,
type TourPackingLinkState,
} from '@trek/shared';
/** A packing item as the viewer may see it, with what a link shows of it. */
interface VisiblePackingItem {
id: number;
name: string;
category: string | null;
checked: number | null;
quantity: number;
}
/** One item of a linked list as an assistant reads it. */
interface TourPackingViewItem {
id: number;
name: string;
category: string | null;
quantity: number;
packed: boolean;
}
/**
* P2D-XD-01: a tour's packing link as an assistant reads it: what it points
* at, the items of it the user may see with how many are packed, and the
* tour's own facts as context for a suggestion. Unknown facts stay null.
*/
interface TourPackingView {
packing_link: TourPackingLink | null;
/** How the link reads; null while the tour points at nothing. */
state: TourPackingLinkState | null;
items: TourPackingViewItem[];
packed: number;
total: number;
tour: {
name: string;
tour_type: string;
distance_km: number | null;
elevation_gain_m: number | null;
elevation_loss_m: number | null;
walking_minutes: number | null;
planned_duration_minutes: number | null;
difficulty: string | null;
max_hiking_difficulty: number | null;
};
}
/** A saved tour of the trip, by the ids a route or a tool names it with. */
interface TourInTrip {
tripId: number;
placeId: number;
tour: TourListRow;
}
/**
* P2D-XD-01: a tour points at the packing list of its trip, as a whole or at
* one of its categories. Packing keeps the list, its items and who sees which:
* the link is read against the items the user may see, and nothing here
* copies, changes or deletes one. Linking needs the Packing addon on and, for a
* category, that the user can see an item of it; removing a link leaves the
* list as it was. REST and MCP call the same methods.
*/
@Injectable()
export class TourPackingLinkService {
constructor(
@InjectRepository(TourPackingLinks) private readonly links: TourPackingLinksRepository,
@InjectRepository(Tours) private readonly toursRepo: ToursRepository,
private readonly tours: ToursService,
private readonly packing: PackingService,
private readonly addons: AddonsService,
) {}
/** The saved tour of this trip; 404 for a tour of another trip, a plain place or a malformed id. */
private async tourIn(tripId: number | string, placeId: number | string): Promise<TourInTrip> {
const tid = toRowId(tripId);
const pid = toRowId(placeId);
const tour = tid !== null && pid !== null ? await this.toursRepo.findInTrip(tid, pid) : undefined;
if (!tour || tid === null || pid === null) throw new DomainError(404, 'Tour not found');
return { tripId: tid, placeId: pid, tour };
}
/** Packing has to be on for a link to be made or read through. */
private async requirePacking(): Promise<void> {
if (!(await this.addons.isAddonEnabled(ADDON_IDS.PACKING))) {
throw new DomainError(404, 'Packing addon is not enabled', { code: 'packing_addon_off' });
}
}
/** The packing items of the trip this user may see, in the order Packing lists them. */
private async visibleItems(tripId: number, userId: number): Promise<VisiblePackingItem[]> {
const items: VisiblePackingItem[] = await this.packing.listItems(tripId, userId);
return items;
}
/** What the tour points at; null while it points at nothing. */
async read(tripId: number | string, placeId: number | string): Promise<TourPackingLinkResponse> {
const { placeId: pid } = await this.tourIn(tripId, placeId);
return { packing_link: (await this.links.findForTour(pid)) ?? null };
}
/**
* Points the tour at the whole packing list or at one of its categories,
* replacing what it pointed at. A category must hold an item this user can
* see, so a link never names one they cannot reach. Answers the tour with
* its new link.
*/
async link(
tripId: string,
placeId: string,
body: TourPackingLinkRequest,
userId: number,
socketId?: string,
): Promise<TourDetailResponse> {
const tour = await this.tourIn(tripId, placeId);
await this.requirePacking();
if (body.category !== null) {
const items = await this.visibleItems(tour.tripId, userId);
if (!items.some((item) => item.category === body.category)) {
throw new DomainError(400, 'Packing category not found', { code: 'packing_category_not_found' });
}
}
await this.links.put(tour.placeId, body.category, userId);
return await this.announce(tripId, tour.placeId, socketId);
}
/** Lets go of what the tour points at. The packing list and its items stay as they are. */
async unlink(tripId: string, placeId: string, socketId?: string): Promise<TourDetailResponse> {
const tour = await this.tourIn(tripId, placeId);
await this.links.remove(tour.placeId);
return await this.announce(tripId, tour.placeId, socketId);
}
/** Tells the trip's other clients and answers the tour with its link as it is now. */
private async announce(tripId: string, placeId: number, socketId?: string): Promise<TourDetailResponse> {
this.tours.broadcastToursChanged(tripId, [placeId], socketId);
const detail = await this.tours.getTour(tripId, String(placeId));
return { ...detail, packing_link: (await this.links.findForTour(placeId)) ?? null };
}
/**
* The link as an assistant reads it: the items the user may see of what it
* points at, and the tour's facts as context. Reading changes nothing.
*/
async view(tripId: number, placeId: number, userId: number): Promise<TourPackingView> {
const { tour } = await this.tourIn(tripId, placeId);
await this.requirePacking();
const link = (await this.links.findForTour(placeId)) ?? null;
const context = {
name: tour.name,
tour_type: tour.tour_type,
distance_km: tour.distance,
elevation_gain_m: tour.elevation_gain,
elevation_loss_m: tour.elevation_loss,
walking_minutes: tour.duration,
planned_duration_minutes: tour.planned_duration_minutes,
difficulty: tour.difficulty,
max_hiking_difficulty: tour.max_hiking_difficulty,
};
if (!link) return { packing_link: null, state: null, items: [], packed: 0, total: 0, tour: context };
const linked = linkedPackingItems(link, await this.visibleItems(tripId, userId));
return {
packing_link: link,
state: linked.state,
items: linked.items.map((item) => ({
id: item.id,
name: item.name,
category: item.category,
quantity: item.quantity,
packed: Boolean(item.checked),
})),
packed: linked.packed,
total: linked.items.length,
tour: context,
};
}
}
+104
View File
@@ -0,0 +1,104 @@
import { ADDON_IDS } from '../../addons';
import { canRead, canReadTrips, canWrite } from '../../mcp/scopes';
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
import {
McpController,
Tool,
TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_WRITE,
ok,
type McpContext,
} from '../../nest-mcp';
import { addonGate, type HasAddons } from '../addons/addon-gate';
import { AddonsService } from '../addons/addons.service';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
import { TourPackingLinkService } from './tour-packing-link.service';
import { idSchema, tourPackingLinkRequestSchema, type TourPackingLinkRequest } from '@trek/shared';
const toursOn = addonGate(ADDON_IDS.TOURS);
const packingOn = addonGate(ADDON_IDS.PACKING);
/** A tour's packing link reaches into Packing, so both addons have to be on. */
async function tourPackingOn(ctx: McpContext, self: HasAddons): Promise<boolean> {
return (await toursOn(ctx, self)) && (await packingOn(ctx, self));
}
const tourIds = {
tripId: idSchema,
placeId: idSchema.describe('The place id of the tour, as list_tours gives it'),
};
/**
* P2D-XD-01: the packing list a tour points at, over the same service and the
* same checks as REST: reading needs the trip, pointing the tour somewhere and
* letting go need 'place_edit'. Packing keeps its items; nothing here adds,
* ticks off or removes one.
*/
@McpController()
export class TourPackingMcp {
constructor(
private readonly packingLinks: TourPackingLinkService,
private readonly access: TripAccessService,
private readonly guards: McpToolGuardsService,
// Read by the addon gate of every tool here.
readonly addons: AddonsService,
) {}
/** The trip open to the user and, for a write, 'place_edit' on it; the refusal to answer, or null. */
private async refusal(tripId: number, userId: number, write: boolean) {
if (!(await this.access.findAccessible(tripId, userId))) return noAccess();
if (write && !(await this.guards.hasTripPermission('place_edit', tripId, userId))) return permissionDenied();
return null;
}
@Tool({
name: 'get_tour_packing',
description:
'Read the packing list a saved tour points at: packing_link names it (category null for the whole packing list of the trip, otherwise one category of it; null while the tour points at nothing), state says how it reads (ready, empty while it holds no item yet, or missing when its category has no item the user can see any more, renamed, cleared or kept to other travellers), and items lists what the user may see of it with quantity and whether each is packed. tour carries the tour’s own facts (type, distance in km, ascent and descent in metres, walking and planned minutes, difficulty, the SAC limit of a hike), unknown ones null, as context for suggesting what to pack. Suggestions stay suggestions: add an item only through the packing tools and only when the user asks for it.',
inputSchema: tourIds,
annotations: TOOL_ANNOTATIONS_READONLY,
when: tourPackingOn,
access: (ctx) => canReadTrips(ctx.scopes) && canRead(ctx.scopes, 'packing'),
})
async getTourPacking({ tripId, placeId }: { tripId: number; placeId: number }, ctx: McpContext) {
const refused = await this.refusal(tripId, ctx.userId, false);
if (refused) return refused;
return ok(await this.packingLinks.view(tripId, placeId, ctx.userId));
}
@Tool({
name: 'link_tour_packing',
description:
'Point a saved tour at the packing list of its trip: category null for the whole list, or the name of one of its categories exactly as its items carry it (one the user can see an item of). It replaces what the tour pointed at before. Nothing is copied or changed in the packing list. Needs place_edit on the trip and the Packing addon.',
inputSchema: { ...tourIds, category: tourPackingLinkRequestSchema.shape.category },
annotations: TOOL_ANNOTATIONS_WRITE,
when: tourPackingOn,
access: (ctx) => canWrite(ctx.scopes, 'trips') && canRead(ctx.scopes, 'packing'),
})
async linkTourPacking(
{ tripId, placeId, category }: { tripId: number; placeId: number } & TourPackingLinkRequest,
ctx: McpContext,
) {
const refused = await this.refusal(tripId, ctx.userId, true);
if (refused) return refused;
const detail = await this.packingLinks.link(String(tripId), String(placeId), { category }, ctx.userId);
return ok({ packing_link: detail.packing_link ?? null });
}
@Tool({
name: 'unlink_tour_packing',
description:
'Let a saved tour stop pointing at its packing list. The packing list, its categories and its items stay exactly as they are. Needs place_edit on the trip.',
inputSchema: tourIds,
annotations: TOOL_ANNOTATIONS_WRITE,
when: tourPackingOn,
access: { group: 'trips', mode: 'write' },
})
async unlinkTourPacking({ tripId, placeId }: { tripId: number; placeId: number }, ctx: McpContext) {
const refused = await this.refusal(tripId, ctx.userId, true);
if (refused) return refused;
const detail = await this.packingLinks.unlink(String(tripId), String(placeId));
return ok({ packing_link: detail.packing_link ?? null });
}
}
+14 -1
View File
@@ -4,6 +4,7 @@ import { TourActivities } from '../../db/entities/TourActivities.entity';
import { TourActivityExclusions } from '../../db/entities/TourActivityExclusions.entity';
import { TourChangeSteps } from '../../db/entities/TourChangeSteps.entity';
import { TourObstacleReviews } from '../../db/entities/TourObstacleReviews.entity';
import { TourPackingLinks } from '../../db/entities/TourPackingLinks.entity';
import { TourSources } from '../../db/entities/TourSources.entity';
import { TourStationVisits } from '../../db/entities/TourStationVisits.entity';
import { TourTypes } from '../../db/entities/TourTypes.entity';
@@ -15,6 +16,7 @@ import { CollectionsModule } from '../collections/collections.module';
import { MapsModule } from '../maps/maps.module';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { OverpassModule } from '../overpass/overpass.module';
import { PackingModule } from '../packing/packing.module';
import { PaddleObstaclesModule } from '../paddle-obstacles/paddle-obstacles.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { PlaceImportModule } from '../place-import/place-import.module';
@@ -46,6 +48,9 @@ import { TourLibraryController, TourTakeOverController } from './tour-library.co
import { TourLibraryMcp } from './tour-library.mcp';
import { TourLibraryService } from './tour-library.service';
import { TourObstacleReviewsService } from './tour-obstacle-reviews.service';
import { TourPackingLinkController } from './tour-packing-link.controller';
import { TourPackingLinkService } from './tour-packing-link.service';
import { TourPackingMcp } from './tour-packing.mcp';
import { PaddleCheckCache } from './tour-paddle-check.cache';
import { TourPaddleCheckService } from './tour-paddle-check.service';
import { TourPaddlePlanService } from './tour-paddle-plan.service';
@@ -90,7 +95,9 @@ import { Module } from '@nestjs/common';
* TourActivityStatsService, over the trips TripMembershipModule says they can
* open, with the tours the user left out of them. Whole tours kept in a
* collection (LIB-03) are this domain's own rows; the collection's roles and
* its live notice to its members come from CollectionsService.
* its live notice to its members come from CollectionsService. A tour points at
* the packing list of its trip (P2D-XD-01) through a row of its own; the list
* and who sees which of its items stay PackingService's.
*/
@Module({
imports: [
@@ -116,6 +123,8 @@ import { Module } from '@nestjs/common';
AssignmentsDomainModule,
// A collection keeps whole tours (LIB-03): its roles decide who sees, keeps and removes one.
CollectionsModule,
// A tour's packing link is read against the items Packing lets the user see (P2D-XD-01).
PackingModule,
MikroOrmModule.forFeature([
CollectionTours,
Tours,
@@ -123,6 +132,7 @@ import { Module } from '@nestjs/common';
TourWaypoints,
TourSources,
TourObstacleReviews,
TourPackingLinks,
TourStationVisits,
TourChangeSteps,
TourActivities,
@@ -147,6 +157,7 @@ import { Module } from '@nestjs/common';
ToursWandererController,
TourLibraryController,
CollectionToursController,
TourPackingLinkController,
],
providers: [
ToursService,
@@ -171,6 +182,7 @@ import { Module } from '@nestjs/common';
TourActivitiesService,
TourActivityStatsService,
CollectionToursService,
TourPackingLinkService,
ToursMcp,
TourLibraryMcp,
TourWalkImportMcp,
@@ -180,6 +192,7 @@ import { Module } from '@nestjs/common';
TourActivitiesMcp,
TourActivityStatsMcp,
CollectionToursMcp,
TourPackingMcp,
],
})
export class ToursModule {}
+4 -4
View File
@@ -733,8 +733,9 @@ export class TripsService {
if (newPlaceId) await this.tagsRepo.insertIgnore(newPlaceId, [t.tag_id]); // TP47
}
// A Tour is its place plus the `tours` facet, its import record, its obstacle decisions and the waypoints its
// route was planned through. The facet row goes first, since the others reference it; without them it is no Tour.
// A Tour is its place plus the `tours` facet, its import record, its obstacle decisions, its packing link and
// the waypoints its route was planned through. The facet row goes first, since the others reference it;
// without them it is no Tour.
const oldTours = await this.toursRepo.listRowsForTrip(Number(sourceTripId));
const copiedTours = new Map<number, number>();
for (const { place_id, ...tour } of oldTours) {
@@ -743,8 +744,7 @@ export class TripsService {
await this.toursRepo.insertCopy(newPlaceId, tour, placeMap);
copiedTours.set(place_id, newPlaceId);
}
await Promise.all([...copiedTours].map(([from, to]) => this.toursRepo.copySource(from, to)));
await Promise.all([...copiedTours].map(([from, to]) => this.toursRepo.copyObstacleReviews(from, to)));
for (const [from, to] of copiedTours) await this.toursRepo.copyTourRelations(from, to);
const waypointsByPlace = new Map<number, TourWaypointRow[]>();
for (const { place_id, ...waypoint } of await this.tourWaypointsRepo.listForTrip(Number(sourceTripId))) {
@@ -0,0 +1,230 @@
/**
* A tour's packing link (P2D-XD-01), through the real JwtAuthGuard, AddonGuard
* and TripAccessGuard against a migrated and seeded temp SQLite db, every
* answer checked against its response contract. The permission check is a
* container spy and the broadcasts go to a FakeRealtimeService.
*
* Fixtures: user 1 owns trip 5 and its packing list, user 2 is a member of
* trip 5 whom the spy denies 'place_edit' and who keeps one item to
* themselves, user 3 has no access to the trip.
*/
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
import { PackingItems } from '../../src/db/entities/PackingItems.entity';
import { Places } from '../../src/db/entities/Places.entity';
import { TourPackingLinks } from '../../src/db/entities/TourPackingLinks.entity';
import { Trips } from '../../src/db/entities/Trips.entity';
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
import { JourneyDomainService } from '../../src/nest/journey/journey-domain.service';
import { PermissionsService } from '../../src/nest/permissions/permissions.service';
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
import { ToursModule } from '../../src/nest/tours/tours.module';
import { createSnapshotTestDb } from '../helpers/db-mock';
import { makePackingItem } from '../helpers/factories/packing';
import { makePlace } from '../helpers/factories/places';
import { countRows, deleteRows, findRows, insertRows } from '../helpers/factories/rows';
import { setAddonEnabled } from '../helpers/factories/settings';
import { addTripMember } from '../helpers/factories/trips';
import { makeUser } from '../helpers/factories/users';
import { FakeRealtimeService } from '../helpers/fake-realtime';
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
import { TestUnitOfWorkModule } from '../helpers/test-uow';
import { sessionCookie } from './harness';
import { Test } from '@nestjs/testing';
import cookieParser from 'cookie-parser';
import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi, type MockInstance } from 'vitest';
vi.mock('../../src/nest/audit/audit-log.logger', () => ({
LOG_LEVEL: 'error',
logInfo: vi.fn(),
logDebug: vi.fn(),
logError: vi.fn(),
logWarn: vi.fn(),
}));
const { journeyHooks } = vi.hoisted(() => ({
journeyHooks: {
reconcileTripSkeletons: vi.fn().mockResolvedValue(undefined),
onPlaceCreated: vi.fn().mockResolvedValue(undefined),
onPlaceUpdated: vi.fn().mockResolvedValue(undefined),
onPlaceDeleted: vi.fn().mockResolvedValue(undefined),
},
}));
const db = createSnapshotTestDb();
const realtime = new FakeRealtimeService();
let orm: TestOrm;
let checkPermission: MockInstance;
const OWNER = 1;
const MEMBER = 2;
const OUTSIDER = 3;
const tourBody = {
name: 'Ridge walk',
route_geometry: [
[47, 11, 600],
[47.01, 11.01, 700],
],
waypoints: [
{ lat: 47, lng: 11, role: 'start', sequence: 0 },
{ lat: 47.01, lng: 11.01, role: 'end', sequence: 1 },
],
max_hiking_difficulty: 3,
duration_seconds: 3600,
};
describe('Tour packing link e2e (real guards + temp SQLite)', () => {
let server: Server;
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({
imports: [
await TestUnitOfWorkModule.forRoot(db),
await createTestMikroOrmModule(db),
RealtimeModule,
ToursModule,
],
})
.overrideProvider(RealtimeService)
.useValue(realtime)
.overrideProvider(JourneyDomainService)
.useValue(journeyHooks)
.compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
nest.useGlobalPipes(new ZodValidationPipe());
nest.useGlobalFilters(new TrekExceptionFilter());
await nest.init();
return nest;
}
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
const path = (placeId: number) => `/api/trips/5/tours/${placeId}/packing-link`;
const createTour = async () => {
const res = await request(server).post('/api/trips/5/tours').set(as(OWNER)).send(tourBody);
expect(res.status).toBe(201);
return res.body.tour.place_id as number;
};
beforeAll(async () => {
orm = await createTestOrm(db);
// Pinned ids: the session cookies sign for exactly these users.
await makeUser(orm, { id: 1, username: 'owner', email: 'owner@example.test', role: 'user', password_version: 0 });
await makeUser(orm, { id: 2, username: 'member', email: 'member@example.test', role: 'user', password_version: 0 });
await makeUser(orm, {
id: 3,
username: 'outsider',
email: 'outsider@example.test',
role: 'user',
password_version: 0,
});
await insertRows(orm, Trips, [{ id: 5, user: 1, title: 'Alps' }]);
await addTripMember(orm, 5, 2);
app = await build();
checkPermission = vi.spyOn(app.get(PermissionsService), 'checkPermission');
server = app.getHttpServer();
});
beforeEach(async () => {
checkPermission.mockImplementation(
async (action: string, _role: string, _owner: number, userId: number) =>
!(action === 'place_edit' && userId === MEMBER),
);
await setAddonEnabled(orm, 'tours', true);
await setAddonEnabled(orm, 'packing', true);
realtime.broadcastMock.mockClear();
await deleteRows(orm, TourPackingLinks);
await deleteRows(orm, PackingItems);
await deleteRows(orm, DayAssignments);
await deleteRows(orm, Places);
await makePackingItem(orm, 5, { name: 'Boots', category: 'Hiking gear', sort_order: 1 });
await makePackingItem(orm, 5, { name: 'Diary', category: 'Secret', is_private: 1, owner: MEMBER, sort_order: 2 });
});
afterAll(async () => {
await app.close();
await orm.close();
});
it('links a category, reads it back, moves it to the whole list and lets go, leaving every item as it was', async () => {
const tour = await createTour();
const before = await findRows(orm, PackingItems, {}, { id: 'asc' });
const empty = await request(server).get(path(tour)).set(as(MEMBER));
expect(empty.status).toBe(200);
expect(empty.body).toEqual({ packing_link: null });
const linked = await request(server)
.put(path(tour))
.set(as(OWNER))
.set('X-Socket-Id', 'sock-1')
.send({ category: 'Hiking gear' });
expect(linked.status).toBe(200);
expect(linked.body.tour).toMatchObject({ place_id: tour, name: 'Ridge walk' });
expect(linked.body.packing_link).toEqual({ category: 'Hiking gear', linked_at: expect.any(String) });
expect(realtime.broadcastMock).toHaveBeenCalledWith('5', 'tours:changed', { placeIds: [tour] }, 'sock-1');
expect((await request(server).get(path(tour)).set(as(MEMBER))).body).toEqual({
packing_link: linked.body.packing_link,
});
const whole = await request(server).put(path(tour)).set(as(OWNER)).send({ category: null });
expect(whole.status).toBe(200);
expect(whole.body.packing_link.category).toBeNull();
expect(await countRows(orm, TourPackingLinks)).toBe(1);
const removed = await request(server).delete(path(tour)).set(as(OWNER));
expect(removed.status).toBe(200);
expect(removed.body.packing_link).toBeNull();
expect(await countRows(orm, TourPackingLinks)).toBe(0);
expect(await findRows(orm, PackingItems, {}, { id: 'asc' })).toEqual(before);
});
it('refuses a member without place_edit, a stranger, a body it cannot read and a category the user cannot see', async () => {
const tour = await createTour();
expect((await request(server).put(path(tour)).set(as(MEMBER)).send({ category: null })).status).toBe(403);
expect((await request(server).delete(path(tour)).set(as(MEMBER))).status).toBe(403);
expect((await request(server).get(path(tour)).set(as(OUTSIDER))).status).toBe(404);
expect((await request(server).put(path(tour)).set(as(OUTSIDER)).send({ category: null })).status).toBe(404);
expect((await request(server).put(path(tour)).set(as(OWNER)).send({})).status).toBe(400);
expect((await request(server).put(path(tour)).set(as(OWNER)).send({ category: '' })).status).toBe(400);
// The member's private item is not the owner's to point at.
const hidden = await request(server).put(path(tour)).set(as(OWNER)).send({ category: 'Secret' });
expect(hidden.status).toBe(400);
expect(hidden.body).toEqual({ error: 'Packing category not found' });
const unknown = await request(server).put(path(tour)).set(as(OWNER)).send({ category: 'Climbing' });
expect(unknown.status).toBe(400);
expect(await countRows(orm, TourPackingLinks)).toBe(0);
});
it('answers a place that is no tour, a malformed id and switched-off addons as not found', async () => {
const tour = await createTour();
const cafe = await makePlace(orm, 5, { name: 'Cafe' });
const notTour = await request(server).get(path(cafe.id)).set(as(OWNER));
expect(notTour.status).toBe(404);
expect(notTour.body).toEqual({ error: 'Tour not found' });
expect((await request(server).get('/api/trips/5/tours/x/packing-link').set(as(OWNER))).status).toBe(404);
expect((await request(server).get(path(tour))).status).toBe(401);
await request(server).put(path(tour)).set(as(OWNER)).send({ category: null });
await setAddonEnabled(orm, 'packing', false);
const noPacking = await request(server).put(path(tour)).set(as(OWNER)).send({ category: 'Hiking gear' });
expect(noPacking.status).toBe(404);
expect(noPacking.body).toEqual({ error: 'Packing addon is not enabled' });
// The link stays readable and can be let go while Packing is off.
expect((await request(server).get(path(tour)).set(as(OWNER))).body.packing_link.category).toBeNull();
expect((await request(server).delete(path(tour)).set(as(OWNER))).status).toBe(200);
await setAddonEnabled(orm, 'tours', false);
const noTours = await request(server).get(path(tour)).set(as(OWNER));
expect(noTours.status).toBe(404);
expect(noTours.body).toEqual({ error: 'Tours addon is not enabled' });
});
});
+11
View File
@@ -1,4 +1,5 @@
import { TourActivities } from '../../../src/db/entities/TourActivities.entity';
import { TourPackingLinks } from '../../../src/db/entities/TourPackingLinks.entity';
import { TourStationVisits, type TTourStationVisitsStatus } from '../../../src/db/entities/TourStationVisits.entity';
import { TourWaypoints, type TTourWaypointsImportance } from '../../../src/db/entities/TourWaypoints.entity';
import { Tours } from '../../../src/db/entities/Tours.entity';
@@ -86,3 +87,13 @@ export function makeTourActivity(
): Promise<TourActivityRow> {
return createRow(orm, TourActivities, { place: placeId, trackPlace: trackPlaceId }, overrides);
}
/** P2D-XD-01: points the tour at its trip's packing list (category null) or at one category of it. */
export async function linkTourPacking(
orm: FactoryOrm,
placeId: number,
category: string | null,
linkedBy: number | null = null,
): Promise<void> {
await insertRow(orm, TourPackingLinks, { place: placeId, category, linkedByRef: linkedBy });
}
+4 -3
View File
@@ -44,14 +44,15 @@ describe('ALL_ENTITIES', () => {
* + tour_change_steps, the changes to a tour saved from a confirmed proposal
* + tour_activities, the recorded tracks assigned to a tour
* + tour_activity_exclusions, the tours a user left out of their own activity sums
* + collection_tours, the whole tours a collection keeps)
* + collection_tours, the whole tours a collection keeps
* + tour_packing_links, the packing list or category a tour points at)
* is registered, and no two share a class name (a silent duplicate would
* shadow one of them in `orm.getMetadata()`, exactly the kind of drift
* `entity-schema-parity.test.ts` can't see — it iterates the metadata map,
* which de-duplicates by class name).
*/
it('ENT-003: exactly 147 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(147);
it('ENT-003: exactly 148 entities, every class name unique', () => {
expect(ALL_ENTITIES.length).toBe(148);
const names = ALL_ENTITIES.map((s) => s.meta.className);
expect(new Set(names).size).toBe(names.length);
});
@@ -77,6 +77,7 @@ const UNNUMBERED = [
'Migration20200101046000_a_tour_waypoint_can_end_a_stage',
'Migration20200101046010_a_day_can_hold_one_stage_of_a_tour',
'Migration20200101046100_a_collection_keeps_whole_tours',
'Migration20200101046110_a_tour_points_at_its_packing_list',
];
// The last step the positional runner ever had; planLegacyBaseline refuses a
// schema_version past it.
@@ -0,0 +1,105 @@
/**
* `TourPackingLinksRepository` (P2D-XD-01): the packing list, or the category
* of it, a tour points at. Seeded through the ORM factories over the migrated
* snapshot schema.
*/
import { PackingItems } from '../../../../src/db/entities/PackingItems.entity';
import { Places } from '../../../../src/db/entities/Places.entity';
import { TourPackingLinks } from '../../../../src/db/entities/TourPackingLinks.entity';
import { Users } from '../../../../src/db/entities/Users.entity';
import type { TourPackingLinksRepository } from '../../../../src/db/repositories/TourPackingLinks.repository';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { makePackingItem } from '../../../helpers/factories/packing';
import { makePlace } from '../../../helpers/factories/places';
import { countRows, deleteRows, findRow, updateRows } from '../../../helpers/factories/rows';
import { linkTourPacking, makeTour } from '../../../helpers/factories/tours';
import { makeTrip } from '../../../helpers/factories/trips';
import { makeUser } from '../../../helpers/factories/users';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const testDb = createSnapshotTestDb();
let t: TestOrm;
let repo: TourPackingLinksRepository;
beforeAll(async () => {
t = await createTestOrm(testDb);
repo = t.repo(TourPackingLinks);
});
beforeEach(() => {
resetTestDb(testDb);
t.clear();
});
afterAll(async () => {
await t.close();
testDb.close();
});
/** A trip with a hike and a packing item, the user who links and a second tour that points at nothing. */
async function fixture() {
const { user } = await makeUser(t);
const trip = await makeTrip(t, user.id);
const hike = await makePlace(t, trip.id, { name: 'Ridge' });
await makeTour(t, hike.id);
const walk = await makePlace(t, trip.id, { name: 'Old town' });
await makeTour(t, walk.id, { tourTypeRef: 'walk' });
const item = await makePackingItem(t, trip.id, { name: 'Boots', category: 'Hiking gear' });
return { user, trip, hike, walk, item };
}
describe('TourPackingLinksRepository', () => {
it('TPLREPO-001: a tour without a link reads as undefined', async () => {
const { hike } = await fixture();
expect(await repo.findForTour(hike.id)).toBeUndefined();
});
it('TPLREPO-002: put points the tour at a category, or at the whole list with null', async () => {
const { user, hike, walk } = await fixture();
await repo.put(hike.id, 'Hiking gear', user.id);
await repo.put(walk.id, null, user.id);
expect(await repo.findForTour(hike.id)).toEqual({ category: 'Hiking gear', linked_at: expect.any(String) });
expect(await repo.findForTour(walk.id)).toEqual({ category: null, linked_at: expect.any(String) });
expect((await findRow(t, TourPackingLinks, { place: hike.id }))?.linked_by).toBe(user.id);
});
it('TPLREPO-003: a second put replaces what the tour pointed at, on the same row, with a new time', async () => {
const { user, hike } = await fixture();
const { user: other } = await makeUser(t);
await repo.put(hike.id, 'Hiking gear', user.id);
await updateRows(t, TourPackingLinks, { place: hike.id }, { linked_at: '2020-01-01 00:00:00' });
await repo.put(hike.id, null, other.id);
const row = await findRow(t, TourPackingLinks, { place: hike.id });
expect(row).toMatchObject({ category: null, linked_by: other.id });
expect(row?.linked_at).not.toBe('2020-01-01 00:00:00');
expect(await countRows(t, TourPackingLinks)).toBe(1);
});
it('TPLREPO-004: remove lets go of the link and says whether there was one, and leaves the packing items alone', async () => {
const { user, hike, walk } = await fixture();
await repo.put(hike.id, 'Hiking gear', user.id);
expect(await repo.remove(hike.id)).toBe(true);
expect(await repo.remove(hike.id)).toBe(false);
expect(await repo.remove(walk.id)).toBe(false);
expect(await repo.findForTour(hike.id)).toBeUndefined();
expect(await countRows(t, PackingItems)).toBe(1);
});
it('TPLREPO-005: the link goes with its tour, and turns its author unknown when that account goes', async () => {
const { user, hike, walk } = await fixture();
const { user: linker } = await makeUser(t);
await linkTourPacking(t, hike.id, 'Hiking gear', user.id);
await linkTourPacking(t, walk.id, null, linker.id);
await deleteRows(t, Users, { id: linker.id });
const kept = await findRow(t, TourPackingLinks, { place: walk.id });
expect(kept?.category).toBeNull();
expect(kept?.linked_by ?? null).toBeNull();
await deleteRows(t, Places, { id: hike.id });
expect(await repo.findForTour(hike.id)).toBeUndefined();
expect(await repo.findForTour(walk.id)).toEqual({ category: null, linked_at: expect.any(String) });
});
});
@@ -6,6 +6,7 @@
*/
import { DayAssignments } from '../../../../src/db/entities/DayAssignments.entity';
import { Places } from '../../../../src/db/entities/Places.entity';
import { TourPackingLinks } from '../../../../src/db/entities/TourPackingLinks.entity';
import { TourSources } from '../../../../src/db/entities/TourSources.entity';
import { TourWaypoints } from '../../../../src/db/entities/TourWaypoints.entity';
import { Tours } from '../../../../src/db/entities/Tours.entity';
@@ -14,7 +15,8 @@ import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
import { createDay, createDayAssignment, createPlace, createTrip, createUser } from '../../../helpers/factories';
import { makePlace } from '../../../helpers/factories/places';
import { findRows, insertRow, insertRows, updateRows } from '../../../helpers/factories/rows';
import { countRows, findRow, findRows, insertRow, insertRows, updateRows } from '../../../helpers/factories/rows';
import { linkTourPacking } from '../../../helpers/factories/tours';
import { makeDay } from '../../../helpers/factories/trips';
import { resetTestDb } from '../../../helpers/test-db';
import { createTestOrm, type TestOrm } from '../../../helpers/test-orm';
@@ -667,4 +669,27 @@ describe('ToursRepository writes', () => {
});
expect((await repo.findProvenance(other.id, copiedPlanned.id))?.source_instance).toBeNull();
});
it('TOURREPO-012: a trip copy takes a tour’s packing link onto its copy, and nothing for a tour that had none', async () => {
const { trip, other } = fixture();
const linked = createPlace(testDb, trip.id);
await repo.insertTour({ ...METRICS, place_id: linked.id });
await linkTourPacking(t, linked.id, 'Hiking gear');
const plain = createPlace(testDb, trip.id);
await repo.insertTour({ ...METRICS, place_id: plain.id });
const linkedCopy = createPlace(testDb, other.id);
await repo.insertTour({ ...METRICS, place_id: linkedCopy.id });
const plainCopy = createPlace(testDb, other.id);
await repo.insertTour({ ...METRICS, place_id: plainCopy.id });
await repo.copyTourRelations(linked.id, linkedCopy.id);
await repo.copyTourRelations(plain.id, plainCopy.id);
const source = await findRow(t, TourPackingLinks, { place: linked.id });
expect(await findRow(t, TourPackingLinks, { place: linkedCopy.id })).toMatchObject({
category: 'Hiking gear',
linked_at: source?.linked_at,
});
expect(await countRows(t, TourPackingLinks, { place: plainCopy.id })).toBe(0);
});
});
@@ -0,0 +1,68 @@
/**
* TourPackingLinkController (P2D-XD-01): the route metadata of a tour's packing
* link and its delegation to TourPackingLinkService. Parity with the MCP tools
* lives here too: reading needs the trip only, both writes 'place_edit', the
* same action the tools check.
*/
import 'reflect-metadata';
import { AddonGuard } from '../../../src/nest/addons/addon.guard';
import { REQUIRE_ADDON } from '../../../src/nest/addons/require-addon.decorator';
import { JwtAuthGuard } from '../../../src/nest/auth-core/jwt-auth.guard';
import { TRIP_PERMISSION_KEY, TripAccessGuard } from '../../../src/nest/permissions/trip-access.guard';
import { TourPackingLinkController } from '../../../src/nest/tours/tour-packing-link.controller';
import type { TourPackingLinkService } from '../../../src/nest/tours/tour-packing-link.service';
import type { User } from '../../../src/types';
import { RequestMethod } from '@nestjs/common';
import { GUARDS_METADATA, METHOD_METADATA, PATH_METADATA } from '@nestjs/common/constants';
import { describe, expect, it, vi } from 'vitest';
const link = { category: 'Hiking gear', linked_at: '2026-10-20 09:00:00' };
const detail = { tour: { place_id: 3 }, waypoints: [], packing_link: link };
function controllerWith() {
const service = {
read: vi.fn(async () => ({ packing_link: link })),
link: vi.fn(async () => detail),
unlink: vi.fn(async () => ({ ...detail, packing_link: null })),
};
return { service, controller: new TourPackingLinkController(service as unknown as TourPackingLinkService) };
}
describe('TourPackingLinkController', () => {
it('TPL-CTL-001: sits behind the addon guard before auth and trip access; only the writes need place_edit', () => {
expect(Reflect.getMetadata(PATH_METADATA, TourPackingLinkController)).toBe('api/trips/:tripId/tours');
expect(Reflect.getMetadata(GUARDS_METADATA, TourPackingLinkController)).toEqual([
AddonGuard,
JwtAuthGuard,
TripAccessGuard,
]);
expect(Reflect.getMetadata(REQUIRE_ADDON, TourPackingLinkController)).toEqual({ addonId: 'tours', label: 'Tours' });
const routes = [
['read', RequestMethod.GET, undefined],
['link', RequestMethod.PUT, 'place_edit'],
['unlink', RequestMethod.DELETE, 'place_edit'],
] as const;
for (const [handler, method, permission] of routes) {
const fn = TourPackingLinkController.prototype[handler];
expect(Reflect.getMetadata(METHOD_METADATA, fn)).toBe(method);
expect(Reflect.getMetadata(PATH_METADATA, fn)).toBe(':placeId/packing-link');
expect(Reflect.getMetadata(TRIP_PERMISSION_KEY, fn)).toBe(permission);
}
});
it('TPL-CTL-002: hands the trip, tour, body, user and socket id to the service and answers what it answers', async () => {
const { service, controller } = controllerWith();
const user = { id: 4 } as User;
expect(await controller.read('7', '3')).toEqual({ packing_link: link });
expect(service.read).toHaveBeenCalledExactlyOnceWith('7', '3');
expect(await controller.link(user, '7', '3', { category: 'Hiking gear' }, 'sock-1')).toBe(detail);
expect(service.link).toHaveBeenCalledExactlyOnceWith('7', '3', { category: 'Hiking gear' }, 4, 'sock-1');
expect((await controller.unlink('7', '3', 'sock-2')).packing_link).toBeNull();
expect(service.unlink).toHaveBeenCalledExactlyOnceWith('7', '3', 'sock-2');
});
});
@@ -0,0 +1,231 @@
/**
* TourPackingLinkService (P2D-XD-01): a tour points at the packing list of its
* trip or at one of its categories, read against the items Packing lets the
* user see. The service comes out of ToursModule over a snapshot test db; rows
* are seeded through the ORM factories and broadcasts go to a FakeRealtimeService.
*/
import { PackingItems } from '../../../src/db/entities/PackingItems.entity';
import { TourPackingLinks } from '../../../src/db/entities/TourPackingLinks.entity';
import { DomainError } from '../../../src/nest/common/domain-error';
import { TourPackingLinkService } from '../../../src/nest/tours/tour-packing-link.service';
import { ToursModule } from '../../../src/nest/tours/tours.module';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { makePackingItem } from '../../helpers/factories/packing';
import { makePlace } from '../../helpers/factories/places';
import { countRows, findRows } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
import { linkTourPacking, makeTour } from '../../helpers/factories/tours';
import { addTripMember, makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let links: TourPackingLinkService;
const orm = () => t.get(MikroORM);
beforeAll(async () => {
t = await createTestModule({ db, imports: [ToursModule] });
links = t.get(TourPackingLinkService);
});
beforeEach(async () => {
resetTestDb(db);
t.realtime.broadcastMock.mockClear();
await setAddonEnabled(orm(), 'packing', true);
});
afterAll(async () => {
await t.close();
db.close();
});
/**
* A trip of the owner with a member: a hike, a plain place, and a packing list
* whose "Hiking gear" holds two items (one packed), "Snacks" only the
* placeholder of a new category, and "Secret" an item the member keeps to
* themselves. Another trip has a tour of its own.
*/
async function fixture() {
const { user: owner } = await makeUser(orm());
const { user: member } = await makeUser(orm());
const trip = await makeTrip(orm(), owner.id, { title: 'Alps' });
await addTripMember(orm(), trip.id, member.id);
const hike = await makePlace(orm(), trip.id, { name: 'Ridge' });
await makeTour(orm(), hike.id, {
distance: 12.5,
elevation_gain: 800,
duration: 240,
difficulty: 'T3',
max_hiking_difficulty: 3,
});
const cafe = await makePlace(orm(), trip.id, { name: 'Cafe' });
const boots = await makePackingItem(orm(), trip.id, {
name: 'Boots',
category: 'Hiking gear',
checked: 1,
sort_order: 1,
});
const jacket = await makePackingItem(orm(), trip.id, {
name: 'Rain jacket',
category: 'Hiking gear',
quantity: 2,
sort_order: 2,
});
await makePackingItem(orm(), trip.id, { name: '...', category: 'Snacks', sort_order: 3 });
await makePackingItem(orm(), trip.id, {
name: 'Diary',
category: 'Secret',
is_private: 1,
owner: member.id,
sort_order: 4,
});
const other = await makeTrip(orm(), owner.id, { title: 'Coast' });
const otherTour = await makePlace(orm(), other.id, { name: 'Cliffs' });
await makeTour(orm(), otherTour.id);
return { owner, member, trip, hike, cafe, boots, jacket, other, otherTour };
}
describe('TourPackingLinkService', () => {
it('TPL-SVC-001: a tour points at nothing until it is linked, then at the whole list, and says so to the trip', async () => {
const f = await fixture();
expect(await links.read(f.trip.id, f.hike.id)).toEqual({ packing_link: null });
const answer = await links.link(String(f.trip.id), String(f.hike.id), { category: null }, f.owner.id, 'sock-1');
expect(answer.tour.place_id).toBe(f.hike.id);
expect(answer.packing_link).toEqual({ category: null, linked_at: expect.any(String) });
expect(t.realtime.broadcastMock).toHaveBeenCalledWith(
String(f.trip.id),
'tours:changed',
{ placeIds: [f.hike.id] },
'sock-1',
);
expect(await links.read(String(f.trip.id), String(f.hike.id))).toEqual({ packing_link: answer.packing_link });
});
it('TPL-SVC-002: a category is linked by its exact name, and a new link replaces the old one', async () => {
const f = await fixture();
await links.link(String(f.trip.id), String(f.hike.id), { category: null }, f.owner.id);
const answer = await links.link(String(f.trip.id), String(f.hike.id), { category: 'Hiking gear' }, f.owner.id);
expect(answer.packing_link?.category).toBe('Hiking gear');
// A category that only holds the placeholder of a new one is there too.
await links.link(String(f.trip.id), String(f.hike.id), { category: 'Snacks' }, f.owner.id);
expect(await countRows(orm(), TourPackingLinks)).toBe(1);
});
it('TPL-SVC-003: a category the user cannot see an item of is refused, a private one of another member included', async () => {
const f = await fixture();
for (const category of ['Climbing', 'hiking gear', 'Secret']) {
await expect(
links.link(String(f.trip.id), String(f.hike.id), { category }, f.owner.id),
).rejects.toMatchObject({ status: 400, publicMessage: 'Packing category not found' });
}
// The member who keeps it may link it.
const own = await links.link(String(f.trip.id), String(f.hike.id), { category: 'Secret' }, f.member.id);
expect(own.packing_link?.category).toBe('Secret');
});
it('TPL-SVC-004: with Packing off nothing is linked, and an existing link can still be let go', async () => {
const f = await fixture();
await linkTourPacking(orm(), f.hike.id, 'Hiking gear', f.owner.id);
await setAddonEnabled(orm(), 'packing', false);
const refused = await links
.link(String(f.trip.id), String(f.hike.id), { category: null }, f.owner.id)
.catch((err: unknown) => err);
expect(refused).toBeInstanceOf(DomainError);
expect(refused).toMatchObject({ status: 404, publicMessage: 'Packing addon is not enabled' });
await expect(links.view(f.trip.id, f.hike.id, f.owner.id)).rejects.toMatchObject({ status: 404 });
const answer = await links.unlink(String(f.trip.id), String(f.hike.id));
expect(answer.packing_link).toBeNull();
});
it('TPL-SVC-005: removing the link leaves the packing list and every item as it was', async () => {
const f = await fixture();
await linkTourPacking(orm(), f.hike.id, 'Hiking gear', f.owner.id);
const before = await findRows(orm(), PackingItems, {}, { id: 'asc' });
const answer = await links.unlink(String(f.trip.id), String(f.hike.id), 'sock-2');
expect(answer.packing_link).toBeNull();
expect(await links.read(f.trip.id, f.hike.id)).toEqual({ packing_link: null });
expect(await findRows(orm(), PackingItems, {}, { id: 'asc' })).toEqual(before);
expect(t.realtime.broadcastMock).toHaveBeenCalledWith(
String(f.trip.id),
'tours:changed',
{ placeIds: [f.hike.id] },
'sock-2',
);
// Letting go of nothing is no error.
expect((await links.unlink(String(f.trip.id), String(f.hike.id))).packing_link).toBeNull();
});
it('TPL-SVC-006: a tour of another trip, a plain place or a malformed id is not found', async () => {
const f = await fixture();
const attempts = [
() => links.read(f.trip.id, f.otherTour.id),
() => links.read(f.trip.id, f.cafe.id),
() => links.read('abc', f.hike.id),
() => links.read(f.trip.id, '1.5'),
() => links.link(String(f.trip.id), String(f.otherTour.id), { category: null }, f.owner.id),
() => links.unlink(String(f.trip.id), String(f.cafe.id)),
() => links.view(f.other.id, f.hike.id, f.owner.id),
];
for (const attempt of attempts) {
await expect(attempt()).rejects.toMatchObject({ status: 404, publicMessage: 'Tour not found' });
}
expect(await countRows(orm(), TourPackingLinks)).toBe(0);
});
it('TPL-SVC-007: an assistant reads the linked items it may see with the packed count and the tour as context', async () => {
const f = await fixture();
const unlinked = await links.view(f.trip.id, f.hike.id, f.owner.id);
expect(unlinked).toEqual({
packing_link: null,
state: null,
items: [],
packed: 0,
total: 0,
tour: {
name: 'Ridge',
tour_type: 'hike',
distance_km: 12.5,
elevation_gain_m: 800,
elevation_loss_m: null,
walking_minutes: 240,
planned_duration_minutes: null,
difficulty: 'T3',
max_hiking_difficulty: 3,
},
});
await linkTourPacking(orm(), f.hike.id, 'Hiking gear', f.owner.id);
const gear = await links.view(f.trip.id, f.hike.id, f.owner.id);
expect(gear).toMatchObject({
packing_link: { category: 'Hiking gear' },
state: 'ready',
items: [
{ id: f.boots.id, name: 'Boots', category: 'Hiking gear', quantity: 1, packed: true },
{ id: f.jacket.id, name: 'Rain jacket', category: 'Hiking gear', quantity: 2, packed: false },
],
packed: 1,
total: 2,
});
});
it('TPL-SVC-008: what the link reads as follows the viewer: empty, missing, or the whole list without others’ private items', async () => {
const f = await fixture();
await linkTourPacking(orm(), f.hike.id, 'Snacks', f.owner.id);
expect((await links.view(f.trip.id, f.hike.id, f.owner.id)).state).toBe('empty');
await links.link(String(f.trip.id), String(f.hike.id), { category: 'Secret' }, f.member.id);
expect(await links.view(f.trip.id, f.hike.id, f.owner.id)).toMatchObject({ state: 'missing', items: [], total: 0 });
expect(await links.view(f.trip.id, f.hike.id, f.member.id)).toMatchObject({ state: 'ready', total: 1 });
await links.link(String(f.trip.id), String(f.hike.id), { category: null }, f.owner.id);
const whole = await links.view(f.trip.id, f.hike.id, f.owner.id);
expect(whole.items.map((item) => item.name)).toEqual(['Boots', 'Rain jacket']);
expect(whole).toMatchObject({ state: 'ready', packed: 1, total: 2 });
});
});
@@ -0,0 +1,151 @@
/**
* TourPackingMcp (P2D-XD-01): the packing list a tour points at, over the same
* service and the same checks as REST. The suite takes its subject from the
* container over a snapshot test db; the addon gate is the registry's.
*/
import { PackingItems } from '../../../src/db/entities/PackingItems.entity';
import { TourPackingLinks } from '../../../src/db/entities/TourPackingLinks.entity';
import type { McpContext } from '../../../src/nest-mcp';
import { getEntry, type ClassRef } from '../../../src/nest-mcp/metadata';
import { AddonsService } from '../../../src/nest/addons/addons.service';
import { McpToolGuardsService } from '../../../src/nest/mcp-shared/mcp-tool-guards.service';
import { TourPackingMcp } from '../../../src/nest/tours/tour-packing.mcp';
import { ToursModule } from '../../../src/nest/tours/tours.module';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { makePackingItem } from '../../helpers/factories/packing';
import { makePlace } from '../../helpers/factories/places';
import { countRows } from '../../helpers/factories/rows';
import { setAddonEnabled } from '../../helpers/factories/settings';
import { makeTour } from '../../helpers/factories/tours';
import { makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { resetTestDb } from '../../helpers/test-db';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let orm: TestOrm;
let mcp: TourPackingMcp;
beforeAll(async () => {
t = await createTestModule({ db, imports: [ToursModule] });
mcp = t.get(TourPackingMcp);
orm = await createTestOrm(db);
});
beforeEach(async () => {
resetTestDb(db);
orm.clear();
vi.restoreAllMocks();
await setAddonEnabled(orm, 'packing', true);
});
afterAll(async () => {
await orm.close();
await t.close();
db.close();
});
const ctx = (userId: number) => ({ userId }) as McpContext;
function read(result: { content: Array<{ type: string; text: string }>; isError?: boolean }) {
const text = result.content[0]?.text ?? '';
return result.isError ? { error: text } : JSON.parse(text);
}
/** A trip with a hike and two items of "Hiking gear", one packed; a user who cannot open the trip. */
async function fixture() {
const { user } = await makeUser(orm);
const { user: outsider } = await makeUser(orm);
const trip = await makeTrip(orm, user.id, { title: 'Alps' });
const hike = await makePlace(orm, trip.id, { name: 'Ridge' });
await makeTour(orm, hike.id, { distance: 9 });
await makePackingItem(orm, trip.id, { name: 'Boots', category: 'Hiking gear', checked: 1, sort_order: 1 });
await makePackingItem(orm, trip.id, { name: 'Map', category: 'Hiking gear', sort_order: 2 });
return { user, outsider, trip, hike };
}
describe('TourPackingMcp', () => {
it('TPL-MCP-001: links a category, reads its items with the tour as context, then lets go of it', async () => {
const f = await fixture();
const ids = { tripId: f.trip.id, placeId: f.hike.id };
expect(read(await mcp.getTourPacking(ids, ctx(f.user.id)))).toMatchObject({
packing_link: null,
state: null,
tour: { name: 'Ridge', tour_type: 'hike', distance_km: 9 },
});
const linked = read(await mcp.linkTourPacking({ ...ids, category: 'Hiking gear' }, ctx(f.user.id)));
expect(linked).toEqual({ packing_link: { category: 'Hiking gear', linked_at: expect.any(String) } });
expect(read(await mcp.getTourPacking(ids, ctx(f.user.id)))).toMatchObject({
state: 'ready',
items: [
{ name: 'Boots', packed: true },
{ name: 'Map', packed: false },
],
packed: 1,
total: 2,
});
expect(read(await mcp.unlinkTourPacking(ids, ctx(f.user.id)))).toEqual({ packing_link: null });
expect(await countRows(orm, TourPackingLinks)).toBe(0);
expect(await countRows(orm, PackingItems)).toBe(2);
});
it('TPL-MCP-002: refuses a trip the user cannot open, and a write without place_edit, as REST does', async () => {
const f = await fixture();
const ids = { tripId: f.trip.id, placeId: f.hike.id };
const noTrip = { error: 'Trip not found or access denied.' };
expect(read(await mcp.getTourPacking(ids, ctx(f.outsider.id)))).toEqual(noTrip);
expect(read(await mcp.linkTourPacking({ ...ids, category: null }, ctx(f.outsider.id)))).toEqual(noTrip);
expect(read(await mcp.unlinkTourPacking(ids, ctx(f.outsider.id)))).toEqual(noTrip);
const denied = vi.spyOn(t.get(McpToolGuardsService), 'hasTripPermission').mockResolvedValue(false);
expect((await mcp.linkTourPacking({ ...ids, category: null }, ctx(f.user.id))).isError).toBe(true);
expect((await mcp.unlinkTourPacking(ids, ctx(f.user.id))).isError).toBe(true);
expect(denied).toHaveBeenCalledWith('place_edit', f.trip.id, f.user.id);
// Reading asks for no permission beyond the trip.
expect((await mcp.getTourPacking(ids, ctx(f.user.id))).isError).toBeUndefined();
expect(await countRows(orm, TourPackingLinks)).toBe(0);
});
it('TPL-MCP-003: a category the user cannot see is refused through the same service as REST', async () => {
const f = await fixture();
await expect(
mcp.linkTourPacking({ tripId: f.trip.id, placeId: f.hike.id, category: 'Climbing' }, ctx(f.user.id)),
).rejects.toThrow('Packing category not found');
await expect(
mcp.getTourPacking({ tripId: f.trip.id, placeId: 999_999 }, ctx(f.user.id)),
).rejects.toThrow('Tour not found');
});
it('TPL-MCP-004: the tools are there only while Tours and Packing are on, and only for the scopes they need', async () => {
const options = (name: string) => {
const entry = getEntry(TourPackingMcp as unknown as ClassRef, name);
if (entry?.kind !== 'tool') throw new Error(`${name} is no tool`);
return entry.options;
};
const enabled = vi.spyOn(t.get(AddonsService), 'isAddonEnabled').mockResolvedValue(true);
for (const name of ['getTourPacking', 'linkTourPacking', 'unlinkTourPacking']) {
const gate = options(name).when;
enabled.mockResolvedValue(true);
expect(await gate?.(ctx(1), mcp)).toBe(true);
enabled.mockImplementation(async (id: string) => id !== 'packing');
expect(await gate?.(ctx(1), mcp)).toBe(false);
enabled.mockImplementation(async (id: string) => id !== 'tours');
expect(await gate?.(ctx(1), mcp)).toBe(false);
}
const allowed = (name: string, scopes: string[]) => {
const access = options(name).access;
return typeof access === 'function' ? access({ userId: 1, scopes } as McpContext) : access;
};
expect(allowed('getTourPacking', ['trips:read', 'packing:read'])).toBe(true);
expect(allowed('getTourPacking', ['trips:read'])).toBe(false);
expect(allowed('linkTourPacking', ['trips:write', 'packing:read'])).toBe(true);
expect(allowed('linkTourPacking', ['trips:write'])).toBe(false);
expect(allowed('linkTourPacking', ['trips:read', 'packing:write'])).toBe(false);
expect(allowed('unlinkTourPacking', [])).toEqual({ group: 'trips', mode: 'write' });
});
});
@@ -0,0 +1,64 @@
/**
* TripsService.copy and a tour's packing link (P2D-XD-01): the copied tour
* points at the same packing list or category of the copied trip, whose
* packing list is copied too, and the source keeps its own link.
*
* Real in-memory SQLite over the container: the service comes out of
* TripsModule, and the rows are seeded and read through the ORM factories.
*/
import { PackingItems } from '../../../src/db/entities/PackingItems.entity';
import { Places } from '../../../src/db/entities/Places.entity';
import { TourPackingLinks } from '../../../src/db/entities/TourPackingLinks.entity';
import { TripsModule } from '../../../src/nest/trips/trips.module';
import { TripsService } from '../../../src/nest/trips/trips.service';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { makePackingItem } from '../../helpers/factories/packing';
import { makePlace } from '../../helpers/factories/places';
import { countRows, findRow } from '../../helpers/factories/rows';
import { linkTourPacking, makeTour } from '../../helpers/factories/tours';
import { makeTrip } from '../../helpers/factories/trips';
import { makeUser } from '../../helpers/factories/users';
import { createTestModule, type TestModule } from '../../helpers/test-module';
import { MikroORM } from '@mikro-orm/core';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
const db = createSnapshotTestDb();
let t: TestModule;
let svc: TripsService;
const orm = () => t.get(MikroORM);
beforeAll(async () => {
t = await createTestModule({ db, imports: [TripsModule] });
svc = t.get(TripsService);
});
afterAll(async () => {
await t.close();
db.close();
});
describe('copy: a tour pointing at its packing list (P2D-XD-01)', () => {
it('TRIP-SVC-096: the copied tour points at the same category of the copied list; a tour without a link gets none', async () => {
const { user } = await makeUser(orm());
const trip = await makeTrip(orm(), user.id, { title: 'Alps' });
const hike = await makePlace(orm(), trip.id, { name: 'Ridge' });
await makeTour(orm(), hike.id);
const walk = await makePlace(orm(), trip.id, { name: 'Old town' });
await makeTour(orm(), walk.id, { tourTypeRef: 'walk' });
await makePackingItem(orm(), trip.id, { name: 'Boots', category: 'Hiking gear' });
await linkTourPacking(orm(), hike.id, 'Hiking gear', user.id);
const newTripId = await svc.copy(trip.id, user.id, 'Alps again');
const copiedHike = await findRow(orm(), Places, { trip: newTripId, name: 'Ridge' });
const copiedWalk = await findRow(orm(), Places, { trip: newTripId, name: 'Old town' });
expect(await findRow(orm(), TourPackingLinks, { place: copiedHike?.id })).toMatchObject({
category: 'Hiking gear',
});
expect(await countRows(orm(), TourPackingLinks, { place: copiedWalk?.id })).toBe(0);
expect(await countRows(orm(), PackingItems, { trip: newTripId, category: 'Hiking gear' })).toBe(1);
// The source keeps its own link.
expect(await findRow(orm(), TourPackingLinks, { place: hike.id })).toMatchObject({ category: 'Hiking gear' });
});
});