mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 10:44:23 +00:00
fix: eleven reported bugs across atlas, budget, collections, journey, vacay and the LLM settings (#1923)
* fix(mcp): accept per-leg times on create_transport and update_transport metadata was pinned to Record<string, string>, so a legs array could not get through and a multi-leg flight built over MCP lost every intermediate time. The booking ended up with correct endpoints and no legs, which every reader then treats as a single segment. legs is now a real, typed parameter with its contract in @trek/shared, shaped exactly the way the planner form and the importers write metadata.legs. The folding checks what the readers depend on: one leg fewer than endpoints (the AirTrail dedupe builds its signatures on that), day ids that belong to the trip, airport codes that agree with their endpoint, and the times, where a stopover endpoint carries the departure and the last one the arrival. metadata keeps its type and its replace semantics. Segments smuggled through metadata.legs as a JSON string used to be stored and then ignored by everything that read them; they are refused now and point at the legs parameter instead. Closes #1914 * fix(atlas): refuse a bucket list entry that is already on the list Nothing gave a bucket entry an identity, so the same country could be added as often as it was clicked. A wish is now identified by name, country, target date and, where it has them, coordinates. A different target date is a different wish and still lands, which is what the report asked for; two real places sharing a name stay separate because their coordinates differ. Empty string and NULL are normalised on both sides of the comparison, otherwise the dateless case, which is the one that was reported, would slip through. Deliberately no unique index and no migration. better-sqlite3 is synchronous and the server is a single process, so the race an index would guard against cannot happen here, and an index would have needed a destructive dedupe of existing rows first. create_bucket_list_item had no target_date parameter at all, so over MCP the allowed "same place, other date" case was unreachable. It takes one now. The plugin RPC reports the duplicate as bad params instead of letting it surface as an internal error. Closes #1898 * fix(settings): keep a free-form LLM endpoint in admin hands Any account could name the address the server calls, and the guard in front of it deliberately allows loopback and LAN so a self-hosted Ollama works. That is a reasonable trade for whoever runs the instance, because the network is theirs. It is not one for an arbitrary account, which could aim a request from inside that network at a target only it chose and read how the target answered. A free base URL, and the local provider that is one by another name, now come only from an admin controlled source: the addon config, the instance-wide defaults, or an admin's own settings. OpenAI and Anthropic stay available to everyone, because they go to a fixed address with the user's own key. The resolver is where this is enforced, since it is the single point both the booking import and the plugin host pass through, and the only one that also covers values already sitting in the database. The write path refuses as well, so nothing is stored that would never be read. The hint text promised something users no longer have, so it changed with it. Closes #1772 * fix(calendar): span a date-only booking to its end date A DATE event without DTEND is exactly one day per RFC 5545, so a multi-day booking that carries an end date still collapsed onto its first day. It gets an exclusive DTEND now, built the same way the stay branch already builds one. A booking without an end date serialises byte for byte as before. While in here: the stays query joins reservations on the accommodation, and two bookings pointed at the same stay fanned it out into two events sharing one UID. Duplicate UIDs in a feed are undefined behaviour and calendar clients pick one at random. The same "at most one booking per stay" assumption sat in the accommodations service, where it was worse than cosmetic: accommodation_id carries no foreign key, so deleting a stay took only the first booking and left the second pointing at something that no longer existed. Both the sync and the delete walk all of them now. The callers keep reading linkedReservationId; the list is additional. Refs #1869 * fix(vacay): say that the region is required, because it is The placeholder called the region optional while the add button stayed disabled until one was picked. The wording predates multiple calendars per plan, which is what introduced the gate. Only the value of the existing key changed, in all locales, so the key set stays identical. Two things the same screen got wrong were in the way of a clean answer: The button was clickable while the region list was still loading, which put the user in exactly the state the wording describes, and it is the state the report was filed from. It waits for the list now. Changing the country on an existing calendar kept the previous country's regions on screen, so a German region could be picked for the Netherlands. The list is cleared with the country, which only works in combination with the loading gate: without it, the empty list would happen to enable the button instead. Closes #1813 * fix(collections): let a saved place's address be corrected The edit form offered name, category and labels, and the address only on the way in. The cause was not the form: the update contract never declared address, so the validation pipe stripped it and the UPDATE had no column for it. Coordinates were pulled through for #1435 and the address was missed. It travels the whole chain now, contract to service to both forms. No migration, the column has always been there. The mobile add sheet had no address input at all, showing whatever the search result carried as read-only, so editing would have worked while creating still would not. It has one. The MCP tool description had drifted further than the address, never having mentioned the coordinates either. Both are in it now. Closes #1870 * fix(collections): keep the place search usable after the first save The add dialog stays open on purpose so several places can be added in a row, but after a save it gave no way back into the search. A search with no results was silent, with no empty state and no toast, so typing another name and pressing enter looked like nothing happened. The reporter described both halves and it is the silent search that matches "nothing happens" most closely. There is an empty state now, using a key that already existed in every locale and was unused. The search row is sticky inside the dialog body, so it stays reachable after the save instead of sitting above the scroll position. Also fixed while in here: refreshing the collection after each add reset the select mode, the selection and the label filter. In the very flow this dialog is built for, the user quietly lost all three. Closes #1921 * fix(vacay): make the phone year grid and the dock button do what they look like Two separate faults met on this screen. Tapping a day in the year grid did nothing unless the edit mode was already on, and the only way into it was a floating button that looks exactly like the one the dock draws in the same spot. A tap now opens that month in the editor, where the cells are big enough to hit. At 390px the grid cells are around 21px, which is too small to be mutating data with in the first place. The dock's plus was not wired for this route, so it fell through to creating a trip on the dashboard. Two different actions were stacked in one place, and the wrong one was on top whenever the screen had not painted yet, which includes the time its chunk is still loading. The dock leaves the slot to the screen now, and holds the geometry so the tab groups stay symmetric. Closes #1811 * fix(budget): settle in whole cents so balances stop drifting The report is a balance that moves on its own, with nothing added, edited or removed, on a trip where everything is in euro. Two mechanisms were behind it and both are real. The display currency is a fourth value, a per-user setting, so "everything is in euro" never covered it. Each balance was converted and rounded on its own, and the set no longer summed to zero: at 0.855 and 0.9312 it came out one cent over, at 0.94 it came out even. That cent appears and disappears with the six hour rate cache alone, which is exactly the symptom. The flows were rounded separately from the balances, so the two never had to agree. And a receipt line nobody was ticked for counted toward the total, and therefore toward the payer's credit, while landing in no share. That difference is permanent, and the client sent it that way. The settlement converts once, at the edge, and does integer arithmetic after that. Equal splits distribute the credited cents by largest remainder rather than the entered total, so credits and debits of one expense cancel exactly even in a foreign currency. Display conversion goes through the same largest-remainder allocation, so the sum survives it. With that, the 0.01 epsilon can go. It could never create a cent, but it stranded them: a one cent balance was filtered out of the flows while staying visible in the list, which is the "settle up offers nothing" half of the report. Closes #1382 * fix(journey): reach the book export and the suggestion toggle on a phone Below 1024px the hero card is dropped, and it held the only way to either action. The floating bar that replaces it was never given them. It has them now, and the hero is unmounted rather than hidden, so there is no second invisible copy of the same controls in the document. The bar's own buttons moved onto the appearance tokens while they were being touched. The phone screen never had either action at all and now carries both. The book itself was hardwired to English, cover and dates included, while the keys for it had been sitting in every locale unused. It takes the page's translator and locale, sets the document language, and prints mood and weather, which were on screen but never in the book. Closes #1848 * fix(journey): offer the connected photo providers in the phone entry editor The desktop editor grew an external photo source in #1632; the phone editor that came out of the mobile rewrite never did, so editing an entry on a phone had no way to Immich or Synology. It mirrors the desktop mechanics, including the part that is easy to miss: a save that creates the entry and then fails on the photos keeps the sheet open, and without remembering what was just created the retry creates a second entry. The sheet no longer kicks off its own addon load. The list is loaded once on boot and this only reacts to it; a second load races the other consumers and overwrites the store when it lands. Closes #1808 * fix(mobile): let the document scroll so Safari can collapse its URL bar iOS Safari only shrinks its address bar when the document scrolls, and TREK's never did: the root was locked and the mobile shell put a scroll container inside it. On the bottom tab layout that costs about a sixth of the viewport, permanently. Below 768px the document is the scroller again and the full-bleed screens measure their own height instead of leaning on the shell. That makes the body scroll locks real for the first time on a phone, and they were not ready for it. Three of them reset the overflow unconditionally, one of those on every run of its effect rather than on unmount, so a system notice could hand the page back while a sheet was still open. They all go through one reference counted lock now, which is the part that had to land first. Worth knowing for the issue: this reaches the flow screens. The trip planner, the journal, the atlas and the vacay screen keep their own full-height scrollers and still will not collapse the bar. Closes #1809 * fix(mobile): keep the screen gradient visible behind the translucent cards The gradient layer introduced with the scroll change sat at z-index -10. A negative layer paints above the canvas but below the backgrounds of ordinary blocks, and body carries an opaque one, so the gradient was hidden behind it. The mobile cards are translucent and take their depth from what is behind them, so every surface ended up compositing against a single flat colour and the whole phone UI read as one tone. The layer is positioned at z-index 0 now and the content above it at 10, which puts both over body's background. Same visual as before the scroll change, and the shell still owns no scroll container. * test(reservations): teach the accommodation delete stub about the id lists The RPC walks every linked booking since the delete stopped stopping at the first one. The stub still answered with the two singular fields, so the loop had nothing to iterate and the cascade events never fired. * fix(settings): move the free-form LLM endpoint out of user settings entirely Hiding it from non-admins closed the hole, but it left the option sitting in the admin's own personal settings, which is not what was asked for and not where it belongs: an instance has exactly one address it calls out to, and there was a second, invisible place to set it. The provider list is now the two hosted ones for everybody, the endpoint field is gone, and the resolver takes the address from the admin-controlled instance defaults for every caller including an admin. It no longer reads the users table at all. The write path refuses the keys for everyone, so nothing can be stored that would never be read. The endpoint is configured on the addon in the admin settings, which already carries provider, model, base URL and key, plus the Ollama model list. Nothing is lost, it just has one home now. Behaviour change worth a release note: an admin who set a personal Ollama endpoint has to move it to the addon config. A non-admin was already in that position after the previous commit. Refs #1772 * fix(journey): make the book preview usable on a phone The preview document carried no viewport, so a phone laid it out at its default 980px while the page is A4 landscape and about 1123px wide. It spilled out of the frame, which reads as being zoomed far in. Declaring the real width lets the browser scale the page to fit. Printing is unaffected, it goes by @page. The preview chrome had the same problem in miniature: a title and two labels on one row, sized inline, which does not fit a phone and fits translated labels even less. It moved to a stylesheet, and below 640px the card goes full-bleed, the decorative title steps aside and the two actions share the width. Refs #1848 * fix(mobile): stop the shell trapping the screens' own overlays Lifting the background layer into the positioned range meant the content wrapper had to be positioned too, and a positioned wrapper with a z-index is a stacking context. Every fixed overlay a screen renders inside it got clamped to that level: the vacay view/edit FAB sits at z-50 precisely so it beats the dock at z-40, and it disappeared behind it. The layer goes back to a negative z-index and the wrapper back to no positioning at all. What it needed in the first place was for body to stop painting over it, which is one line in the phone media block rather than a new stacking context. * fix(mobile): let the phone background override actually win A media query adds no specificity, so the themed body rule further down the file kept winning on source order and painted over the shell's background layer. The override is on html body now. The gradient was back to being invisible, which is the flat single-tone phone UI again. * fix(vacay): draw today's ring around the day instead of replacing it On the phone, today short-circuited the day-cell matrix and returned a ring on an empty cell. A vacation day or a company holiday logged for today was stored and counted in the totals, but the cell showed nothing, so it read as if the tap had not taken. Today is an annotation now, layered like the school band and the shared-calendar rings, which is how the desktop month card has always treated it. The strong ink stays only where the cell has no fill of its own, since --m-ink is light in dark mode and would disappear on a pastel. * fix(map): stop serving a stale GL style document from the service worker The Workbox rule for Mapbox matched every URL under api.mapbox.com, and the style document lives there too. Under StaleWhileRevalidate the map was built from the previous revision on every load, with the refresh landing one load too late, so a style republished in Studio with different label languages kept rendering the old ones. The network tab showed a 200 throughout, because the service worker's own answer is a real 200, which is why this looked like the app rewriting text-field at runtime. The style now has its own rule ahead of the tile rules, on NetworkFirst so it is current whenever the network is, and still cached so the map opens offline. Its own small cache too: sharing an LRU with three thousand tiles made the staleness come and go at random. OpenFreeMap styles had the same problem and are covered by the same rule. Closes #1924
This commit is contained in:
@@ -111,12 +111,12 @@ export class AccommodationsController {
|
||||
if (!this.accommodations.get(id, tripId)) {
|
||||
throw new HttpException({ error: 'Accommodation not found' }, 404);
|
||||
}
|
||||
const { linkedReservationId, deletedBudgetItemId } = this.accommodations.remove(id);
|
||||
if (linkedReservationId) {
|
||||
this.accommodations.broadcast(tripId, 'reservation:deleted', { reservationId: linkedReservationId }, socketId);
|
||||
const { linkedReservationIds, deletedBudgetItemIds } = this.accommodations.remove(id);
|
||||
for (const reservationId of linkedReservationIds) {
|
||||
this.accommodations.broadcast(tripId, 'reservation:deleted', { reservationId }, socketId);
|
||||
}
|
||||
if (deletedBudgetItemId) {
|
||||
this.accommodations.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId }, socketId);
|
||||
for (const itemId of deletedBudgetItemIds) {
|
||||
this.accommodations.broadcast(tripId, 'budget:deleted', { itemId }, socketId);
|
||||
}
|
||||
this.accommodations.broadcast(tripId, 'accommodation:deleted', { accommodationId: Number(id) }, socketId);
|
||||
return { success: true };
|
||||
|
||||
@@ -179,9 +179,11 @@ export class AccommodationsMcp {
|
||||
if (!this.accommodations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('day_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
if (!this.accommodations.getAccommodation(accommodationId, tripId)) return { content: [{ type: 'text' as const, text: 'Accommodation not found.' }], isError: true };
|
||||
const { linkedReservationId } = this.accommodations.deleteAccommodation(accommodationId);
|
||||
this.guards.safeBroadcast(tripId, 'accommodation:deleted', { id: accommodationId, linkedReservationId });
|
||||
return ok({ success: true, linkedReservationId });
|
||||
// linkedReservationId stays the first one so the tool's answer keeps its shape;
|
||||
// linkedReservationIds carries the rest for a block that had more than one booking.
|
||||
const { linkedReservationId, linkedReservationIds } = this.accommodations.deleteAccommodation(accommodationId);
|
||||
this.guards.safeBroadcast(tripId, 'accommodation:deleted', { id: accommodationId, linkedReservationId, linkedReservationIds });
|
||||
return ok({ success: true, linkedReservationId, linkedReservationIds });
|
||||
}
|
||||
|
||||
@ResourceTemplate({
|
||||
|
||||
@@ -99,9 +99,9 @@ export class AccommodationsRpc {
|
||||
throw new ForbiddenResource(`no accommodation ${accommodationId} on trip ${tripId}`);
|
||||
}
|
||||
// Deleting a block can take its partner reservation and budget item with it.
|
||||
const { linkedReservationId, deletedBudgetItemId } = this.days.deleteAccommodation(accommodationId);
|
||||
if (linkedReservationId) this.realtime.broadcast(tripId, 'reservation:deleted', { reservationId: linkedReservationId });
|
||||
if (deletedBudgetItemId) this.realtime.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId });
|
||||
const { linkedReservationIds, deletedBudgetItemIds } = this.days.deleteAccommodation(accommodationId);
|
||||
for (const reservationId of linkedReservationIds) this.realtime.broadcast(tripId, 'reservation:deleted', { reservationId });
|
||||
for (const itemId of deletedBudgetItemIds) this.realtime.broadcast(tripId, 'budget:deleted', { itemId });
|
||||
this.realtime.broadcast(tripId, 'accommodation:deleted', { accommodationId });
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
@@ -198,36 +198,59 @@ export class AccommodationsService {
|
||||
newPlaceId, newStartDayId, newEndDayId, newCheckIn, newCheckInEnd, newCheckOut, newConfirmation, newNotes, id
|
||||
);
|
||||
|
||||
// Sync check-in/out/confirmation to linked reservation
|
||||
const linkedRes = this.db.get<{ id: number; metadata: string | null }>('SELECT id, metadata FROM reservations WHERE accommodation_id = ?', Number(id));
|
||||
if (linkedRes) {
|
||||
const meta = linkedRes.metadata ? JSON.parse(linkedRes.metadata) : {};
|
||||
// Sync check-in/out/confirmation to every linked reservation. The booking form
|
||||
// lets more than one hotel booking point at the same block and there is no
|
||||
// unique constraint on reservations.accommodation_id, so a single .get() would
|
||||
// silently leave the others on the old times.
|
||||
const linkedRes = this.db.all<{ id: number; metadata: string | null }>('SELECT id, metadata FROM reservations WHERE accommodation_id = ?', Number(id));
|
||||
for (const res of linkedRes) {
|
||||
const meta = res.metadata ? JSON.parse(res.metadata) : {};
|
||||
if (newCheckIn) meta.check_in_time = newCheckIn;
|
||||
if (newCheckInEnd) meta.check_in_end_time = newCheckInEnd;
|
||||
if (newCheckOut) meta.check_out_time = newCheckOut;
|
||||
this.db.run('UPDATE reservations SET metadata = ?, confirmation_number = COALESCE(?, confirmation_number) WHERE id = ?',
|
||||
JSON.stringify(meta), newConfirmation || null, linkedRes.id);
|
||||
JSON.stringify(meta), newConfirmation || null, res.id);
|
||||
}
|
||||
|
||||
return this.getAccommodationWithPlace(Number(id));
|
||||
}
|
||||
|
||||
/** Delete accommodation and its linked reservation (and any linked budget item), atomically. */
|
||||
deleteAccommodation(id: string | number): { linkedReservationId: number | null; deletedBudgetItemId: number | null } {
|
||||
/**
|
||||
* Delete accommodation and its linked reservations (and any linked budget items),
|
||||
* atomically.
|
||||
*
|
||||
* Takes ALL linked reservations, not just the first: reservations.accommodation_id
|
||||
* carries no foreign key and no unique constraint, so a second booking pointed at
|
||||
* the same block used to survive the delete as a row referencing an accommodation
|
||||
* that no longer exists. `linkedReservationId` / `deletedBudgetItemId` stay on the
|
||||
* result as the first of each, because the RPC, MCP and REST callers read them.
|
||||
*/
|
||||
deleteAccommodation(id: string | number): {
|
||||
linkedReservationId: number | null;
|
||||
deletedBudgetItemId: number | null;
|
||||
linkedReservationIds: number[];
|
||||
deletedBudgetItemIds: number[];
|
||||
} {
|
||||
return this.db.transaction(() => {
|
||||
const linkedRes = this.db.get<{ id: number }>('SELECT id FROM reservations WHERE accommodation_id = ?', Number(id));
|
||||
let deletedBudgetItemId: number | null = null;
|
||||
if (linkedRes) {
|
||||
const linkedBudget = this.db.get<{ id: number }>('SELECT id FROM budget_items WHERE reservation_id = ?', linkedRes.id);
|
||||
const linkedRes = this.db.all<{ id: number }>('SELECT id FROM reservations WHERE accommodation_id = ?', Number(id));
|
||||
const deletedBudgetItemIds: number[] = [];
|
||||
for (const res of linkedRes) {
|
||||
const linkedBudget = this.db.get<{ id: number }>('SELECT id FROM budget_items WHERE reservation_id = ?', res.id);
|
||||
if (linkedBudget) {
|
||||
this.db.run('DELETE FROM budget_items WHERE id = ?', linkedBudget.id);
|
||||
deletedBudgetItemId = linkedBudget.id;
|
||||
deletedBudgetItemIds.push(linkedBudget.id);
|
||||
}
|
||||
this.db.run('DELETE FROM reservations WHERE id = ?', linkedRes.id);
|
||||
this.db.run('DELETE FROM reservations WHERE id = ?', res.id);
|
||||
}
|
||||
|
||||
this.db.run('DELETE FROM day_accommodations WHERE id = ?', id);
|
||||
return { linkedReservationId: linkedRes ? linkedRes.id : null, deletedBudgetItemId };
|
||||
const linkedReservationIds = linkedRes.map(r => r.id);
|
||||
return {
|
||||
linkedReservationId: linkedReservationIds[0] ?? null,
|
||||
deletedBudgetItemId: deletedBudgetItemIds[0] ?? null,
|
||||
linkedReservationIds,
|
||||
deletedBudgetItemIds,
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
import type { Response } from 'express';
|
||||
import type { AtlasLocateResponse, RegionGeo } from '@trek/shared';
|
||||
import type { User } from '../../types';
|
||||
import { AtlasService } from './atlas.service';
|
||||
import { AtlasService, BucketItemExistsError } from './atlas.service';
|
||||
import { AtlasMarkRegionDto, AtlasCreateBucketItemDto, AtlasUpdateBucketItemDto } from './atlas.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { CurrentUser } from '../auth/current-user.decorator';
|
||||
@@ -33,7 +33,9 @@ import { CurrentUser } from '../auth/current-user.decorator';
|
||||
* hand-rolled 'name and country_code are required' — the todo/places trade);
|
||||
* the whitespace-only bucket name keeps its legacy 'Name is required' 400.
|
||||
* No addon gate — the legacy route has none, so adding one would break
|
||||
* clients when the addon is off.
|
||||
* clients when the addon is off. The one status the legacy route never sent is
|
||||
* the bucket-list 409: adding the same wish twice used to append a second row
|
||||
* (#1898).
|
||||
*/
|
||||
@Controller('api/addons/atlas')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@@ -151,7 +153,16 @@ export class AtlasController {
|
||||
throw new HttpException({ error: 'Name is required' }, 400);
|
||||
}
|
||||
const { name, lat, lng, country_code, notes, target_date } = body;
|
||||
return { item: this.atlas.createBucketItem(user.id, { name, lat, lng, country_code, notes, target_date }) };
|
||||
try {
|
||||
return { item: this.atlas.createBucketItem(user.id, { name, lat, lng, country_code, notes, target_date }) };
|
||||
} catch (err) {
|
||||
// #1898: the same wish twice is a conflict, not a server error. Bespoke
|
||||
// { error } body like the neighbouring 400/404s.
|
||||
if (err instanceof BucketItemExistsError) {
|
||||
throw new HttpException({ error: 'Already on your bucket list' }, 409);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@Put('bucket-list/:id')
|
||||
@@ -161,7 +172,17 @@ export class AtlasController {
|
||||
@Body() body: AtlasUpdateBucketItemDto,
|
||||
): { item: unknown } {
|
||||
const { name, notes, lat, lng, country_code, target_date } = body;
|
||||
const item = this.atlas.updateBucketItem(user.id, id, { name, notes, lat, lng, country_code, target_date });
|
||||
let item: unknown;
|
||||
try {
|
||||
item = this.atlas.updateBucketItem(user.id, id, { name, notes, lat, lng, country_code, target_date });
|
||||
} catch (err) {
|
||||
// #1898: editing a wish onto an existing one conflicts the same way a
|
||||
// duplicate create does.
|
||||
if (err instanceof BucketItemExistsError) {
|
||||
throw new HttpException({ error: 'Already on your bucket list' }, 409);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (!item) {
|
||||
throw new HttpException({ error: 'Item not found' }, 404);
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import {
|
||||
} from '@trek/nest-mcp';
|
||||
import { z } from 'zod';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AtlasService } from './atlas.service';
|
||||
import { AtlasService, BucketItemExistsError } from './atlas.service';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
@@ -16,6 +16,11 @@ import { AuthService } from '../auth/auth.service';
|
||||
* (see atlas.controller.ts). */
|
||||
const atlasAddonOn = addonGate(ADDON_IDS.ATLAS);
|
||||
|
||||
/** The MCP echo of the REST 409 (#1898) — same wording, tool-shaped. */
|
||||
function bucketDuplicateResult() {
|
||||
return { content: [{ type: 'text' as const, text: 'That is already on your bucket list.' }], isError: true };
|
||||
}
|
||||
|
||||
function jsonContent(uri: string, data: unknown) {
|
||||
return {
|
||||
contents: [{
|
||||
@@ -37,7 +42,8 @@ function jsonContent(uri: string, data: unknown) {
|
||||
* checks and no broadcasts; writes deny demo users, reads do not. The legacy
|
||||
* registrar's casing divergence from REST (mark_region_visited /
|
||||
* get_country_atlas_places passed codes through un-uppercased) was fixed in
|
||||
* the trailing quirk commit — both sides now uppercase.
|
||||
* the trailing quirk commit — both sides now uppercase. The one input schema
|
||||
* that grew since is create_bucket_list_item's target_date (#1898).
|
||||
*/
|
||||
@McpController()
|
||||
export class AtlasMcp {
|
||||
@@ -58,18 +64,28 @@ export class AtlasMcp {
|
||||
lng: z.number().optional(),
|
||||
country_code: z.string().length(2).toUpperCase().optional().describe('ISO 3166-1 alpha-2 country code'),
|
||||
notes: z.string().max(1000).optional(),
|
||||
// #1898 made the target date part of an item's identity, so without this
|
||||
// parameter MCP could only ever create one entry per destination — the
|
||||
// "same place, different date" case the report calls for was unreachable.
|
||||
// update_bucket_list_item has had the field all along.
|
||||
target_date: z.string().nullable().optional().describe('When you plan to go, e.g. "2027-05"'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
when: atlasAddonOn,
|
||||
access: { group: 'atlas', mode: 'write' },
|
||||
})
|
||||
async createBucketListItem(
|
||||
{ name, lat, lng, country_code, notes }: { name: string; lat?: number; lng?: number; country_code?: string; notes?: string },
|
||||
{ name, lat, lng, country_code, notes, target_date }: { name: string; lat?: number; lng?: number; country_code?: string; notes?: string; target_date?: string | null },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const item = this.atlas.createBucketItem(ctx.userId, { name, lat, lng, country_code, notes });
|
||||
return ok({ item });
|
||||
try {
|
||||
const item = this.atlas.createBucketItem(ctx.userId, { name, lat, lng, country_code, notes, target_date });
|
||||
return ok({ item });
|
||||
} catch (err) {
|
||||
if (err instanceof BucketItemExistsError) return bucketDuplicateResult();
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -244,7 +260,13 @@ export class AtlasMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const item = this.atlas.updateBucketItem(ctx.userId, itemId, { name, notes, lat, lng, country_code, target_date });
|
||||
let item: unknown;
|
||||
try {
|
||||
item = this.atlas.updateBucketItem(ctx.userId, itemId, { name, notes, lat, lng, country_code, target_date });
|
||||
} catch (err) {
|
||||
if (err instanceof BucketItemExistsError) return bucketDuplicateResult();
|
||||
throw err;
|
||||
}
|
||||
if (!item) return { content: [{ type: 'text' as const, text: 'Bucket list item not found.' }], isError: true };
|
||||
return ok({ item });
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors';
|
||||
import { asPayload, num } from '../plugins/host/rpc-params';
|
||||
import type { PluginRpcContext } from '../plugins/host/rpc-kit/types';
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AtlasService } from './atlas.service';
|
||||
import { AtlasService, BucketItemExistsError } from './atlas.service';
|
||||
|
||||
/**
|
||||
* The atlas surface a plugin may reach (#plugins): visited countries and regions plus
|
||||
@@ -86,7 +86,14 @@ export class AtlasRpc {
|
||||
const input = asPayload(params.input);
|
||||
if (typeof input.name !== 'string' || input.name.trim() === '') throw new BadParams('bucket item name is required');
|
||||
this.requireAtlasAddon();
|
||||
return this.atlas.createBucketItem(userId, input as never);
|
||||
try {
|
||||
return this.atlas.createBucketItem(userId, input as never);
|
||||
} catch (err) {
|
||||
// #1898: a repeated wish is the caller's mistake, not ours. Without this the
|
||||
// plugin sees a generic internal error and cannot tell the two apart.
|
||||
if (err instanceof BucketItemExistsError) throw new BadParams('bucket item already exists');
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
@PluginMethod('atlas.deleteBucketItem', { permission: 'db:write:atlas' })
|
||||
|
||||
@@ -34,6 +34,15 @@ export type UpdateBucketData = {
|
||||
target_date?: string | null;
|
||||
};
|
||||
|
||||
/** The columns that decide whether two bucket-list rows are the same wish (#1898). */
|
||||
type BucketIdentity = {
|
||||
name: string;
|
||||
lat: number | null;
|
||||
lng: number | null;
|
||||
country_code: string | null;
|
||||
target_date: string | null;
|
||||
};
|
||||
|
||||
// Bundled/geocoded region codes are always "<countryCode>-<rest>" (ISO 3166-2 format, and
|
||||
// buildRegionInfo's synthesized fallback follows the same convention) — used to recover a
|
||||
// region's country when there's no visited_regions row to read it from (a place-derived
|
||||
@@ -42,6 +51,26 @@ function countryCodeFromRegionCode(regionCode: string): string {
|
||||
return (regionCode.split('-')[0] || '').toUpperCase();
|
||||
}
|
||||
|
||||
/**
|
||||
* The same bucket-list wish, added twice (#1898). Deliberately a plain Error and
|
||||
* not an HttpException: the service is shared with the MCP tools and the plugin
|
||||
* RPC host, which shape their own errors — only atlas.controller.ts turns this
|
||||
* into the 409.
|
||||
*/
|
||||
export class BucketItemExistsError extends Error {
|
||||
constructor() {
|
||||
super('Already on your bucket list');
|
||||
this.name = 'BucketItemExistsError';
|
||||
}
|
||||
}
|
||||
|
||||
// An empty string and NULL are the same "not set" for a bucket item's country and
|
||||
// target date, so they must not produce two different identities (#1898) — the
|
||||
// bucket forms send '' where the map dialogs send null.
|
||||
function blankToNull(value: string | null | undefined): string | null {
|
||||
return value === undefined || value === null || value === '' ? null : value;
|
||||
}
|
||||
|
||||
/**
|
||||
* DI-native atlas domain service — the legacy services/atlasService SQL
|
||||
* (stats aggregation, visited countries/regions with the #1490 tombstones,
|
||||
@@ -742,26 +771,77 @@ export class AtlasService {
|
||||
return this.db.prepare('SELECT * FROM bucket_list WHERE user_id = ? ORDER BY created_at DESC').all(userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* What makes two bucket-list rows the same wish (#1898): the same user, the
|
||||
* same name (trimmed, case-insensitive) and the same country, target date and
|
||||
* coordinates. The coordinates are part of it so two genuinely different
|
||||
* places that share a name ("Altstadt") can sit side by side, and the target
|
||||
* date is part of it because one entry per planned date is exactly what the
|
||||
* report asks for. `IS` compares NULLs as equal, so "no coordinates" matches
|
||||
* "no coordinates" instead of the NULL-is-never-equal SQLite default.
|
||||
* `lower()` is ASCII-only in SQLite, which is what the client mirrors.
|
||||
*/
|
||||
private findDuplicateBucketItem(userId: number, key: BucketIdentity, excludeId?: number): { id: number } | undefined {
|
||||
return this.db
|
||||
.prepare(
|
||||
`SELECT id FROM bucket_list
|
||||
WHERE user_id = ?
|
||||
AND lower(trim(name)) = lower(trim(?))
|
||||
AND country_code IS ?
|
||||
AND target_date IS ?
|
||||
AND lat IS ?
|
||||
AND lng IS ?
|
||||
AND id IS NOT ?
|
||||
LIMIT 1`,
|
||||
)
|
||||
.get(userId, key.name, key.country_code, key.target_date, key.lat, key.lng, excludeId ?? null) as
|
||||
| { id: number }
|
||||
| undefined;
|
||||
}
|
||||
|
||||
createBucketItem(userId: number, data: CreateBucketData) {
|
||||
const identity: BucketIdentity = {
|
||||
name: data.name.trim(),
|
||||
lat: data.lat ?? null,
|
||||
lng: data.lng ?? null,
|
||||
country_code: blankToNull(data.country_code),
|
||||
target_date: blankToNull(data.target_date),
|
||||
};
|
||||
// #1898: the same wish must not stack up. A different target date (or a
|
||||
// different place under the same name) is a different wish and still lands.
|
||||
if (this.findDuplicateBucketItem(userId, identity)) throw new BucketItemExistsError();
|
||||
const result = this.db
|
||||
.prepare(
|
||||
'INSERT INTO bucket_list (user_id, name, lat, lng, country_code, notes, target_date) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
)
|
||||
.run(
|
||||
userId,
|
||||
data.name.trim(),
|
||||
data.lat ?? null,
|
||||
data.lng ?? null,
|
||||
data.country_code ?? null,
|
||||
identity.name,
|
||||
identity.lat,
|
||||
identity.lng,
|
||||
identity.country_code,
|
||||
data.notes ?? null,
|
||||
data.target_date ?? null,
|
||||
identity.target_date,
|
||||
);
|
||||
return this.db.prepare('SELECT * FROM bucket_list WHERE id = ?').get(result.lastInsertRowid);
|
||||
}
|
||||
|
||||
updateBucketItem(userId: number, itemId: string | number, data: UpdateBucketData) {
|
||||
const item = this.db.prepare('SELECT * FROM bucket_list WHERE id = ? AND user_id = ?').get(itemId, userId);
|
||||
const item = this.db.prepare('SELECT * FROM bucket_list WHERE id = ? AND user_id = ?').get(itemId, userId) as
|
||||
| (BucketIdentity & { id: number })
|
||||
| undefined;
|
||||
if (!item) return null;
|
||||
// #1898: an edit must not land on top of another wish either — same guard as
|
||||
// create, over the values the row will have once the UPDATE below ran. The
|
||||
// row itself is excluded, so re-saving it unchanged stays a no-op.
|
||||
const next: BucketIdentity = {
|
||||
name: data.name?.trim() || item.name,
|
||||
lat: data.lat !== undefined ? (data.lat ?? null) : item.lat,
|
||||
lng: data.lng !== undefined ? (data.lng ?? null) : item.lng,
|
||||
country_code: data.country_code !== undefined ? blankToNull(data.country_code) : blankToNull(item.country_code),
|
||||
target_date: data.target_date !== undefined ? blankToNull(data.target_date) : blankToNull(item.target_date),
|
||||
};
|
||||
if (this.findDuplicateBucketItem(userId, next, item.id)) throw new BucketItemExistsError();
|
||||
// Post-fold quirk fixes: the value bindings use `?? null` (the legacy
|
||||
// `|| null` wrote NULL for lat/lng 0 and empty-string notes), and the
|
||||
// UPDATE + re-select are user-scoped (defense-in-depth; the ownership
|
||||
@@ -787,9 +867,9 @@ export class AtlasService {
|
||||
data.lng !== undefined ? 1 : 0,
|
||||
data.lng !== undefined ? (data.lng ?? null) : null,
|
||||
data.country_code !== undefined ? 1 : 0,
|
||||
data.country_code !== undefined ? (data.country_code ?? null) : null,
|
||||
data.country_code !== undefined ? next.country_code : null,
|
||||
data.target_date !== undefined ? 1 : 0,
|
||||
data.target_date !== undefined ? (data.target_date ?? null) : null,
|
||||
data.target_date !== undefined ? next.target_date : null,
|
||||
itemId,
|
||||
userId,
|
||||
);
|
||||
|
||||
@@ -40,6 +40,30 @@ export function splitLegacyTicketNote(
|
||||
return { note, ticket };
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-denominate whole trip-currency cents into whole display-currency cents
|
||||
* without losing or inventing one (#1382).
|
||||
*
|
||||
* Rounding every balance on its own lets the rounded set drift away from the sum
|
||||
* it came from: a squared-up trip viewed in another currency then shows a cent
|
||||
* that no payment flow can ever clear, and the drift moves whenever the live rate
|
||||
* does — money appearing without a single expense being touched. Rounding down
|
||||
* and handing the leftover to the largest fractions keeps Σ(converted) equal to
|
||||
* converted(Σ). `factor === 1` (the display currency IS the trip currency, the
|
||||
* common case) is the identity and never touches a float.
|
||||
*/
|
||||
function allocateDisplayCents(cents: number[], factor: number): number[] {
|
||||
if (factor === 1) return [...cents];
|
||||
const exact = cents.map(c => c * factor);
|
||||
const out = exact.map(v => Math.floor(v));
|
||||
const drift = Math.round(cents.reduce((a, c) => a + c, 0) * factor) - out.reduce((a, v) => a + v, 0);
|
||||
const byFraction = exact
|
||||
.map((v, i) => ({ i, frac: v - Math.floor(v) }))
|
||||
.sort((a, b) => b.frac - a.frac || a.i - b.i);
|
||||
for (let k = 0; k < drift && k < byFraction.length; k++) out[byFraction[k].i] += 1;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Budget domain service — owns the budget SQL (moved from the legacy
|
||||
* services/budgetService.ts: identical statements, the `||` falsy-coercion
|
||||
@@ -590,13 +614,21 @@ export class BudgetService {
|
||||
return summary.map(s => ({ ...s, avatar_url: avatarUrl(s) }));
|
||||
}
|
||||
|
||||
private splitEqualShares(total: number, members: { user_id: number }[], itemId: number): Record<number, number> {
|
||||
/**
|
||||
* Largest-remainder split of an expense across its participants. Takes and
|
||||
* returns **whole cents**, so the shares add back up to the input exactly —
|
||||
* the settlement ledger is netted in integer cents (#1382).
|
||||
*
|
||||
* The remainder cent rotates with the item id rather than always landing on the
|
||||
* first member, so across several expenses the rounding evens out instead of
|
||||
* always favouring the same person.
|
||||
*/
|
||||
private splitEqualShares(totalCents: number, members: { user_id: number }[], itemId: number): Record<number, number> {
|
||||
const n = members.length;
|
||||
if (n === 0) return {};
|
||||
|
||||
const totalCents = Math.round(total * 100);
|
||||
const baseCents = Math.floor(totalCents / n);
|
||||
const remainder = totalCents % n;
|
||||
const remainder = totalCents - baseCents * n;
|
||||
|
||||
const shares: Record<number, number> = {};
|
||||
const sortedMembers = [...members].sort((a, b) => a.user_id - b.user_id);
|
||||
@@ -605,7 +637,7 @@ export class BudgetService {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const member = sortedMembers[i];
|
||||
const hasExtraCent = ((i - startIndex + n) % n) < remainder;
|
||||
shares[member.user_id] = (baseCents + (hasExtraCent ? 1 : 0)) / 100;
|
||||
shares[member.user_id] = baseCents + (hasExtraCent ? 1 : 0);
|
||||
}
|
||||
|
||||
return shares;
|
||||
@@ -640,8 +672,12 @@ export class BudgetService {
|
||||
return amount;
|
||||
};
|
||||
// trip-currency → display currency, applied once to the final netted totals.
|
||||
const toDisplay = (v: number): number =>
|
||||
base === tripCurrency ? v : (rates && rates[tripCurrency] > 0 ? v / rates[tripCurrency] : v);
|
||||
// Held as a plain factor so it is exactly linear: the balances are converted as
|
||||
// one set (allocateDisplayCents) rather than one at a time, which is what keeps
|
||||
// them adding up to zero in whatever currency the viewer picked (#1382).
|
||||
const displayFactor = base === tripCurrency
|
||||
? 1
|
||||
: (rates && rates[tripCurrency] > 0 ? 1 / rates[tripCurrency] : 1);
|
||||
// A recorded settle-up amount is entered in whatever display currency the payer
|
||||
// was viewing. New rows capture that currency and the rate frozen at settle time
|
||||
// (#1445), so a settled position stays balanced when live rates drift — mirroring
|
||||
@@ -678,12 +714,16 @@ export class BudgetService {
|
||||
WHERE bp.budget_item_id IN (SELECT id FROM budget_items WHERE trip_id = ?)
|
||||
`, tripId);
|
||||
|
||||
// Net balance per user, in the requested base currency: positive = is owed
|
||||
// money, negative = owes money. Each expense's amounts are converted from their
|
||||
// own currency to the base with live rates, so mixed-currency trips net correctly.
|
||||
const balances: Record<number, { user_id: number; username: string; avatar_url: string | null; balance: number }> = {};
|
||||
// Net balance per user, in whole cents of the TRIP currency: positive = is owed
|
||||
// money, negative = owes money. Every amount is converted out of its own currency
|
||||
// and rounded to a cent once, at the boundary — from there on the ledger is
|
||||
// integer arithmetic, so Σ(balances) is exactly 0 and no sub-cent residual can
|
||||
// build up behind the two-decimal figures the user sees (#1382).
|
||||
const toTripCents = (amount: number, itemCurrency: string | null | undefined, itemRate?: number | null): number =>
|
||||
Math.round(toTrip(amount, itemCurrency, itemRate) * 100);
|
||||
const balances: Record<number, { user_id: number; username: string; avatar_url: string | null; cents: number }> = {};
|
||||
const ensure = (id: number, src: { username?: string; avatar?: string | null }) => {
|
||||
if (!balances[id]) balances[id] = { user_id: id, username: src.username || '', avatar_url: avatarUrl(src), balance: 0 };
|
||||
if (!balances[id]) balances[id] = { user_id: id, username: src.username || '', avatar_url: avatarUrl(src), cents: 0 };
|
||||
return balances[id];
|
||||
};
|
||||
|
||||
@@ -694,16 +734,31 @@ export class BudgetService {
|
||||
|
||||
// Payers are credited what they actually paid (converted to trip currency with
|
||||
// the item's stored exchange rate)…
|
||||
for (const p of payers) ensure(p.user_id, p).balance += toTrip(p.amount > 0 ? p.amount : 0, item.currency, item.exchange_rate);
|
||||
let creditCents = 0;
|
||||
for (const p of payers) {
|
||||
const paid = toTripCents(p.amount > 0 ? p.amount : 0, item.currency, item.exchange_rate);
|
||||
ensure(p.user_id, p).cents += paid;
|
||||
creditCents += paid;
|
||||
}
|
||||
// …and each split participant owes their share — a custom per-member amount
|
||||
// when one is set, otherwise an equal share of the expense total.
|
||||
// when one is set, otherwise an equal share of the expense.
|
||||
//
|
||||
// The equal split divides what the payers were actually credited, not
|
||||
// total_price: the two are the same figure (the write path derives the total
|
||||
// from the payer sum), but converting the total separately would round to a
|
||||
// different cent on a foreign-currency expense and leave the item off by one.
|
||||
// With nobody down as a payer there is nothing to divide, so the recorded total
|
||||
// stands in and an unpaid bill keeps reading as money owed.
|
||||
const hasCustomSplit = members.some(m => m.amount !== null && m.amount !== undefined);
|
||||
const equalShares = !hasCustomSplit ? this.splitEqualShares(item.total_price, members, item.id) : {};
|
||||
const splitCents = creditCents > 0
|
||||
? creditCents
|
||||
: toTripCents(item.total_price, item.currency, item.exchange_rate);
|
||||
const equalShares = !hasCustomSplit ? this.splitEqualShares(splitCents, members, item.id) : {};
|
||||
for (const m of members) {
|
||||
const memberShare = hasCustomSplit && m.amount !== null && m.amount !== undefined
|
||||
? toTrip(m.amount, item.currency, item.exchange_rate)
|
||||
: toTrip(equalShares[m.user_id] || 0, item.currency, item.exchange_rate);
|
||||
ensure(m.user_id, m).balance -= memberShare;
|
||||
? toTripCents(m.amount, item.currency, item.exchange_rate)
|
||||
: (equalShares[m.user_id] || 0);
|
||||
ensure(m.user_id, m).cents -= memberShare;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -714,19 +769,29 @@ export class BudgetService {
|
||||
// surfaces as an amount still to square up instead of silently vanishing.
|
||||
const settlements = this.listSettlements(tripId);
|
||||
const ensureSettled = (id: number, username: string | undefined, avatar_url: string | null | undefined) => {
|
||||
if (!balances[id]) balances[id] = { user_id: id, username: username || '', avatar_url: avatar_url ?? null, balance: 0 };
|
||||
if (!balances[id]) balances[id] = { user_id: id, username: username || '', avatar_url: avatar_url ?? null, cents: 0 };
|
||||
return balances[id];
|
||||
};
|
||||
for (const s of settlements) {
|
||||
const inTrip = settleToTrip(s.amount, s.currency, s.exchange_rate);
|
||||
ensureSettled(s.from_user_id, s.from_username, s.from_avatar_url).balance += inTrip;
|
||||
ensureSettled(s.to_user_id, s.to_username, s.to_avatar_url).balance -= inTrip;
|
||||
// Rounded to a trip cent per transfer, so recording one in a display currency
|
||||
// can't leave a sliver of a cent behind to accumulate over a trip's lifetime.
|
||||
const inTrip = Math.round(settleToTrip(s.amount, s.currency, s.exchange_rate) * 100);
|
||||
ensureSettled(s.from_user_id, s.from_username, s.from_avatar_url).cents += inTrip;
|
||||
ensureSettled(s.to_user_id, s.to_username, s.to_avatar_url).cents -= inTrip;
|
||||
}
|
||||
|
||||
// Into the display currency as one set, then simplify — balances and flows are
|
||||
// derived from the same integers, so what the balances say is owed is exactly
|
||||
// what "Settle up" offers to move, down to the last cent (#1382).
|
||||
const ledger = Object.values(balances);
|
||||
const displayCents = allocateDisplayCents(ledger.map(b => b.cents), displayFactor);
|
||||
|
||||
// Calculate optimized payment flows (greedy algorithm)
|
||||
const people = Object.values(balances).filter(b => Math.abs(b.balance) > 0.01);
|
||||
const debtors = people.filter(p => p.balance < -0.01).map(p => ({ ...p, amount: -p.balance }));
|
||||
const creditors = people.filter(p => p.balance > 0.01).map(p => ({ ...p, amount: p.balance }));
|
||||
const people = ledger
|
||||
.map((b, i) => ({ user_id: b.user_id, username: b.username, avatar_url: b.avatar_url, cents: displayCents[i] }))
|
||||
.filter(b => b.cents !== 0);
|
||||
const debtors = people.filter(p => p.cents < 0).map(p => ({ ...p, amount: -p.cents }));
|
||||
const creditors = people.filter(p => p.cents > 0).map(p => ({ ...p, amount: p.cents }));
|
||||
|
||||
// Sort by amount descending for efficient matching
|
||||
debtors.sort((a, b) => b.amount - a.amount);
|
||||
@@ -737,21 +802,22 @@ export class BudgetService {
|
||||
let di = 0, ci = 0;
|
||||
while (di < debtors.length && ci < creditors.length) {
|
||||
const transfer = Math.min(debtors[di].amount, creditors[ci].amount);
|
||||
if (transfer > 0.01) {
|
||||
flows.push({
|
||||
from: { user_id: debtors[di].user_id, username: debtors[di].username, avatar_url: debtors[di].avatar_url },
|
||||
to: { user_id: creditors[ci].user_id, username: creditors[ci].username, avatar_url: creditors[ci].avatar_url },
|
||||
amount: Math.round(toDisplay(transfer) * 100) / 100,
|
||||
});
|
||||
}
|
||||
flows.push({
|
||||
from: { user_id: debtors[di].user_id, username: debtors[di].username, avatar_url: debtors[di].avatar_url },
|
||||
to: { user_id: creditors[ci].user_id, username: creditors[ci].username, avatar_url: creditors[ci].avatar_url },
|
||||
amount: transfer / 100,
|
||||
});
|
||||
debtors[di].amount -= transfer;
|
||||
creditors[ci].amount -= transfer;
|
||||
if (debtors[di].amount < 0.01) di++;
|
||||
if (creditors[ci].amount < 0.01) ci++;
|
||||
if (debtors[di].amount === 0) di++;
|
||||
if (creditors[ci].amount === 0) ci++;
|
||||
}
|
||||
|
||||
return {
|
||||
balances: Object.values(balances).map(b => ({ ...b, balance: Math.round(toDisplay(b.balance) * 100) / 100 })),
|
||||
balances: ledger.map((b, i) => ({
|
||||
user_id: b.user_id, username: b.username, avatar_url: b.avatar_url,
|
||||
balance: displayCents[i] / 100,
|
||||
})),
|
||||
flows,
|
||||
settlements,
|
||||
};
|
||||
|
||||
@@ -313,7 +313,12 @@ export class CalendarService {
|
||||
// A stay wins over everything below: it is the only source that knows how
|
||||
// long the booking lasts. Emitted as an all-day range over every night, so
|
||||
// the hotel sits above the day in a subscribed calendar instead of
|
||||
// appearing once on the arrival day (#1586). DTEND is exclusive, hence +1.
|
||||
// appearing once on the arrival day (#1586).
|
||||
// end_day_id is the CHECK-OUT day, and the block is meant to cover it too:
|
||||
// a 26th-to-30th booking should read as a five-day block, not as the four
|
||||
// nights it contains. DTEND is exclusive, so it is check-out plus one day.
|
||||
// Dropping that +1 hides the departure day; it is not a stray off-by-one
|
||||
// (#1869).
|
||||
if (isDate(r.stay_start_date)) {
|
||||
const lastDay = isDate(r.stay_end_date) && r.stay_end_date >= r.stay_start_date
|
||||
? r.stay_end_date
|
||||
@@ -362,6 +367,18 @@ export class CalendarService {
|
||||
}
|
||||
return out;
|
||||
}
|
||||
// Date-only start. RFC 5545 makes a DATE event without DTEND exactly one
|
||||
// day long, so a booking that does record an end date still collapsed
|
||||
// onto its first day (#1869); an all-day multi-day event coming through
|
||||
// the booking import (kitinerary-mapper passes date-only start/end
|
||||
// straight through) is the common shape. Same rule as the stay branch:
|
||||
// DTEND is exclusive, hence the end day plus one. Only the date part is
|
||||
// used, because DTSTART;VALUE=DATE and a timed DTEND may not be mixed.
|
||||
const endDatePart = r.reservation_end_time ? String(r.reservation_end_time).split('T')[0] : '';
|
||||
if (isDate(endDatePart) && endDatePart >= r.reservation_time) {
|
||||
return `DTSTART;VALUE=DATE:${fmtDate(r.reservation_time)}\r\n` +
|
||||
`DTEND;VALUE=DATE:${fmtDate(addDays(endDatePart, 1))}\r\n`;
|
||||
}
|
||||
return `DTSTART;VALUE=DATE:${fmtDate(r.reservation_time)}\r\n`;
|
||||
}
|
||||
|
||||
@@ -414,16 +431,23 @@ export class CalendarService {
|
||||
// all-day event cannot carry a time, and "be there at 15:00" is the part a
|
||||
// subscriber actually wants a reminder for. Emitted per stay rather than per
|
||||
// reservation so a stay whose reservation was deleted still shows them.
|
||||
// The reservation is read through a subquery rather than a LEFT JOIN: nothing
|
||||
// stops two bookings from pointing at the same accommodation, and a join fans
|
||||
// the stay out into one row per booking. Since the check-in/check-out UIDs are
|
||||
// keyed by the stay, that emitted the same UID twice and clients then pick one
|
||||
// of the duplicates at random (#1869). Lowest id wins so the title is stable
|
||||
// across exports.
|
||||
const stays = this.db.prepare(`
|
||||
SELECT a.id, a.check_in, a.check_in_end, a.check_out,
|
||||
sd.date AS start_date, ed.date AS end_date,
|
||||
p.name AS place_name, p.address AS place_address, p.lat AS place_lat, p.lng AS place_lng,
|
||||
r.title AS reservation_title
|
||||
(SELECT r.title FROM reservations r
|
||||
WHERE r.accommodation_id = a.id
|
||||
ORDER BY r.id ASC LIMIT 1) AS reservation_title
|
||||
FROM day_accommodations a
|
||||
LEFT JOIN days sd ON a.start_day_id = sd.id
|
||||
LEFT JOIN days ed ON a.end_day_id = ed.id
|
||||
LEFT JOIN places p ON a.place_id = p.id
|
||||
LEFT JOIN reservations r ON r.accommodation_id = a.id
|
||||
WHERE a.trip_id = ?
|
||||
ORDER BY a.id ASC
|
||||
`).all(tripId) as any[];
|
||||
|
||||
@@ -203,7 +203,7 @@ export class CollectionsMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'update_collection_place',
|
||||
description: 'Update a saved place\'s name, description, notes, status, category, links, tags, labels, image, or move it to another collection (set collection_id).',
|
||||
description: 'Update a saved place\'s name, address, coordinates (lat/lng), description, notes, status, category, links, tags, labels, image, or move it to another collection (set collection_id).',
|
||||
inputSchema: { placeId: z.number().int().positive(), ...collectionPlaceUpdateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
when: collectionsAddonOn,
|
||||
|
||||
@@ -653,6 +653,7 @@ export class CollectionsService {
|
||||
if (body.notes !== undefined) { updates.push('notes = ?'); params.push(body.notes ?? null); }
|
||||
if (body.lat !== undefined) { updates.push('lat = ?'); params.push(body.lat ?? null); }
|
||||
if (body.lng !== undefined) { updates.push('lng = ?'); params.push(body.lng ?? null); }
|
||||
if (body.address !== undefined) { updates.push('address = ?'); params.push(body.address ?? null); }
|
||||
if (body.status !== undefined) { updates.push('status = ?'); params.push(body.status); }
|
||||
if (body.category_id !== undefined) { updates.push('category_id = ?'); params.push(body.category_id ?? null); }
|
||||
if (body.image_url !== undefined) { updates.push('image_url = ?'); params.push(body.image_url ?? null); }
|
||||
|
||||
@@ -25,7 +25,8 @@ export class LlmConfigResolver {
|
||||
/**
|
||||
* Resolve the effective LLM config for a user, gated by the addon.
|
||||
* Order: addon disabled → null; admin instance config wins; else per-user config;
|
||||
* else null. This is the single place the API key is decrypted.
|
||||
* else null. This is the single place the API key is decrypted, and the single
|
||||
* place that decides which endpoint the server is allowed to call (#1772).
|
||||
*/
|
||||
resolve(userId: number): ResolvedLlmConfig | null {
|
||||
if (!this.addons.isAddonEnabled(ADDON_IDS.LLM_PARSING)) return null;
|
||||
@@ -61,14 +62,31 @@ export class LlmConfigResolver {
|
||||
const provider = asProvider(settings.llm_provider);
|
||||
const model = typeof settings.llm_model === 'string' ? settings.llm_model.trim() : '';
|
||||
if (!provider || !model) return null;
|
||||
|
||||
// #1772: the address this server calls is instance configuration, never a
|
||||
// personal preference. The request leaves OUR network and safeFetchLlm
|
||||
// deliberately allows loopback/LAN so a self-hosted Ollama keeps working,
|
||||
// which is a reasonable trade for whoever runs the instance and a network
|
||||
// probe for anyone else. An instance has exactly one such address, so it
|
||||
// comes from the admin-set instance-wide defaults for EVERY user, including
|
||||
// an admin's own row. This is the choke point every consumer passes
|
||||
// (booking import and the plugin RPC surface), and the only place that also
|
||||
// catches values already sitting in the db.
|
||||
const endpoints = this.settings.getAdminUserDefaults();
|
||||
// 'local' is an endpoint choice too ("some address I name"), so without an
|
||||
// admin-set local endpoint there is no config at all, never a silent
|
||||
// redirect to a different provider.
|
||||
if (provider === 'local' && asProvider(endpoints.llm_provider) !== 'local') return null;
|
||||
const baseUrl =
|
||||
typeof endpoints.llm_base_url === 'string' && endpoints.llm_base_url.trim()
|
||||
? endpoints.llm_base_url.trim()
|
||||
: undefined;
|
||||
|
||||
const apiKey = this.settings.getDecryptedUserSetting(userId, 'llm_api_key') ?? undefined;
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
baseUrl:
|
||||
typeof settings.llm_base_url === 'string' && settings.llm_base_url.trim()
|
||||
? settings.llm_base_url.trim()
|
||||
: undefined,
|
||||
baseUrl,
|
||||
apiKey,
|
||||
multimodal: settings.llm_multimodal === true,
|
||||
};
|
||||
|
||||
@@ -13,8 +13,11 @@ import { DaysService } from '../days/days.service';
|
||||
import { findByIata } from '../airports/airports.data';
|
||||
import type { EndpointInput } from './reservations.service';
|
||||
import { AssignmentsService } from '../assignments/assignments.service';
|
||||
import { transportLegsInputSchema, type TransportLegInput } from '@trek/shared';
|
||||
|
||||
const TRANSPORT_TYPES = ['flight', 'train', 'car', 'cruise'] as const;
|
||||
/** Only these two carry per-segment detail; a car or cruise has no legs. */
|
||||
const LEG_TRANSPORT_TYPES = ['flight', 'train'] as const;
|
||||
|
||||
const endpointObjectSchema = z.object({
|
||||
role: z.enum(['from', 'to', 'stop']).describe('Endpoint role: "from" (origin), "to" (destination), or "stop" (intermediate)'),
|
||||
@@ -72,6 +75,205 @@ function parseId(value: string | string[]): number | null {
|
||||
return Number.isInteger(n) && n > 0 ? n : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Multi-leg bookings (#1914)
|
||||
//
|
||||
// A stopover booking splits over two stores: the endpoints hold the geometry,
|
||||
// `metadata.legs` holds each segment's own day, time and airline/train identity.
|
||||
// The endpoint of a stop carries the ONWARD DEPARTURE only (the planner form
|
||||
// writes `isLast ? arrTime : depTime`), so without legs the arrival at that stop
|
||||
// exists nowhere and every reader falls back to showing one time twice, which is
|
||||
// the symptom in the report. These helpers accept the same leg shape the form
|
||||
// and the importers write, and keep the two stores in step.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const legsSchema = transportLegsInputSchema.optional().describe(
|
||||
'Per-segment detail of a stopover flight or train: one entry per segment, in route order, exactly ONE FEWER than endpoints[]. '
|
||||
+ 'Each leg carries its own departure and arrival day + local time (dep_day_id/dep_time, arr_day_id/arr_time) plus airline/flight_number (flights) or train_number/platform (trains). '
|
||||
+ "Required for a booking with stopovers: a stop's endpoint stores only the onward departure, so without legs that one time is shown as both the arrival and the departure. "
|
||||
+ 'Omit it for a direct booking. Blank endpoint times/dates, day_id/end_day_id and reservation_time are derived from the legs; a value that contradicts them is rejected.'
|
||||
);
|
||||
|
||||
type MetaRecord = Record<string, unknown>;
|
||||
|
||||
/**
|
||||
* `reservations.metadata` as stored: a JSON string, or (from an old
|
||||
* double-encoding bug the client readers still heal around) a JSON string of a
|
||||
* JSON string. Reading it must never throw: a booking with unparseable metadata
|
||||
* still has to accept a legs update.
|
||||
*/
|
||||
function parseStoredMetadata(raw: unknown): MetaRecord {
|
||||
if (typeof raw !== 'string' || !raw) return {};
|
||||
try {
|
||||
let parsed: unknown = JSON.parse(raw);
|
||||
if (typeof parsed === 'string') parsed = JSON.parse(parsed);
|
||||
return typeof parsed === 'object' && parsed !== null ? parsed as MetaRecord : {};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
}
|
||||
|
||||
interface LegPlan {
|
||||
legs: TransportLegInput[];
|
||||
type: string;
|
||||
/** Resolved geometry the legs run over (one more entry than legs). */
|
||||
endpoints: EndpointInput[];
|
||||
baseMetadata: MetaRecord;
|
||||
/** Stored legs of the same booking, for the day-planner positions. */
|
||||
previousLegs: unknown[];
|
||||
startDayId?: number;
|
||||
endDayId?: number;
|
||||
reservationTime?: string;
|
||||
reservationEndTime?: string;
|
||||
// A day row carries an optional date, so the caller cannot promise one. Every
|
||||
// read below treats a dateless day as "no date known" rather than stamping undefined.
|
||||
lookupDay: (id: number) => { date?: string | null } | undefined;
|
||||
}
|
||||
|
||||
interface LegOutcome {
|
||||
metadata: MetaRecord;
|
||||
endpoints: EndpointInput[];
|
||||
/** True when a blank endpoint time/date was filled in from the legs. */
|
||||
endpointsChanged: boolean;
|
||||
day_id?: number;
|
||||
end_day_id?: number;
|
||||
reservation_time?: string;
|
||||
reservation_end_time?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate the legs against the endpoints and fold them into the metadata.
|
||||
* Returns the values the write should use, or the first error as text.
|
||||
*/
|
||||
function applyLegs(plan: LegPlan): LegOutcome | { error: string } {
|
||||
const { legs, lookupDay } = plan;
|
||||
const last = legs.length - 1;
|
||||
|
||||
if (!(LEG_TRANSPORT_TYPES as readonly string[]).includes(plan.type))
|
||||
return { error: 'legs are only supported for flight and train bookings.' };
|
||||
// Readers treat legs.length > 1 as the multi-segment marker and the form drops
|
||||
// a single-leg list on the next save, so a 1-entry list would be inert.
|
||||
if (legs.length < 2)
|
||||
return { error: 'legs describes a booking with at least one stopover, so it needs at least 2 entries. Omit legs for a direct booking.' };
|
||||
if (plan.endpoints.length !== legs.length + 1)
|
||||
return { error: `legs must contain exactly one entry fewer than endpoints (got ${legs.length} legs for ${plan.endpoints.length} endpoints).` };
|
||||
|
||||
for (let i = 0; i < legs.length; i++) {
|
||||
for (const field of ['dep_day_id', 'arr_day_id'] as const) {
|
||||
const dayId = legs[i][field];
|
||||
if (dayId != null && !lookupDay(dayId))
|
||||
return { error: `legs[${i}].${field} does not belong to this trip.` };
|
||||
}
|
||||
}
|
||||
|
||||
const firstDepDay = legs[0].dep_day_id ?? null;
|
||||
const lastArrDay = legs[last].arr_day_id ?? null;
|
||||
if (plan.startDayId != null && firstDepDay != null && plan.startDayId !== firstDepDay)
|
||||
return { error: `start_day_id (${plan.startDayId}) does not match legs[0].dep_day_id (${firstDepDay}).` };
|
||||
if (plan.endDayId != null && lastArrDay != null && plan.endDayId !== lastArrDay)
|
||||
return { error: `end_day_id (${plan.endDayId}) does not match legs[${last}].arr_day_id (${lastArrDay}).` };
|
||||
|
||||
const endpoints = plan.endpoints.map(e => ({ ...e }));
|
||||
let endpointsChanged = false;
|
||||
const syncEndpoint = (index: number, time: string | null | undefined, dayId: number | null | undefined, label: string): string | null => {
|
||||
const ep = endpoints[index];
|
||||
if (dayId != null && !ep.local_date) {
|
||||
const day = lookupDay(dayId);
|
||||
if (day?.date) { ep.local_date = day.date; endpointsChanged = true; }
|
||||
}
|
||||
if (!time) return null;
|
||||
if (!ep.local_time) { ep.local_time = time; endpointsChanged = true; return null; }
|
||||
if (ep.local_time !== time)
|
||||
return `${label} (${time}) does not match endpoints[${index}].local_time (${ep.local_time}). A stop's endpoint carries the onward departure time; only the final endpoint carries an arrival time.`;
|
||||
return null;
|
||||
};
|
||||
|
||||
const merged: MetaRecord[] = [];
|
||||
for (let i = 0; i < legs.length; i++) {
|
||||
const leg = legs[i];
|
||||
const depEp = endpoints[i];
|
||||
const arrEp = endpoints[i + 1];
|
||||
// Codes only: a train endpoint is a free-text station label, and comparing
|
||||
// those would reject perfectly good input over a spelling difference.
|
||||
if (leg.from && depEp.code && leg.from.toUpperCase() !== depEp.code.toUpperCase())
|
||||
return { error: `legs[${i}].from (${leg.from}) does not match endpoints[${i}] (${depEp.code}).` };
|
||||
if (leg.to && arrEp.code && leg.to.toUpperCase() !== arrEp.code.toUpperCase())
|
||||
return { error: `legs[${i}].to (${leg.to}) does not match endpoints[${i + 1}] (${arrEp.code}).` };
|
||||
|
||||
const depConflict = syncEndpoint(i, leg.dep_time, leg.dep_day_id, `legs[${i}].dep_time`);
|
||||
if (depConflict) return { error: depConflict };
|
||||
|
||||
const entry: MetaRecord = {
|
||||
from: leg.from ?? depEp.code ?? depEp.name,
|
||||
to: leg.to ?? arrEp.code ?? arrEp.name,
|
||||
};
|
||||
for (const key of ['airline', 'flight_number', 'train_number', 'platform', 'seat'] as const) {
|
||||
const value = leg[key];
|
||||
if (value) entry[key] = value;
|
||||
}
|
||||
entry.dep_day_id = leg.dep_day_id ?? null;
|
||||
entry.dep_time = leg.dep_time ?? null;
|
||||
entry.arr_day_id = leg.arr_day_id ?? null;
|
||||
entry.arr_time = leg.arr_time ?? null;
|
||||
// day_positions belongs to the day planner, not to this input, so carry the
|
||||
// stored value at the same index over, exactly as a form re-save does.
|
||||
const positions = (plan.previousLegs[i] as MetaRecord | undefined)?.day_positions;
|
||||
if (positions) entry.day_positions = positions;
|
||||
merged.push(entry);
|
||||
}
|
||||
|
||||
const arrConflict = syncEndpoint(legs.length, legs[last].arr_time, lastArrDay, `legs[${last}].arr_time`);
|
||||
if (arrConflict) return { error: arrConflict };
|
||||
|
||||
const metadata: MetaRecord = { ...plan.baseMetadata, legs: merged };
|
||||
const first = merged[0];
|
||||
const final = merged[last];
|
||||
// Mirror the flat keys off the first/last leg the way the form and the
|
||||
// importers do, so readers that never learned about legs keep working. Never
|
||||
// overwrite what the caller set itself.
|
||||
const mirror = (key: string, value: unknown) => {
|
||||
if (value != null && metadata[key] == null) metadata[key] = value;
|
||||
};
|
||||
if (plan.type === 'flight') {
|
||||
mirror('departure_airport', first.from);
|
||||
mirror('arrival_airport', final.to);
|
||||
mirror('airline', first.airline);
|
||||
mirror('flight_number', first.flight_number);
|
||||
} else {
|
||||
mirror('train_number', first.train_number);
|
||||
mirror('platform', first.platform);
|
||||
}
|
||||
mirror('seat', first.seat);
|
||||
|
||||
const dayId = plan.startDayId ?? firstDepDay ?? undefined;
|
||||
const endDayId = plan.endDayId ?? lastArrDay ?? undefined;
|
||||
// Same fallback as the form's buildTime: date the time when the day is known,
|
||||
// otherwise keep the bare 'HH:mm' rather than dropping it.
|
||||
const stamp = (day: number | undefined, time: string | null | undefined) => {
|
||||
if (!time) return undefined;
|
||||
const row = day === undefined ? undefined : lookupDay(day);
|
||||
return row?.date ? `${row.date}T${time}` : time;
|
||||
};
|
||||
|
||||
return {
|
||||
metadata,
|
||||
endpoints,
|
||||
endpointsChanged,
|
||||
day_id: dayId,
|
||||
end_day_id: endDayId,
|
||||
reservation_time: plan.reservationTime ?? stamp(dayId, legs[0].dep_time),
|
||||
reservation_end_time: plan.reservationEndTime ?? stamp(endDayId, legs[last].arr_time),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* `metadata` is a flat string map, so segments smuggled through it can only ever
|
||||
* land as an inert JSON string that every reader skips (`Array.isArray` fails),
|
||||
* the silent dead end reported in #1914. Refuse it and name the right parameter.
|
||||
*/
|
||||
const LEGS_IN_METADATA_ERROR =
|
||||
'Pass the segments of a multi-leg booking in the legs parameter, not in metadata.legs. Metadata values are plain strings, so a JSON string there is stored but ignored by every reader.';
|
||||
|
||||
/**
|
||||
* Reservations MCP surface — ported 1:1 from the legacy registrars: the five
|
||||
* tools from src/mcp/tools/reservations.ts and the
|
||||
@@ -361,7 +563,7 @@ export class ReservationsMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'create_transport',
|
||||
description: 'Create a transport booking (flight, train, car, or cruise) for a trip. Use endpoints[] to record origin/destination and intermediate stops — for flights, set code to the IATA airport code (use search_airports first). Created as pending — confirm with update_transport. Set price to record the cost; it will appear on the booking and in the Budget tab.',
|
||||
description: 'Create a transport booking (flight, train, car, or cruise) for a trip. Use endpoints[] to record origin/destination and intermediate stops — for flights, set code to the IATA airport code (use search_airports first). For a booking WITH STOPOVERS also pass legs[] (one entry per segment, one fewer than endpoints[]), otherwise every segment inherits the stop time as both its arrival and its departure. Created as pending — confirm with update_transport. Set price to record the cost; it will appear on the booking and in the Budget tab.',
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
type: z.enum(['flight', 'train', 'car', 'cruise']),
|
||||
@@ -373,8 +575,9 @@ export class ReservationsMcp {
|
||||
reservation_end_time: z.string().optional().describe('ISO 8601 datetime or time string for arrival'),
|
||||
confirmation_number: z.string().max(100).optional(),
|
||||
notes: z.string().max(1000).optional(),
|
||||
metadata: z.record(z.string(), z.string()).optional().describe('Type-specific metadata: flights → { airline, flight_number, departure_airport, arrival_airport }; trains → { train_number, platform, seat }'),
|
||||
metadata: z.record(z.string(), z.string()).optional().describe('Type-specific metadata: flights → { airline, flight_number, departure_airport, arrival_airport }; trains → { train_number, platform, seat }. Values are plain strings, so per-segment detail belongs in legs[], not here.'),
|
||||
endpoints: endpointSchema,
|
||||
legs: legsSchema,
|
||||
needs_review: z.boolean().optional(),
|
||||
price: z.number().nonnegative().optional().describe('Transport cost — shown on the booking and linked in the Budget tab'),
|
||||
budget_category: z.string().max(100).optional().describe('Budget category for the price entry (defaults to transport type)'),
|
||||
@@ -383,11 +586,11 @@ export class ReservationsMcp {
|
||||
access: { group: 'reservations', mode: 'write' },
|
||||
})
|
||||
async createTransport(
|
||||
{ tripId, type, title, status, start_day_id, end_day_id, reservation_time, reservation_end_time, confirmation_number, notes, metadata, endpoints, needs_review, price, budget_category }: {
|
||||
{ tripId, type, title, status, start_day_id, end_day_id, reservation_time, reservation_end_time, confirmation_number, notes, metadata, endpoints, legs, needs_review, price, budget_category }: {
|
||||
tripId: number; type: 'flight' | 'train' | 'car' | 'cruise'; title: string;
|
||||
status?: 'pending' | 'confirmed' | 'cancelled'; start_day_id?: number; end_day_id?: number;
|
||||
reservation_time?: string; reservation_end_time?: string; confirmation_number?: string; notes?: string;
|
||||
metadata?: Record<string, string>; endpoints?: TransportEndpoint[]; needs_review?: boolean;
|
||||
metadata?: Record<string, string>; endpoints?: TransportEndpoint[]; legs?: TransportLegInput[]; needs_review?: boolean;
|
||||
price?: number; budget_category?: string;
|
||||
},
|
||||
ctx: McpContext,
|
||||
@@ -396,6 +599,8 @@ export class ReservationsMcp {
|
||||
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
|
||||
if (metadata && 'legs' in metadata) return errorResult(LEGS_IN_METADATA_ERROR);
|
||||
|
||||
if (start_day_id && !this.days.getDay(start_day_id, tripId))
|
||||
return errorResult('start_day_id does not belong to this trip.');
|
||||
if (end_day_id && !this.days.getDay(end_day_id, tripId))
|
||||
@@ -404,22 +609,50 @@ export class ReservationsMcp {
|
||||
const resolved = resolveEndpointCoords(endpoints);
|
||||
if ('error' in resolved) return errorResult(resolved.error);
|
||||
|
||||
const meta: Record<string, string> = { ...(metadata ?? {}) };
|
||||
const meta: Record<string, unknown> = { ...(metadata ?? {}) };
|
||||
let transportEndpoints = resolved.endpoints;
|
||||
let dayId = start_day_id;
|
||||
let spanEndDayId = end_day_id;
|
||||
let departureTime = reservation_time;
|
||||
let arrivalTime = reservation_end_time;
|
||||
|
||||
if (legs !== undefined) {
|
||||
const applied = applyLegs({
|
||||
legs,
|
||||
type,
|
||||
endpoints: resolved.endpoints,
|
||||
baseMetadata: meta,
|
||||
previousLegs: [],
|
||||
startDayId: start_day_id,
|
||||
endDayId: end_day_id,
|
||||
reservationTime: reservation_time,
|
||||
reservationEndTime: reservation_end_time,
|
||||
lookupDay: (id) => this.days.getDay(id, tripId),
|
||||
});
|
||||
if ('error' in applied) return errorResult(applied.error);
|
||||
Object.assign(meta, applied.metadata);
|
||||
transportEndpoints = applied.endpoints;
|
||||
dayId = applied.day_id;
|
||||
spanEndDayId = applied.end_day_id;
|
||||
departureTime = applied.reservation_time;
|
||||
arrivalTime = applied.reservation_end_time;
|
||||
}
|
||||
|
||||
if (price != null) meta.price = String(price);
|
||||
|
||||
const { reservation } = this.reservations.create(tripId, {
|
||||
title,
|
||||
type,
|
||||
reservation_time,
|
||||
reservation_end_time,
|
||||
reservation_time: departureTime,
|
||||
reservation_end_time: arrivalTime,
|
||||
location: undefined,
|
||||
confirmation_number,
|
||||
notes,
|
||||
day_id: start_day_id,
|
||||
end_day_id: end_day_id ?? start_day_id,
|
||||
day_id: dayId,
|
||||
end_day_id: spanEndDayId ?? dayId,
|
||||
status: status ?? 'pending',
|
||||
metadata: Object.keys(meta).length > 0 ? meta : undefined,
|
||||
endpoints: resolved.endpoints,
|
||||
endpoints: transportEndpoints,
|
||||
needs_review,
|
||||
});
|
||||
|
||||
@@ -438,7 +671,7 @@ export class ReservationsMcp {
|
||||
|
||||
@Tool({
|
||||
name: 'update_transport',
|
||||
description: 'Update an existing transport booking. Pass endpoints[] to replace the full list of stops (origin, destination, intermediates). Use status "confirmed" to confirm.',
|
||||
description: 'Update an existing transport booking. Pass endpoints[] to replace the full list of stops (origin, destination, intermediates), and legs[] to write the per-segment times of a stopover booking. Sending legs[] without metadata keeps the stored metadata (departure_airport, airtrail_ids, transit) and only replaces the segments. Use status "confirmed" to confirm.',
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
reservationId: z.number().int().positive(),
|
||||
@@ -451,19 +684,20 @@ export class ReservationsMcp {
|
||||
reservation_end_time: z.string().optional().describe('ISO 8601 datetime or time string for arrival'),
|
||||
confirmation_number: z.string().max(100).optional(),
|
||||
notes: z.string().max(1000).optional(),
|
||||
metadata: z.record(z.string(), z.string()).optional().describe('Type-specific metadata: flights → { airline, flight_number, departure_airport, arrival_airport }; trains → { train_number, platform, seat }'),
|
||||
metadata: z.record(z.string(), z.string()).optional().describe('Type-specific metadata: flights → { airline, flight_number, departure_airport, arrival_airport }; trains → { train_number, platform, seat }. Replaces the stored metadata wholesale. Values are plain strings, so per-segment detail belongs in legs[], not here.'),
|
||||
endpoints: endpointSchema,
|
||||
legs: legsSchema,
|
||||
needs_review: z.boolean().optional(),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: { group: 'reservations', mode: 'write' },
|
||||
})
|
||||
async updateTransport(
|
||||
{ tripId, reservationId, type, title, status, start_day_id, end_day_id, reservation_time, reservation_end_time, confirmation_number, notes, metadata, endpoints, needs_review }: {
|
||||
{ tripId, reservationId, type, title, status, start_day_id, end_day_id, reservation_time, reservation_end_time, confirmation_number, notes, metadata, endpoints, legs, needs_review }: {
|
||||
tripId: number; reservationId: number; type?: 'flight' | 'train' | 'car' | 'cruise'; title?: string;
|
||||
status?: 'pending' | 'confirmed' | 'cancelled'; start_day_id?: number; end_day_id?: number;
|
||||
reservation_time?: string; reservation_end_time?: string; confirmation_number?: string; notes?: string;
|
||||
metadata?: Record<string, string>; endpoints?: TransportEndpoint[]; needs_review?: boolean;
|
||||
metadata?: Record<string, string>; endpoints?: TransportEndpoint[]; legs?: TransportLegInput[]; needs_review?: boolean;
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
@@ -471,6 +705,8 @@ export class ReservationsMcp {
|
||||
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
|
||||
if (metadata && 'legs' in metadata) return errorResult(LEGS_IN_METADATA_ERROR);
|
||||
|
||||
const existing = this.reservations.getReservation(reservationId, tripId);
|
||||
if (!existing) return errorResult('Transport not found.');
|
||||
|
||||
@@ -491,17 +727,57 @@ export class ReservationsMcp {
|
||||
resolvedEndpoints = resolved.endpoints;
|
||||
}
|
||||
|
||||
let nextMetadata: unknown = metadata;
|
||||
let dayId = start_day_id;
|
||||
let spanEndDayId: number | undefined = end_day_id;
|
||||
let departureTime = reservation_time;
|
||||
let arrivalTime = reservation_end_time;
|
||||
|
||||
if (legs !== undefined) {
|
||||
const stored = parseStoredMetadata(existing.metadata);
|
||||
const applied = applyLegs({
|
||||
legs,
|
||||
type: resolvedType,
|
||||
// Endpoints the caller did not replace stay the geometry the legs run
|
||||
// over, so read them back (the row carries them) instead of guessing.
|
||||
endpoints: resolvedEndpoints ?? (this.reservations.getReservationWithJoins(reservationId)?.endpoints ?? []).map(e => ({
|
||||
role: e.role, sequence: e.sequence, name: e.name, code: e.code,
|
||||
lat: e.lat, lng: e.lng, timezone: e.timezone,
|
||||
local_time: e.local_time, local_date: e.local_date,
|
||||
})),
|
||||
// metadata keeps replacing wholesale when it is sent; a legs-only update
|
||||
// must not drop departure_airport / airtrail_ids / transit, so it merges
|
||||
// into what is stored instead.
|
||||
baseMetadata: metadata !== undefined ? { ...metadata } : { ...stored },
|
||||
previousLegs: Array.isArray(stored.legs) ? stored.legs as unknown[] : [],
|
||||
startDayId: start_day_id,
|
||||
endDayId: end_day_id,
|
||||
reservationTime: reservation_time,
|
||||
reservationEndTime: reservation_end_time,
|
||||
lookupDay: (id) => this.days.getDay(id, tripId),
|
||||
});
|
||||
if ('error' in applied) return errorResult(applied.error);
|
||||
nextMetadata = applied.metadata;
|
||||
dayId = applied.day_id;
|
||||
spanEndDayId = applied.end_day_id;
|
||||
departureTime = applied.reservation_time;
|
||||
arrivalTime = applied.reservation_end_time;
|
||||
// Rewrite the endpoints only when the legs actually filled a blank time or
|
||||
// date in; an unchanged list is left alone so its rows survive.
|
||||
if (applied.endpointsChanged) resolvedEndpoints = applied.endpoints;
|
||||
}
|
||||
|
||||
const { reservation } = this.reservations.update(reservationId, tripId, {
|
||||
title,
|
||||
type,
|
||||
reservation_time,
|
||||
reservation_end_time,
|
||||
reservation_time: departureTime,
|
||||
reservation_end_time: arrivalTime,
|
||||
confirmation_number,
|
||||
notes,
|
||||
day_id: start_day_id,
|
||||
end_day_id,
|
||||
day_id: dayId,
|
||||
end_day_id: spanEndDayId,
|
||||
status,
|
||||
metadata,
|
||||
metadata: nextMetadata,
|
||||
endpoints: resolvedEndpoints,
|
||||
needs_review,
|
||||
}, existing);
|
||||
|
||||
@@ -2,7 +2,7 @@ import { Body, Controller, Get, HttpCode, HttpException, Post, Put, Req, UseGuar
|
||||
import type { Request } from 'express';
|
||||
import { MASKED_SETTING_VALUE } from '@trek/shared';
|
||||
import type { User } from '../../types';
|
||||
import { SettingsService } from './settings.service';
|
||||
import { SettingsService, isAdminOnlyLlmSetting } from './settings.service';
|
||||
import { SettingUpsertDto, SettingsBulkDto } from './settings.dto';
|
||||
import { AdminDefaultUserSettingsDto } from '../admin/admin.dto';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
@@ -18,12 +18,37 @@ import { CurrentUser } from '../auth/current-user.decorator';
|
||||
* the DTO classes in settings.dto.ts + the global ZodValidationPipe (400 with
|
||||
* the standard `{ error }` envelope on mismatch — this replaced the legacy
|
||||
* bespoke 'Key is required' / 'Settings object is required' checks).
|
||||
*
|
||||
* One key group is authorized rather than merely validated: the LLM endpoint
|
||||
* settings answer 403 here for everyone, admins included, because they are
|
||||
* instance configuration and live on their own admin routes (#1772).
|
||||
*/
|
||||
@Controller('api/settings')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
export class SettingsController {
|
||||
constructor(private readonly settings: SettingsService) {}
|
||||
|
||||
/**
|
||||
* #1772: the write half of the rule that the endpoint is instance
|
||||
* configuration. There is no key allow-list on this route, so anyone could
|
||||
* otherwise park an `llm_base_url` (or `llm_provider: 'local'`) in their own
|
||||
* settings row. The resolver ignores such a row anyway; refusing it here
|
||||
* means the caller finds out instead of silently saving something that never
|
||||
* takes effect.
|
||||
*
|
||||
* Admins are not exempt: they set the instance endpoint on the addon, or via
|
||||
* PUT /api/admin/default-user-settings, both of which are separate routes
|
||||
* behind AdminGuard. A personal row would be a second, invisible place for
|
||||
* the same value.
|
||||
*/
|
||||
private assertMayWriteLlmEndpoint(settings: Record<string, unknown>) {
|
||||
for (const [key, value] of Object.entries(settings)) {
|
||||
if (isAdminOnlyLlmSetting(key, value)) {
|
||||
throw new HttpException({ error: 'Admin access required' }, 403);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@Get()
|
||||
list(@CurrentUser() user: User) {
|
||||
return { settings: this.settings.getUserSettings(user.id) };
|
||||
@@ -31,6 +56,7 @@ export class SettingsController {
|
||||
|
||||
@Put()
|
||||
upsert(@CurrentUser() user: User, @Body() body: SettingUpsertDto) {
|
||||
this.assertMayWriteLlmEndpoint({ [body.key]: body.value });
|
||||
// The client echoes a redacted secret back unchanged — treat as a no-op.
|
||||
if (body.value === MASKED_SETTING_VALUE) {
|
||||
return { success: true, key: body.key, unchanged: true };
|
||||
@@ -42,6 +68,7 @@ export class SettingsController {
|
||||
@Post('bulk')
|
||||
@HttpCode(200) // Express answers bulk with res.json (200), not the POST-default 201.
|
||||
bulk(@CurrentUser() user: User, @Body() body: SettingsBulkDto) {
|
||||
this.assertMayWriteLlmEndpoint(body.settings);
|
||||
try {
|
||||
const updated = this.settings.bulkUpsertSettings(user.id, body.settings);
|
||||
return { success: true, updated };
|
||||
|
||||
@@ -50,6 +50,23 @@ const VALID_VALUES: Partial<Record<DefaultableKey, unknown[]>> = {
|
||||
|
||||
const BOOLEAN_KEYS = new Set<DefaultableKey>(['blur_booking_codes', 'mapbox_3d_enabled', 'mapbox_quality_mode', 'llm_multimodal']);
|
||||
|
||||
/**
|
||||
* #1772: per-user LLM settings a non-admin must not write. Both of them pick
|
||||
* the address this server sends its own LLM requests to (provider 'local' means
|
||||
* nothing but "an endpoint I name"), and the SSRF guard in front of those
|
||||
* requests allows loopback/LAN on purpose so a self-hosted Ollama works. Only
|
||||
* whoever runs the instance can judge what is reachable from it.
|
||||
*
|
||||
* Clearing stays open to everyone: both Settings sections always send
|
||||
* `llm_base_url: ''` while the field is hidden, so a row written before this
|
||||
* rule cleans itself up on the next save instead of blocking it.
|
||||
*/
|
||||
export function isAdminOnlyLlmSetting(key: string, value: unknown): boolean {
|
||||
if (key === 'llm_base_url') return typeof value === 'string' && value.trim() !== '';
|
||||
if (key === 'llm_provider') return value === 'local';
|
||||
return false;
|
||||
}
|
||||
|
||||
function parseValue(raw: string): unknown {
|
||||
try { return JSON.parse(raw); } catch { return raw; }
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user