fix(roadtrip): keep the stay on each visit, not on the place (#3092)

A nullable day_assignments.stay_minutes holds the stay of one visit; a visit without one keeps reading the place's duration, so existing trips drive as before. REST PUT /trips/:tripId/assignments/:id/stay and the MCP tool set_assignment_stay write it with day_edit.
This commit is contained in:
Maurice
2026-11-14 17:48:57 +01:00
parent 535761dbd5
commit bac4599d64
40 changed files with 510 additions and 96 deletions
@@ -31,6 +31,7 @@ export class DayAssignments {
accommodation_id?: number | null;
route_excluded: number & Opt = 0;
tour_stage_key?: string | null;
stay_minutes?: number | null;
assignment_participants_collection = new Collection<AssignmentParticipants>(this);
file_links_collection = new Collection<FileLinks>(this);
reservations_collection = new Collection<Reservations>(this);
@@ -70,6 +71,7 @@ export const DayAssignmentsSchema = defineEntity({
accommodation_id: p.integer().nullable().index('idx_day_assignments_accommodation_id'),
route_excluded: p.integer().default(0),
tour_stage_key: p.text().nullable(),
stay_minutes: p.integer().nullable(),
assignment_participants_collection: () => p.oneToMany(AssignmentParticipants).mappedBy('assignment').hidden(),
file_links_collection: () => p.oneToMany(FileLinks).mappedBy('assignment').hidden(),
reservations_collection: () => p.oneToMany(Reservations).mappedBy('assignment').hidden(),
@@ -20,4 +20,5 @@ export interface DayAssignmentsTable {
accommodation_id: InsertOptional<number | null>;
route_excluded: InsertOptional<number>;
tour_stage_key: InsertOptional<string | null>;
stay_minutes: InsertOptional<number | null>;
}
@@ -0,0 +1,20 @@
import { addColumnIfMissing } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* #3092: how long the drive stands at a stop belongs to the visit, not to the
* place. A place planned twice on one road trip day (once to stop, once only to
* steer the route past it) could not be given two different stays, because the
* only value was `places.duration_minutes`.
*
* `stay_minutes` is the visit's own length. It stays null on every existing row,
* and a null visit keeps reading the place's `duration_minutes`, so a trip
* planned before this step drives exactly as it did.
*/
export class Migration20200101046420_a_visit_keeps_its_own_stay extends Migration {
override name = 'Migration20200101046420_a_visit_keeps_its_own_stay';
override async up(): Promise<void> {
await addColumnIfMissing(this, 'day_assignments', 'stay_minutes', 'stay_minutes INTEGER');
}
}
@@ -266,6 +266,8 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
accommodation_id: number | null;
/** MDT-02: one stage of a multi-day tour, by its starting stop's key; absent for the whole tour or a place. */
tour_stage_key?: string | null;
/** #3092: the visit's own stay; absent or null reads the place's. */
stay_minutes?: number | null;
}): Promise<number> {
return await this.insert({
day: input.day_id,
@@ -274,6 +276,7 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
notes: input.notes,
accommodation_id: input.accommodation_id,
tour_stage_key: input.tour_stage_key ?? null,
stay_minutes: input.stay_minutes ?? null,
});
}
@@ -424,6 +427,14 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
await this.nativeUpdate({ id }, { end_day });
}
/**
* `UPDATE day_assignments SET stay_minutes = ? WHERE id = ?` (#3092). Null hands the
* visit back to the stay its place carries.
*/
async setStayMinutes(id: number, stay_minutes: number | null): Promise<void> {
await this.nativeUpdate({ id }, { stay_minutes });
}
/** AS25 — `UPDATE day_assignments SET notes = ? WHERE id = ?`. */
async setNotes(id: number, notes: string | null): Promise<void> {
await this.nativeUpdate({ id }, { notes });
@@ -542,6 +553,8 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
end_day: number;
/** MDT-02: the copied tour keeps its stops' keys, so a day holding one of its stages keeps holding it. */
tour_stage_key?: string | null;
/** #3092: the visit's own stay goes with it. */
stay_minutes?: number | null;
}): Promise<number> {
return await this.insert({
day: input.day_id,
@@ -637,7 +650,9 @@ export class DayAssignmentsRepository extends TrekRepository<DayAssignments> {
'p.lng as lng',
eb.fn.coalesce('a.assignment_time', 'p.place_time').as('time'),
eb.fn.coalesce('a.assignment_end_time', 'p.end_time').as('end_time'),
'p.duration_minutes as duration_minutes',
// A visit's own stay before the place's (#3092): the same place planned twice
// on a day can be stood at for two different lengths.
eb.fn.coalesce('a.stay_minutes', 'p.duration_minutes').as('duration_minutes'),
'a.end_day as end_day',
'a.leg_transport_mode as leg_transport_mode',
'a.incoming_leg_transport_mode as incoming_leg_transport_mode',
@@ -149,8 +149,8 @@ type CalendarReservationKyselyDB = Pick<DB, 'reservations' | 'places' | 'day_acc
/**
* CL4 (`CalendarService.buildTripCalendar`'s assignment read, for every dated
* day at once) — `SELECT da.*, p.name as place_name, p.address as
* place_address, p.lat as place_lat, p.lng as place_lng, p.duration_minutes
* as place_duration_minutes, COALESCE(da.assignment_time, p.place_time) as
* place_address, p.lat as place_lat, p.lng as place_lng, COALESCE(da.stay_minutes,
* p.duration_minutes) as place_duration_minutes, COALESCE(da.assignment_time, p.place_time) as
* effective_time, COALESCE(da.assignment_end_time, p.end_time) as
* effective_end_time FROM
* day_assignments da JOIN places p ON da.place_id = p.id WHERE da.day_id IN
@@ -917,7 +917,7 @@ export class ReservationsRepository extends TrekRepository<Reservations> {
'p.address as place_address',
'p.lat as place_lat',
'p.lng as place_lng',
'p.duration_minutes as place_duration_minutes',
eb.fn.coalesce('da.stay_minutes', 'p.duration_minutes').as('place_duration_minutes'),
eb.fn.coalesce('da.assignment_time', 'p.place_time').as('effective_time'),
eb.fn.coalesce('da.assignment_end_time', 'p.end_time').as('effective_end_time'),
])
@@ -115,6 +115,8 @@ export interface DayAssignmentRow {
route_excluded: number;
/** MDT-02: the stage of a multi-day tour the day holds, by its starting stop's key; null for anything else. */
tour_stage_key: string | null;
/** #3092: how long the drive stands at this visit; null reads the place's `duration_minutes`. */
stay_minutes: number | null;
}
const _dayAssignmentRowKeys: AssertRowKeys<DayAssignmentRow, DayAssignments> = true;
@@ -172,6 +174,7 @@ export interface RoadtripVisitRow {
lng: number | null;
time: string | null;
end_time: string | null;
/** The visit's own stay where it has one (#3092), else the place's. */
duration_minutes: number | null;
end_day: number;
leg_transport_mode: string | null;
@@ -1,6 +1,7 @@
import type { User } from '../../types';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import {
AssignmentCreateDto,
@@ -8,6 +9,7 @@ import {
AssignmentMoveDto,
AssignmentTimeDto,
AssignmentEndDayDto,
AssignmentStayDto,
AssignmentNotesDto,
AssignmentTransportDto,
AssignmentRouteDto,
@@ -15,6 +17,7 @@ import {
} from './assignments.dto';
import { AssignmentsService } from './assignments.service';
import { Body, Controller, Delete, Get, Headers, HttpException, Param, Post, Put, UseGuards } from '@nestjs/common';
import { assignmentResponseSchema } from '@trek/shared';
/**
* /api/trips/:tripId/days/:dayId/assignments — the day's ordered itinerary items.
@@ -221,6 +224,25 @@ export class AssignmentOpsController {
return { assignment };
}
// #3092: the stay of one visit, so two visits of a place can last differently.
// Same guard shape and 404 body as end-day; no reconcile, the stay touches
// neither the day's order nor the journey skeleton.
@RequirePermission('day_edit')
@Put(':id/stay')
@ResponseContract(assignmentResponseSchema)
async stay(
@Param('tripId') tripId: string,
@Param('id') id: string,
@Body() body: AssignmentStayDto,
@Headers('x-socket-id') socketId?: string,
) {
const visit = await this.assignments.getAssignmentForTrip(id, tripId);
if (!visit) throw new HttpException({ error: 'Assignment not found' }, 404);
const assignment = await this.assignments.setStay(visit.id, body.stay_minutes);
this.assignments.broadcast(tripId, 'assignment:updated', { assignment }, socketId);
return { assignment };
}
// #2163: the per-assignment note was write-once (create bodies, MCP, plugin
// RPC) with no edit path anywhere. Same guard shape and 404 body as its
// neighbours; no reconcile — the note doesn't touch the journey skeleton.
@@ -4,6 +4,7 @@ import {
assignmentMoveRequestSchema,
assignmentTimeRequestSchema,
assignmentEndDayRequestSchema,
assignmentStayRequestSchema,
assignmentNotesRequestSchema,
assignmentTransportRequestSchema,
assignmentRouteRequestSchema,
@@ -24,6 +25,7 @@ export class AssignmentReorderDto extends createZodDto(assignmentReorderRequestS
export class AssignmentMoveDto extends createZodDto(assignmentMoveRequestSchema) {}
export class AssignmentTimeDto extends createZodDto(assignmentTimeRequestSchema) {}
export class AssignmentEndDayDto extends createZodDto(assignmentEndDayRequestSchema) {}
export class AssignmentStayDto extends createZodDto(assignmentStayRequestSchema) {}
export class AssignmentNotesDto extends createZodDto(assignmentNotesRequestSchema) {}
export class AssignmentTransportDto extends createZodDto(assignmentTransportRequestSchema) {}
export class AssignmentRouteDto extends createZodDto(assignmentRouteRequestSchema) {}
@@ -17,7 +17,9 @@ import {
idSchema,
assignmentCreateRequestSchema,
assignmentEndDayRequestSchema,
assignmentStayRequestSchema,
type AssignmentEndDayRequest,
type AssignmentStayRequest,
} from '@trek/shared';
import { z } from 'zod';
@@ -102,6 +104,31 @@ export class AssignmentsMcp {
return ok({ assignment });
}
@Tool({
name: 'set_assignment_stay',
description:
'Set how long the road trip stands at this one visit, in minutes. Two visits of the same place keep their own stays: 0 drives past without stopping. Pass null to use the stay of the place (its duration_minutes) again.',
inputSchema: {
tripId: idSchema,
assignmentId: idSchema,
...assignmentStayRequestSchema.shape,
},
annotations: TOOL_ANNOTATIONS_WRITE,
access: { group: 'places', mode: 'write' },
})
async setAssignmentStay(
{ tripId, assignmentId, stay_minutes }: AssignmentStayRequest & { tripId: number; assignmentId: number },
ctx: McpContext,
) {
if (!(await this.assignments.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
if (!(await this.assignments.getAssignmentForTrip(assignmentId, tripId)))
return errorResult('Assignment not found.');
const assignment = await this.assignments.setStay(assignmentId, stay_minutes);
this.guards.safeBroadcast(tripId, 'assignment:updated', { assignment });
return ok({ assignment });
}
@Tool({
name: 'unassign_place',
description: 'Remove a place assignment from a day.',
@@ -566,6 +566,18 @@ export class AssignmentsService {
return await this.getAssignmentWithPlace(idNum);
}
/**
* How long the drive stands at one visit (#3092). The stay used to be the place's
* alone, so the same place planned twice on a day could not be stopped at once and
* only driven past the other time. Null hands the visit back to the place's own
* `duration_minutes`. No auto-sort and no journey reconcile: a stay moves neither
* the day's order nor the skeleton mirror.
*/
async setStay(id: number, stayMinutes: number | null) {
await this.dayAssignmentsRepo.setStayMinutes(id, stayMinutes);
return await this.getAssignmentWithPlace(id);
}
/**
* Edit the per-assignment note after creation (#2163) — until now the note
* was write-once via the create paths (REST body, MCP tools, plugin RPC) and
+2
View File
@@ -38,6 +38,8 @@ export function formatAssignmentWithPlace(
assignment_time: a.assignment_time ?? null,
assignment_end_time: a.assignment_end_time ?? null,
end_day: a.end_day === 1,
// How long the drive stands at this visit (#3092); null reads the place's duration_minutes.
stay_minutes: a.stay_minutes ?? null,
leg_transport_mode: a.leg_transport_mode ?? null,
incoming_leg_transport_mode: a.incoming_leg_transport_mode ?? null,
// Kept on the day but not driven to (#2532).
+1
View File
@@ -198,6 +198,7 @@ export class DaysService {
day_id: a.day_id,
order_index: a.order_index,
end_day: a.end_day === 1,
stay_minutes: a.stay_minutes ?? null,
route_excluded: a.route_excluded === 1,
notes: a.notes,
// Repeated here for the same reason stop_type is: the day list hides the stop
+1
View File
@@ -753,6 +753,7 @@ export class TripsService {
reservation_status: a.reservation_status, reservation_notes: a.reservation_notes,
reservation_datetime: a.reservation_datetime, assignment_time: a.assignment_time,
assignment_end_time: a.assignment_end_time, end_day: a.end_day ?? 0, tour_stage_key: a.tour_stage_key,
stay_minutes: a.stay_minutes ?? null,
});
assignmentMap.set(a.id, newAssignmentId);
}