{/* ── An import could not read every detail for sure ── */}
- {!!res.needs_review && (
+ {!!liveRes?.needs_review && (
{
- 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 {
* import is reported instead of failing on the unique index.
*/
async findIdByExternal(trip_id: number, external_source: string, external_id: string): Promise {
- 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()
+ .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 {
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 {
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 {
return due.reduce>(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 {
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 {
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 {
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>): BookingImportService {
+ const args = DEP_ORDER.map((name) => deps[name]);
+ return new BookingImportService(...(args as ConstructorParameters));
+}
+
+// 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 => 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();
});
});