mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-30 16:33:16 +00:00
382ba79584
A visit is a place planned on a day of one of the reader's trips; nothing is kept or confirmed by hand. A place keeps a log of changes to its details, links the tours and bookings it is about, and carries tags private to the reader, which a copy into a trip takes along only when picked. Contracts, routes, MCP tools and migrations for both engines.
184 lines
8.7 KiB
TypeScript
184 lines
8.7 KiB
TypeScript
/**
|
||
* Visits read from the trips (D7/PLC-10 to PLC-23) through the real
|
||
* JwtAuthGuard, TripAccessGuard and AddonGuard against a migrated and seeded
|
||
* temp SQLite db, the visit clock pinned on the second day of the fixture's
|
||
* trip Alps: the history and the counts on All places, the trip's visited
|
||
* places, the list, the stop's participants, losing access, the refused
|
||
* queries, that nothing can be written, and the media of an entry.
|
||
*/
|
||
import { AssignmentParticipants } from '../../src/db/entities/AssignmentParticipants.entity';
|
||
import { DayAssignments } from '../../src/db/entities/DayAssignments.entity';
|
||
import { TripMembers } from '../../src/db/entities/TripMembers.entity';
|
||
import { TrekExceptionFilter } from '../../src/nest/common/trek-exception.filter';
|
||
import { ZodValidationPipe } from '../../src/nest/common/zod-validation.pipe';
|
||
import { PlaceVisitsClock } from '../../src/nest/places-library/place-visits.clock';
|
||
import { PlaceVisitsModule } from '../../src/nest/places-library/place-visits.module';
|
||
import { RealtimeModule } from '../../src/nest/realtime/realtime.module';
|
||
import { RealtimeService } from '../../src/nest/realtime/realtime.service';
|
||
import { createSnapshotTestDb } from '../helpers/db-mock';
|
||
import { makeDayAssignment } from '../helpers/factories/itinerary';
|
||
import { createRow, deleteRows, findRow } from '../helpers/factories/rows';
|
||
import { setAddonEnabled } from '../helpers/factories/settings';
|
||
import { addTripMember, makeDay, readTripDays } from '../helpers/factories/trips';
|
||
import { FakeRealtimeService } from '../helpers/fake-realtime';
|
||
import { oneByOne } from '../helpers/one-by-one';
|
||
import { seedLibrary, type LibraryFixture } from '../helpers/places-library-fixture';
|
||
import { resetTestDb } from '../helpers/test-db';
|
||
import { createTestMikroOrmModule, createTestOrm, type TestOrm } from '../helpers/test-orm';
|
||
import { TestUnitOfWorkModule } from '../helpers/test-uow';
|
||
import { sessionCookie } from './harness';
|
||
import type { INestApplication } from '@nestjs/common';
|
||
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 } from 'vitest';
|
||
|
||
const db = createSnapshotTestDb();
|
||
const realtime = new FakeRealtimeService();
|
||
|
||
let app: INestApplication;
|
||
let server: Server;
|
||
let orm: TestOrm;
|
||
let f: LibraryFixture;
|
||
|
||
const as = (userId: number) => ({ Cookie: sessionCookie(userId) });
|
||
const VISITS = '/api/place-visits';
|
||
const LIBRARY = '/api/addons/collections/library/places';
|
||
const TODAY = '2026-07-02';
|
||
|
||
beforeAll(async () => {
|
||
const moduleRef = await Test.createTestingModule({
|
||
imports: [
|
||
await TestUnitOfWorkModule.forRoot(db),
|
||
await createTestMikroOrmModule(db),
|
||
RealtimeModule,
|
||
PlaceVisitsModule,
|
||
],
|
||
})
|
||
.overrideProvider(RealtimeService)
|
||
.useValue(realtime)
|
||
.compile();
|
||
app = moduleRef.createNestApplication();
|
||
app.use(cookieParser());
|
||
app.useGlobalPipes(new ZodValidationPipe());
|
||
app.useGlobalFilters(new TrekExceptionFilter());
|
||
await app.init();
|
||
server = app.getHttpServer() as Server;
|
||
orm = await createTestOrm(db);
|
||
});
|
||
beforeEach(async () => {
|
||
resetTestDb(db);
|
||
orm.clear();
|
||
realtime.reset();
|
||
vi.restoreAllMocks();
|
||
vi.spyOn(app.get(PlaceVisitsClock), 'today').mockReturnValue(TODAY);
|
||
f = await seedLibrary(orm);
|
||
await setAddonEnabled(orm, 'collections', true);
|
||
});
|
||
afterAll(async () => {
|
||
await app.close();
|
||
await orm.close();
|
||
db.close();
|
||
});
|
||
|
||
async function entryOf(userId: number, key: string) {
|
||
const res = await request(server).get(LIBRARY).set(as(userId));
|
||
expect(res.status).toBe(200);
|
||
return res.body.entries.find((row: { key: string }) => row.key === key);
|
||
}
|
||
|
||
describe('Place visits e2e (real guards + temp SQLite)', () => {
|
||
it('answers 401 without a session and refuses queries it does not take', async () => {
|
||
expect((await request(server).get(VISITS)).status).toBe(401);
|
||
expect((await request(server).get(`/api/trips/${f.alps.id}/place-visits/mine`)).status).toBe(401);
|
||
const refused = await oneByOne(
|
||
[{ kind: 'own', id: '1' }, { kind: 'trip', id: '0x5' }, { kind: 'trip' }, { kind: 'trip', id: '1', extra: '1' }],
|
||
(query) => request(server).get(`${VISITS}/place`).query(query).set(as(f.me.id)),
|
||
);
|
||
expect(refused.map((res) => res.status)).toEqual([400, 400, 400, 400]);
|
||
const list = await oneByOne([{ limit: '0' }, { limit: '201' }, { trip_id: 'abc' }], (query) =>
|
||
request(server).get(VISITS).query(query).set(as(f.me.id)),
|
||
);
|
||
expect(list.map((res) => res.status)).toEqual([400, 400, 400]);
|
||
});
|
||
|
||
it('has nothing to write: confirming, correcting and deleting a visit are gone', async () => {
|
||
const tries = await oneByOne(
|
||
[
|
||
() =>
|
||
request(server).post(VISITS).set(as(f.me.id)).send({ visited_on: '2026-07-01', place_id: f.places.cafe.id }),
|
||
() => request(server).patch(`${VISITS}/1`).set(as(f.me.id)).send({ note: 'x' }),
|
||
() => request(server).delete(`${VISITS}/1`).set(as(f.me.id)),
|
||
() => request(server).get(`${VISITS}/candidates`).set(as(f.me.id)),
|
||
() => request(server).get(`/api/trips/${f.alps.id}/place-visits/suggestions`).set(as(f.me.id)),
|
||
],
|
||
(call) => call(),
|
||
);
|
||
expect(tries.map((res) => res.status)).toEqual([404, 404, 404, 404, 404]);
|
||
});
|
||
|
||
it('reads the history and the counts of All places from the dated days that have come', async () => {
|
||
const [, day2, day3] = await readTripDays(orm, f.alps.id);
|
||
if (!day2 || !day3) throw new Error('Alps has three days');
|
||
await makeDayAssignment(orm, day2.id, f.places.cafe.id, { assignment_time: '12:00' });
|
||
await makeDayAssignment(orm, day2.id, f.places.cafe.id, { assignment_time: '10:00' });
|
||
await makeDayAssignment(orm, day3.id, f.places.cafe.id);
|
||
const undated = await makeDay(orm, f.alps.id, { date: null });
|
||
await makeDayAssignment(orm, undated.id, f.places.museum.id);
|
||
|
||
const history = await request(server)
|
||
.get(`${VISITS}/place`)
|
||
.query({ kind: 'list', id: f.saved.savedCafe.id })
|
||
.set(as(f.me.id));
|
||
expect(history.status).toBe(200);
|
||
expect(history.body).toMatchObject({ visit_count: 2, last_visit: TODAY });
|
||
expect(
|
||
history.body.visits.map((v: { visited_on: string; visited_time: string }) => [v.visited_on, v.visited_time]),
|
||
).toEqual([
|
||
[TODAY, '10:00'],
|
||
['2026-07-01', '09:00'],
|
||
]);
|
||
expect(await entryOf(f.me.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 2, last_visit: TODAY });
|
||
expect(await entryOf(f.me.id, `trip:${f.places.museum.id}`)).toMatchObject({ visit_count: 0, last_visit: null });
|
||
|
||
const mine = await request(server).get(`/api/trips/${f.alps.id}/place-visits/mine`).set(as(f.me.id));
|
||
expect(mine.body).toEqual({
|
||
place_ids: [f.places.cafe.id],
|
||
places: [{ place_id: f.places.cafe.id, visit_count: 2, last_visit: TODAY }],
|
||
});
|
||
const list = await request(server).get(VISITS).query({ limit: '1' }).set(as(f.me.id));
|
||
expect(list.body).toMatchObject({ total: 2, visits: [{ visited_on: TODAY, trip: { id: f.alps.id } }] });
|
||
});
|
||
|
||
it('counts a stop for its participants only, and nothing once the trip is out of reach', async () => {
|
||
await addTripMember(orm, f.alps.id, f.friend.id);
|
||
await createRow(orm, AssignmentParticipants, { assignment: (await firstCafeStop()).id, user: f.friend.id });
|
||
expect(await entryOf(f.me.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 0 });
|
||
expect(await entryOf(f.friend.id, `trip:${f.places.cafe.id}`)).toMatchObject({ visit_count: 1 });
|
||
|
||
await deleteRows(orm, TripMembers, { trip: f.alps.id, user: f.friend.id });
|
||
expect((await request(server).get(VISITS).set(as(f.friend.id))).body).toEqual({ visits: [], total: 0 });
|
||
expect((await request(server).get(`/api/trips/${f.alps.id}/place-visits/mine`).set(as(f.friend.id))).status).toBe(
|
||
404,
|
||
);
|
||
});
|
||
|
||
it('reads the media of an entry behind the Collections addon; the visits are no addon’s', async () => {
|
||
const media = await request(server).get(`${LIBRARY}/trip/${f.places.cafe.id}/media`).set(as(f.me.id));
|
||
expect(media.status).toBe(200);
|
||
expect(media.body).toEqual({ images: [], journey_photos: [], files: [] });
|
||
await setAddonEnabled(orm, 'collections', false);
|
||
expect((await request(server).get(`${LIBRARY}/trip/${f.places.cafe.id}/media`).set(as(f.me.id))).status).toBe(404);
|
||
expect((await request(server).get(VISITS).set(as(f.me.id))).status).toBe(200);
|
||
});
|
||
});
|
||
|
||
/** The stop that plans Café Central on the first day of Alps in the fixture. */
|
||
async function firstCafeStop() {
|
||
const stop = await findRow(orm, DayAssignments, { day: f.day1.id, place: f.places.cafe.id });
|
||
if (!stop) throw new Error('the fixture plans Café Central on day 1');
|
||
return stop;
|
||
}
|