fix(files): attach a loose file while the trip has Documents off

update and link go through when the request itself attaches the file to a booking, place, stop or expense, on REST and MCP alike, and upload_trip_file takes budget_item_id like the REST upload.
This commit is contained in:
Maurice
2026-11-23 15:34:15 +01:00
parent 8a2045c619
commit a0d66eb898
7 changed files with 126 additions and 17 deletions
+6 -5
View File
@@ -18,7 +18,7 @@ import { StorageService } from '../storage/storage.service';
import { AllowedFileTypesService } from './allowed-file-types.service';
import { MAX_FILE_SIZE, BLOCKED_EXTENSIONS, isUploadTypeAllowed, isVideoExtension } from './files.constants';
import { FileUploadDto, FileUpdateDto, FileLinkDto } from './files.dto';
import { FilesService } from './files.service';
import { FilesService, attachesFile } from './files.service';
import {
Body,
Controller,
@@ -155,8 +155,9 @@ export class FilesController {
}
}
/** 404 for a file only the file manager shows, while the trip has Documents off. */
private async assertReachable(trip: TripAccess, file: TripFileRow) {
/** 404 for a file only the file manager shows, while the trip has Documents off and the request does not attach it. */
private async assertReachable(trip: TripAccess, file: TripFileRow, targets: Parameters<typeof attachesFile>[0] = {}) {
if (attachesFile(targets)) return;
if (await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS)) return;
if (await this.files.isAttached(file)) return;
throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404);
@@ -274,7 +275,7 @@ export class FilesController {
if (!file) {
throw new HttpException({ error: 'File not found' }, 404);
}
await this.assertReachable(trip, file);
await this.assertReachable(trip, file, body);
await this.assertLinkTargets(tripId, {
reservation_id: body.reservation_id,
place_id: body.place_id,
@@ -409,7 +410,7 @@ export class FilesController {
if (!file) {
throw new HttpException({ error: 'File not found' }, 404);
}
await this.assertReachable(trip, file);
await this.assertReachable(trip, file, body);
await this.assertLinkTargets(tripId, {
reservation_id: body.reservation_id,
assignment_id: body.assignment_id,
+14 -8
View File
@@ -17,7 +17,7 @@ import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { contentTypeFor } from '../storage/content-type';
import { AllowedFileTypesService } from './allowed-file-types.service';
import { MAX_FILE_SIZE, isUploadTypeAllowed } from './files.constants';
import { FilesService, FileContentError, FILE_CONTENT_MAX } from './files.service';
import { FilesService, FileContentError, FILE_CONTENT_MAX, attachesFile } from './files.service';
import { idSchema, fileLinkRequestSchema, fileUpdateRequestSchema } from '@trek/shared';
import type { FileLinkRequest, FileUpdateRequest } from '@trek/shared';
@@ -70,8 +70,9 @@ function contentRefusal(err: FileContentError): string {
*
* The Documents addon is the file manager, gated as the REST routes gate it: while
* the trip has it off, the list leaves out the files only the manager shows, the
* trash is refused, and so is any tool on such a file. A file that belongs to a
* booking, place, expense, note or message stays reachable, and the upload stays open.
* trash is refused, and so is any tool on such a file unless the call itself attaches
* it. A file that belongs to a booking, place, expense, note or message stays
* reachable, and the upload stays open.
*/
@McpController()
export class FilesMcp {
@@ -82,7 +83,8 @@ export class FilesMcp {
readonly addons: AddonsService,
) {}
private async reachable(tripId: number, file: TripFileRow): Promise<boolean> {
private async reachable(tripId: number, file: TripFileRow, targets: FileLinkRequest = {}): Promise<boolean> {
if (attachesFile(targets)) return true;
return (await this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS)) || (await this.files.isAttached(file));
}
@@ -142,7 +144,7 @@ export class FilesMcp {
@Tool({
name: 'upload_trip_file',
description: `Add a document to a trip, e.g. a booking confirmation PDF or a ticket, and optionally attach it to a booking or a place in the same call. Pass the bytes base64-encoded in content, up to ${UPLOAD_MAX_MB} MB decoded. The file name has to carry an extension the trip's file manager accepts; the type is derived from it. Returns the new file, whose ID works with read_trip_file and link_trip_file.`,
description: `Add a document to a trip, e.g. a booking confirmation PDF or a ticket, and optionally attach it to a booking, a place or an expense in the same call. Pass the bytes base64-encoded in content, up to ${UPLOAD_MAX_MB} MB decoded. The file name has to carry an extension the trip's file manager accepts; the type is derived from it. Returns the new file, whose ID works with read_trip_file and link_trip_file.`,
inputSchema: {
tripId: idSchema,
filename: z
@@ -159,6 +161,7 @@ export class FilesMcp {
description: z.string().max(1000).optional().describe('Free-text description'),
reservation_id: idSchema.optional().describe('Booking on the same trip to attach the file to'),
place_id: idSchema.optional().describe('Place on the same trip to attach the file to'),
budget_item_id: idSchema.optional().describe('Expense on the same trip to attach the file to (a receipt)'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
access: { group: 'files', mode: 'write' },
@@ -171,6 +174,7 @@ export class FilesMcp {
description,
reservation_id,
place_id,
budget_item_id,
}: {
tripId: number;
filename: string;
@@ -178,6 +182,7 @@ export class FilesMcp {
description?: string;
reservation_id?: number;
place_id?: number;
budget_item_id?: number;
},
ctx: McpContext,
) {
@@ -195,11 +200,12 @@ export class FilesMcp {
if (bytes.length === 0) return errorResult('The file is empty.');
if (bytes.length > UPLOAD_MAX)
return errorResult(`File is too large (over ${UPLOAD_MAX_MB} MB). Ask the user to upload it in TREK instead.`);
const foreign = await this.files.findForeignLinkTarget(tripId, { reservation_id, place_id });
const foreign = await this.files.findForeignLinkTarget(tripId, { reservation_id, place_id, budget_item_id });
if (foreign) return errorResult(`Linked item does not belong to this trip (${foreign}).`);
const file = await this.files.createFileFromBytes(tripId, { originalname, mimetype, bytes }, ctx.userId, {
reservation_id: reservation_id ?? null,
place_id: place_id ?? null,
budget_item_id: budget_item_id ?? null,
description: description ?? null,
});
this.guards.safeBroadcast(tripId, 'file:created', { file });
@@ -237,7 +243,7 @@ export class FilesMcp {
if (!(await this.guards.hasTripPermission('file_edit', tripId, ctx.userId))) return permissionDenied();
const current = await this.files.getFileById(fileId, tripId);
if (!current) return errorResult('File not found.');
if (!(await this.reachable(tripId, current))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS));
if (!(await this.reachable(tripId, current, fields))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS));
// Same enforcement as the REST route's assertLinkTargets, through the same
// service method: a foreign reservation id would otherwise come back with its
// title attached the next time this file is listed.
@@ -280,7 +286,7 @@ export class FilesMcp {
if (!(await this.guards.hasTripPermission('file_edit', tripId, ctx.userId))) return permissionDenied();
const file = await this.files.getFileById(fileId, tripId);
if (!file) return errorResult('File not found.');
if (!(await this.reachable(tripId, file))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS));
if (!(await this.reachable(tripId, file, targets))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS));
// The REST body allows all three to be absent and stores a link row pointing at
// nothing. A tool caller that gets here with no target made a mistake, and saying
// so is more useful than a success that attached the file to nothing.
+22 -1
View File
@@ -71,6 +71,22 @@ function isAttachedFile(file: TripFileRow, fileLinks: FileLinkTargetRow[]): bool
return fileLinks.some((l) => l.reservation_id || l.assignment_id || l.place_id || l.budget_item_id);
}
/**
* Whether a write names a booking, place, stop or expense to attach the file to.
* Such a write makes a loose file one that belongs somewhere, so it goes through
* while the trip has Documents off.
*/
export function attachesFile(targets: {
reservation_id?: string | number | null;
assignment_id?: string | number | null;
place_id?: string | number | null;
budget_item_id?: string | number | null;
}): boolean {
return [targets.reservation_id, targets.assignment_id, targets.place_id, targets.budget_item_id].some(
(id) => coerceLinkId(id) !== null,
);
}
export interface FileLink {
file_id: number;
reservation_id: number | null;
@@ -426,7 +442,12 @@ export class FilesService {
tripId: string | number,
upload: { originalname: string; mimetype: string; bytes: Buffer },
uploadedBy: number,
opts: { place_id?: number | null; reservation_id?: number | null; description?: string | null },
opts: {
place_id?: number | null;
reservation_id?: number | null;
budget_item_id?: number | null;
description?: string | null;
},
) {
const filename = await this.storeBytes(upload);
return this.createFile(