fix(roadtrip): keep the shaping a traveller did, through every path that moves a stop

A via records which stop it follows by POSITION, so anything that renumbers a
day's stops moves the ground under it. The road-trip rail corrects for that;
almost nothing else did.

reanchor() never renumbered `sequence`. It is allocated per leg and starts at 0
in each, and re-anchoring MERGES two legs whenever the stop between them goes
away — so leg A's 0,1 ended up beside leg B's 0,1, and everything that draws the
route orders by sequence. The drive ran A0, B0, A1, B1: forward, back, and
forward again. Persisted, surviving a reload, and unrepairable except by deleting
the vias. The old anchor is read before the updates and used as the primary sort
key, so the vias of the earlier leg stay ahead of the ones that merged into it.

Reordering the only two stops of a day deleted every via on it. A reorder is
modelled as remove-then-insert, and the removal half refuses to treat a two-stop
day as still having a drive — right when a stop really goes away, catastrophic
when nothing was removed. Two stops is exactly the shape "follow this track"
produces, up to nine vias on that one leg, gone to a single drag with no prompt
and no undo.

Removing a stop, reordering within a day, and assigning a place mid-day never
re-anchored at all, though the helpers exist and three other paths use them. The
detour then sat on a leg the traveller never chose, or on a leg that no longer
existed and vanished — until a later stop brought it back bending a road nobody
asked for. Reordering hands a whole new ordering rather than one move, so the
anchors there follow the stop they were pinned behind instead of arithmetic on
the index, which is correct for any permutation.

Duplicating a trip dropped all of it: `stop_type` was missing from the place
insert, and neither via nor day-track table was copied. The duplicate looked
complete and quietly drove somewhere else.

