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