mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 21:33:19 +00:00
fix(files): keep booking, place and expense files reachable with Documents off
The Documents addon now gates only the file manager: the list leaves out loose files, and the trash, starring and loose files answer 404, while uploads, deletes and every file a booking, place, expense, note or message carries stay reachable over REST, the download route, MCP and the offline bundle.
This commit is contained in:
@@ -19,8 +19,8 @@ import path from 'path';
|
||||
* 401 token, 404 trip/file, .pkpass served inline for Wallet. Bytes come from
|
||||
* storage.sendToResponse, whose local branch is the root-relative res.sendFile
|
||||
* form this route needs under the ExpressAdapter. A trip that has Documents off
|
||||
* answers 404 "Documents addon is not enabled" after the trip check, like every
|
||||
* other files route.
|
||||
* still serves the files of its bookings, places, expenses, notes and messages,
|
||||
* and answers 404 "Documents addon is not enabled" for the rest.
|
||||
*/
|
||||
@Public('authenticates itself: the download link carries a short-lived ?token the client mints')
|
||||
@Controller('api/trips/:tripId/files')
|
||||
@@ -45,14 +45,14 @@ export class FilesDownloadController {
|
||||
if (!trip) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS))) {
|
||||
throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404);
|
||||
}
|
||||
|
||||
const file = await this.files.getFileById(id, tripId);
|
||||
if (!file) {
|
||||
throw new HttpException({ error: 'File not found' }, 404);
|
||||
}
|
||||
if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS)) && !(await this.files.isAttached(file))) {
|
||||
throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404);
|
||||
}
|
||||
|
||||
// basename() tolerates a stray prefixed row (legacy rows sometimes stored
|
||||
// a relative path); the storage layer's key validation refuses the rest.
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { TripFileRow } from '../../db/repositories/TripFiles.repository';
|
||||
import type { TripAccess } from '../../db/repositories/Trips.repository';
|
||||
import type { User } from '../../types';
|
||||
import { addonOffMessage } from '../addons/addons.constants';
|
||||
@@ -122,9 +123,11 @@ export function filesUploadFileFilter(allowedTypes: AllowedFileTypesService): Op
|
||||
// the body has been read costs the bandwidth but keeps the answer readable, which is
|
||||
// the behaviour every client already handles.
|
||||
//
|
||||
// Documents is a trip addon: a trip it is off for answers 404 "Documents addon is
|
||||
// not enabled" on every route, after the trip check, with TripAddonGuard beside
|
||||
// TripAccessGuard and inline in the upload. The files themselves stay.
|
||||
// Documents is a trip addon, and it is the file manager: while a trip has it off,
|
||||
// the list leaves out the files only the manager shows, and the trash, starring
|
||||
// and any route on such a file answer 404 "Documents addon is not enabled". A file
|
||||
// that belongs to a booking, place, expense, note or message stays reachable, and
|
||||
// uploads and deletes stay open so those features can attach and roll back.
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@RequireAddon(ADDON_IDS.DOCUMENTS, 'Documents')
|
||||
export class FilesController {
|
||||
@@ -152,7 +155,14 @@ export class FilesController {
|
||||
}
|
||||
}
|
||||
|
||||
@UseGuards(TripAccessGuard, TripAddonGuard)
|
||||
/** 404 for a file only the file manager shows, while the trip has Documents off. */
|
||||
private async assertReachable(trip: TripAccess, file: TripFileRow) {
|
||||
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);
|
||||
}
|
||||
|
||||
@UseGuards(TripAccessGuard)
|
||||
@Get()
|
||||
@ResponseContract(tripFilesResponseSchema)
|
||||
async list(
|
||||
@@ -161,7 +171,11 @@ export class FilesController {
|
||||
@Param('tripId') tripId: string,
|
||||
@Query('trash') trash?: string,
|
||||
) {
|
||||
return { files: await this.files.listFiles(tripId, trash === 'true') };
|
||||
const documentsOn = await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS);
|
||||
if (!documentsOn && trash === 'true') {
|
||||
throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404);
|
||||
}
|
||||
return { files: await this.files.listFiles(tripId, trash === 'true', !documentsOn) };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@@ -191,9 +205,6 @@ export class FilesController {
|
||||
if (!trip) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
if (!(await this.addons.isEnabledForTrip(trip.id, ADDON_IDS.DOCUMENTS))) {
|
||||
throw new HttpException({ error: addonOffMessage(ADDON_IDS.DOCUMENTS) }, 404);
|
||||
}
|
||||
// Inline rather than DemoWriteGuard: the 404 above has to come first, so a demo
|
||||
// user still cannot learn which trips exist.
|
||||
if (isDemoWriteBlocked(this.env, user.email)) {
|
||||
@@ -245,7 +256,7 @@ export class FilesController {
|
||||
return { file: created };
|
||||
}
|
||||
|
||||
@UseGuards(TripAccessGuard, TripAddonGuard)
|
||||
@UseGuards(TripAccessGuard)
|
||||
@Put(':id')
|
||||
@ResponseContract(tripFileResponseSchema)
|
||||
async update(
|
||||
@@ -263,6 +274,7 @@ export class FilesController {
|
||||
if (!file) {
|
||||
throw new HttpException({ error: 'File not found' }, 404);
|
||||
}
|
||||
await this.assertReachable(trip, file);
|
||||
await this.assertLinkTargets(tripId, {
|
||||
reservation_id: body.reservation_id,
|
||||
place_id: body.place_id,
|
||||
@@ -311,7 +323,7 @@ export class FilesController {
|
||||
return { success: true, deleted };
|
||||
}
|
||||
|
||||
@UseGuards(TripAccessGuard, TripAddonGuard)
|
||||
@UseGuards(TripAccessGuard)
|
||||
@Delete(':id/permanent')
|
||||
@ResponseContract(successResponseSchema)
|
||||
async permanent(
|
||||
@@ -333,7 +345,7 @@ export class FilesController {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@UseGuards(TripAccessGuard, TripAddonGuard)
|
||||
@UseGuards(TripAccessGuard)
|
||||
@Delete(':id')
|
||||
@ResponseContract(successResponseSchema)
|
||||
async remove(
|
||||
@@ -378,7 +390,7 @@ export class FilesController {
|
||||
return { file: restored };
|
||||
}
|
||||
|
||||
@UseGuards(TripAccessGuard, TripAddonGuard)
|
||||
@UseGuards(TripAccessGuard)
|
||||
@Post(':id/link')
|
||||
@HttpCode(200) // Express answers link with res.json (200).
|
||||
@ResponseContract(fileLinkCreateResponseSchema)
|
||||
@@ -397,6 +409,7 @@ export class FilesController {
|
||||
if (!file) {
|
||||
throw new HttpException({ error: 'File not found' }, 404);
|
||||
}
|
||||
await this.assertReachable(trip, file);
|
||||
await this.assertLinkTargets(tripId, {
|
||||
reservation_id: body.reservation_id,
|
||||
assignment_id: body.assignment_id,
|
||||
@@ -416,7 +429,7 @@ export class FilesController {
|
||||
return { success: true, links };
|
||||
}
|
||||
|
||||
@UseGuards(TripAccessGuard, TripAddonGuard)
|
||||
@UseGuards(TripAccessGuard)
|
||||
@Delete(':id/link/:linkId')
|
||||
@ResponseContract(successResponseSchema)
|
||||
async unlink(
|
||||
@@ -437,11 +450,12 @@ export class FilesController {
|
||||
if (!file) {
|
||||
throw new HttpException({ error: 'File not found' }, 404);
|
||||
}
|
||||
await this.assertReachable(trip, file);
|
||||
await this.files.unlinkFile(id, linkId, this.files.restWriter(tripId, user, socketId));
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@UseGuards(TripAccessGuard, TripAddonGuard)
|
||||
@UseGuards(TripAccessGuard)
|
||||
@Get(':id/links')
|
||||
@ResponseContract(fileLinksResponseSchema)
|
||||
async links(
|
||||
@@ -454,6 +468,7 @@ export class FilesController {
|
||||
if (!file) {
|
||||
throw new HttpException({ error: 'File not found' }, 404);
|
||||
}
|
||||
await this.assertReachable(trip, file);
|
||||
return { links: await this.files.getFileLinks(id) };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import type { TripFileRow } from '../../db/repositories/TripFiles.repository';
|
||||
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import {
|
||||
McpController,
|
||||
@@ -10,7 +11,7 @@ import {
|
||||
errorResult,
|
||||
ok,
|
||||
} from '../../nest-mcp';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { addonOffMessage } from '../addons/addons.constants';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { contentTypeFor } from '../storage/content-type';
|
||||
@@ -24,12 +25,6 @@ import { z } from 'zod';
|
||||
|
||||
const CONTENT_MAX_MB = Math.round(FILE_CONTENT_MAX / (1024 * 1024));
|
||||
|
||||
/**
|
||||
* The trip file manager is the Documents addon: its tools are offered while it is on for the
|
||||
* instance or a trip of the caller, and each call needs it on for the trip it names (the host's
|
||||
* tool gate), as every files route answers 404 "Documents addon is not enabled" otherwise.
|
||||
*/
|
||||
const documentsAddonOn = addonGate(ADDON_IDS.DOCUMENTS);
|
||||
/**
|
||||
* The upload tool's cap: the same 10 MB a read hands back, or the operator's
|
||||
* upload limit when that is lower. The bytes travel base64 inside one JSON-RPC
|
||||
@@ -72,6 +67,11 @@ function contentRefusal(err: FileContentError): string {
|
||||
* transport. It is policed like the multipart route: the same extension rules
|
||||
* through isUploadTypeAllowed, the file_upload right, the demo block and the
|
||||
* same-trip check on what it attaches to, plus a tighter size cap.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
@McpController()
|
||||
export class FilesMcp {
|
||||
@@ -82,6 +82,10 @@ export class FilesMcp {
|
||||
readonly addons: AddonsService,
|
||||
) {}
|
||||
|
||||
private async reachable(tripId: number, file: TripFileRow): Promise<boolean> {
|
||||
return (await this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS)) || (await this.files.isAttached(file));
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'list_trip_files',
|
||||
description:
|
||||
@@ -92,11 +96,12 @@ export class FilesMcp {
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'files', mode: 'read' },
|
||||
when: documentsAddonOn,
|
||||
})
|
||||
async listTripFiles({ tripId, trash }: { tripId: number; trash?: boolean }, ctx: McpContext) {
|
||||
if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
return ok({ files: await this.files.listFiles(tripId, trash === true) });
|
||||
const documentsOn = await this.addons.isEnabledForTrip(tripId, ADDON_IDS.DOCUMENTS);
|
||||
if (!documentsOn && trash === true) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS));
|
||||
return ok({ files: await this.files.listFiles(tripId, trash === true, !documentsOn) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -111,10 +116,11 @@ export class FilesMcp {
|
||||
// passport scan are different privileges, and the plugin host draws the same
|
||||
// line (db:read:files vs db:read:files:content).
|
||||
access: { group: 'files', mode: 'content' },
|
||||
when: documentsAddonOn,
|
||||
})
|
||||
async readTripFile({ tripId, fileId }: { tripId: number; fileId: number }, ctx: McpContext) {
|
||||
if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
const file = await this.files.getFileById(fileId, tripId);
|
||||
if (file && !(await this.reachable(tripId, file))) return errorResult(addonOffMessage(ADDON_IDS.DOCUMENTS));
|
||||
try {
|
||||
const { name, mimetype, bytes } = await this.files.readContent(tripId, fileId);
|
||||
const asText = isTextual(mimetype);
|
||||
@@ -156,7 +162,6 @@ export class FilesMcp {
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: { group: 'files', mode: 'write' },
|
||||
when: documentsAddonOn,
|
||||
})
|
||||
async uploadTripFile(
|
||||
{
|
||||
@@ -223,7 +228,6 @@ export class FilesMcp {
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: { group: 'files', mode: 'write' },
|
||||
when: documentsAddonOn,
|
||||
})
|
||||
async updateTripFile(
|
||||
{ tripId, fileId, ...fields }: { tripId: number; fileId: number } & FileUpdateRequest,
|
||||
@@ -233,6 +237,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));
|
||||
// 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.
|
||||
@@ -266,7 +271,6 @@ export class FilesMcp {
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: { group: 'files', mode: 'write' },
|
||||
when: documentsAddonOn,
|
||||
})
|
||||
async linkTripFile(
|
||||
{ tripId, fileId, ...targets }: { tripId: number; fileId: number } & FileLinkRequest,
|
||||
@@ -274,7 +278,9 @@ export class FilesMcp {
|
||||
) {
|
||||
if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('file_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (!(await this.files.getFileById(fileId, tripId))) return errorResult('File not found.');
|
||||
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));
|
||||
// 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.
|
||||
@@ -298,7 +304,6 @@ export class FilesMcp {
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
access: { group: 'files', mode: 'write' },
|
||||
when: documentsAddonOn,
|
||||
})
|
||||
async unlinkTripFile(
|
||||
{ tripId, fileId, linkId }: { tripId: number; fileId: number; linkId: number },
|
||||
@@ -309,7 +314,9 @@ export class FilesMcp {
|
||||
// deleteFileLink scopes by (linkId, fileId) only, so the file has to be resolved
|
||||
// against :tripId first, exactly as the REST route does it. Otherwise a member of
|
||||
// any trip could drop a link row belonging to a foreign trip's file.
|
||||
if (!(await this.files.getFileById(fileId, tripId))) return errorResult('File not found.');
|
||||
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));
|
||||
await this.files.unlinkFile(fileId, linkId, await this.guards.tripWriter(tripId, ctx.userId));
|
||||
return ok({ success: true });
|
||||
}
|
||||
@@ -324,11 +331,12 @@ export class FilesMcp {
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'files', mode: 'read' },
|
||||
when: documentsAddonOn,
|
||||
})
|
||||
async listTripFileLinks({ tripId, fileId }: { tripId: number; fileId: number }, ctx: McpContext) {
|
||||
if (!(await this.files.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.files.getFileById(fileId, tripId))) return errorResult('File not found.');
|
||||
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));
|
||||
return ok({ links: await this.files.getFileLinks(fileId) });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,6 +61,16 @@ function withLinkedIds(file: TripFileJoinRow, fileLinks: FileLinkTargetRow[]) {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a file belongs to something besides the Documents file manager: a
|
||||
* booking, place, expense, collab note or chat message. Such a file stays
|
||||
* reachable while a trip has Documents off.
|
||||
*/
|
||||
function isAttachedFile(file: TripFileRow, fileLinks: FileLinkTargetRow[]): boolean {
|
||||
if (file.reservation_id || file.place_id || file.note_id || file.message_id) return true;
|
||||
return fileLinks.some((l) => l.reservation_id || l.assignment_id || l.place_id || l.budget_item_id);
|
||||
}
|
||||
|
||||
export interface FileLink {
|
||||
file_id: number;
|
||||
reservation_id: number | null;
|
||||
@@ -349,11 +359,17 @@ export class FilesService {
|
||||
};
|
||||
}
|
||||
|
||||
async listFiles(tripId: string | number, showTrash: boolean) {
|
||||
const tripIdNum = toRowId(tripId) ?? -1;
|
||||
const files = await this.tripFilesRepo.listForTrip(tripIdNum, showTrash);
|
||||
/** Whether the file belongs to a booking, place, expense, note or message rather than to the file manager alone. */
|
||||
async isAttached(file: TripFileRow): Promise<boolean> {
|
||||
return isAttachedFile(file, await this.fileLinksRepo.listForFiles([file.id]));
|
||||
}
|
||||
|
||||
const fileIds = files.map((f) => f.id);
|
||||
/** `attachedOnly` leaves out the files only the file manager shows, for a trip that has Documents off. */
|
||||
async listFiles(tripId: string | number, showTrash: boolean, attachedOnly = false) {
|
||||
const tripIdNum = toRowId(tripId) ?? -1;
|
||||
const all = await this.tripFilesRepo.listForTrip(tripIdNum, showTrash);
|
||||
|
||||
const fileIds = all.map((f) => f.id);
|
||||
const links = await this.fileLinksRepo.listForFiles(fileIds);
|
||||
const linksMap: Record<number, FileLinkTargetRow[]> = {};
|
||||
for (const link of links) {
|
||||
@@ -361,6 +377,7 @@ export class FilesService {
|
||||
linksMap[link.file_id].push(link);
|
||||
}
|
||||
|
||||
const files = attachedOnly ? all.filter((f) => isAttachedFile(f, linksMap[f.id] || [])) : all;
|
||||
return files.map((f) => withLinkedIds(f, linksMap[f.id] || []));
|
||||
}
|
||||
|
||||
|
||||
@@ -106,9 +106,10 @@ export class TripReadModelService {
|
||||
* Aggregates every trip sub-collection for offline caching (legacy /:id/bundle).
|
||||
*
|
||||
* A section whose addon is off for this trip (Lists for packing and todos,
|
||||
* Costs, Documents) goes out as an empty list rather than being left out, so
|
||||
* a client that replaces its cache from the bundle drops what it may no
|
||||
* longer show, and one that expects every key still finds it.
|
||||
* Costs) goes out as an empty list rather than being left out, so a client
|
||||
* that replaces its cache from the bundle drops what it may no longer show,
|
||||
* and one that expects every key still finds it. With Documents off the files
|
||||
* keep the ones a booking, place, expense, note or message carries.
|
||||
*/
|
||||
async bundle(tripId: string, trip: { id: number; user_id: number }, viewerId: number) {
|
||||
const { days } = await this.days.list(tripId);
|
||||
@@ -125,7 +126,7 @@ export class TripReadModelService {
|
||||
todoItems: packingOn ? await this.todo.listItems(tripId) : [],
|
||||
budgetItems: (await on(ADDON_IDS.BUDGET)) ? await this.budget.listBudgetItems(tripId) : [],
|
||||
reservations: await this.reservations.list(tripId),
|
||||
files: (await on(ADDON_IDS.DOCUMENTS)) ? await this.files.listFiles(tripId, false) : [],
|
||||
files: await this.files.listFiles(tripId, false, !(await on(ADDON_IDS.DOCUMENTS))),
|
||||
accommodations: await this.accommodations.list(tripId),
|
||||
members: [owner, ...(members || [])].filter(Boolean),
|
||||
};
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
* trip switched it on (allowed), and the instance has it on and the trip
|
||||
* switched it off (refused with `<Label> addon is not enabled`, data kept).
|
||||
* A trip without a choice follows the instance, so the instance switch now
|
||||
* closes the lists, costs, collab and files routes too.
|
||||
* closes the lists, costs, collab and file manager routes too. Documents is
|
||||
* the file manager only: a file a booking, place or expense carries stays
|
||||
* reachable while it is off.
|
||||
*/
|
||||
import { buildApp } from '../../src/bootstrap';
|
||||
import { BudgetItems } from '../../src/db/entities/BudgetItems.entity';
|
||||
@@ -16,8 +18,9 @@ import { createLocalMcpServer, McpRegistryService } from '../../src/nest-mcp';
|
||||
import { withRequestContext } from '../../src/nest/database/request-context';
|
||||
import { makeBudgetItem } from '../helpers/factories/budget';
|
||||
import { makeCollabNote } from '../helpers/factories/collab';
|
||||
import { makeTripFile } from '../helpers/factories/files';
|
||||
import { linkFile, makeTripFile } from '../helpers/factories/files';
|
||||
import { makePackingItem } from '../helpers/factories/packing';
|
||||
import { makeReservation } from '../helpers/factories/reservations';
|
||||
import { countRows } from '../helpers/factories/rows';
|
||||
import { setAddonEnabled, setTripAddon } from '../helpers/factories/settings';
|
||||
import { makeTodoItem } from '../helpers/factories/todos';
|
||||
@@ -85,7 +88,7 @@ const ROUTES: ReadonlyArray<[string, string, (tripId: number) => string]> = [
|
||||
['packing', 'Packing', (id) => `/api/trips/${id}/todo`],
|
||||
['budget', 'Costs', (id) => `/api/trips/${id}/budget`],
|
||||
['collab', 'Collab', (id) => `/api/trips/${id}/collab/notes`],
|
||||
['documents', 'Documents', (id) => `/api/trips/${id}/files`],
|
||||
['documents', 'Documents', (id) => `/api/trips/${id}/files?trash=true`],
|
||||
['roadtrip', 'Road trip', (id) => `/api/trips/${id}/roadtrip/vias`],
|
||||
['tours', 'Tours', (id) => `/api/trips/${id}/tours`],
|
||||
];
|
||||
@@ -145,15 +148,37 @@ describe('trip-scoped REST', () => {
|
||||
expect(anonymous.status).toBe(401);
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-004: the multipart upload refuses in its handler, so the caller reads the 404 body', async () => {
|
||||
it('TRIPADDON-ENF-004: with Documents off a booking still attaches, lists and opens its file, and a receipt still uploads', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'documents', false);
|
||||
const res = await request(app.getHttpServer())
|
||||
.post(`/api/trips/${chosen.id}/files`)
|
||||
.set('Cookie', sessionCookie(owner.id))
|
||||
.attach('file', Buffer.from('%PDF-1.4 test'), 'ticket.pdf');
|
||||
expect(res.status).toBe(404);
|
||||
expect(res.body).toEqual({ error: 'Documents addon is not enabled' });
|
||||
await setAddonEnabled(orm, 'documents', false);
|
||||
const booking = await makeReservation(orm, chosen.id, { title: 'Ferry' });
|
||||
const upload = (fields: Record<string, string>) => {
|
||||
const req = request(app.getHttpServer())
|
||||
.post(`/api/trips/${chosen.id}/files`)
|
||||
.set('Cookie', sessionCookie(owner.id));
|
||||
for (const [key, value] of Object.entries(fields)) req.field(key, value);
|
||||
return req.attach('file', Buffer.from('%PDF-1.4 test'), 'ferry.pdf');
|
||||
};
|
||||
const attached = await upload({ reservation_id: String(booking.id) });
|
||||
expect(attached.status).toBe(201);
|
||||
// A receipt for an expense not saved yet goes up without a link; the expense links it.
|
||||
expect((await upload({})).status).toBe(201);
|
||||
|
||||
const list = await get(owner.id, `/api/trips/${chosen.id}/files`);
|
||||
expect(list.status).toBe(200);
|
||||
expect((list.body.files as Array<{ id: number }>).map((f) => f.id)).toEqual([attached.body.file.id]);
|
||||
|
||||
const loose = await makeTripFile(orm, chosen.id, { original_name: 'notes.pdf' });
|
||||
const [opened, refused] = await oneByOne(
|
||||
[
|
||||
() => get(owner.id, `/api/trips/${chosen.id}/files/${attached.body.file.id}/download`),
|
||||
() => get(owner.id, `/api/trips/${chosen.id}/files/${loose.id}/download`),
|
||||
],
|
||||
(send) => send(),
|
||||
);
|
||||
expect(opened.status).toBe(200);
|
||||
expect(refused.status).toBe(404);
|
||||
expect(refused.body).toEqual({ error: 'Documents addon is not enabled' });
|
||||
});
|
||||
|
||||
it('TRIPADDON-ENF-005: switching back on brings every row back where it was', async () => {
|
||||
@@ -195,15 +220,18 @@ describe('routes about no one trip', () => {
|
||||
});
|
||||
|
||||
describe('what leaves the trip in bulk', () => {
|
||||
it('TRIPADDON-ENF-020: the offline bundle sends empty lists for the addons the trip has off', async () => {
|
||||
it('TRIPADDON-ENF-020: the offline bundle sends empty lists for the addons the trip has off, and only attached files', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
await setTripAddon(orm, chosen.id, 'packing', false);
|
||||
await setTripAddon(orm, chosen.id, 'documents', false);
|
||||
const booking = await makeReservation(orm, chosen.id, { title: 'Ferry' });
|
||||
const ticket = await makeTripFile(orm, chosen.id, { original_name: 'ferry.pdf' });
|
||||
await linkFile(orm, ticket.id, { reservation: booking.id });
|
||||
const res = await get(owner.id, `/api/trips/${chosen.id}/bundle`);
|
||||
expect(res.status).toBe(200);
|
||||
expect(res.body.packingItems).toEqual([]);
|
||||
expect(res.body.todoItems).toEqual([]);
|
||||
expect(res.body.files).toEqual([]);
|
||||
expect((res.body.files as Array<{ original_name: string }>).map((f) => f.original_name)).toEqual(['ferry.pdf']);
|
||||
expect((res.body.budgetItems as Array<{ name: string }>).map((item) => item.name)).toEqual(['Hotel']);
|
||||
});
|
||||
|
||||
@@ -304,6 +332,25 @@ describe('MCP', () => {
|
||||
expect(res.answer).not.toHaveProperty('packing');
|
||||
expect(res.answer).not.toHaveProperty('budget');
|
||||
});
|
||||
it('TRIPADDON-ENF-034: with Documents off the file tools still reach the files a booking carries, and only those', async () => {
|
||||
const { owner, chosen } = await world();
|
||||
await setAddonEnabled(orm, 'documents', false);
|
||||
const booking = await makeReservation(orm, chosen.id, { title: 'Ferry' });
|
||||
const ticket = await makeTripFile(orm, chosen.id, { original_name: 'ferry.pdf', reservation: booking.id });
|
||||
const loose = await makeTripFile(orm, chosen.id, { original_name: 'notes.pdf' });
|
||||
const listed = await callTool(owner.id, 'list_trip_files', { tripId: chosen.id });
|
||||
expect(listed.error).toBeNull();
|
||||
expect((listed.answer?.files as Array<{ id: number }>).map((f) => f.id)).toEqual([ticket.id]);
|
||||
expect((await callTool(owner.id, 'list_trip_files', { tripId: chosen.id, trash: true })).error).toBe(
|
||||
'Documents addon is not enabled',
|
||||
);
|
||||
expect(
|
||||
(await callTool(owner.id, 'list_trip_file_links', { tripId: chosen.id, fileId: ticket.id })).error,
|
||||
).toBeNull();
|
||||
expect((await callTool(owner.id, 'list_trip_file_links', { tripId: chosen.id, fileId: loose.id })).error).toBe(
|
||||
'Documents addon is not enabled',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('what a booking writes into Costs', () => {
|
||||
|
||||
@@ -74,16 +74,22 @@ const trip = { id: 5, user_id: 42 } as never;
|
||||
|
||||
// The 404 "Trip not found" cases moved to trip-access.guard.test.ts with the check.
|
||||
describe('FilesController (parity with the legacy /api/trips/:tripId/files route)', () => {
|
||||
it('every route but the multipart upload asks the trip and then the Documents addon of that trip', () => {
|
||||
it('only the file manager routes ask the Documents addon of the trip in a guard', () => {
|
||||
expect(Reflect.getMetadata(REQUIRE_ADDON, FilesController)).toEqual({ addonId: 'documents', label: 'Documents' });
|
||||
const proto = FilesController.prototype as unknown as Record<string, unknown>;
|
||||
const routes = Object.getOwnPropertyNames(FilesController.prototype)
|
||||
.map((name) => proto[name])
|
||||
.filter((fn) => typeof fn === 'function' && Reflect.getMetadata('method', fn as object) !== undefined);
|
||||
const guarded = routes.filter((fn) => fn !== FilesController.prototype.upload);
|
||||
expect(guarded.length).toBeGreaterThan(8);
|
||||
for (const handler of guarded) {
|
||||
expect(Reflect.getMetadata('__guards__', handler as object)).toEqual([TripAccessGuard, TripAddonGuard]);
|
||||
const proto = FilesController.prototype;
|
||||
for (const handler of [proto.star, proto.emptyTrash, proto.restore]) {
|
||||
expect(Reflect.getMetadata('__guards__', handler)).toEqual([TripAccessGuard, TripAddonGuard]);
|
||||
}
|
||||
for (const handler of [
|
||||
proto.list,
|
||||
proto.update,
|
||||
proto.remove,
|
||||
proto.permanent,
|
||||
proto.link,
|
||||
proto.unlink,
|
||||
proto.links,
|
||||
]) {
|
||||
expect(Reflect.getMetadata('__guards__', handler)).toEqual([TripAccessGuard]);
|
||||
}
|
||||
// A guard on the multipart route would answer before multer read the body (ECONNRESET), so it checks inside.
|
||||
expect(Reflect.getMetadata('__guards__', FilesController.prototype.upload)).toBeUndefined();
|
||||
@@ -94,7 +100,44 @@ describe('FilesController (parity with the legacy /api/trips/:tripId/files route
|
||||
expect(await fc(fsvc({ listFiles } as Partial<FilesService>)).list(user, trip, '5', 'true')).toEqual({
|
||||
files: [{ id: 1 }],
|
||||
});
|
||||
expect(listFiles).toHaveBeenCalledWith('5', true);
|
||||
expect(listFiles).toHaveBeenCalledWith('5', true, false);
|
||||
});
|
||||
|
||||
it('GET / with Documents off lists only attached files and refuses the trash', async () => {
|
||||
const listFiles = vi.fn().mockReturnValue([{ id: 1 }]);
|
||||
const controller = fc(fsvc({ listFiles } as Partial<FilesService>), addonsOff);
|
||||
expect(await controller.list(user, trip, '5')).toEqual({ files: [{ id: 1 }] });
|
||||
expect(listFiles).toHaveBeenCalledWith('5', false, true);
|
||||
expect(await rejected(controller.list(user, trip, '5', 'true'))).toEqual({
|
||||
status: 404,
|
||||
body: { error: 'Documents addon is not enabled' },
|
||||
});
|
||||
});
|
||||
|
||||
it('a file only the file manager shows answers 404 on its routes while Documents is off, an attached one does not', async () => {
|
||||
const svc = fsvc({
|
||||
getFileById: vi.fn().mockReturnValue({ id: 9 }),
|
||||
isAttached: vi.fn().mockResolvedValue(false),
|
||||
updateFile: vi.fn(),
|
||||
linkFile: vi.fn(),
|
||||
unlinkFile: vi.fn(),
|
||||
getFileLinks: vi.fn(),
|
||||
restWriter: vi.fn(),
|
||||
} as Partial<FilesService>);
|
||||
const off = { error: 'Documents addon is not enabled' };
|
||||
expect(await rejected(fc(svc, addonsOff).update(user, trip, '5', '9', {}))).toEqual({ status: 404, body: off });
|
||||
expect(await rejected(fc(svc, addonsOff).link(user, trip, '5', '9', {}))).toEqual({ status: 404, body: off });
|
||||
expect(await rejected(fc(svc, addonsOff).unlink(user, trip, '5', '9', '3'))).toEqual({ status: 404, body: off });
|
||||
expect(await rejected(fc(svc, addonsOff).links(user, trip, '5', '9'))).toEqual({ status: 404, body: off });
|
||||
expect(svc.updateFile).not.toHaveBeenCalled();
|
||||
expect(svc.unlinkFile).not.toHaveBeenCalled();
|
||||
|
||||
const attached = fsvc({
|
||||
getFileById: vi.fn().mockReturnValue({ id: 9 }),
|
||||
isAttached: vi.fn().mockResolvedValue(true),
|
||||
getFileLinks: vi.fn().mockReturnValue([{ id: 3 }]),
|
||||
} as Partial<FilesService>);
|
||||
expect(await fc(attached, addonsOff).links(user, trip, '5', '9')).toEqual({ links: [{ id: 3 }] });
|
||||
});
|
||||
|
||||
describe('POST / (upload)', () => {
|
||||
@@ -109,14 +152,11 @@ describe('FilesController (parity with the legacy /api/trips/:tripId/files route
|
||||
});
|
||||
|
||||
const file = { filename: 'a.pdf' } as Express.Multer.File;
|
||||
it('404 while Documents is off for the trip, after the trip check and before anything is stored', async () => {
|
||||
const svc = fsvc({ verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1 }) });
|
||||
expect(await rejected(fc(svc, addonsOff).upload(user, '5', file, {}))).toEqual({
|
||||
status: 404,
|
||||
body: { error: 'Documents addon is not enabled' },
|
||||
});
|
||||
expect(addonsOff.isEnabledForTrip).toHaveBeenCalledWith(5, 'documents');
|
||||
expect(storageStub.put).not.toHaveBeenCalled();
|
||||
it('stores the upload while Documents is off for the trip, so bookings, places and receipts still attach', async () => {
|
||||
const createFile = vi.fn().mockReturnValue({ id: 9 });
|
||||
const svc = fsvc({ verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1 }), createFile });
|
||||
expect(await fc(svc, addonsOff).upload(user, '5', file, { reservation_id: '4' })).toEqual({ file: { id: 9 } });
|
||||
expect(storageStub.put).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('403 in demo mode for a demo email', async () => {
|
||||
@@ -499,13 +539,26 @@ describe('FilesDownloadController', () => {
|
||||
).toEqual({ status: 404, body: { error: 'File not found' } });
|
||||
});
|
||||
|
||||
it('404 while Documents is off for the trip, before the file is looked up', async () => {
|
||||
const s = dsvc({ verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1 }) });
|
||||
expect(await rejected(new FilesDownloadController(s, dstor(), addonsOff).download(req, res, '5', '9'))).toEqual({
|
||||
status: 404,
|
||||
body: { error: 'Documents addon is not enabled' },
|
||||
});
|
||||
expect(s.getFileById).not.toHaveBeenCalled();
|
||||
it('while Documents is off for the trip, serves an attached file and 404s one only the file manager shows', async () => {
|
||||
const loose = dsvc({
|
||||
verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1 }),
|
||||
isAttached: vi.fn().mockResolvedValue(false),
|
||||
} as Partial<FilesService>);
|
||||
const storage = dstor();
|
||||
expect(await rejected(new FilesDownloadController(loose, storage, addonsOff).download(req, res, '5', '9'))).toEqual(
|
||||
{
|
||||
status: 404,
|
||||
body: { error: 'Documents addon is not enabled' },
|
||||
},
|
||||
);
|
||||
expect(storage.sendToResponse).not.toHaveBeenCalled();
|
||||
|
||||
const attached = dsvc({
|
||||
verifyTripAccess: vi.fn().mockReturnValue({ id: 5, user_id: 1 }),
|
||||
isAttached: vi.fn().mockResolvedValue(true),
|
||||
} as Partial<FilesService>);
|
||||
await new FilesDownloadController(attached, storage, addonsOff).download(req, res, '5', '9');
|
||||
expect(storage.sendToResponse).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('404 when the object is gone from storage', async () => {
|
||||
|
||||
@@ -373,6 +373,22 @@ describe('listFiles', () => {
|
||||
expect(files.find((f) => f.id === pinned.id).linked_assignment_ids).toEqual([stop.id]);
|
||||
expect(files.find((f) => f.id === bare.id).linked_assignment_ids).toEqual([]);
|
||||
});
|
||||
|
||||
it('FILE-SVC-014c: attachedOnly keeps the files a booking, place or expense carries and leaves out loose ones', async () => {
|
||||
const { user, trip } = seedTrip();
|
||||
const reservation = createReservation(testDb, trip.id);
|
||||
const place = createPlace(testDb, trip.id);
|
||||
const item = await insertBudgetItem(trip.id, 'Dinner');
|
||||
const onBooking = await makeFile(trip.id, user.id, {}, { reservation_id: reservation.id });
|
||||
const onPlace = await makeFile(trip.id, user.id, {}, { place_id: place.id });
|
||||
const receipt = await makeFile(trip.id, user.id, {}, { budget_item_id: item });
|
||||
const loose = await makeFile(trip.id, user.id);
|
||||
|
||||
const files = (await svc.listFiles(trip.id, false, true)) as Record<string, unknown>[];
|
||||
expect(files.map((f) => f.id).sort()).toEqual([onBooking.id, onPlace.id, receipt.id].sort());
|
||||
expect(await svc.isAttached((await svc.getFileById(receipt.id, trip.id))!)).toBe(true);
|
||||
expect(await svc.isAttached((await svc.getFileById(loose.id, trip.id))!)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
// ── receipts on an expense ────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user