A failed read of the via list emptied it. That read runs after every write and
feeds the routing key, so a 502, a dropped connection or a tab going offline
re-routed the whole trip along the roads the traveller had steered away from,
with nothing said and nothing retried — indistinguishable from having deleted
them. Only a 404 or 403 empties now; anything else keeps the last known list and
says it may be stale.
This commit is contained in:
Maurice
2026-09-07 14:00:22 +02:00
committed by Maurice
parent c1f7587704
commit 1e1dd9b814
18 changed files with 579 additions and 28 deletions
+19 -2
View File
@@ -7,7 +7,7 @@ import { DatabaseService, type TripAccess } from '../database/database.service';
import type { PlaceWithTags } from '../database/database.service';
import { PermissionsService } from '../permissions/permissions.service';
import { MapsService, GOOGLE_SHORT_HOSTS, isGoogleMapsHost } from '../maps/maps.service';
import { parseDirectionsUrl } from './maps-dir.helpers';
import { isDirectionsUrl, parseDirectionsUrl } from './maps-dir.helpers';
import type { Place, User } from '../../types';
import { QueryHelpersService } from '../query-helpers/query-helpers.service';
import { ratingAggregate } from '../common/rowShape';
@@ -948,6 +948,18 @@ export class PlacesService {
}
}
// A route, once the redirect is followed. The dispatch upstream decides on
// the raw URL, and a short link's path is `/<code>` — it matches nothing, so
// every route shared from the Google Maps app arrived here and was answered
// with "could not extract list ID", which is the complaint the directions
// import was written to remove. The Share sheet on a phone produces exactly
// this shape, and the box says a directions link works.
//
// Handed on with the resolved URL, so the hop is not made twice.
if (isDirectionsUrl(resolvedUrl)) {
return this.importGoogleDirections(tripId, resolvedUrl, opts);
}
// Pattern: /placelists/list/{ID}
const plMatch = resolvedUrl.match(/placelists\/list\/([A-Za-z0-9_-]+)/);
if (plMatch) listId = plMatch[1];
@@ -1155,7 +1167,12 @@ export class PlacesService {
}
if (!wp.name) continue;
try {
const hits = await this.maps.searchNominatim(wp.name);
// Background lane, which is what this method's own contract asks of a
// bulk caller: up to thirty sequential lookups, each taking the next
// slot on a 1.1 s process-wide throttle. On the interactive lane every
// other member of the instance typing in the place search box waits
// behind the whole import.
const hits = await this.maps.searchNominatim(wp.name, undefined, 'background');
const hit = hits.find((h) => h.lat !== null && h.lng !== null);
// The name from the link, not the one the geocoder answers with: somebody who
// typed a nickname into Google should not find a street address on their trip.
@@ -182,8 +182,20 @@ export class RoadtripService {
input: { vias: { id: number; after_order_index: number }[]; remove?: number[] },
): RoadtripVia[] {
return this.db.transaction(() => {
// Read before writing: the OLD anchor is what says which of two merged
// legs came first, and after the updates that information is gone.
const before = new Map(
this.db
.all<{ id: number; after_order_index: number; sequence: number }>(
'SELECT id, after_order_index, sequence FROM roadtrip_vias WHERE day_id = ?',
dayId,
)
.map((v) => [v.id, v]),
);
for (const id of input.remove ?? []) {
this.db.run('DELETE FROM roadtrip_vias WHERE id = ? AND day_id = ?', id, dayId);
before.delete(id);
}
for (const via of input.vias) {
this.db.run(
@@ -193,6 +205,44 @@ export class RoadtripService {
dayId,
);
}
// Renumber, because `sequence` is allocated per leg and starts at 0 in
// each. Re-anchoring MERGES two legs whenever a stop between them goes
// away, and their two independent series then sit side by side: leg A's
// 0,1 next to leg B's 0,1. Everything that draws the route orders by
// sequence, so the drive ran through A0, B0, A1, B1 — forward, back, and
// forward again — and the wrong order was persisted, survived a reload
// and could not be repaired except by deleting the vias.
//
// The old anchor is the primary key of the sort: the vias of the earlier
// leg belong ahead of the ones from the leg that merged into it. Old
// sequence orders within a leg, and the id settles the rest so the result
// never depends on row order.
const rows = this.db.all<{ id: number; after_order_index: number }>(
'SELECT id, after_order_index FROM roadtrip_vias WHERE day_id = ?',
dayId,
);
const byLeg = new Map<number, { id: number }[]>();
for (const row of rows) {
const list = byLeg.get(row.after_order_index) ?? [];
list.push(row);
byLeg.set(row.after_order_index, list);
}
for (const list of byLeg.values()) {
list.sort((a, b) => {
const pa = before.get(a.id);
const pb = before.get(b.id);
return (
(pa?.after_order_index ?? 0) - (pb?.after_order_index ?? 0) ||
(pa?.sequence ?? 0) - (pb?.sequence ?? 0) ||
a.id - b.id
);
});
list.forEach((row, index) => {
this.db.run('UPDATE roadtrip_vias SET sequence = ? WHERE id = ? AND day_id = ?', index, row.id, dayId);
});
}
return this.listForDay(dayId);
});
}
+36 -3
View File
@@ -552,17 +552,50 @@ export class TripsService {
INSERT INTO places (trip_id, name, description, lat, lng, address, category_id, price, currency,
reservation_status, reservation_notes, reservation_datetime, place_time, end_time,
duration_minutes, notes, image_url, google_place_id, google_ftid, website, phone, transport_mode, osm_id,
route_geometry, route_color)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
route_geometry, route_color, stop_type)
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
`);
for (const p of oldPlaces) {
const r = insertPlace.run(newTripId, p.name, p.description, p.lat, p.lng, p.address, p.category_id,
p.price, p.currency, p.reservation_status, p.reservation_notes, p.reservation_datetime,
p.place_time, p.end_time, p.duration_minutes, p.notes, p.image_url, p.google_place_id,
p.google_ftid, p.website, p.phone, p.transport_mode, p.osm_id, p.route_geometry, p.route_color);
p.google_ftid, p.website, p.phone, p.transport_mode, p.osm_id, p.route_geometry, p.route_color,
p.stop_type);
placeMap.set(p.id, r.lastInsertRowid);
}
// The road-trip shaping goes with the copy. A via is not decoration: it is
// the road the traveller chose over the one the router prefers, and a day
// track is the line a day was fitted to. Leaving them behind gave back a
// trip that looks complete and quietly drives somewhere else — visible
// only once somebody starts editing the copy, with nothing to recover
// from. Both tables are keyed by day, so they ride on `dayMap`.
const oldVias = this.db.prepare(`
SELECT v.* FROM roadtrip_vias v JOIN days d ON d.id = v.day_id WHERE d.trip_id = ?
`).all(sourceTripId) as any[];
const insertVia = this.db.prepare(
'INSERT INTO roadtrip_vias (day_id, after_order_index, sequence, lat, lng) VALUES (?, ?, ?, ?, ?)',
);
for (const v of oldVias) {
const newDayId = dayMap.get(v.day_id);
if (newDayId) insertVia.run(newDayId, v.after_order_index, v.sequence, v.lat, v.lng);
}
const oldTracks = this.db.prepare(`
SELECT t.* FROM roadtrip_day_tracks t JOIN days d ON d.id = t.day_id WHERE d.trip_id = ?
`).all(sourceTripId) as any[];
const insertTrack = this.db.prepare(
'INSERT INTO roadtrip_day_tracks (day_id, place_id, stray_km) VALUES (?, ?, ?)',
);
for (const t of oldTracks) {
const newDayId = dayMap.get(t.day_id);
// The track is a place of the trip, so it has been copied too — but skip
// the row rather than point it at the original, the way the assignment
// and accommodation loops below skip an id they cannot map.
const newPlaceId = placeMap.get(t.place_id);
if (newDayId && newPlaceId) insertTrack.run(newDayId, newPlaceId, t.stray_km);
}
const oldTags = this.db.prepare(`
SELECT pt.* FROM place_tags pt JOIN places p ON p.id = pt.place_id WHERE p.trip_id = ?
`).all(sourceTripId) as any[];