mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
fix(trips): a day added before the start leaves the plan on its dates
Adding a day before a trip's start with "Keep bookings on their dates" moved almost everything a day earlier and emptied the last day. The day grid was always rebuilt by position: the n-th day row took the n-th date of the new range. With bookings kept on their dates, only timed bookings and stays were re-anchored afterwards. Places, day notes, bookings with no time and a booking's place in a day's order stayed on their re-dated rows and slid to the day before. Days added at both ends had the same problem. planDayGrid now takes keepDates. When the new range still holds every dated day, each of them keeps its date and the new days go around them. The server passes it unless the traveller chose to shift everything, and the trip dialog's warning check uses the same rule. A moved or shorter range still follows the positional rule the dialog describes, and "Shift everything" still moves the whole plan with the new start. Two things keyed outside the day rows followed the old rule. Road trip day boundaries are keyed by day number, so a new first day left each one on the day before its own. They now follow their days to their new numbers and go out to every screen. The owner's leave days moved by the change of start even when days were only added. They now move by as far as the trip's first day moved, which is nothing when days are only added. The help text of the option and the MCP description say what happens when days are added. Closes #3119
This commit is contained in:
@@ -72,6 +72,15 @@ export class RoadtripDayBoundariesRepository extends TrekRepository<RoadtripDayB
|
||||
await this.nativeDelete({ trip: trip_id, day_number });
|
||||
}
|
||||
|
||||
/**
|
||||
* RB4 for several days at once (`DaysService.followDayNumbers`) — `DELETE FROM
|
||||
* roadtrip_day_boundaries WHERE trip_id = ? AND day_number IN (...)`.
|
||||
*/
|
||||
async deleteForDays(trip_id: number, day_numbers: readonly number[]): Promise<void> {
|
||||
if (day_numbers.length === 0) return;
|
||||
await this.nativeDelete({ trip: trip_id, day_number: { $in: [...day_numbers] } });
|
||||
}
|
||||
|
||||
/**
|
||||
* RB5 (`DaysService.shiftBoundariesBack`, the dated append) — `SELECT
|
||||
* day_number FROM roadtrip_day_boundaries WHERE trip_id = ? AND day_number
|
||||
|
||||
@@ -737,6 +737,50 @@ export class DaysService {
|
||||
return { ...appended, trip: await this.getTripForViewer(trip, viewerId) };
|
||||
}
|
||||
|
||||
/**
|
||||
* After the trip's days were laid out again (TripsService.generateDays), each
|
||||
* road trip day boundary follows its day to the number the day now has: they
|
||||
* are keyed by day number, not by day (#3119). `before` is the days as they
|
||||
* were, `rows` the new order. One on a day that went applies to no day and
|
||||
* goes; one on a number no day held stays, unless a day takes that number now.
|
||||
* Two steps, through numbers above every old and new one, since the number is
|
||||
* the primary key and a CHECK keeps it at 1 or above. Returns the list after
|
||||
* the move, or null when nothing changed. Runs inside the caller's transaction.
|
||||
*/
|
||||
async followDayNumbers(
|
||||
tripId: number,
|
||||
before: readonly { id: number; day_number: number }[],
|
||||
rows: readonly { id: number | null }[],
|
||||
): Promise<RoadtripDayBoundary[] | null> {
|
||||
const dayAt = new Map(before.map((d) => [d.day_number, d.id]));
|
||||
const numberOf = new Map<number, number>();
|
||||
rows.forEach((row, i) => {
|
||||
if (row.id !== null) numberOf.set(row.id, i + 1);
|
||||
});
|
||||
// RB6
|
||||
const numbers = await this.roadtripDayBoundariesRepo.listDayNumbers(tripId);
|
||||
const moves: { from: number; to: number }[] = [];
|
||||
const dropped: number[] = [];
|
||||
for (const from of numbers) {
|
||||
const dayId = dayAt.get(from);
|
||||
const to = dayId === undefined ? from : numberOf.get(dayId);
|
||||
if (to === undefined) dropped.push(from);
|
||||
else if (to !== from) moves.push({ from, to });
|
||||
}
|
||||
const taken = new Set(moves.map((m) => m.to));
|
||||
dropped.push(...numbers.filter((n) => !dayAt.has(n) && taken.has(n)));
|
||||
if (moves.length === 0 && dropped.length === 0) return null;
|
||||
// RB4
|
||||
await this.roadtripDayBoundariesRepo.deleteForDays(tripId, dropped);
|
||||
const parked = Math.max(...numbers, ...taken) + 1;
|
||||
// RB7, twice. Within each step every target is distinct, so the order of
|
||||
// the moves does not matter; the second step starts once all are parked.
|
||||
await Promise.all(moves.map((m) => this.roadtripDayBoundariesRepo.moveDayNumber(tripId, m.from, m.from + parked)));
|
||||
await Promise.all(moves.map((m) => this.roadtripDayBoundariesRepo.moveDayNumber(tripId, m.from + parked, m.to)));
|
||||
// RB1
|
||||
return await this.roadtripDayBoundariesRepo.listForTrip(tripId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Boundaries are keyed by day number, so the ones on the days that moved back
|
||||
* move back with them. One at a time and from the last one down: the key is
|
||||
|
||||
@@ -226,6 +226,9 @@ export class TripsController {
|
||||
else logInfo(`${user.email} removed reminder for trip "${result.newTitle}"`);
|
||||
}
|
||||
this.trips.broadcast(id, 'trip:updated', { trip: result.updatedTrip }, socketId);
|
||||
// To every screen, the saving one included: it holds the boundaries outside the trip.
|
||||
if (result.boundaries)
|
||||
this.trips.broadcast(id, 'roadtripBoundary:changed', { boundaries: result.boundaries }, undefined);
|
||||
return { trip: result.updatedTrip };
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof NotFoundError) throw new HttpException({ error: e.message }, 404);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { ValidationError } from '../common/domain-errors';
|
||||
import { MAX_TRIP_DAYS, tripSpanDays, type PermissionKey } from '@trek/shared';
|
||||
import { addIsoDays, MAX_TRIP_DAYS, tripSpanDays, type PermissionKey } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* Pure helpers of the trips domain, moved out of trips.service.ts. Nothing
|
||||
@@ -61,3 +61,23 @@ export function tripUpdatePermissions(body: object): { action: PermissionKey; re
|
||||
if (TRIP_EDIT_FIELDS.some(sent)) needed.push({ action: 'trip_edit', refusal: 'No permission to edit this trip' });
|
||||
return needed;
|
||||
}
|
||||
|
||||
/**
|
||||
* The start the owner's leave days move to when the trip's dates change: the
|
||||
* old start moved by as far as the trip's first dated day moved. When the days
|
||||
* move with a new start, that is the new start; when days were only added
|
||||
* around the plan, the first day kept its date and the leave stays (#3119).
|
||||
* Without a dated day to go by, the new start as it always was.
|
||||
*/
|
||||
export function leaveStartFor(
|
||||
oldStart: string | null | undefined,
|
||||
daysBefore: readonly { id: number; date: string | null }[],
|
||||
dateNow: ReadonlyMap<number, string | null>,
|
||||
newStart: string | null | undefined,
|
||||
): string | null | undefined {
|
||||
const first = daysBefore.find((d) => d.date);
|
||||
const firstNow = first ? dateNow.get(first.id) : null;
|
||||
if (!oldStart || !first?.date || !firstNow) return newStart;
|
||||
const moved = Math.round((Date.parse(`${firstNow}T00:00:00Z`) - Date.parse(`${first.date}T00:00:00Z`)) / 86_400_000);
|
||||
return addIsoDays(oldStart, moved);
|
||||
}
|
||||
|
||||
@@ -251,7 +251,7 @@ export class TripsMcp {
|
||||
.enum(['keep_bookings', 'shift_all'])
|
||||
.optional()
|
||||
.describe(
|
||||
'When changing dates: keep_bookings (default) keeps dated reservations/accommodations on their dates while day plans move; shift_all moves the whole itinerary, bookings included',
|
||||
'When changing dates: keep_bookings (default) leaves everything on its date when days are only added before the start or after the end, and when the trip moves keeps dated reservations/accommodations on their dates while day plans move; shift_all moves the whole itinerary, bookings included',
|
||||
),
|
||||
costs_mode: tripUpdateRequestSchema.shape.costs_mode.describe(
|
||||
'How the trip keeps its costs: split (who paid and who shares each expense, with settling up) or totals (what the trip costs, nothing split). Who paid and the shares stay stored either way. Needs the budget_edit permission rather than trip_edit',
|
||||
@@ -336,13 +336,14 @@ export class TripsMcp {
|
||||
// role, as REST hands it on, so an admin's edit of a trip they do not own is one.
|
||||
const { role } = await this.guards.tripWriter(tripId, ctx.userId);
|
||||
try {
|
||||
const { updatedTrip, removedDays } = await this.trips.update(
|
||||
const { updatedTrip, removedDays, boundaries } = await this.trips.update(
|
||||
tripId,
|
||||
ctx.userId,
|
||||
{ ...fields, date_shift_mode },
|
||||
role,
|
||||
);
|
||||
this.guards.safeBroadcast(tripId, 'trip:updated', { trip: updatedTrip });
|
||||
if (boundaries) this.guards.safeBroadcast(tripId, 'roadtripBoundary:changed', { boundaries });
|
||||
// Only when days went, so the answer to a rename or a longer trip stays as it was.
|
||||
return ok({ trip: updatedTrip, ...(removedDays.length > 0 ? { removed_days: removedDays } : {}) });
|
||||
} catch (err) {
|
||||
|
||||
@@ -173,6 +173,8 @@ export class TripsRpc {
|
||||
role ?? 'user',
|
||||
);
|
||||
this.realtime.broadcast(tripId, 'trip:updated', { trip: result.updatedTrip });
|
||||
if (result.boundaries)
|
||||
this.realtime.broadcast(tripId, 'roadtripBoundary:changed', { boundaries: result.boundaries });
|
||||
return result.updatedTrip;
|
||||
} catch (e) {
|
||||
if (e instanceof ValidationError) throw new BadParams(e.message);
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
type ActiveTrip,
|
||||
type DayGridPlan,
|
||||
type DayGridRemoval,
|
||||
type RoadtripDayBoundary,
|
||||
type TrekWsPayload,
|
||||
type TrekWsTripEventName,
|
||||
type TripUpdateRequest,
|
||||
@@ -52,7 +53,7 @@ import { inOrder } from '../common/in-order';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { legacyBoundIntegerText } from '../common/row-id';
|
||||
import { appClock } from '../common/timezoneService';
|
||||
import { assertTripSpan } from './trips.helpers';
|
||||
import { assertTripSpan, leaveStartFor } from './trips.helpers';
|
||||
|
||||
interface CreateTripData {
|
||||
title: string;
|
||||
@@ -78,6 +79,8 @@ export interface UpdateTripResult {
|
||||
oldReminder: number;
|
||||
/** The day rows a changed range took away, as they stood before; empty when none went. */
|
||||
removedDays: DayGridRemoval[];
|
||||
/** The road trip day boundaries after they followed their days, or null when none moved. */
|
||||
boundaries: RoadtripDayBoundary[] | null;
|
||||
}
|
||||
|
||||
export interface DeleteTripInfo {
|
||||
@@ -88,36 +91,6 @@ export interface DeleteTripInfo {
|
||||
ownerEmail?: string;
|
||||
}
|
||||
|
||||
export interface AddMemberResult {
|
||||
member: { id: number; username: string; email: string; avatar?: string | null; role: string; avatar_url: string | null };
|
||||
targetUserId: number;
|
||||
tripTitle: string;
|
||||
}
|
||||
|
||||
export interface TransferOwnershipResult {
|
||||
tripTitle: string;
|
||||
fromEmail: string;
|
||||
toEmail: string;
|
||||
}
|
||||
|
||||
// ── Guest members (#1362) ───────────────────────────────────────────────────
|
||||
//
|
||||
// A guest is a credential-less users row (is_guest=1) joined into trip_members, so
|
||||
// it is assignable everywhere a real member is (budget splits, packing, to-dos, day
|
||||
// participants) yet can never authenticate (the auth/global-list guards exclude
|
||||
// is_guest=1). The display name lives in users.username so every existing JOIN that
|
||||
// renders a member name shows the guest correctly; a synthetic, non-deliverable
|
||||
// email keeps the UNIQUE/NOT NULL constraints satisfied.
|
||||
|
||||
export interface GuestMember {
|
||||
id: number;
|
||||
username: string;
|
||||
email: string;
|
||||
role: 'member';
|
||||
is_guest: true;
|
||||
avatar_url: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trip aggregate root, DI-native. Membership, the calendar export and the two
|
||||
* read aggregates live in their own domains now; what is left is the write core
|
||||
@@ -330,8 +303,11 @@ export class TripsService {
|
||||
* load-bearing against `UNIQUE(trip_id, day_number)`). The whole rebuild
|
||||
* runs in one `uow.transactional` — a savepoint when `updateTrip`'s own
|
||||
* block already holds the transaction, its own transaction from `create`.
|
||||
* `keepDates` lets every day the new range still holds keep its date (#3119).
|
||||
* The road trip day boundaries follow their days to the numbers they take;
|
||||
* `boundaries` is the list after that, or null when none had to move.
|
||||
*/
|
||||
async generateDays(tripId: number | bigint | string, startDate: string | null, endDate: string | null, dayCount?: number): Promise<DayGridPlan> {
|
||||
async generateDays(tripId: number | bigint | string, startDate: string | null, endDate: string | null, dayCount?: number, keepDates = false): Promise<DayGridPlan & { boundaries: RoadtripDayBoundary[] | null }> {
|
||||
const trip_id = Number(tripId);
|
||||
return await this.uow.transactional(async () => {
|
||||
const existing = await this.daysRepo.listForDayGrid(trip_id); // TP77
|
||||
@@ -343,6 +319,7 @@ export class TripsService {
|
||||
startDate,
|
||||
endDate,
|
||||
dayCount,
|
||||
keepDates,
|
||||
});
|
||||
|
||||
const dateBefore = new Map(existing.map(d => [d.id, d.date]));
|
||||
@@ -356,7 +333,7 @@ export class TripsService {
|
||||
else await this.daysRepo.setDayNumberAndDate(row.id, i + 1, row.date); // TP9
|
||||
}
|
||||
for (const gone of plan.removed) await this.daysRepo.deleteById(gone.id); // TP11
|
||||
return plan;
|
||||
return { ...plan, boundaries: await this.days.followDayNumbers(trip_id, existing, plan.rows) };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -486,6 +463,7 @@ export class TripsService {
|
||||
// The row, the leave entries that follow its dates and the rebuilt day grid are
|
||||
// one write: a failure halfway used to leave a trip whose days missed its dates.
|
||||
let removedDays: DayGridRemoval[] = [];
|
||||
let boundaries: RoadtripDayBoundary[] | null = null; // the road trip day boundaries, when they moved with their days
|
||||
let vacayId: number | undefined; // the vacay plan whose leave days moved along (#2604)
|
||||
await this.uow.transactional(async () => {
|
||||
// Before the row: the rebase reads the outgoing currency off it (#1543).
|
||||
@@ -507,20 +485,27 @@ export class TripsService {
|
||||
costs_mode: newCostsMode,
|
||||
});
|
||||
|
||||
if (trip.start_date && trip.end_date && newStart && newStart !== trip.start_date)
|
||||
vacayId = await this.vacay.shiftOwnerEntriesForTripWindow(trip.user_id, trip.start_date, trip.end_date, newStart);
|
||||
|
||||
if (regenerate) {
|
||||
// Accommodations have no absolute date columns, so their pre-change dates must be
|
||||
// snapshotted before generateDays re-dates the day rows in place.
|
||||
const prevDays = await this.daysRepo.listOrderedForReorder(tripIdNum); // TP26
|
||||
const prevDateByDayId = new Map(prevDays.map(d => [d.id, d.date]));
|
||||
removedDays = (await this.generateDays(tripId, newStart || null, newEnd || null, dayCount)).removed;
|
||||
if (data.date_shift_mode === 'shift_all') {
|
||||
// Unless everything shifts, a range that still holds every day (one more day
|
||||
// before the start or after the end) leaves each day, and all on it, on its
|
||||
// date (#3119); only a moved or shorter range re-dates the days by position.
|
||||
const shiftAll = data.date_shift_mode === 'shift_all';
|
||||
const grid = await this.generateDays(tripId, newStart || null, newEnd || null, dayCount, !shiftAll);
|
||||
removedDays = grid.removed;
|
||||
boundaries = grid.boundaries;
|
||||
const newDays = await this.daysRepo.listOrderedForReorder(tripIdNum); // TP27
|
||||
const newDateByDayId = new Map(newDays.map(d => [d.id, d.date]));
|
||||
// The owner's leave days follow the plan, not the new start (#3119).
|
||||
const leaveStart = leaveStartFor(trip.start_date, prevDays, newDateByDayId, newStart);
|
||||
if (trip.start_date && trip.end_date && leaveStart && leaveStart !== trip.start_date)
|
||||
vacayId = await this.vacay.shiftOwnerEntriesForTripWindow(trip.user_id, trip.start_date, trip.end_date, leaveStart);
|
||||
if (shiftAll) {
|
||||
// Explicit "shift everything": bookings stay glued to their (re-dated) day rows,
|
||||
// so re-stamp reservation_time to follow — same rules as reorderDays/insertDay.
|
||||
const newDays = await this.daysRepo.listOrderedForReorder(tripIdNum); // TP27
|
||||
const newDateByDayId = new Map(newDays.map(d => [d.id, d.date]));
|
||||
await this.days.restampReservationDates(tripIdNum, prevDateByDayId, newDateByDayId);
|
||||
} else {
|
||||
// Default: generateDays re-dates day rows positionally; re-anchor dated bookings to
|
||||
@@ -554,7 +539,7 @@ export class TripsService {
|
||||
// same reasoning as `create`'s TP19 re-select above.
|
||||
const updatedTrip = await this.tripsRepo.findForViewer(tripId, userId);
|
||||
|
||||
return { updatedTrip, changes, isAdminEdit, ownerEmail, newTitle, newReminder, oldReminder, removedDays };
|
||||
return { updatedTrip, changes, isAdminEdit, ownerEmail, newTitle, newReminder, oldReminder, removedDays, boundaries };
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
Reference in New Issue
Block a user