mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-29 16:10:07 +00:00
feat(roadtrip): share trip preferences and improve service stops
This commit is contained in:
@@ -1,3 +1,4 @@
|
||||
import { ROADTRIP_PREFERENCE_KEYS } from '@trek/shared';
|
||||
import { readEnv } from '../app-config';
|
||||
import { encrypt_api_key } from '../nest/common/crypto/apiKeyCrypto';
|
||||
|
||||
@@ -4550,6 +4551,11 @@ function runMigrations(db: Database.Database): void {
|
||||
PRIMARY KEY (trip_id, day_number)
|
||||
)`);
|
||||
},
|
||||
() => {
|
||||
db.exec('CREATE TABLE IF NOT EXISTS roadtrip_preferences (trip_id INTEGER NOT NULL REFERENCES trips(id) ON DELETE CASCADE, key TEXT NOT NULL, value TEXT NOT NULL, PRIMARY KEY (trip_id, key))');
|
||||
const inherit = db.prepare('INSERT OR IGNORE INTO roadtrip_preferences (trip_id, key, value) SELECT t.id, s.key, s.value FROM trips t JOIN settings s ON s.user_id = t.user_id WHERE s.key = ? AND s.value IS NOT NULL');
|
||||
for (const key of ROADTRIP_PREFERENCE_KEYS) inherit.run(key);
|
||||
},
|
||||
];
|
||||
|
||||
if (currentVersion < migrations.length) {
|
||||
|
||||
@@ -74,7 +74,7 @@ export class RoadtripPlanService {
|
||||
return {
|
||||
days,
|
||||
visits,
|
||||
settings: this.preferences.read(userId),
|
||||
settings: this.preferences.read(tripId),
|
||||
profiles: this.router.profiles(),
|
||||
vias: this.roadtrip.listForTrip(tripId),
|
||||
tracks: this.roadtrip.tracksForTrip(tripId),
|
||||
|
||||
@@ -27,7 +27,7 @@ export class RoadtripPlanningMcp {
|
||||
@Tool({
|
||||
name: 'get_roadtrip_context',
|
||||
description:
|
||||
'Read the saved roadtrip days, visits, pinned times, stays, stop types, fill levels, travel modes, via points, followed tracks and manual day endings. Includes your personal driving preferences. No routing request and no browser needed. Coordinates missing from a visit prevent it from being routed. Use calculate_roadtrip to get the derived day layout. Edit visits with the existing place and assignment tools; change their saved order with reorder_day_assignments. Settings affect your account; visits and manual boundaries affect the shared trip.',
|
||||
'Read the saved roadtrip days, visits, pinned times, stays, stop types, fill levels, travel modes, via points, followed tracks and manual day endings. Includes the shared driving preferences for this trip. No routing request and no browser needed. Coordinates missing from a visit prevent it from being routed. Use calculate_roadtrip to get the derived day layout. Edit visits with the existing place and assignment tools; change their saved order with reorder_day_assignments. Settings, visits and manual boundaries all belong to the shared trip.',
|
||||
inputSchema: { tripId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { AddonGuard } from '../addons/addon.guard';
|
||||
import { RequireAddon } from '../addons/require-addon.decorator';
|
||||
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
|
||||
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
|
||||
import { RoadtripPreferencesService } from './roadtrip-preferences.service';
|
||||
import { Body, Controller, Get, Param, Put, UseGuards } from '@nestjs/common';
|
||||
import { roadtripPreferencesUpdateSchema } from '@trek/shared';
|
||||
|
||||
import { createZodDto } from 'nestjs-zod';
|
||||
|
||||
class PreferencesDto extends createZodDto(roadtripPreferencesUpdateSchema) {}
|
||||
|
||||
@Controller('api/trips/:tripId/roadtrip/preferences')
|
||||
@UseGuards(AddonGuard, JwtAuthGuard, TripAccessGuard)
|
||||
@RequireAddon(ADDON_IDS.ROADTRIP, 'Road trip')
|
||||
export class RoadtripPreferencesController {
|
||||
constructor(private readonly preferences: RoadtripPreferencesService) {}
|
||||
|
||||
@Get()
|
||||
read(@Param('tripId') tripId: string) {
|
||||
return { tripId: Number(tripId), preferences: this.preferences.read(Number(tripId)) };
|
||||
}
|
||||
|
||||
@Put()
|
||||
@RequirePermission('day_edit')
|
||||
update(@Param('tripId') tripId: string, @Body() patch: PreferencesDto) {
|
||||
return { tripId: Number(tripId), preferences: this.preferences.update(Number(tripId), patch) };
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { ADDON_IDS } from '../../addons';
|
||||
import { noAccess, permissionDenied } from '../../mcp/tools/_shared';
|
||||
import {
|
||||
McpController,
|
||||
Tool,
|
||||
@@ -11,9 +12,13 @@ import {
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { RoadtripPreferencesService } from './roadtrip-preferences.service';
|
||||
import { roadtripPreferencesUpdateSchema, type RoadtripPreferences } from '@trek/shared';
|
||||
|
||||
import { z } from 'zod';
|
||||
|
||||
const when = addonGate(ADDON_IDS.ROADTRIP);
|
||||
|
||||
@McpController()
|
||||
@@ -22,32 +27,37 @@ export class RoadtripPreferencesMcp {
|
||||
private readonly preferences: RoadtripPreferencesService,
|
||||
private readonly auth: AuthService,
|
||||
readonly addons: AddonsService,
|
||||
private readonly db: DatabaseService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
) {}
|
||||
|
||||
@Tool({
|
||||
name: 'get_roadtrip_settings',
|
||||
description:
|
||||
'Read your personal driving preferences, including daily start and end times, day-ending behavior, vehicle specifications, range, fill percentage, driving limits, avoided road classes and route display options. These preferences apply to all your trips, not to other travellers. Missing numbers mean no limit, missing daily times disable automatic scheduling, missing vehicle means unspecified, and missing end mode means route. Range and consumption always use kilometres, litres and kWh. Instance URLs and credentials are not exposed.',
|
||||
inputSchema: {},
|
||||
'Read the shared driving preferences for one trip, including daily start and end times, day-ending behavior, vehicle specifications, range, fill percentage, driving limits, avoided road classes and route display options. Every member of this trip sees the same preferences. Missing numbers mean no limit, missing daily times disable automatic scheduling, missing vehicle means unspecified, and missing end mode means route. Range and consumption always use kilometres, litres and kWh. Instance URLs and credentials are not exposed.',
|
||||
inputSchema: { tripId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
access: { group: 'settings', mode: 'read' },
|
||||
access: { group: 'trips', mode: 'read' },
|
||||
when,
|
||||
})
|
||||
async read(_input: Record<string, never>, ctx: McpContext) {
|
||||
return ok({ settings: this.preferences.read(ctx.userId), scope: 'current_user' });
|
||||
async read({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
return ok({ tripId, settings: this.preferences.read(tripId), scope: 'trip' });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
name: 'update_roadtrip_settings',
|
||||
description:
|
||||
'Change personal driving preferences for all your trips. Read get_roadtrip_settings first for relative changes. Daily times use HH:mm; clear either with an empty string to disable automatic daily scheduling. Fixed visit times retain priority. Numeric zero clears a limit. Vehicle specifications take precedence over manual range when complete; clear the relevant specifications to use a manual range. Avoid classes are a comma-separated selection of toll,motorway,ferry. Unspecified fields remain unchanged. End mode route pauses at the cutoff; stop ends at the last reachable visit. Per-visit end_day and dragged boundaries are edited with set_assignment_end_day and set_day_boundary. This never changes instance routing URLs or credentials.',
|
||||
inputSchema: { settings: roadtripPreferencesUpdateSchema },
|
||||
'Change the shared driving preferences for this trip. Changes apply to all its travellers and require permission to edit days. Read get_roadtrip_settings first for relative changes. Daily times use HH:mm; clear either with an empty string to disable automatic daily scheduling. Fixed visit times retain priority. Numeric zero clears a limit. Vehicle specifications take precedence over manual range when complete; clear the relevant specifications to use a manual range. Avoid classes are a comma-separated selection of toll,motorway,ferry. Unspecified fields remain unchanged. End mode route pauses at the cutoff; stop ends at the last reachable visit. Per-visit end_day and dragged boundaries are edited with set_assignment_end_day and set_day_boundary. This never changes instance routing URLs or credentials.',
|
||||
inputSchema: { tripId: z.number().int().positive(), settings: roadtripPreferencesUpdateSchema },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
access: { group: 'settings', mode: 'write' },
|
||||
access: { group: 'trips', mode: 'write' },
|
||||
when,
|
||||
})
|
||||
async update({ settings }: { settings: RoadtripPreferences }, ctx: McpContext) {
|
||||
async update({ tripId, settings }: { tripId: number; settings: RoadtripPreferences }, ctx: McpContext) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
return ok({ settings: this.preferences.update(ctx.userId, settings), scope: 'current_user' });
|
||||
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('day_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
return ok({ tripId, settings: this.preferences.update(tripId, settings), scope: 'trip' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import { SettingsService } from '../settings/settings.service';
|
||||
import { HttpException, Injectable } from '@nestjs/common';
|
||||
import {
|
||||
ROADTRIP_PREFERENCE_KEYS,
|
||||
@@ -11,12 +11,22 @@ import {
|
||||
@Injectable()
|
||||
export class RoadtripPreferencesService {
|
||||
constructor(
|
||||
private readonly settings: SettingsService,
|
||||
private readonly db: DatabaseService,
|
||||
private readonly realtime: RealtimeService,
|
||||
) {}
|
||||
|
||||
read(userId: number): RoadtripPreferences {
|
||||
const settings = this.settings.getUserSettings(userId);
|
||||
read(tripId: number): RoadtripPreferences {
|
||||
const settings: Record<string, unknown> = {};
|
||||
for (const row of this.db.all<{ key: string; value: string }>(
|
||||
'SELECT key, value FROM roadtrip_preferences WHERE trip_id = ?',
|
||||
tripId,
|
||||
)) {
|
||||
try {
|
||||
settings[row.key] = JSON.parse(row.value);
|
||||
} catch {
|
||||
settings[row.key] = row.value;
|
||||
}
|
||||
}
|
||||
const preferences: Record<string, unknown> = {};
|
||||
for (const key of ROADTRIP_PREFERENCE_KEYS) {
|
||||
const parsed = roadtripPreferencesSchema.shape[key].safeParse(settings[key]);
|
||||
@@ -25,15 +35,24 @@ export class RoadtripPreferencesService {
|
||||
return roadtripPreferencesSchema.parse(preferences);
|
||||
}
|
||||
|
||||
update(userId: number, patch: RoadtripPreferences): RoadtripPreferences {
|
||||
update(tripId: number, patch: RoadtripPreferences): RoadtripPreferences {
|
||||
const validated = roadtripPreferencesUpdateSchema.parse(patch);
|
||||
const next = { ...this.read(userId), ...validated };
|
||||
if (next.roadtrip_day_start && next.roadtrip_day_end && next.roadtrip_day_end <= next.roadtrip_day_start) {
|
||||
throw new HttpException({ error: 'Day end must be later than day start.' }, 400);
|
||||
}
|
||||
this.settings.bulkUpsertSettings(userId, validated);
|
||||
const saved = this.read(userId);
|
||||
this.realtime.broadcastToUser(userId, { type: 'roadtripPreferences:changed', preferences: saved });
|
||||
const saved = this.db.transaction(() => {
|
||||
const next = { ...this.read(tripId), ...validated };
|
||||
if (next.roadtrip_day_start && next.roadtrip_day_end && next.roadtrip_day_end <= next.roadtrip_day_start) {
|
||||
throw new HttpException({ error: 'Day end must be later than day start.' }, 400);
|
||||
}
|
||||
for (const [key, value] of Object.entries(validated)) {
|
||||
this.db.run(
|
||||
'INSERT INTO roadtrip_preferences (trip_id, key, value) VALUES (?, ?, ?) ON CONFLICT(trip_id, key) DO UPDATE SET value = excluded.value',
|
||||
tripId,
|
||||
key,
|
||||
JSON.stringify(value),
|
||||
);
|
||||
}
|
||||
return this.read(tripId);
|
||||
});
|
||||
this.realtime.broadcast(String(tripId), 'roadtripPreferences:changed', { preferences: saved });
|
||||
return saved;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,31 +1,51 @@
|
||||
import { Module } from '@nestjs/common';
|
||||
import { RoadtripController } from './roadtrip.controller';
|
||||
import { RoadtripService } from './roadtrip.service';
|
||||
import { RoadtripMcp } from './roadtrip.mcp';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
|
||||
import { PermissionsModule } from '../permissions/permissions.module';
|
||||
import { AuthModule } from '../auth/auth.module';
|
||||
import { PluginsRuntimeModule } from '../plugins/plugins-runtime.module';
|
||||
import { RealtimeModule } from '../realtime/realtime.module';
|
||||
import { AddonsModule } from '../addons/addons.module';
|
||||
import { DayBoundariesController } from './day-boundaries.controller';
|
||||
import { DayBoundariesService } from './day-boundaries.service';
|
||||
import { DayBoundariesMcp } from './day-boundaries.mcp';
|
||||
import { SettingsModule } from '../settings/settings.module';
|
||||
import { RoadtripPreferencesService } from './roadtrip-preferences.service';
|
||||
import { RoadtripPreferencesMcp } from './roadtrip-preferences.mcp';
|
||||
import { RoadtripRouterService } from './roadtrip-router.service';
|
||||
import { DayBoundariesController } from './day-boundaries.controller';
|
||||
import { DayBoundariesMcp } from './day-boundaries.mcp';
|
||||
import { DayBoundariesService } from './day-boundaries.service';
|
||||
import { RoadtripPlanService } from './roadtrip-plan.service';
|
||||
import { RoadtripPlanningMcp } from './roadtrip-planning.mcp';
|
||||
import { PluginsRuntimeModule } from '../plugins/plugins-runtime.module';
|
||||
import { MapsModule } from '../maps/maps.module';
|
||||
import { RoadtripPreferencesController } from './roadtrip-preferences.controller';
|
||||
import { RoadtripPreferencesMcp } from './roadtrip-preferences.mcp';
|
||||
import { RoadtripPreferencesService } from './roadtrip-preferences.service';
|
||||
import { RoadtripRouterService } from './roadtrip-router.service';
|
||||
import { RoadtripController } from './roadtrip.controller';
|
||||
import { RoadtripMcp } from './roadtrip.mcp';
|
||||
import { RoadtripService } from './roadtrip.service';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/** Road trip domain (#1797): the points a drive is routed through. Registered in AppModule. */
|
||||
@Module({
|
||||
// McpShared brings the tool guards, Auth the demo check, Permissions the trip guard,
|
||||
// Addons the enabled-check the MCP tools gate on (the controller has @RequireAddon).
|
||||
imports: [McpSharedModule, PermissionsModule, AuthModule, AddonsModule, RealtimeModule, SettingsModule, PluginsRuntimeModule, MapsModule],
|
||||
controllers: [RoadtripController, DayBoundariesController],
|
||||
providers: [RoadtripService, RoadtripMcp, DayBoundariesService, DayBoundariesMcp, RoadtripPreferencesService, RoadtripPreferencesMcp, RoadtripRouterService, RoadtripPlanService, RoadtripPlanningMcp],
|
||||
imports: [
|
||||
McpSharedModule,
|
||||
PermissionsModule,
|
||||
AuthModule,
|
||||
AddonsModule,
|
||||
RealtimeModule,
|
||||
SettingsModule,
|
||||
PluginsRuntimeModule,
|
||||
MapsModule,
|
||||
],
|
||||
controllers: [RoadtripPreferencesController, RoadtripController, DayBoundariesController],
|
||||
providers: [
|
||||
RoadtripService,
|
||||
RoadtripMcp,
|
||||
DayBoundariesService,
|
||||
DayBoundariesMcp,
|
||||
RoadtripPreferencesService,
|
||||
RoadtripPreferencesMcp,
|
||||
RoadtripRouterService,
|
||||
RoadtripPlanService,
|
||||
RoadtripPlanningMcp,
|
||||
],
|
||||
exports: [RoadtripService],
|
||||
})
|
||||
export class RoadtripModule {}
|
||||
|
||||
@@ -624,6 +624,7 @@ export class TripsService {
|
||||
}
|
||||
}
|
||||
|
||||
this.db.prepare('INSERT INTO roadtrip_preferences (trip_id, key, value) SELECT ?, key, value FROM roadtrip_preferences WHERE trip_id = ?').run(newTripId, sourceTripId);
|
||||
const oldBoundaries = this.db.prepare('SELECT * FROM roadtrip_day_boundaries WHERE trip_id = ?').all(sourceTripId) as {
|
||||
day_number: number; from_assignment_id: number; to_assignment_id: number | null; fraction: number;
|
||||
}[];
|
||||
|
||||
Reference in New Issue
Block a user