mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 01:28:55 +00:00
939452f9d8
* refactor(server): route every trip-access check through DatabaseService
Twelve Nest services carry the same verifyTripAccess/canEdit pair. Six already
asked DatabaseService.canAccessTrip; the other six went through
services/tripAccess, a nine-line re-export of the identical function. Same
query, same result, two ways to reach it.
All twelve now take the injected route, so services/tripAccess is gone.
The bigger duplication was in the types. Thirteen files declared their own
`Trip` for the same return value, in three different shapes:
NonNullable<ReturnType<typeof verifyTripAccess>> 6x
{ user_id: number } 4x
TripAccess 3x
The narrow one is why assignments, days, places and accommodations all wrote
`as Trip | null | undefined` on the call — the cast existed to shrink
TripAccess down to a local type that was never meant to differ from it. All
thirteen now say TripAccess, and the four casts are gone with no other change.
middleware/tripAccess.ts goes too: it was already dead in production — nothing
under src/ imported requireTripAccess or requireTripOwner, only comments in the
services that had absorbed them. Its test went with it.
* refactor(server): fold the query helpers and trip joins into the container
Two more legacy files whose only reason for staying outside the container was
that they predated it.
services/queryHelpers.ts held five exports doing two different jobs. Three are
the batch loaders that keep the list endpoints off N+1 queries — they hit the
database and are now QueryHelpersService over the injected connection, imported
by assignments, days, places and share. The other two, formatAssignmentWithPlace
and ratingAggregate, touch no database at all; they sat next to the loaders only
because the loaders were free functions too. Those stay free functions, in
common/rowShape.ts.
The README note on the assignments service claimed the loaders had to stay in
services/ because the day, share and place services were unmigrated. All three
have since moved, so the reason is gone.
services/tripMembership.ts becomes TripMembershipService in its own module. It
could have folded into auth or trip-invite, but both call it — as do oidc and
the plugin RPC host — and putting it in either would have made AuthModule and
TripInviteModule import each other.
Neither module is @Global, matching PermissionsModule: e2e TestingModules
resolve them transitively through each consumer's explicit import.
Test seams changed shape accordingly. Two path mocks of services/tripMembership
became injected stubs; the trip-invite e2e overrides the provider in the
container instead. The oidc test keeps the real implementation, which is what
OIDC-SVC-045 was always asserting.
ratingAggregate moved out of the ungated services/ tree into the coverage-gated
one, so it gets the direct tests it never had — as does the tags/participants
pass-through, which two long-dead fixture variables in the moved test file had
been waiting for.
Also drops four stale comments that outlived their subject: the requireTripAccess
middleware they pointed at was deleted in the previous commit.
90 lines
4.6 KiB
TypeScript
90 lines
4.6 KiB
TypeScript
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
|
import { HttpException } from '@nestjs/common';
|
|
|
|
// Mock the heavy side-effect imports so the service module loads cleanly; the
|
|
// preview() path under test only touches the extractor + llmParse deps.
|
|
vi.mock('../../../../src/db/database', () => ({
|
|
db: { prepare: vi.fn() }, closeDb: () => {}, reinitialize: () => {},
|
|
// Trip access reaches these through DatabaseService; preview() never calls
|
|
// them, but the module-level import has to resolve.
|
|
canAccessTrip: vi.fn(), isOwner: () => false, getPlaceWithTags: () => null,
|
|
}));
|
|
import { db as dbConn } from '../../../../src/db/database';
|
|
import { DatabaseService } from '../../../../src/nest/database/database.service';
|
|
vi.mock('../../../../src/websocket', () => ({ broadcast: vi.fn() }));
|
|
const permissionsStub = { checkPermission: vi.fn(() => true) };
|
|
|
|
import { BookingImportService } from '../../../../src/nest/booking-import/booking-import.service';
|
|
|
|
const HOTEL_KI = { '@type': 'LodgingReservation', reservationNumber: 'ABC', reservationFor: { name: 'Hotel X' }, checkinTime: '2026-06-11T15:00', checkoutTime: '2026-06-12T11:00' };
|
|
const file = (name = 'a.pdf') => ({ buffer: Buffer.from('x'), originalname: name } as any);
|
|
|
|
function make(opts: { kit?: boolean; ai?: boolean; extract?: any; parse?: any }) {
|
|
const extractor = { isAvailable: () => opts.kit ?? false, extract: vi.fn(opts.extract ?? (async () => [])) };
|
|
const llmParse = { isAvailable: () => opts.ai ?? false, parse: vi.fn(opts.parse ?? (async () => ({ kiItems: [], warnings: [] }))) };
|
|
const reservations = { create: vi.fn() };
|
|
// budget/addons/realtime/maps ride the confirm() path only — the preview()
|
|
// tests never reach them, so stubs beyond the positional slots aren't needed.
|
|
const maps = { searchNominatim: vi.fn() };
|
|
// Places became a constructor dep with the place DI fold (was a path mock of
|
|
// services/placeService); only confirm() reaches it, so a bare create stub does.
|
|
const places = { create: vi.fn() };
|
|
return { svc: new BookingImportService(extractor as any, llmParse as any, new DatabaseService(dbConn), reservations as never, permissionsStub as never, undefined as never, undefined as never, undefined as never, maps as never, places as never), extractor, llmParse, reservations, maps, places };
|
|
}
|
|
|
|
beforeEach(() => vi.clearAllMocks());
|
|
|
|
describe('BookingImportService.preview', () => {
|
|
it('no-ai: maps kitinerary items, does not force needs_review, reports aiUsed:false', async () => {
|
|
const { svc, llmParse } = make({ kit: true, ai: false, extract: async () => [HOTEL_KI] });
|
|
const res = await svc.preview([file()], 'no-ai', 1);
|
|
expect(res.items).toHaveLength(1);
|
|
expect(res.items[0].needs_review).toBeFalsy();
|
|
expect(res.files).toEqual([{ fileName: 'a.pdf', aiAvailable: false, aiUsed: false }]);
|
|
expect(llmParse.parse).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it('throws 503 when neither parser is available', async () => {
|
|
const { svc } = make({ kit: false, ai: false });
|
|
try {
|
|
await svc.preview([file()], 'no-ai', 1);
|
|
throw new Error('expected throw');
|
|
} catch (err) {
|
|
expect(err).toBeInstanceOf(HttpException);
|
|
expect((err as HttpException).getStatus()).toBe(503);
|
|
}
|
|
});
|
|
|
|
it('fallback-on-empty: runs the LLM when kitinerary finds nothing and flags needs_review', async () => {
|
|
const { svc, extractor, llmParse } = make({
|
|
kit: true, ai: true,
|
|
extract: async () => [],
|
|
parse: async () => ({ kiItems: [HOTEL_KI], warnings: [] }),
|
|
});
|
|
const res = await svc.preview([file()], 'fallback-on-empty', 1);
|
|
expect(extractor.extract).toHaveBeenCalled();
|
|
expect(llmParse.parse).toHaveBeenCalled();
|
|
expect(res.items).toHaveLength(1);
|
|
expect(res.items[0].needs_review).toBe(true);
|
|
expect(res.files![0]).toEqual({ fileName: 'a.pdf', aiAvailable: true, aiUsed: true });
|
|
});
|
|
|
|
it('fallback-on-empty: skips the LLM when kitinerary already found items', async () => {
|
|
const { svc, llmParse } = make({ kit: true, ai: true, extract: async () => [HOTEL_KI] });
|
|
const res = await svc.preview([file()], 'fallback-on-empty', 1);
|
|
expect(llmParse.parse).not.toHaveBeenCalled();
|
|
expect(res.files![0].aiUsed).toBe(false);
|
|
});
|
|
|
|
it('force-ai: skips kitinerary entirely and uses the LLM', async () => {
|
|
const { svc, extractor, llmParse } = make({
|
|
kit: true, ai: true,
|
|
parse: async () => ({ kiItems: [HOTEL_KI], warnings: [] }),
|
|
});
|
|
const res = await svc.preview([file()], 'force-ai', 1);
|
|
expect(extractor.extract).not.toHaveBeenCalled();
|
|
expect(llmParse.parse).toHaveBeenCalled();
|
|
expect(res.items[0].needs_review).toBe(true);
|
|
});
|
|
});
|