feat(budget): attach receipts and invoices to expenses

This commit is contained in:
dersimoezdag
2026-09-06 15:48:35 +02:00
committed by Maurice
parent b2a196d1e7
commit 06ecc5135c
37 changed files with 1293 additions and 34 deletions
+20
View File
@@ -4415,6 +4415,26 @@ function runMigrations(db: Database.Database): void {
WHERE UPPER(country_code) = 'CN' AND region_code = 'CN-GUANGZHOUPROVINCE'`,
).run();
},
/**
* Let a file hang off an expense, so a receipt or an invoice can be attached
* to what it paid for.
*
* A column on `file_links` rather than a table of its own: the row already
* ties one file to one thing, and every other attachment kind is a column
* here too. The unique index stops the same receipt being linked twice;
* SQLite treats NULLs as distinct, so the rows that exist today, which all
* carry a NULL here, do not collide with each other.
*
* Appended LAST: the array is index-addressed against schema_version.
*/
() => {
const flCols = db.prepare("SELECT name FROM pragma_table_info('file_links')").all() as Array<{ name: string }>;
if (!flCols.some((c) => c.name === 'budget_item_id')) {
db.exec('ALTER TABLE file_links ADD COLUMN budget_item_id INTEGER REFERENCES budget_items(id) ON DELETE CASCADE');
}
db.exec('CREATE UNIQUE INDEX IF NOT EXISTS idx_file_links_file_budget ON file_links(file_id, budget_item_id)');
db.exec('CREATE INDEX IF NOT EXISTS idx_file_links_budget_item_id ON file_links(budget_item_id)');
},
];
if (currentVersion < migrations.length) {
+151 -2
View File
@@ -4,7 +4,7 @@ import type { TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
import { PermissionsService } from '../permissions/permissions.service';
import { avatarUrl } from '../common/avatarUrl';
import type { User, BudgetItem, BudgetItemMember, BudgetItemPayer } from '../../types';
import type { User, BudgetItem, BudgetItemMember, BudgetItemPayer, BudgetItemReceipt } from '../../types';
import { ExchangeRatesService } from './exchange-rates.service';
type Trip = TripAccess;
@@ -143,6 +143,32 @@ export class BudgetService {
return rows.map(p => ({ ...p, avatar_url: avatarUrl(p) }));
}
private loadItemReceipts(itemId: number | string): BudgetItemReceipt[] {
const rows = this.db.all<{
id: number;
filename: string;
original_name: string;
file_size: number | null;
mime_type: string | null;
trip_id: number;
}>(`
SELECT f.id, f.filename, f.original_name, f.file_size, f.mime_type, f.trip_id
FROM trip_files f
JOIN file_links fl ON fl.file_id = f.id
WHERE f.deleted_at IS NULL AND fl.budget_item_id = ?
ORDER BY f.created_at ASC
`, itemId);
return rows.map(f => ({
id: f.id,
filename: f.filename,
original_name: f.original_name,
file_size: f.file_size,
mime_type: f.mime_type,
url: `/api/trips/${f.trip_id}/files/${f.id}/download`,
}));
}
/**
* The subset of `userIds` that is actually on this trip. Used to be a plain
* existence check against `users`, which let any id on the instance become a
@@ -177,6 +203,37 @@ export class BudgetService {
return total;
}
/**
* Move a receipt file to trash if it is only linked to this budget item and
* not referenced by any other reservation, place, or day assignment.
*/
private trashOrphanReceipt(fileId: number | string, budgetItemId: number | string) {
const file = this.db.get<{ id: number; place_id: number | null; reservation_id: number | null }>(
'SELECT id, place_id, reservation_id FROM trip_files WHERE id = ? AND deleted_at IS NULL',
fileId,
);
if (!file) return;
// Check if file is tied directly to another entity via legacy columns
if (file.place_id || file.reservation_id) return;
// Check if file is linked via file_links to another reservation, place, assignment, or other budget item
const otherLinks = this.db.get<{ count: number }>(`
SELECT COUNT(*) as count FROM file_links
WHERE file_id = ? AND (
reservation_id IS NOT NULL OR
place_id IS NOT NULL OR
assignment_id IS NOT NULL OR
(budget_item_id IS NOT NULL AND budget_item_id != ?)
)
`, fileId, budgetItemId);
if (otherLinks && otherLinks.count > 0) return;
// It is an orphan receipt solely belonging to this budget item: move to trash
this.db.run('UPDATE trip_files SET deleted_at = CURRENT_TIMESTAMP WHERE id = ?', fileId);
}
// -------------------------------------------------------------------------
// CRUD
// -------------------------------------------------------------------------
@@ -225,9 +282,42 @@ export class BudgetService {
}
}
const receiptsByItem: Record<number, BudgetItemReceipt[]> = {};
if (itemIds.length > 0) {
const placeholders = itemIds.map(() => '?').join(',');
const allReceipts = this.db.all<{
id: number;
filename: string;
original_name: string;
file_size: number | null;
mime_type: string | null;
trip_id: number;
budget_item_id: number;
}>(`
SELECT f.id, f.filename, f.original_name, f.file_size, f.mime_type, f.trip_id, fl.budget_item_id
FROM trip_files f
JOIN file_links fl ON fl.file_id = f.id
WHERE f.deleted_at IS NULL AND fl.budget_item_id IN (${placeholders})
ORDER BY f.created_at ASC
`, ...itemIds);
for (const r of allReceipts) {
if (!receiptsByItem[r.budget_item_id]) receiptsByItem[r.budget_item_id] = [];
receiptsByItem[r.budget_item_id].push({
id: r.id,
filename: r.filename,
original_name: r.original_name,
file_size: r.file_size,
mime_type: r.mime_type,
url: `/api/trips/${r.trip_id}/files/${r.id}/download`,
});
}
}
items.forEach(item => {
item.members = membersByItem[item.id] || [];
item.payers = payersByItem[item.id] || [];
item.receipts = receiptsByItem[item.id] || [];
});
return items;
}
@@ -352,6 +442,7 @@ export class BudgetService {
ticket_json?: string | null;
reservation_id?: number | null;
place_id?: number | null;
receipt_file_ids?: number[];
},
) {
return this.db.transaction(() => {
@@ -409,19 +500,32 @@ export class BudgetService {
for (const uid of memberIds) insert.run(itemId, uid);
}
if (data.receipt_file_ids && data.receipt_file_ids.length > 0) {
const insertLink = this.db.prepare('INSERT OR IGNORE INTO file_links (file_id, budget_item_id) VALUES (?, ?)');
for (const fid of data.receipt_file_ids) {
// Verify file belongs to this trip
const belongs = this.db.get('SELECT id FROM trip_files WHERE id = ? AND trip_id = ? AND deleted_at IS NULL', fid, tripId);
if (belongs) {
insertLink.run(fid, itemId);
}
}
}
const item = this.db.get<BudgetItem>('SELECT * FROM budget_items WHERE id = ?', itemId)!;
item.members = this.loadItemMembers(itemId);
item.payers = this.loadItemPayers(itemId);
item.receipts = this.loadItemReceipts(itemId);
return item;
});
}
/** Fetch a single budget item hydrated with its members and payers, scoped to the trip. */
/** Fetch a single budget item hydrated with its members, payers, and receipts, scoped to the trip. */
getBudgetItem(id: string | number, tripId: string | number): BudgetItem | null {
const item = this.db.get<BudgetItem>('SELECT * FROM budget_items WHERE id = ? AND trip_id = ?', id, tripId);
if (!item) return null;
item.members = this.loadItemMembers(id);
item.payers = this.loadItemPayers(id);
item.receipts = this.loadItemReceipts(id);
return item;
}
@@ -445,6 +549,7 @@ export class BudgetService {
members?: { user_id: number; amount?: number | null }[];
persons?: number | null; days?: number | null; note?: string | null; sort_order?: number; expense_date?: string | null;
ticket_json?: string | null;
receipt_file_ids?: number[];
},
) {
return this.db.transaction(() => {
@@ -522,9 +627,39 @@ export class BudgetService {
}
}
if (data.receipt_file_ids !== undefined) {
// Find existing receipt file IDs for this budget item
const oldReceiptFiles = this.db.all<{ id: number }>(`
SELECT f.id FROM trip_files f
JOIN file_links fl ON fl.file_id = f.id
WHERE f.deleted_at IS NULL AND fl.budget_item_id = ?
`, id).map(r => r.id);
// Sync receipts: delete previous links and add new ones
this.db.run('DELETE FROM file_links WHERE budget_item_id = ?', id);
if (data.receipt_file_ids.length > 0) {
const insertLink = this.db.prepare('INSERT OR IGNORE INTO file_links (file_id, budget_item_id) VALUES (?, ?)');
for (const fid of data.receipt_file_ids) {
const belongs = this.db.get('SELECT id FROM trip_files WHERE id = ? AND trip_id = ? AND deleted_at IS NULL', fid, tripId);
if (belongs) {
insertLink.run(fid, id);
}
}
}
// Any previously attached receipt that was unlinked now moves to trash if orphan
const newSet = new Set(data.receipt_file_ids);
for (const oldFid of oldReceiptFiles) {
if (!newSet.has(oldFid)) {
this.trashOrphanReceipt(oldFid, id);
}
}
}
const updated = this.db.get<BudgetItem>('SELECT * FROM budget_items WHERE id = ?', id)!;
updated.members = this.loadItemMembers(id);
updated.payers = this.loadItemPayers(id);
updated.receipts = this.loadItemReceipts(id);
return updated;
});
}
@@ -551,7 +686,21 @@ export class BudgetService {
);
if (!item) return false;
return this.db.transaction(() => {
// Find all receipts attached to this item before deleting it
const receiptFiles = this.db.all<{ id: number }>(`
SELECT f.id FROM trip_files f
JOIN file_links fl ON fl.file_id = f.id
WHERE f.deleted_at IS NULL AND fl.budget_item_id = ?
`, id).map(r => r.id);
// Move exclusively attached receipts to trash
for (const fid of receiptFiles) {
this.trashOrphanReceipt(fid, id);
}
this.db.run('DELETE FROM file_links WHERE budget_item_id = ?', id);
this.db.run('DELETE FROM budget_items WHERE id = ?', id);
// The booking keeps a copy of this expense's total in its metadata, and
// the reservation update path preserves that copy across edits. With the
// expense gone there is nothing left to mirror, so drop it here rather
+13 -7
View File
@@ -91,10 +91,10 @@ export class FilesController {
) {}
// A file may only point at reservations/assignments/places from its own trip.
// A file may only point at reservations/assignments/places/budget_items from its own trip.
// Reject cross-trip ids before they are stored — the reservation JOIN would
// otherwise leak the foreign reservation's title back to the caller.
private assertLinkTargets(tripId: string, body: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null }) {
private assertLinkTargets(tripId: string, body: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null; budget_item_id?: string | number | null }) {
if (this.files.findForeignLinkTarget(tripId, body)) {
throw new HttpException({ error: 'Linked item does not belong to this trip' }, 400);
}
@@ -148,7 +148,7 @@ export class FilesController {
throw new HttpException({ error: 'File is too large' }, 400);
}
try {
this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, place_id: body.place_id });
this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, place_id: body.place_id, budget_item_id: body.budget_item_id });
} catch (err) {
cleanup();
throw err;
@@ -165,6 +165,7 @@ export class FilesController {
place_id: body.place_id,
description: body.description,
reservation_id: body.reservation_id,
budget_item_id: body.budget_item_id,
});
this.files.broadcast(tripId, 'file:created', { file: created }, socketId);
return { file: created };
@@ -180,8 +181,13 @@ export class FilesController {
if (!file) {
throw new HttpException({ error: 'File not found' }, 404);
}
this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, place_id: body.place_id });
const updated = this.files.updateFile(id, file, { description: body.description, place_id: body.place_id, reservation_id: body.reservation_id });
this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, place_id: body.place_id, budget_item_id: body.budget_item_id });
const updated = this.files.updateFile(id, file, {
description: body.description,
place_id: body.place_id,
reservation_id: body.reservation_id,
budget_item_id: body.budget_item_id,
});
this.files.broadcast(tripId, 'file:updated', { file: updated }, socketId);
return { file: updated };
}
@@ -268,8 +274,8 @@ export class FilesController {
if (!file) {
throw new HttpException({ error: 'File not found' }, 404);
}
this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, assignment_id: body.assignment_id, place_id: body.place_id });
const links = this.files.createFileLink(id, { reservation_id: body.reservation_id, assignment_id: body.assignment_id, place_id: body.place_id });
this.assertLinkTargets(tripId, { reservation_id: body.reservation_id, assignment_id: body.assignment_id, place_id: body.place_id, budget_item_id: body.budget_item_id });
const links = this.files.createFileLink(id, { reservation_id: body.reservation_id, assignment_id: body.assignment_id, place_id: body.place_id, budget_item_id: body.budget_item_id });
return { success: true, links };
}
+25 -8
View File
@@ -37,6 +37,7 @@ export interface FileLink {
file_id: number;
reservation_id: number | null;
place_id: number | null;
budget_item_id: number | null;
}
/**
@@ -137,8 +138,8 @@ export class FilesService {
*/
findForeignLinkTarget(
tripId: string | number,
opts: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null }
): 'reservation_id' | 'assignment_id' | 'place_id' | null {
opts: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null; budget_item_id?: string | number | null }
): 'reservation_id' | 'assignment_id' | 'place_id' | 'budget_item_id' | null {
if (opts.reservation_id && !this.db.get('SELECT 1 FROM reservations WHERE id = ? AND trip_id = ?', opts.reservation_id, tripId)) {
return 'reservation_id';
}
@@ -148,6 +149,9 @@ export class FilesService {
if (opts.assignment_id && !this.db.get('SELECT 1 FROM day_assignments a JOIN days d ON a.day_id = d.id WHERE a.id = ? AND d.trip_id = ?', opts.assignment_id, tripId)) {
return 'assignment_id';
}
if (opts.budget_item_id && !this.db.get('SELECT 1 FROM budget_items WHERE id = ? AND trip_id = ?', opts.budget_item_id, tripId)) {
return 'budget_item_id';
}
return null;
}
@@ -229,7 +233,7 @@ export class FilesService {
const linksMap: Record<number, FileLink[]> = {};
if (fileIds.length > 0) {
const placeholders = fileIds.map(() => '?').join(',');
const links = this.db.all<FileLink>(`SELECT file_id, reservation_id, place_id FROM file_links WHERE file_id IN (${placeholders})`, ...fileIds);
const links = this.db.all<FileLink>(`SELECT file_id, reservation_id, place_id, budget_item_id FROM file_links WHERE file_id IN (${placeholders})`, ...fileIds);
for (const link of links) {
if (!linksMap[link.file_id]) linksMap[link.file_id] = [];
linksMap[link.file_id].push(link);
@@ -242,6 +246,7 @@ export class FilesService {
...formatFile(f),
linked_reservation_ids: fileLinks.filter(l => l.reservation_id).map(l => l.reservation_id),
linked_place_ids: fileLinks.filter(l => l.place_id).map(l => l.place_id),
linked_budget_item_ids: fileLinks.filter(l => l.budget_item_id).map(l => l.budget_item_id),
};
});
}
@@ -250,7 +255,7 @@ export class FilesService {
tripId: string | number,
file: { filename: string; originalname: string; size: number; mimetype: string },
uploadedBy: number,
opts: { place_id?: string | number | null; reservation_id?: string | number | null; description?: string | null }
opts: { place_id?: string | number | null; reservation_id?: string | number | null; budget_item_id?: string | number | null; description?: string | null }
) {
const result = this.db.run(`
INSERT INTO trip_files (trip_id, place_id, reservation_id, filename, original_name, file_size, mime_type, description, uploaded_by)
@@ -267,6 +272,10 @@ export class FilesService {
uploadedBy
);
if (opts.budget_item_id) {
this.db.run('INSERT OR IGNORE INTO file_links (file_id, budget_item_id) VALUES (?, ?)', result.lastInsertRowid, opts.budget_item_id);
}
const created = this.db.get<TripFile>(`${FILE_SELECT} WHERE f.id = ?`, result.lastInsertRowid)!;
return formatFile(created);
}
@@ -274,7 +283,7 @@ export class FilesService {
updateFile(
id: string | number,
current: TripFile,
updates: { description?: string; place_id?: string | number | null; reservation_id?: string | number | null }
updates: { description?: string; place_id?: string | number | null; reservation_id?: string | number | null; budget_item_id?: string | number | null }
) {
this.db.run(`
UPDATE trip_files SET
@@ -289,6 +298,14 @@ export class FilesService {
id
);
if (updates.budget_item_id !== undefined) {
if (updates.budget_item_id) {
this.db.run('INSERT OR IGNORE INTO file_links (file_id, budget_item_id) VALUES (?, ?)', id, updates.budget_item_id);
} else {
this.db.run('DELETE FROM file_links WHERE file_id = ? AND budget_item_id IS NOT NULL', id);
}
}
const updated = this.db.get<TripFile>(`${FILE_SELECT} WHERE f.id = ?`, id)!;
return formatFile(updated);
}
@@ -355,10 +372,10 @@ export class FilesService {
// of returning a success-shaped links list (the legacy catch swallowed it).
createFileLink(
fileId: string | number,
opts: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null }
opts: { reservation_id?: string | number | null; assignment_id?: string | number | null; place_id?: string | number | null; budget_item_id?: string | number | null }
) {
this.db.run('INSERT OR IGNORE INTO file_links (file_id, reservation_id, assignment_id, place_id) VALUES (?, ?, ?, ?)',
fileId, opts.reservation_id || null, opts.assignment_id || null, opts.place_id || null
this.db.run('INSERT OR IGNORE INTO file_links (file_id, reservation_id, assignment_id, place_id, budget_item_id) VALUES (?, ?, ?, ?, ?)',
fileId, opts.reservation_id || null, opts.assignment_id || null, opts.place_id || null, opts.budget_item_id || null
);
return this.db.all('SELECT * FROM file_links WHERE file_id = ?', fileId);
}
+10
View File
@@ -127,6 +127,15 @@ export interface PackingItem {
created_at?: string;
}
export interface BudgetItemReceipt {
id: number;
filename: string;
original_name: string;
file_size?: number | null;
mime_type?: string | null;
url: string;
}
export interface BudgetItem {
id: number;
trip_id: number;
@@ -150,6 +159,7 @@ export interface BudgetItem {
created_at?: string;
members?: BudgetItemMember[];
payers?: BudgetItemPayer[];
receipts?: BudgetItemReceipt[];
}
export interface BudgetItemMember {