Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

fix(mail-ingest): server gates after joining dev, and smaller admin buttons

Maurice53833fd21269
diff --git a/client/src/components/Admin/mailIngest/MailIngestAdminCard.tsx b/client/src/components/Admin/mailIngest/MailIngestAdminCard.tsx
index e2c658957..f28c50dab 100644
--- a/client/src/components/Admin/mailIngest/MailIngestAdminCard.tsx
+++ b/client/src/components/Admin/mailIngest/MailIngestAdminCard.tsx
@@ -29,6 +29,9 @@ import { useMailIngestAdmin, type MailIngestAdmin } from './useMailIngestAdmin';
type T = TranslationFn;
+/** The card's buttons sit inside the form, one size below the page's: caption type, tighter padding. */
+const SMALL = 'px-3 py-1.5 text-caption';
+
/** The address a mail service posts to, shown so the admin can paste it into the sender's settings. */
function InboundUrl({ t }: { t: T }) {
const toast = useToast();
@@ -39,7 +42,7 @@ function InboundUrl({ t }: { t: T }) {
<span className={READONLY_BOX}>{url}</span>
<button
type="button"
- className={SETTINGS_BUTTON}
+ className={`${SETTINGS_BUTTON} ${SMALL}`}
aria-label={t('mailAdmin.copyUrl')}
onClick={() => void copyText(url).then((ok) => (ok ? toast.success(t('common.copied')) : undefined))}
>
@@ -249,7 +252,7 @@ function Setup({ admin, form, t, locale }: { admin: MailIngestAdmin; form: MailA
<div className="flex flex-wrap items-center gap-2">
<button
type="button"
- className={SETTINGS_BUTTON_PRIMARY}
+ className={`${SETTINGS_BUTTON_PRIMARY} ${SMALL}`}
disabled={!admin.dirty || admin.problems.length > 0 || admin.saving}
onClick={admin.save}
>
@@ -258,7 +261,7 @@ function Setup({ admin, form, t, locale }: { admin: MailIngestAdmin; form: MailA
</button>
<button
type="button"
- className={SETTINGS_BUTTON}
+ className={`${SETTINGS_BUTTON} ${SMALL}`}
disabled={admin.testing || admin.dirty || form.transport === 'off'}
onClick={admin.runTest}
>
diff --git a/client/src/components/Layout/Navbar.tsx b/client/src/components/Layout/Navbar.tsx
index e8fa13459..7670c83a5 100644
--- a/client/src/components/Layout/Navbar.tsx
+++ b/client/src/components/Layout/Navbar.tsx
@@ -14,9 +14,8 @@ import AssistantLauncher from '../Assistant/AssistantLauncher'
import { resolvePluginIcon } from '../shared/PluginIcon'
import { visibleManagedNavItems } from '../../managed'
import { useCollapseOnOverflow } from '../../hooks/useCollapseOnOverflow'
-import { useMailIngestStore, watchMailInbox } from '../../store/mailIngestStore'
import { openMailInbox } from '../MailIngest/mailInboxOpener'
-import { useMailInboxLink } from '../MailIngest/useMailInboxLink'
+import { useMailInboxShell } from '../MailIngest/useMailInboxShell'
import MailInboxDialog from '../MailIngest/MailInboxDialog'
const ADDON_ICONS: Record<string, LucideIcon> = { CalendarDays, Briefcase, Globe, Compass, Bookmark }
@@ -48,16 +47,7 @@ export default function Navbar({ tripTitle, tripId, onBack, showBack, onSettings
const [userMenuOpen, setUserMenuOpen] = useState<boolean>(false)
const [scrolled, setScrolled] = useState<boolean>(false)
// The booking mail import's inbox: its menu entry shows only where the import is on for this person.
- const mailImport = useMailIngestStore(s => s.settings)
- const mailPending = useMailIngestStore(s => s.pending)
- const mailImportOn = !!mailImport?.available && mailImport.prefs.enabled
- useMailInboxLink(mailImportOn)
- const userId = user?.id
- useEffect(() => {
- if (!userId) return
- void useMailIngestStore.getState().loadSettings()
- return watchMailInbox()
- }, [userId])
+ const { on: mailImportOn, pending: mailPending } = useMailInboxShell(user?.id)
const darkMode = settings.dark_mode
const dark = darkMode === true || darkMode === 'dark' || (darkMode === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)
diff --git a/client/src/components/MailIngest/useMailInboxShell.ts b/client/src/components/MailIngest/useMailInboxShell.ts
new file mode 100644
index 000000000..275c945a1
--- /dev/null
+++ b/client/src/components/MailIngest/useMailInboxShell.ts
@@ -0,0 +1,24 @@
+import { useEffect } from 'react';
+import { useMailIngestStore, watchMailInbox } from '../../store/mailIngestStore';
+import { useMailInboxLink } from './useMailInboxLink';
+
+/**
+ * Everything a shell needs for the inbox of forwarded bookings: reads the
+ * person's import settings once they are signed in, follows the server's
+ * inbox events, opens the inbox from a ?inbox=mail link, and answers whether
+ * the import is on (the menu entry and the dialog show only then) and how many
+ * entries wait (the badge). The desktop Navbar and the phone's MMailInboxHost
+ * mount it, one per shell.
+ */
+export function useMailInboxShell(userId: number | undefined): { on: boolean; pending: number } {
+ const settings = useMailIngestStore((s) => s.settings);
+ const pending = useMailIngestStore((s) => s.pending);
+ const on = !!settings?.available && settings.prefs.enabled;
+ useMailInboxLink(on);
+ useEffect(() => {
+ if (!userId) return;
+ void useMailIngestStore.getState().loadSettings();
+ return watchMailInbox();
+ }, [userId]);
+ return { on, pending };
+}
diff --git a/client/src/mobile/screens/mail/MMailInboxHost.tsx b/client/src/mobile/screens/mail/MMailInboxHost.tsx
index 58c3c919b..9588650fd 100644
--- a/client/src/mobile/screens/mail/MMailInboxHost.tsx
+++ b/client/src/mobile/screens/mail/MMailInboxHost.tsx
@@ -1,24 +1,15 @@
-import { useEffect, type ReactElement } from 'react';
-import { useMailInboxLink } from '../../../components/MailIngest/useMailInboxLink';
+import type { ReactElement } from 'react';
+import { useMailInboxShell } from '../../../components/MailIngest/useMailInboxShell';
import { useAuthStore } from '../../../store/authStore';
-import { useMailIngestStore, watchMailInbox } from '../../../store/mailIngestStore';
import MMailInboxSheet from './MMailInboxSheet';
/**
- * The phone shell's one inbox of bookings from forwarded mails: reads the
- * person's import settings once they are signed in (the user menu's badge
- * needs them), follows the server's inbox events, and mounts the sheet only
+ * The phone shell's one inbox of bookings from forwarded mails: the shell's
+ * inbox wiring (settings, events, ?inbox=mail) and the sheet, mounted only
* where the import is on.
*/
export default function MMailInboxHost(): ReactElement | null {
const userId = useAuthStore((s) => s.user?.id);
- const settings = useMailIngestStore((s) => s.settings);
- useEffect(() => {
- if (!userId) return;
- void useMailIngestStore.getState().loadSettings();
- return watchMailInbox();
- }, [userId]);
- const on = !!settings?.available && settings.prefs.enabled;
- useMailInboxLink(on);
+ const { on } = useMailInboxShell(userId);
return on ? <MMailInboxSheet /> : null;
}
diff --git a/client/src/mobile/screens/trip/sheets/MTransportSheet.tsx b/client/src/mobile/screens/trip/sheets/MTransportSheet.tsx
index 75e734512..af6273ced 100644
--- a/client/src/mobile/screens/trip/sheets/MTransportSheet.tsx
+++ b/client/src/mobile/screens/trip/sheets/MTransportSheet.tsx
@@ -233,10 +233,10 @@ export default function MTransportSheet({ planner, shell }: MTripSheetsProps) {
<div className="m-scroll-fade mt-2 min-h-0 flex-1 overflow-y-auto px-[18px] pb-[18px] pt-[14px]">
{/* ── An import could not read every detail for sure ── */}
- {!!res.needs_review && (
+ {!!liveRes?.needs_review && (
<MReviewNotice
onConfirm={canEdit ? () => {
- planner.tripActions.updateReservation(planner.tripId, res.id, { needs_review: 0 })
+ planner.tripActions.updateReservation(planner.tripId, liveRes.id, { needs_review: 0 })
.then(() => planner.toast.success(t('reservations.reviewConfirmed')))
.catch(() => planner.toast.error(t('reservations.toast.updateError')))
} : undefined}
diff --git a/server/src/db/entities/MailIngestAddresses.entity.ts b/server/src/db/entities/MailIngestAddresses.entity.ts
index e3a5fe465..d238acbe4 100644
--- a/server/src/db/entities/MailIngestAddresses.entity.ts
+++ b/server/src/db/entities/MailIngestAddresses.entity.ts
@@ -24,10 +24,7 @@ export const MailIngestAddressesSchema = defineEntity({
class: MailIngestAddresses,
repository: () => MailIngestAddressesRepository,
indexes: [
- {
- name: 'idx_mail_ingest_addresses_user',
- properties: ['user_id', 'trip_id'],
- },
+ { name: 'idx_mail_ingest_addresses_user', properties: ['user_id', 'trip_id'] },
],
uniques: [{ properties: ['token_hash'] }],
properties: {
diff --git a/server/src/db/entities/MailIngestCandidates.entity.ts b/server/src/db/entities/MailIngestCandidates.entity.ts
index 7586559fe..355bdb6dc 100644
--- a/server/src/db/entities/MailIngestCandidates.entity.ts
+++ b/server/src/db/entities/MailIngestCandidates.entity.ts
@@ -38,10 +38,6 @@ export const MailIngestCandidatesSchema = defineEntity({
class: MailIngestCandidates,
repository: () => MailIngestCandidatesRepository,
indexes: [
- {
- name: 'idx_mail_ingest_candidates_message',
- properties: ['message_id', 'position'],
- },
{
name: 'idx_mail_ingest_candidates_resolved',
properties: ['resolved_trip_id', 'content_hash'],
@@ -50,6 +46,10 @@ export const MailIngestCandidatesSchema = defineEntity({
name: 'idx_mail_ingest_candidates_user',
properties: ['user_id', 'resolution'],
},
+ {
+ name: 'idx_mail_ingest_candidates_message',
+ properties: ['message_id', 'position'],
+ },
],
properties: {
id: p.integer().primary(),
diff --git a/server/src/db/entities/MailIngestMessages.entity.ts b/server/src/db/entities/MailIngestMessages.entity.ts
index 6da0cbce3..f0bd13251 100644
--- a/server/src/db/entities/MailIngestMessages.entity.ts
+++ b/server/src/db/entities/MailIngestMessages.entity.ts
@@ -47,14 +47,14 @@ export const MailIngestMessagesSchema = defineEntity({
name: 'idx_mail_ingest_messages_address',
properties: ['address_id', 'received_at'],
},
- {
- name: 'idx_mail_ingest_messages_due',
- properties: ['status', 'next_attempt_at'],
- },
{
name: 'idx_mail_ingest_messages_user',
properties: ['user_id', 'received_at'],
},
+ {
+ name: 'idx_mail_ingest_messages_due',
+ properties: ['status', 'next_attempt_at'],
+ },
],
uniques: [{ properties: ['dedupe_hash'] }],
properties: {
diff --git a/server/src/db/repositories/Reservations.repository.ts b/server/src/db/repositories/Reservations.repository.ts
index eb7ef5ac3..41167c0e5 100644
--- a/server/src/db/repositories/Reservations.repository.ts
+++ b/server/src/db/repositories/Reservations.repository.ts
@@ -528,10 +528,13 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
* import is reported instead of failing on the unique index.
*/
async findIdByExternal(trip_id: number, external_source: string, external_id: string): Promise<number | undefined> {
- const row = await this.qb('r')
- .select(['r.id'])
- .where({ trip: trip_id, external_source, external_id })
- .execute<{ id: number } | undefined>('get', false);
+ const row = await this.kysely<DB>()
+ .selectFrom('reservations')
+ .select(['id'])
+ .where('trip_id', '=', trip_id)
+ .where('external_source', '=', external_source)
+ .where('external_id', '=', external_id)
+ .executeTakeFirst();
return row?.id;
}
diff --git a/server/src/nest/booking-import/booking-import.module.ts b/server/src/nest/booking-import/booking-import.module.ts
index 41810dd9e..248da11d5 100644
--- a/server/src/nest/booking-import/booking-import.module.ts
+++ b/server/src/nest/booking-import/booking-import.module.ts
@@ -1,11 +1,10 @@
import { Days } from '../../db/entities/Days.entity';
import { Reservations } from '../../db/entities/Reservations.entity';
-import { Users } from '../../db/entities/Users.entity';
import { AddonsModule } from '../addons/addons.module';
import { BudgetModule } from '../budget/budget.module';
import { LlmParseModule } from '../llm-parse/llm-parse.module';
import { MapsModule } from '../maps/maps.module';
-import { PermissionsModule } from '../permissions/permissions.module';
+import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { PlacesModule } from '../places/places.module';
import { ReservationsModule } from '../reservations/reservations.module';
import { BookingImportService } from './booking-import.service';
@@ -15,23 +14,23 @@ import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
/**
- * `MikroOrmModule.forFeature([Days, Reservations, Users])` (Plan 3h Task 4, BI1/BI2):
+ * `MikroOrmModule.forFeature([Days, Reservations])` (Plan 3h Task 4, BI1/BI2):
* `BookingImportService.resolveDayId` reaches `DaysRepository.findByTripAndDate`
* and `ReservationsRepository.findNearestDayId`; confirm() reads the duplicate
- * key through `ReservationsRepository` and the importing person's role through
- * `UsersRepository` for its own permission check.
+ * key through `ReservationsRepository`, and asks McpToolGuardsService whether
+ * the importing person may edit the trip's bookings.
*/
@Module({
imports: [
KitineraryExtractorModule,
LlmParseModule,
ReservationsModule,
- PermissionsModule,
+ McpSharedModule,
BudgetModule,
AddonsModule,
MapsModule,
PlacesModule,
- MikroOrmModule.forFeature([Days, Reservations, Users]),
+ MikroOrmModule.forFeature([Days, Reservations]),
],
providers: [BookingImportService, ImportJobsService],
// The HTTP surface lives in reservation-import/, which shares the prefix with
diff --git a/server/src/nest/booking-import/booking-import.service.ts b/server/src/nest/booking-import/booking-import.service.ts
index 906776d78..79c5f7d24 100644
--- a/server/src/nest/booking-import/booking-import.service.ts
+++ b/server/src/nest/booking-import/booking-import.service.ts
@@ -1,10 +1,8 @@
import { ADDON_IDS } from '../../addons';
import { Days } from '../../db/entities/Days.entity';
import { Reservations } from '../../db/entities/Reservations.entity';
-import { Users } from '../../db/entities/Users.entity';
import { DaysRepository } from '../../db/repositories/Days.repository';
import { ReservationsRepository } from '../../db/repositories/Reservations.repository';
-import type { UsersRepository } from '../../db/repositories/Users.repository';
import { AddonsService } from '../addons/addons.service';
import { BudgetService } from '../budget/budget.service';
import { DomainError } from '../common/domain-error';
@@ -12,7 +10,7 @@ import { UnitOfWork } from '../database/unit-of-work';
import { imageMimeType } from '../llm-parse/image-input';
import { LlmParseService } from '../llm-parse/llm-parse.service';
import { MapsService } from '../maps/maps.service';
-import { PermissionsService } from '../permissions/permissions.service';
+import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { PlaceOriginsService } from '../places/place-origins.service';
import { PlacesService } from '../places/places.service';
import { RealtimeService } from '../realtime/realtime.service';
@@ -44,7 +42,7 @@ export class BookingImportService {
@InjectRepository(Days) private readonly daysRepo: DaysRepository,
@InjectRepository(Reservations) private readonly reservationsRepo: ReservationsRepository,
private readonly reservations: ReservationsService,
- private readonly permissions: PermissionsService,
+ private readonly guards: McpToolGuardsService,
private readonly budget: BudgetService,
private readonly addons: AddonsService,
private readonly realtime: RealtimeService,
@@ -52,7 +50,6 @@ export class BookingImportService {
private readonly places: PlacesService,
private readonly uow: UnitOfWork,
private readonly origins: PlaceOriginsService,
- @InjectRepository(Users) private readonly usersRepo: UsersRepository,
) {}
/**
@@ -400,9 +397,8 @@ export class BookingImportService {
private async requireBookingEdit(tripId: string, userId: number): Promise<void> {
const trip = await this.reservations.verifyTripAccess(tripId, userId);
if (!trip) throw new DomainError(404, 'Trip not found');
- const role = (await this.usersRepo.getRole(userId)) ?? 'user';
- const isMember = trip.user_id !== userId;
- if (!(await this.permissions.checkPermission('reservation_edit', role, trip.user_id, userId, isMember))) {
+ // The role is the auth domain's; the shared guard asks for it rather than reading its table here.
+ if (!(await this.guards.hasTripPermission('reservation_edit', tripId, userId))) {
throw new DomainError(403, 'No permission');
}
}
diff --git a/server/src/nest/mail-ingest/mail-ingest-apply.service.ts b/server/src/nest/mail-ingest/mail-ingest-apply.service.ts
index 9555146ab..40a265ace 100644
--- a/server/src/nest/mail-ingest/mail-ingest-apply.service.ts
+++ b/server/src/nest/mail-ingest/mail-ingest-apply.service.ts
@@ -229,7 +229,11 @@ export class MailIngestApplyService {
return removed;
}
- /** What an undo tells the trip once it committed, and the documents it moves to the trash. */
+ /**
+ * What an undo tells the trip once it committed, and the documents it moves to the trash.
+ *
+ * @txIndependent runs after the undo committed: each document goes to the trash on its own, and one that fails stays where it was.
+ */
async announceRemoved(removed: RemovedBooking, fileIds: readonly number[]): Promise<void> {
const { tripId } = removed;
for (const accommodationId of removed.accommodationIds) {
diff --git a/server/src/nest/mail-ingest/mail-ingest-imap.job.ts b/server/src/nest/mail-ingest/mail-ingest-imap.job.ts
index 6106caf09..3154d7341 100644
--- a/server/src/nest/mail-ingest/mail-ingest-imap.job.ts
+++ b/server/src/nest/mail-ingest/mail-ingest-imap.job.ts
@@ -87,6 +87,7 @@ export class MailIngestImapJob implements OnApplicationBootstrap {
}
}
+ /** @txIndependent IMAP round trips sit between the writes; each mail and the cursor are complete on their own. */
private async poll(
config: MailIngestImapConfig,
now: Date,
@@ -144,6 +145,7 @@ export class MailIngestImapJob implements OnApplicationBootstrap {
return outcomes.filter((outcome) => outcome === 'taken').length;
}
+ /** @txIndependent each mail is fetched from the box and stored by itself, with network I/O between them. */
private takeAll(session: ImapSession, due: readonly ImapMailRef[]): Promise<ImapOutcome[]> {
return due.reduce<Promise<ImapOutcome[]>>(async (previous, mail) => {
const done = await previous;
diff --git a/server/src/nest/mail-ingest/mail-ingest-intake.service.ts b/server/src/nest/mail-ingest/mail-ingest-intake.service.ts
index ac369aabb..13d0d4276 100644
--- a/server/src/nest/mail-ingest/mail-ingest-intake.service.ts
+++ b/server/src/nest/mail-ingest/mail-ingest-intake.service.ts
@@ -65,6 +65,8 @@ export class MailIngestIntakeService {
* When one of its addresses refuses it for now, the whole mail answers that
* refusal: the transport offers it again, and the copies stored already
* come back as duplicates.
+ *
+ * @txIndependent one copy per recipient address, each stored by itself; a refused copy leaves the others.
*/
async receive(
raw: Buffer,
@@ -85,7 +87,11 @@ export class MailIngestIntakeService {
return combined(results);
}
- /** An .eml the person uploaded, read as if they had forwarded it to their own address. */
+ /**
+ * An .eml the person uploaded, read as if they had forwarded it to their own address.
+ *
+ * @txIndependent the person's own address is provisioned idempotently, then the mail is stored by itself.
+ */
async upload(raw: Buffer, userId: number): Promise<MailIntakeResult> {
const refused = await this.precheck(raw);
if (refused) return { status: 'refused', reason: refused };
diff --git a/server/src/nest/mail-ingest/mail-ingest-relay.job.ts b/server/src/nest/mail-ingest/mail-ingest-relay.job.ts
index 8571fd4da..849be10d6 100644
--- a/server/src/nest/mail-ingest/mail-ingest-relay.job.ts
+++ b/server/src/nest/mail-ingest/mail-ingest-relay.job.ts
@@ -102,7 +102,11 @@ export class MailIngestRelayJob implements OnApplicationBootstrap {
}
}
- /** The pages from `after` on, as many as are left to the run; answers the mails taken in. */
+ /**
+ * The pages from `after` on, as many as are left to the run; answers the mails taken in.
+ *
+ * @txIndependent relay pages and acknowledgements are network round trips between the writes; each mail stands on its own.
+ */
private async drain(relay: MailInboxRelay, after: string | null, pagesLeft: number): Promise<number> {
const answer = await relay.list(PAGE, after);
if (answer === null) return 0;
diff --git a/server/src/nest/notifications/notifications.service.ts b/server/src/nest/notifications/notifications.service.ts
index fe8f054d9..6f4d5b835 100644
--- a/server/src/nest/notifications/notifications.service.ts
+++ b/server/src/nest/notifications/notifications.service.ts
@@ -729,11 +729,6 @@ export class NotificationsService {
return await this.notificationsRepo.deleteAllForRecipient(userId);
}
- /**
- * Run a notification's action for the recipient's answer.
- * @txIndependent the claim commits on its own before the action runs, so a second
- * submit sees it; a failing action releases it again.
- */
/**
* Names what a tap on a yes/no notification does: a domain that sends one
* registers its action here from its module's init, so this module never
@@ -748,6 +743,11 @@ export class NotificationsService {
registerAction(action, handler);
}
+ /**
+ * Run a notification's action for the recipient's answer.
+ * @txIndependent the claim commits on its own before the action runs, so a second
+ * submit sees it; a failing action releases it again.
+ */
async respond(notificationId: number, userId: number, response: NotificationResponse): Promise<RespondResult> {
const notification = await this.notificationsRepo.findByIdForRecipient(notificationId, userId);
diff --git a/server/tests/e2e/mail-ingest.e2e.test.ts b/server/tests/e2e/mail-ingest.e2e.test.ts
index bc3ed9a6f..b59915a6b 100644
--- a/server/tests/e2e/mail-ingest.e2e.test.ts
+++ b/server/tests/e2e/mail-ingest.e2e.test.ts
@@ -7,7 +7,6 @@
* read by the real pipeline, and is added, undone and refused through the
* routes the client and the admin dialog use.
*/
-import { db } from '../../src/db/database';
import { Reservations } from '../../src/db/entities/Reservations.entity';
import { BookingImportService } from '../../src/nest/booking-import/booking-import.service';
import { importExternalId } from '../../src/nest/booking-import/booking-origin';
@@ -22,6 +21,7 @@ import { signWebhookMail } from '../../src/nest/mail-ingest/mail-ingest-webhook.
import { MailIngestModule } from '../../src/nest/mail-ingest/mail-ingest.module';
import { MapsService } from '../../src/nest/maps/maps.service';
import { NotificationsService } from '../../src/nest/notifications/notifications.service';
+import { createSnapshotTestDb } from '../helpers/db-mock';
import { countRows } from '../helpers/factories/rows';
import { setAppSetting } from '../helpers/factories/settings';
import { makeTrip } from '../helpers/factories/trips';
@@ -37,10 +37,8 @@ import type { Server } from 'http';
import request from 'supertest';
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
-vi.mock('../../src/db/database', async () => {
- const { createSnapshotTestDb, buildDbMock } = await import('../helpers/db-mock');
- return buildDbMock(createSnapshotTestDb());
-});
+// A snapshot database of its own, handed to the ORM, the unit of work and the factories.
+const db = createSnapshotTestDb();
const USER = 1;
const OTHER = 2;
diff --git a/server/tests/unit/nest/booking-import/booking-import.service.test.ts b/server/tests/unit/nest/booking-import/booking-import.service.test.ts
index 2d0d2a906..606207cb0 100644
--- a/server/tests/unit/nest/booking-import/booking-import.service.test.ts
+++ b/server/tests/unit/nest/booking-import/booking-import.service.test.ts
@@ -15,9 +15,31 @@ vi.mock('../../../../src/db/database', () => ({
isOwner: () => false,
getPlaceWithTags: () => null,
}));
-const permissionsStub = { checkPermission: vi.fn(async () => true) };
+const guardsStub = { hasTripPermission: vi.fn(async () => true) };
+
+/** The service under test with the named collaborators given, every other one left out. */
+function buildService(deps: Partial<Record<(typeof DEP_ORDER)[number], unknown>>): BookingImportService {
+ const args = DEP_ORDER.map((name) => deps[name]);
+ return new BookingImportService(...(args as ConstructorParameters<typeof BookingImportService>));
+}
+
+// The constructor's order, so a test names what it hands in instead of counting positions.
+const DEP_ORDER = [
+ 'extractor',
+ 'llmParse',
+ 'daysRepo',
+ 'reservationsRepo',
+ 'reservations',
+ 'guards',
+ 'budget',
+ 'addons',
+ 'realtime',
+ 'maps',
+ 'places',
+ 'uow',
+ 'origins',
+] as const;
// confirm() checks the trip and the person's right itself: the trip is reachable, the role a plain user's.
-const usersStub = { getRole: vi.fn(async () => 'user') };
const tripAccess = vi.fn(async (): Promise<{ id: number; user_id: number } | undefined> => ({ id: 5, user_id: 1 }));
// No earlier import holds any key unless a test says so.
const findIdByExternal = vi.fn(async (): Promise<number | undefined> => undefined);
@@ -53,22 +75,16 @@ function make(opts: { kit?: boolean; ai?: boolean; extract?: any; parse?: any })
// 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,
- undefined as never,
- undefined as never,
- reservations as never,
- permissionsStub as never,
- undefined as never,
- undefined as never,
- undefined as never,
- maps as never,
- places as never,
- uowStub as never,
- origins as never,
- usersStub as never,
- ),
+ svc: buildService({
+ extractor,
+ llmParse,
+ reservations,
+ guards: guardsStub,
+ maps,
+ places,
+ uow: uowStub,
+ origins,
+ }),
extractor,
llmParse,
reservations,
@@ -272,22 +288,19 @@ describe('BookingImportService.confirm venue website (#2483)', () => {
};
const places = { create: vi.fn((_tripId: string, _input: { website?: string }) => ({ id: 7 })) };
// No dates on a restaurant, so the day repositories are never reached.
- const svc = new BookingImportService(
- {} as never,
- {} as never,
- undefined as never,
- reservationsRepoStub as never,
- reservations as never,
- permissionsStub as never,
- undefined as never,
- { isAddonEnabled: () => false } as never,
- { broadcast: vi.fn() } as never,
- { geocodeQuery: vi.fn() } as never,
- places as never,
- uowStub as never,
- origins as never,
- usersStub as never,
- );
+ const svc = buildService({
+ extractor: {},
+ llmParse: {},
+ reservationsRepo: reservationsRepoStub,
+ reservations,
+ guards: guardsStub,
+ addons: { isAddonEnabled: () => false },
+ realtime: { broadcast: vi.fn() },
+ maps: { geocodeQuery: vi.fn() },
+ places,
+ uow: uowStub,
+ origins,
+ });
const item = (website?: string) => ({
type: 'restaurant',
title: 'Dîner',
@@ -369,22 +382,20 @@ describe('BookingImportService.confirm writes the booking with its cost', () =>
order.push(event);
}),
};
- const svc = new BookingImportService(
- {} as never,
- {} as never,
- undefined as never,
- reservationsRepoStub as never,
- reservations as never,
- permissionsStub as never,
- budget as never,
- { isAddonEnabled: async () => opts.budget ?? true } as never,
- realtime as never,
- { geocodeQuery: vi.fn() } as never,
- places as never,
- uow as never,
- origins as never,
- usersStub as never,
- );
+ const svc = buildService({
+ extractor: {},
+ llmParse: {},
+ reservationsRepo: reservationsRepoStub,
+ reservations,
+ guards: guardsStub,
+ budget,
+ addons: { isAddonEnabled: async () => opts.budget ?? true },
+ realtime,
+ maps: { geocodeQuery: vi.fn() },
+ places,
+ uow,
+ origins,
+ });
return { svc, reservations, budget, places, realtime, order, costEvents };
}
const priced = {
@@ -546,22 +557,19 @@ describe('BookingImportService.confirm reports every item it did not create', ()
announceCost: vi.fn(),
verifyTripAccess: tripAccess,
};
- const svc = new BookingImportService(
- {} as never,
- {} as never,
- undefined as never,
- reservationsRepoStub as never,
- reservations as never,
- permissionsStub as never,
- undefined as never,
- { isAddonEnabled: async () => false } as never,
- { broadcast: vi.fn() } as never,
- { geocodeQuery: vi.fn() } as never,
- { create: vi.fn() } as never,
- uowStub as never,
- origins as never,
- usersStub as never,
- );
+ const svc = buildService({
+ extractor: {},
+ llmParse: {},
+ reservationsRepo: reservationsRepoStub,
+ reservations,
+ guards: guardsStub,
+ addons: { isAddonEnabled: async () => false },
+ realtime: { broadcast: vi.fn() },
+ maps: { geocodeQuery: vi.fn() },
+ places: { create: vi.fn() },
+ uow: uowStub,
+ origins,
+ });
return { svc, reservations };
}
const NO_LOCAL_TIME = { timezone: null, local_time: null, local_date: null };
@@ -657,10 +665,10 @@ describe('BookingImportService.confirm reports every item it did not create', ()
tripAccess.mockResolvedValueOnce(undefined);
await expect(svc.confirm('5', 1, [flight as never], undefined)).rejects.toMatchObject({ status: 404 });
- permissionsStub.checkPermission.mockResolvedValueOnce(false);
+ guardsStub.hasTripPermission.mockResolvedValueOnce(false);
await expect(svc.confirm('5', 2, [flight as never], undefined)).rejects.toMatchObject({ status: 403 });
- // A member (not the owner) is checked as one, with the role read for them.
- expect(permissionsStub.checkPermission).toHaveBeenLastCalledWith('reservation_edit', 'user', 1, 2, true);
+ // The right is asked of the shared guard for that person and trip, which reads their role.
+ expect(guardsStub.hasTripPermission).toHaveBeenLastCalledWith('reservation_edit', '5', 2);
expect(reservations.createWithCostInTx).not.toHaveBeenCalled();
});
});