mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 10:24:05 +00:00
feat(places): link an expense to a place, the way bookings already do (#1917)
* feat(places): link an expense to a place, the way bookings already do Recording what a museum ticket or a guided tour cost meant leaving the place, opening the Costs tab and typing it in again — while a booking has had a Costs block in its own form all along. The place form now carries that block. Same component, same flow: with nothing linked it offers Create expense, which saves the place and then opens the Costs editor for a new expense pointing at it; once linked it shows the expense with edit and remove. budget_items gains place_id beside the reservation_id it already had, with the same nullable FK and the same ON DELETE SET NULL. Desktop and phone both, and the mobile editor carries the link through its own save path rather than the desktop one. The expense belongs to the place, not to a day assignment, so a place sitting on five days is not five tickets. Hanging it off the assignment would have meant adding a place to three days quietly creating three expenses and removing a day quietly deleting one. Deleting a place takes its expense with it in the same transaction and announces it, on every path that deletes a place: REST, both MCP tools and the plugin RPC. Closes #1298 * test(places): teach the RPC stubs about linkedExpenseIds The delete paths read the linked expense before the place is gone, so the two hand-built PlacesService stubs threw on the new method instead of reaching the hook, the remove and the broadcast — four failures out of one missing line.
This commit is contained in:
@@ -3879,6 +3879,18 @@ function runMigrations(db: Database.Database): void {
|
||||
if (!err.message?.includes('duplicate column name')) throw err;
|
||||
}
|
||||
},
|
||||
// #1298 — an expense can hang off a place, exactly as it already hangs off a
|
||||
// reservation. Same nullable FK, same ON DELETE SET NULL: the delete paths
|
||||
// take the linked expense with the place themselves, so the constraint is a
|
||||
// backstop for anything that removes a place without going through them.
|
||||
// Appended LAST: the array is index-addressed against schema_version, so a
|
||||
// slot inserted above this line never runs on an existing database.
|
||||
() => {
|
||||
const cols = db.prepare("SELECT name FROM pragma_table_info('budget_items')").all() as Array<{ name: string }>;
|
||||
if (!cols.some(c => c.name === 'place_id')) {
|
||||
db.exec('ALTER TABLE budget_items ADD COLUMN place_id INTEGER REFERENCES places(id) ON DELETE SET NULL DEFAULT NULL');
|
||||
}
|
||||
},
|
||||
];
|
||||
|
||||
if (currentVersion < migrations.length) {
|
||||
|
||||
@@ -301,6 +301,7 @@ export class BudgetService {
|
||||
persons?: number | null; days?: number | null; note?: string | null; expense_date?: string | null;
|
||||
ticket_json?: string | null;
|
||||
reservation_id?: number | null;
|
||||
place_id?: number | null;
|
||||
},
|
||||
) {
|
||||
return this.db.transaction(() => {
|
||||
@@ -330,7 +331,7 @@ export class BudgetService {
|
||||
const { note, ticket } = splitLegacyTicketNote(data.note, data.ticket_json);
|
||||
|
||||
const result = this.db.run(
|
||||
'INSERT INTO budget_items (trip_id, category, name, total_price, currency, exchange_rate, persons, days, note, ticket_json, sort_order, expense_date, reservation_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
'INSERT INTO budget_items (trip_id, category, name, total_price, currency, exchange_rate, persons, days, note, ticket_json, sort_order, expense_date, reservation_id, place_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
tripId,
|
||||
cat,
|
||||
data.name,
|
||||
@@ -344,6 +345,7 @@ export class BudgetService {
|
||||
sortOrder,
|
||||
data.expense_date || null,
|
||||
data.reservation_id != null ? data.reservation_id : null,
|
||||
data.place_id != null ? data.place_id : null,
|
||||
);
|
||||
|
||||
const itemId = result.lastInsertRowid as number;
|
||||
|
||||
@@ -287,11 +287,17 @@ export class PlacesController {
|
||||
// journey entries even though removeMany below refuses it. Still ahead of
|
||||
// the DELETE — journey_entries.source_place_id is ON DELETE SET NULL, so
|
||||
// afterwards there is nothing left to detach.
|
||||
for (const id of this.places.scopedIds(tripId, ids)) this.places.onDeleted(id);
|
||||
const scoped = this.places.scopedIds(tripId, ids);
|
||||
for (const id of scoped) this.places.onDeleted(id);
|
||||
// Read the linked expenses before the delete — afterwards the link is gone (#1298).
|
||||
const expenseIds = this.places.linkedExpenseIds(tripId, scoped);
|
||||
const deleted = this.places.removeMany(tripId, ids);
|
||||
for (const id of deleted) {
|
||||
this.places.broadcast(tripId, 'place:deleted', { placeId: id }, socketId);
|
||||
}
|
||||
for (const itemId of expenseIds) {
|
||||
this.places.broadcast(tripId, 'budget:deleted', { itemId }, socketId);
|
||||
}
|
||||
return { deleted, count: deleted.length };
|
||||
}
|
||||
|
||||
@@ -448,10 +454,14 @@ export class PlacesController {
|
||||
throw new HttpException({ error: 'Place not found' }, 404);
|
||||
}
|
||||
this.places.onDeleted(Number(id));
|
||||
const expenseIds = this.places.linkedExpenseIds(tripId, [id]);
|
||||
if (!this.places.remove(tripId, id)) {
|
||||
throw new HttpException({ error: 'Place not found' }, 404);
|
||||
}
|
||||
this.places.broadcast(tripId, 'place:deleted', { placeId: Number(id) }, socketId);
|
||||
for (const itemId of expenseIds) {
|
||||
this.places.broadcast(tripId, 'budget:deleted', { itemId }, socketId);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,9 +232,12 @@ export class PlacesMcp {
|
||||
return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
|
||||
}
|
||||
try { this.journey.onPlaceDeleted(placeId); } catch { /* non-fatal */ } // sync journeys before the row is gone
|
||||
// The link is gone once the place is, so read it first (#1298).
|
||||
const expenseIds = this.places.linkedExpenseIds(tripId, [placeId]);
|
||||
const deleted = this.places.remove(String(tripId), String(placeId));
|
||||
if (!deleted) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
|
||||
this.guards.safeBroadcast(tripId, 'place:deleted', { placeId });
|
||||
for (const itemId of expenseIds) this.guards.safeBroadcast(tripId, 'budget:deleted', { itemId });
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@@ -337,11 +340,15 @@ export class PlacesMcp {
|
||||
// Trip-scoped, and ahead of the DELETE: journey_entries.source_place_id is
|
||||
// ON DELETE SET NULL, so a hook that ran afterwards found nothing left to
|
||||
// detach and left the entries as orphans.
|
||||
for (const id of this.places.scopedIds(String(tripId), placeIds)) {
|
||||
const scoped = this.places.scopedIds(String(tripId), placeIds);
|
||||
for (const id of scoped) {
|
||||
try { this.journey.onPlaceDeleted(id); } catch { /* non-fatal */ }
|
||||
}
|
||||
// The link is gone once the places are, so read it first (#1298).
|
||||
const expenseIds = this.places.linkedExpenseIds(tripId, scoped);
|
||||
const deleted = this.places.removeMany(String(tripId), placeIds);
|
||||
for (const id of deleted) this.guards.safeBroadcast(tripId, 'place:deleted', { placeId: id });
|
||||
for (const itemId of expenseIds) this.guards.safeBroadcast(tripId, 'budget:deleted', { itemId });
|
||||
return ok({ deleted, count: deleted.length });
|
||||
}
|
||||
|
||||
|
||||
@@ -80,10 +80,13 @@ export class PlacesRpc {
|
||||
// journey_entries.source_place_id is ON DELETE SET NULL, so afterwards the hook
|
||||
// finds nothing left to detach and the entries linger as orphans.
|
||||
this.mirrorJourneys(() => this.journey.onPlaceDeleted(placeId));
|
||||
// The link is gone once the place is, so read it first (#1298).
|
||||
const expenseIds = this.places.linkedExpenseIds(tripId, [placeId]);
|
||||
if (!this.places.remove(String(tripId), String(placeId))) {
|
||||
throw new ForbiddenResource(`no place ${placeId} on trip ${tripId}`);
|
||||
}
|
||||
this.realtime.broadcast(tripId, 'place:deleted', { placeId });
|
||||
for (const itemId of expenseIds) this.realtime.broadcast(tripId, 'budget:deleted', { itemId });
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
|
||||
@@ -343,12 +343,32 @@ export class PlacesService {
|
||||
// Delete place
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* The expenses hanging off these places (#1298), so a caller can broadcast the
|
||||
* budget:deleted events for the rows remove()/removeMany() are about to take
|
||||
* with them. Read it BEFORE deleting — afterwards the link is gone.
|
||||
*/
|
||||
linkedExpenseIds(tripId: string | number, placeIds: Array<string | number>): number[] {
|
||||
if (placeIds.length === 0) return [];
|
||||
const rows = this.dbs.all<{ id: number }>(
|
||||
`SELECT id FROM budget_items WHERE trip_id = ? AND place_id IN (${placeIds.map(() => '?').join(',')})`,
|
||||
tripId, ...placeIds,
|
||||
);
|
||||
return rows.map(r => r.id);
|
||||
}
|
||||
|
||||
remove(tripId: string, placeId: string): boolean {
|
||||
const place = this.dbs.get<{ google_place_id: string | null; image_url: string | null }>(
|
||||
'SELECT google_place_id, image_url FROM places WHERE id = ? AND trip_id = ?', placeId, tripId,
|
||||
);
|
||||
if (!place) return false;
|
||||
this.dbs.run('DELETE FROM places WHERE id = ?', placeId);
|
||||
// The linked expense goes with the place, the same way a booking takes its
|
||||
// expense with it (#1298). One transaction, so a place can never survive
|
||||
// half-detached from its money.
|
||||
this.dbs.transaction(() => {
|
||||
this.dbs.run('DELETE FROM budget_items WHERE trip_id = ? AND place_id = ?', tripId, placeId);
|
||||
this.dbs.run('DELETE FROM places WHERE id = ?', placeId);
|
||||
});
|
||||
reclaimPhotoCache(this.photoCache, place.google_place_id, place.image_url);
|
||||
reclaimPlaceImage(place.image_url);
|
||||
return true;
|
||||
@@ -358,12 +378,14 @@ export class PlacesService {
|
||||
if (ids.length === 0) return [];
|
||||
const selectStmt = this.dbs.prepare('SELECT google_place_id, image_url FROM places WHERE id = ? AND trip_id = ?');
|
||||
const deleteStmt = this.dbs.prepare('DELETE FROM places WHERE id = ?');
|
||||
const deleteExpenseStmt = this.dbs.prepare('DELETE FROM budget_items WHERE trip_id = ? AND place_id = ?');
|
||||
const deleted: number[] = [];
|
||||
const reclaimable: { google_place_id: string | null; image_url: string | null }[] = [];
|
||||
this.dbs.transaction(() => {
|
||||
for (const id of ids) {
|
||||
const row = selectStmt.get(id, tripId) as { google_place_id: string | null; image_url: string | null } | undefined;
|
||||
if (!row) continue;
|
||||
deleteExpenseStmt.run(tripId, id);
|
||||
deleteStmt.run(id);
|
||||
deleted.push(id);
|
||||
reclaimable.push(row);
|
||||
|
||||
@@ -139,6 +139,9 @@ export interface BudgetItem {
|
||||
/** Itemized receipt for a per-item split, as JSON. Its own column since #1658. */
|
||||
ticket_json?: string | null;
|
||||
reservation_id?: number | null;
|
||||
/** Set when the expense was created from a place (#1298) — the other side of
|
||||
* the same link reservation_id is for a booking. */
|
||||
place_id?: number | null;
|
||||
paid_by_user_id?: number | null;
|
||||
expense_date?: string | null;
|
||||
sort_order: number;
|
||||
|
||||
Reference in New Issue
Block a user