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

- lint:tx: the mail transports and the intake document why their writes stand
  alone (@txIndependent, network I/O between them, one copy per address); the
  JSDoc of NotificationsService.respond is back above it after the response
  actions were registered in between.
- lint:boundaries: booking-import asks McpToolGuardsService whether the person
  may edit the trip's bookings instead of reading the Users table; its unit
  test builds the service through one named factory.
- lint:query-api: findIdByExternal reads through Kysely.
- lint:test-mocks: the mail e2e hands its own snapshot db to the ORM instead
  of mocking the database module.
- Entities regenerated (index order only).
- Client: the review row reads the live booking, the shells share
  useMailInboxShell, and the admin card's buttons are one size down.
This commit is contained in:
Maurice
2026-11-13 18:58:55 +01:00
parent a7adef5353
commit 53833fd212
18 changed files with 169 additions and 144 deletions
@@ -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: {
@@ -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(),
@@ -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: {
@@ -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;
}
@@ -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
@@ -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');
}
}
@@ -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) {
@@ -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;
@@ -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 };
@@ -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;
@@ -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);