diff --git a/client/src/components/Map/MapView.tsx b/client/src/components/Map/MapView.tsx index 2e728988d..8644dab70 100644 --- a/client/src/components/Map/MapView.tsx +++ b/client/src/components/Map/MapView.tsx @@ -3,7 +3,7 @@ import DOM from 'react-dom' import { categoryIconSvg } from './categoryIconSvg' import { MapContainer, TileLayer, Marker, Polyline, CircleMarker, Circle, useMap, Tooltip } from 'react-leaflet' import MarkerClusterGroup from 'react-leaflet-cluster' -import { makeMarkerDraggable, makePoiDraggable } from './markerDrag' +import { makeMarkerDraggable } from './markerDrag' import { CLUSTER_OPTIONS, createClusterIcon, revealInCluster, type ClusterGroupLike } from './markerCluster' import RoadtripViaMarkers from './RoadtripViaMarkers' import PlannerWaypointMarker from './PlannerWaypointMarker' @@ -55,11 +55,10 @@ import type { Day, Place, Reservation, RouteVia } from '../../types' import type { MapHoverInfo } from './mapHover' import { nightPauseMarker, NIGHT_PAUSE_MIN_ZOOM } from './nightPauseMarker' import NightPauseTooltip from './NightPauseTooltip' -import ClusteredPois from './ClusteredPois' +import PoiMarkers from './PoiMarkers' import { NightPauseDrag } from './NightPauseDrag' import type { DayBoundaryControls } from './dayBoundaryDrag' import type { Poi } from './poiCategories' -import { poiDetailRowKey, poiDetailRows, poiPinCacheKey, poiPinParts } from './poiMarker' import { resolveTrackColor, hasManualTrackColor } from './trackColors' import { SelectedTrackLine, TrackLines } from './TrackLines' import DawarichTrailLayer from './DawarichTrailLayer' @@ -228,59 +227,6 @@ function createPlaceIcon(place, orderNumbers, isSelected) { return fallbackIcon } -// Small coloured pin for an OSM "explore" POI — distinct from the photo-circle -// markers of planned places; the colour matches its pill category. -const poiIconCache = new Map() -function createPoiIcon(poi: Pick, brandWikidata?: string | null) { - // One flat disc in the category's colour with its icon, and never the chain's logo. - // The brands turned a corridor full of petrol stations into a row of advertisements, - // they were unreadable at pin size, and a brand with no logo on file fell back to a - // different picture entirely — so no two pins looked alike. `brandWikidata` is kept in - // the signature because the callers still have it; it simply no longer changes anything. - void brandWikidata - // A plugin category's key carries its colour and icon too, so two looks never share a pin. - const cacheKey = poiPinCacheKey(poi) - const cached = poiIconCache.get(cacheKey) - if (cached) return cached - const { color, svg } = poiPinParts(poi) - const icon = L.divIcon({ - className: '', - html: `
${svg}
`, - iconSize: [26, 26], - iconAnchor: [13, 13], - tooltipAnchor: [0, -14], - }) - poiIconCache.set(cacheKey, icon) - return icon -} - -/** - * The hover tooltip of an explore POI: its name, and for a plugin POI the rows the - * plugin knows about it (the GL hover card shows the same, see buildPoiPopupHtml). - * React text throughout, so nothing a plugin sends is ever read as markup. A POI - * without rows keeps the bare name it has always had. - */ -function PoiTooltipBody({ poi }: Readonly<{ poi: Poi }>) { - const rows = poiDetailRows(poi) - if (!rows.length) return poi.name - // w-max because Leaflet's tooltip pane is 0px wide: without an intrinsic width the - // tooltip shrinks to its narrowest layout and the values wrap a letter per line. The - // label column stops at 45% and wraps, so a long label leaves its value room too. - return ( -
-
{poi.name}
-
- {rows.map(row => ( -
- {row.label} - {row.value} -
- ))} -
-
- ) -} - // Clears the hover tooltip the moment the camera starts moving and suppresses // re-showing it until the move ends: after a click-recenter the marker slides // away under a stationary cursor, so the browser never fires mouseout — and @@ -523,8 +469,8 @@ import { useIsPhone } from '../../mobile/useIsPhone' import type { GeoPosition, TrackingMode } from '../../hooks/useGeolocation' import { selectedPlaceTarget } from './selectedPlaceTarget' import { LngFrameProvider, useLngFrame, useTripLngFrame } from './lngFrameContext' -import { frameLine, frameLng, viewLngFrame, type LngFrame } from '../../utils/lngFrame' -import { LngFrameFollower, MapClickHandler, MapContextMenuHandler, PoiDropTarget, ViewCenterTracker, ViewportController } from './leafletMapBridges' +import { frameLine, frameLng } from '../../utils/lngFrame' +import { LngFrameFollower, MapClickHandler, MapContextMenuHandler, PoiDropTarget, ViewportController } from './leafletMapBridges' function LeafletLocationLayer({ position: fix, mode }: { position: GeoPosition | null; mode: TrackingMode }) { const map = useMap() @@ -761,8 +707,6 @@ export const MapView = memo(function MapView({ // that is decides which layer draws it. A saved raster template still wins, // the default is a vector style. const basemap = useMemo(() => resolveBasemap(tileUrl, OFM_POSITRON), [tileUrl]) - const poiClickRef = useRef(onPoiClick) - poiClickRef.current = onPoiClick /** * Amap's tiles are drawn in GCJ-02 (see gcj02Crs.ts). The projection has to be * decided before the map is constructed, because Leaflet cannot change a map's @@ -774,34 +718,6 @@ export const MapView = memo(function MapView({ // drawn in a longitude frame that keeps it on one copy (#2975). Null for every other // trip, and then each layer below draws exactly what it always drew. const lngFrame = useTripLngFrame(places, dayPlaces, reservations) - // The POIs are fetched for the visible area, which can lie outside the trip's frame - // or on another world copy, so they are drawn on the copy in view instead. - const [poiFrame, setPoiFrame] = useState(null) - const followView = useCallback((centerLng: number) => setPoiFrame(current => viewLngFrame(current, centerLng)), []) - const poiMarkers = useMemo(() => (pois as Poi[]).map((poi: Poi) => ( - onPoiClick?.(poi), - // Wired on add rather than in a layout effect: Leaflet builds the icon element - // itself, and this is the first moment there is one to attach to. - add: (e: { target: { getElement: () => HTMLElement | undefined } }) => { - const el = e.target.getElement() - if (!el) return - // Native clicks avoid Leaflet suppressing a click after an earlier map drag. - el.setAttribute('aria-label', poi.name) - el.onclick = event => { event.stopPropagation(); poiClickRef.current?.(poi) } - if (onPoiDropOnRoute) makePoiDraggable(el, poi.osm_id) - }, - }} - > - - - )), [pois, onPoiClick, onPoiDropOnRoute, poiFrame]) const visibleReservations = useMemo(() => ( visibleRouteReservations(reservations, { visibleConnectionIds, showTransitRoutes, selectedDayId, days, scopeConnectionsToDay }) ), [reservations, visibleConnectionIds, showTransitRoutes, selectedDayId, days, scopeConnectionsToDay]) @@ -1083,7 +999,6 @@ export const MapView = memo(function MapView({ - @@ -1228,7 +1143,7 @@ export const MapView = memo(function MapView({ hiddenDates={dawarichHiddenDates} casingPane={hasCasingPane ? TRACK_CASING_PANE : undefined} /> - {poiMarkers} + {/* Charging stops / rest areas a plugin route places on the drawn day route. Host-vetted data (server-normalized), rendered as plain tone dots. */} {(routeVias as RouteVia[]).filter(v => !v.nightPause || mapZoom >= NIGHT_PAUSE_MIN_ZOOM).map((v, i) => ( diff --git a/client/src/components/Map/PoiMarkers.tsx b/client/src/components/Map/PoiMarkers.tsx new file mode 100644 index 000000000..f94f7211e --- /dev/null +++ b/client/src/components/Map/PoiMarkers.tsx @@ -0,0 +1,133 @@ +import L from 'leaflet'; +import { useEffect, useMemo, useRef, useState } from 'react'; +import { Marker, Tooltip, useMap } from 'react-leaflet'; +import { frameLng, viewLngFrame, type LngFrame } from '../../utils/lngFrame'; +import ClusteredPois from './ClusteredPois'; +import { makePoiDraggable } from './markerDrag'; +import type { Poi } from './poiCategories'; +import { poiDetailRowKey, poiDetailRows, poiPinCacheKey, poiPinParts } from './poiMarker'; + +// Small coloured pin for an OSM "explore" POI — distinct from the photo-circle +// markers of planned places; the colour matches its pill category. +const poiIconCache = new Map(); +function createPoiIcon(poi: Pick) { + // One flat disc in the category's colour with its icon, and never the chain's logo. + // The brands turned a corridor full of petrol stations into a row of advertisements, + // they were unreadable at pin size, and a brand with no logo on file fell back to a + // different picture entirely — so no two pins looked alike. + // A plugin category's key carries its colour and icon too, so two looks never share a pin. + const cacheKey = poiPinCacheKey(poi); + const cached = poiIconCache.get(cacheKey); + if (cached) return cached; + const { color, svg } = poiPinParts(poi); + const icon = L.divIcon({ + className: '', + html: `
${svg}
`, + iconSize: [26, 26], + iconAnchor: [13, 13], + tooltipAnchor: [0, -14], + }); + poiIconCache.set(cacheKey, icon); + return icon; +} + +/** + * The hover tooltip of an explore POI: its name, and for a plugin POI the rows the + * plugin knows about it (the GL hover card shows the same, see buildPoiPopupHtml). + * React text throughout, so nothing a plugin sends is ever read as markup. A POI + * without rows keeps the bare name it has always had. + */ +function PoiTooltipBody({ poi }: Readonly<{ poi: Poi }>) { + const rows = poiDetailRows(poi); + if (!rows.length) return poi.name; + // w-max because Leaflet's tooltip pane is 0px wide: without an intrinsic width the + // tooltip shrinks to its narrowest layout and the values wrap a letter per line. The + // label column stops at 45% and wraps, so a long label leaves its value room too. + return ( +
+
{poi.name}
+
+ {rows.map((row) => ( +
+ {row.label} + {row.value} +
+ ))} +
+
+ ); +} + +/** + * The explore POIs of the Leaflet map, clustered when asked. They are fetched for the + * visible area, which can lie outside the trip's longitude frame or on another world + * copy, so they are drawn on the copy in view, followed as the view moves (#2975). + */ +export default function PoiMarkers({ + pois, + clusterLoosely, + onPoiClick, + draggable, +}: { + pois: Poi[]; + clusterLoosely: boolean; + onPoiClick?: (poi: Poi) => void; + /** Whether a pin can be dragged onto the route. */ + draggable: boolean; +}) { + const map = useMap(); + const [frame, setFrame] = useState(null); + useEffect(() => { + const follow = () => setFrame((current) => viewLngFrame(current, map.getCenter().lng)); + map.whenReady(follow); + map.on('moveend', follow); + return () => { + map.off('moveend', follow); + }; + }, [map]); + // Native clicks keep the newest handler without rebuilding every marker. + const clickRef = useRef(onPoiClick); + useEffect(() => { + clickRef.current = onPoiClick; + }, [onPoiClick]); + + const markers = useMemo( + () => + pois.map((poi) => ( + onPoiClick?.(poi), + // Wired on add rather than in a layout effect: Leaflet builds the icon element + // itself, and this is the first moment there is one to attach to. + add: (e: { target: { getElement: () => HTMLElement | undefined } }) => { + const el = e.target.getElement(); + if (!el) return; + // Native clicks avoid Leaflet suppressing a click after an earlier map drag. + el.setAttribute('aria-label', poi.name); + el.onclick = (event) => { + event.stopPropagation(); + clickRef.current?.(poi); + }; + if (draggable) makePoiDraggable(el, poi.osm_id); + }, + }} + > + + + + + )), + [pois, onPoiClick, draggable, frame] + ); + + return ( + + {markers} + + ); +} diff --git a/client/src/components/Map/leafletMapBridges.tsx b/client/src/components/Map/leafletMapBridges.tsx index c0dbe6c8d..4bd32f4f3 100644 --- a/client/src/components/Map/leafletMapBridges.tsx +++ b/client/src/components/Map/leafletMapBridges.tsx @@ -57,23 +57,6 @@ export function ViewportController({ onViewportChange }: { onViewportChange?: Ma return null; } -/** - * Reports the longitude of the view's centre once the map is laid out and after every - * move, for the layers drawn on the world copy in view rather than in the trip's frame. - */ -export function ViewCenterTracker({ onChange }: { onChange: (centerLng: number) => void }) { - const map = useMap(); - useEffect(() => { - const emit = () => onChange(map.getCenter().lng); - map.whenReady(emit); - map.on('moveend', emit); - return () => { - map.off('moveend', emit); - }; - }, [map, onChange]); - return null; -} - /** * Moves the view along when the longitude frame changes under it (#2975): the trip * is then drawn one world further east or west, and a view left where it was would diff --git a/client/src/components/Planner/DayPlanSidebar.tsx b/client/src/components/Planner/DayPlanSidebar.tsx index 0b5999051..53e085c4a 100644 --- a/client/src/components/Planner/DayPlanSidebar.tsx +++ b/client/src/components/Planner/DayPlanSidebar.tsx @@ -1122,8 +1122,7 @@ function useDayPlanSidebar(props: DayPlanSidebarProps) { const budgetItems = useTripStore(s => s.budgetItems) const costsEnabled = useAddonStore(s => s.isEnabled('budget')) const totalCostLabel = useMemo(() => { - const costs = planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency: currency, displayCurrency: costBase }) - return formatMoneySum(costs.total, costBase, locale, fxRates) + return formatMoneySum(planCosts({ days, assignments, reservations, budgetItems, costsEnabled, tripCurrency: currency, displayCurrency: costBase }).total, costBase, locale, fxRates) }, [days, assignments, reservations, budgetItems, costsEnabled, currency, costBase, locale, fxRates]) return { diff --git a/server/src/db/repositories/CollectionPlaces.repository.ts b/server/src/db/repositories/CollectionPlaces.repository.ts index 22d0c802e..73685b7fd 100644 --- a/server/src/db/repositories/CollectionPlaces.repository.ts +++ b/server/src/db/repositories/CollectionPlaces.repository.ts @@ -145,17 +145,6 @@ export class CollectionPlacesRepository extends TrekRepository return row?.image_url; } - /** `deleteCollection`'s pre-delete read: every saved place's image, released once the list and its places are gone. */ - async imageUrlsOf(collectionId: number): Promise> { - const rows = await this.db_() - .selectFrom('collection_places') - .select('image_url') - .where('collection_id', '=', collectionId) - .where('image_url', 'is not', null) - .execute(); - return rows.map((row) => row.image_url); - } - /** * CL48 (`updatePlace`, TX) — the allow-listed dynamic `UPDATE * collection_places SET ... WHERE id=?`, including the cross-list move diff --git a/server/src/db/repositories/Collections.repository.ts b/server/src/db/repositories/Collections.repository.ts index 78c498a1e..ff446bd69 100644 --- a/server/src/db/repositories/Collections.repository.ts +++ b/server/src/db/repositories/Collections.repository.ts @@ -254,6 +254,23 @@ export class CollectionsRepository extends TrekRepository { await this.readDb().deleteFrom('collections').where('id', '=', id).execute(); } + /** + * `deleteCollection`: deletes a list like `deleteById` and hands back the uploads it + * named, its cover and its saved places' images, read before the cascade takes their + * rows, so they can go like a single place's do once nothing else names them (#2924). + */ + async deleteWithImages(id: number): Promise> { + const cover = (await this.coverImage(id)) ?? null; + const places = await this.readDb() + .selectFrom('collection_places') + .select('image_url') + .where('collection_id', '=', id) + .where('image_url', 'is not', null) + .execute(); + await this.deleteById(id); + return [cover, ...places.map((place) => place.image_url)]; + } + /** * CL36 (`reorderCollections`, TX `:712`) — `UPDATE collections SET * sort_order=? WHERE id=?`, looped per visible id. The legacy statement diff --git a/server/src/nest/budget/budget-money.helpers.ts b/server/src/nest/budget/budget-money.helpers.ts index b17a11e59..15507fc1f 100644 --- a/server/src/nest/budget/budget-money.helpers.ts +++ b/server/src/nest/budget/budget-money.helpers.ts @@ -238,3 +238,79 @@ export function settlementFx(opts: { sCurrency ? tripConverter(sCurrency, sRate, tripCurrency, rates) : (amount: number) => amount / displayFactor; return { currency, displayFactor, displayUnit, toDisplay, converterFor, settleConverterFor, isDirect }; } + +/** One member's settlement ledger: trip-currency cents and display-currency hundredths. */ +interface LedgerHalves { + cents: number; + direct: number; +} + +/** What `netOppositeHalves` hands back when nothing moves. */ +const NOTHING_BACK = { back: 0, backExact: 0 } as const; + +/** + * When the two halves point opposite ways between a pair (the payer is owed in + * display-currency expenses but owes more in the trip currency: one paid a euro train, + * the other a yen hotel), a transfer in the display currency settles the net of both. + * The display-currency credit then moves into the trip half at this transfer's frozen + * rate, against the trip debt it was netted with. Left where it was, it stayed fixed + * while the yen it offset floated with the live rate, and a settled trip reopened as + * soon as the rate moved (#1445). Only as much moves as both halves hold, in whole + * steps of the display currency, so neither side ends up owing the other way. + * + * Only for a transfer in the display currency that moves money (`applies`). Moves it + * on `from` and `to` and returns the hundredths moved (`back`) and their exact + * trip-currency value in cents (`backExact`). + */ +function netOppositeHalves( + applies: boolean, + from: LedgerHalves, + to: LedgerHalves, + convert: (amount: number) => number, + displayUnit: number, +): { back: number; backExact: number } { + if (!applies) return NOTHING_BACK; + const directRoom = Math.min(from.direct, -to.direct); + const tripRoom = Math.min(-from.cents, to.cents); + if (directRoom <= 0 || tripRoom <= 0) return NOTHING_BACK; + const fits = Math.round(tripRoom / convert(1) / displayUnit) * displayUnit; + const back = Math.max(0, Math.min(directRoom, fits)); + const backExact = convert(back / 100) * 100; + const backTrip = Math.round(backExact); + from.direct -= back; + to.direct += back; + from.cents += backTrip; + to.cents -= backTrip; + return { back, backExact }; +} + +/** + * Books one settle-up transfer on the payer's (`from`) and the receiver's (`to`) ledger. + * A transfer in the display currency first pays what the payer owes the receiver in + * display-currency expenses, as typed (#2965), in whole steps of the display currency + * like the direct half it pays (#2604). Only the rest goes through the trip currency at + * its frozen rate, which keeps a debt in the trip currency settled when rates move + * (#1445), rounded to a trip cent per transfer so no sliver of a cent builds up over a + * trip. Halves pointing opposite ways then settle as their net (`netOppositeHalves`). + */ +export function applyTransfer( + from: LedgerHalves, + to: LedgerHalves, + amount: number, + inDisplay: boolean, + convert: (amount: number) => number, + displayUnit: number, +): { paidDirect: number; exact: number; back: number; backExact: number } { + const total = Math.round(amount * 100); + const room = inDisplay ? Math.max(0, Math.min(-from.direct, to.direct)) : 0; + const paidDirect = total > 0 ? Math.floor(Math.min(total, room) / displayUnit) * displayUnit : 0; + from.direct += paidDirect; + to.direct -= paidDirect; + const rest = total === 0 ? 0 : (total - paidDirect) / total; + const exact = convert(amount) * 100 * rest; + const inTrip = Math.round(exact); + from.cents += inTrip; + to.cents -= inTrip; + const { back, backExact } = netOppositeHalves(inDisplay && total > 0, from, to, convert, displayUnit); + return { paidDirect, exact, back, backExact }; +} diff --git a/server/src/nest/budget/budget.service.ts b/server/src/nest/budget/budget.service.ts index b7465a358..07cfa656d 100644 --- a/server/src/nest/budget/budget.service.ts +++ b/server/src/nest/budget/budget.service.ts @@ -31,7 +31,7 @@ import { BUDGET_ITEM_TICKET, RESERVATION_METADATA } from '../../db/json-columns' import { decodeJson, decodeJsonResult, encodeJson } from '../../utils/json-column'; import { DomainError } from '../common/domain-error'; import { GUEST_HAS_PAYMENTS, shareAfterLeaving } from './budget-departure.helpers'; -import { customSplitCents, isFrozenRate, NOT_FROZEN_RATE, settlementFx, summaryShareCents, sumMoney, tripConverter } from './budget-money.helpers'; +import { applyTransfer, customSplitCents, isFrozenRate, NOT_FROZEN_RATE, settlementFx, summaryShareCents, sumMoney, tripConverter } from './budget-money.helpers'; type Trip = TripAccess; @@ -1230,48 +1230,8 @@ export class BudgetService { } const from = ensureSettled(s.from_user_id, s.from_username, s.from_avatar_url); const to = ensureSettled(s.to_user_id, s.to_username, s.to_avatar_url); - // A transfer in the display currency first pays what the payer owes the - // receiver in display-currency expenses, as typed (#2965); only the rest - // goes through the trip currency at its frozen rate, which keeps a debt - // in the trip currency settled when rates move (#1445). - const total = Math.round(s.amount * 100); - const inDisplay = isDirect(s.currency); - const room = inDisplay ? Math.max(0, Math.min(-from.direct, to.direct)) : 0; - // In whole steps of the display currency, like the direct half it pays (#2604). - const paidDirect = total > 0 ? Math.floor(Math.min(total, room) / displayUnit) * displayUnit : 0; - from.direct += paidDirect; - to.direct -= paidDirect; - // 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 rest = total === 0 ? 0 : (total - paidDirect) / total; - const exact = convert(s.amount) * 100 * rest; - const inTrip = Math.round(exact); - from.cents += inTrip; - to.cents -= inTrip; - // When the two halves point opposite ways between this pair (the payer is owed - // in display-currency expenses but owes more in the trip currency: one paid a - // euro train, the other a yen hotel), the transfer settles the net of both. - // The display-currency credit then moves into the trip half at this - // transfer's frozen rate, against the trip debt it was netted with. Left where - // it was, it stayed fixed while the yen it offset floated with the live rate, - // and a settled trip reopened as soon as the rate moved (#1445). Only as much - // moves as both halves hold, so neither side ends up owing the other way. - let back = 0; - let backExact = 0; - if (inDisplay && total > 0) { - const directRoom = Math.min(from.direct, -to.direct); - const tripRoom = Math.min(-from.cents, to.cents); - if (directRoom > 0 && tripRoom > 0) { - const fits = Math.round(tripRoom / convert(1) / displayUnit) * displayUnit; - back = Math.max(0, Math.min(directRoom, fits)); - backExact = convert(back / 100) * 100; - const backTrip = Math.round(backExact); - from.direct -= back; - to.direct += back; - from.cents += backTrip; - to.cents -= backTrip; - } - } + // Both halves of the ledger take the transfer, the display currency's first (applyTransfer). + const { paidDirect, exact, back, backExact } = applyTransfer(from, to, s.amount, isDirect(s.currency), convert, displayUnit); const movedDirect = paidDirect - back; reimbursedDirect[s.to_user_id] = (reimbursedDirect[s.to_user_id] || 0) + movedDirect; reimbursedDirect[s.from_user_id] = (reimbursedDirect[s.from_user_id] || 0) - movedDirect; diff --git a/server/src/nest/collections/collections.service.ts b/server/src/nest/collections/collections.service.ts index 3e29da937..f0bc01366 100644 --- a/server/src/nest/collections/collections.service.ts +++ b/server/src/nest/collections/collections.service.ts @@ -614,13 +614,8 @@ export class CollectionsService { // Snapshot recipients BEFORE the cascade wipes collection_members. const accepted = await this.members.acceptedUserIds(id); const pending = await this.members.pendingUserIds(id); - // The cover and the saved places' images, read before the cascade takes their rows: - // they go like a single place's do, unless a trip place or a copy still names them (#2924). - const cover = (await this.collectionsRepo.coverImage(id)) ?? null; - const images = await this.collectionPlaces.imageUrlsOf(id); - await this.collectionsRepo.deleteById(id); // CASCADE drops members + places + tags - await this.release.releaseValues([cover, ...images]); + await this.release.releaseValues(await this.collectionsRepo.deleteWithImages(id)); // cascades members, places, tags [...new Set([userId, ...accepted, ...pending])] // the owner's tabs too, all but the one that asked .forEach(uid => this.realtime.broadcastToUser(uid, { type: 'collections:deleted', collectionId: id }, socketId)); diff --git a/server/src/nest/journey/journey-domain.service.ts b/server/src/nest/journey/journey-domain.service.ts index 8f37aea82..e9fe16db4 100644 --- a/server/src/nest/journey/journey-domain.service.ts +++ b/server/src/nest/journey/journey-domain.service.ts @@ -85,25 +85,12 @@ export class JourneyDomainService { // (Task 0's confirmation: `canAccessTrip` IS `findAccessible`, not // merely equivalent to it). @InjectRepository(Trips) private readonly tripsRepo: TripsRepository, - // Plan 3g Task 2 (Part B) — the full photos surface (JG19/JG87-116), - // finishing the two sites Task 1 left raw (JG15/JG19) because their - // owning repositories did not exist yet. A genuine new constructor - // parameter pair beyond what Task 1's own constructor-ripple fix - // anticipated — flagged in task-2-report.md per the brief's own - // contingency instruction, with the companion edits to - // `journey-domain.module.ts`'s `forFeature` array and the two shared - // test-wiring helpers (`plugin-host.ts`/`mcp-test-controllers.ts`, - // both confirmed clean via `git status` before editing, per the - // brief's "constructor-ripple rule" allowance) made in this same - // change. + // The journey's photos and the entries they hang on (JG15/JG19/JG87-116). @InjectRepository(JourneyPhotos) private readonly photosRepo: JourneyPhotosRepository, @InjectRepository(JourneyEntryPhotos) private readonly entryPhotosRepo: JourneyEntryPhotosRepository, - // JG44 — `onPlaceUpdated`'s bare `SELECT * FROM places WHERE id = ?`, - // finished via `PlacesRepository.findRaw` (this task's ONE append to - // `Places.repository.ts`, per the task brief — nobody else holds it). + // JG44 — `onPlaceUpdated` reads the place it follows (`PlacesRepository.findRaw`). @InjectRepository(Places) private readonly placesRepo: PlacesRepository, - // Deleting a journey releases the files of the photos only it held. - private readonly release: StorageReleaseService, + private readonly release: StorageReleaseService, // frees the files of a deleted journey's own photos ) {} private ts(): number { @@ -371,10 +358,8 @@ export class JourneyDomainService { if (!(await this.isOwner(journeyId, userId))) return false; // Read first: the delete takes the contributor rows with it. const audience = await this.journeysRepo.listRecipientUserIds(journeyId); - // The gallery goes with the cascade, so its photos are read first. A photo - // row only this journey linked goes too: left behind, it would keep naming - // its file and the storage reclaim would never free it (#2924). One still - // in a trip or another journey keeps its row, and with it its file. + // The gallery goes with the cascade, so it is read first; a photo row only this journey linked goes too, or + // it would keep naming its file and the reclaim never free it (#2924). One a trip still links stays. const photos = await this.uow.transactional(async () => { const gallery = await this.journeysRepo.listGalleryPhotos({ journeyId }); await this.journeysRepo.deleteById(journeyId); diff --git a/server/src/nest/reservations/reservations.service.ts b/server/src/nest/reservations/reservations.service.ts index f45bae7e1..c2f844c55 100644 --- a/server/src/nest/reservations/reservations.service.ts +++ b/server/src/nest/reservations/reservations.service.ts @@ -10,7 +10,7 @@ import { keepMirroredPrice } from './reservation-metadata'; import { endpointRows, groupDayPositions, groupEndpointsByReservation } from './reservations.helpers'; import type { Reservation, User } from '../../types'; import { BudgetService } from '../budget/budget.service'; -import { costCategoryOf, typeToCostCategory } from '@trek/shared'; +import { isDerivedCostCategory, typeToCostCategory } from '@trek/shared'; import { NotificationsService } from '../notifications/notifications.service'; import { AccommodationsService, noStayMirror, type AccommodationMirror } from '../accommodations/accommodations.service'; import { toRowId, legacyBoundIntegerText } from '../common/row-id'; @@ -157,9 +157,6 @@ type AccommodationTimesMeta = { * transaction, the linked-cost side effects and the booking notification, so * REST, MCP and the plugin RPC (ReservationsRpc) stay thin. */ -/** The booking types whose cost the old type map filed under 'other' (see syncBudgetOnUpdate). */ -const FILED_AS_OTHER_BEFORE = new Set(['cable_car', 'event', 'tour', 'cruise', 'bicycle', 'transit', 'transport_other']); - @Injectable() export class ReservationsService { constructor( @@ -1151,14 +1148,8 @@ export class ReservationsService { const oldCat = typeToCostCategory(currentType); const newCat = typeToCostCategory(type); // RS51. Every linked expense (#2084), each only while it still has the derived category. - // Read through costCategoryOf, so a label stored before the fixed keys ("Flight") - // counts as the key it stands for and moves with the type too. - // Before 5.1.1 these types filed their cost under 'other', so an 'other' on one of - // them is still the derived category and moves with the type as it did. - const derived = (category: string | null) => - costCategoryOf(category) === oldCat || (category === 'other' && FILED_AS_OTHER_BEFORE.has(currentType)); const linked = oldCat === newCat ? [] : await this.budgetItemsRepo.listIdAndCategoryByReservation(tripId, id); - for (const item of linked.filter(i => derived(i.category))) { + for (const item of linked.filter(i => isDerivedCostCategory(i.category, currentType))) { const updated = await this.budget.updateBudgetItem(item.id, tripId, { category: newCat }); this.sendCost(tripId, { event: 'budget:updated', payload: { item: updated } }, socketId, collect); } diff --git a/server/tests/unit/nest/journey-domain.delete.test.ts b/server/tests/unit/nest/journey-domain.delete.test.ts new file mode 100644 index 000000000..6d31dd807 --- /dev/null +++ b/server/tests/unit/nest/journey-domain.delete.test.ts @@ -0,0 +1,114 @@ +/** + * JOURNEY-SVC-022b/022c: what deleting a journey does with the photos of its gallery + * (#2924). Split from journey-domain.service.test.ts, which is at its size baseline; + * the service is built the same way. + */ +import { db as testDb } from '../../../src/db/database'; +import { JourneyPhotos } from '../../../src/db/entities/JourneyPhotos.entity'; +import { TrekPhotos } from '../../../src/db/entities/TrekPhotos.entity'; +import { TripPhotos } from '../../../src/db/entities/TripPhotos.entity'; +import { JourneyDomainService } from '../../../src/nest/journey/journey-domain.service'; +import { TrekPhotoRegistrationService } from '../../../src/nest/photos/trek-photo-registration.service'; +import { RealtimeService } from '../../../src/nest/realtime/realtime.service'; +import { createUser, createTrip } from '../../helpers/factories'; +import { findRows } from '../../helpers/factories/rows'; +import { + createTestJourneysRepo, + createTestJourneyContributorsRepo, + createTestJourneyTripsRepo, + createTestJourneyEntriesRepo, + createTestJourneyPhotosRepo, + createTestJourneyEntryPhotosRepo, +} from '../../helpers/journey-repos'; +import { releaseNothing } from '../../helpers/storage-release'; +import { resetTestDb } from '../../helpers/test-db'; +import { createTestUnitOfWork, sharedTestOrm, createTestTripsRepo, createTestPlacesRepo } from '../../helpers/test-uow'; +import type { EntityClass, EntityDTO, FilterQuery } from '@mikro-orm/core'; + +import { describe, it, expect, vi, beforeAll, beforeEach, afterAll } from 'vitest'; + +vi.mock('../../../src/db/database', async () => { + const { createSnapshotTestDb } = await import('../../helpers/db-mock'); + const db = createSnapshotTestDb(); + return { db, closeDb: () => {}, reinitialize: () => {} }; +}); + +const orm = () => sharedTestOrm(testDb); +const release = releaseNothing(); +let svc: JourneyDomainService; + +async function one(entity: EntityClass, where: FilterQuery) { + return (await findRows(await orm(), entity, where))[0] as EntityDTO | undefined; +} + +beforeAll(async () => { + const t = await sharedTestOrm(testDb); + const photosRepo = await createTestJourneyPhotosRepo(testDb); + svc = new JourneyDomainService( + new RealtimeService(), + new TrekPhotoRegistrationService(t.repo(TrekPhotos), t.repo(TripPhotos), photosRepo), + await createTestUnitOfWork(testDb), + await createTestJourneysRepo(testDb), + await createTestJourneyContributorsRepo(testDb), + await createTestJourneyTripsRepo(testDb), + await createTestJourneyEntriesRepo(testDb), + await createTestTripsRepo(testDb), + photosRepo, + await createTestJourneyEntryPhotosRepo(testDb), + await createTestPlacesRepo(testDb), + release, + ); +}); + +beforeEach(() => { + resetTestDb(testDb); +}); + +afterAll(() => { + testDb.close(); +}); + +describe('deleteJourney and its gallery', () => { + it('JOURNEY-SVC-022b: deleting a journey drops the photo rows only it held and releases their files', async () => { + const { user } = createUser(testDb); + const journey = await svc.createJourney(user.id, { title: 'J' }); + const [photo, video] = await svc.uploadGalleryPhotos(journey.id, user.id, [ + { path: 'journey/a.jpg' }, + { path: 'journey/b.mp4', thumbnail: 'journey/b-poster.jpg', mediaType: 'video' }, + ]); + release.releaseValues.mockClear(); + + expect(await svc.deleteJourney(journey.id, user.id)).toBe(true); + + expect(await one(TrekPhotos, { id: { $in: [photo.photo_id, video.photo_id] } })).toBeUndefined(); + expect(release.releaseValues).toHaveBeenCalledTimes(1); + const [values, options] = release.releaseValues.mock.calls[0] as unknown as [Array, unknown]; + expect(values.filter(Boolean).sort()).toEqual(['journey/a.jpg', 'journey/b-poster.jpg', 'journey/b.mp4']); + expect(options).toEqual({ bare: 'journey' }); + }); + + it('JOURNEY-SVC-022c: a photo another journey or a trip still links keeps its row through the delete', async () => { + const { user } = createUser(testDb); + const journey = await svc.createJourney(user.id, { title: 'J' }); + const other = await svc.createJourney(user.id, { title: 'Other' }); + const trip = createTrip(testDb, user.id); + const [shared, inTrip, alone] = await svc.uploadGalleryPhotos(journey.id, user.id, [ + { path: 'journey/shared.jpg' }, + { path: 'journey/trip.jpg' }, + { path: 'journey/alone.jpg' }, + ]); + // The same file uploaded to a second journey reuses its photo row. + const [again] = await svc.uploadGalleryPhotos(other.id, user.id, [{ path: 'journey/shared.jpg' }]); + expect(again.photo_id).toBe(shared.photo_id); + testDb + .prepare('INSERT INTO trip_photos (trip_id, user_id, photo_id) VALUES (?, ?, ?)') + .run(trip.id, user.id, inTrip.photo_id); + + expect(await svc.deleteJourney(journey.id, user.id)).toBe(true); + + expect(await one(TrekPhotos, { id: shared.photo_id })).toBeDefined(); + expect(await one(TrekPhotos, { id: inTrip.photo_id })).toBeDefined(); + expect(await one(TrekPhotos, { id: alone.photo_id })).toBeUndefined(); + expect(await one(JourneyPhotos, { journey: other.id, photo: shared.photo_id })).toBeDefined(); + }); +}); diff --git a/server/tests/unit/nest/journey-domain.service.test.ts b/server/tests/unit/nest/journey-domain.service.test.ts index ff6d52300..9eb5b38ca 100644 --- a/server/tests/unit/nest/journey-domain.service.test.ts +++ b/server/tests/unit/nest/journey-domain.service.test.ts @@ -142,10 +142,7 @@ beforeAll(async () => { svc = new JourneyDomainService( new RealtimeService(), new TrekPhotoRegistrationService(t.repo(TrekPhotos), t.repo(TripPhotos), photosRepoDirect), await createTestUnitOfWork(testDb), journeysRepoDirect, contributorsRepoDirect, journeyTripsRepoDirect, entriesRepoDirect, tripsRepoDirect, - // Plan 3g Task 2's own append to this SAME construction call — the two - // repositories this task builds, plus `PlacesRepository` (JG44) — per - // R9, Task 2 only appends to what Task 1's construction already - // established, never re-touches the wrapping mechanism itself. + // The photos surface (JG87-116), `PlacesRepository` (JG44) and the storage release. photosRepoDirect, entryPhotosRepoDirect, placesRepoDirect, release, ); @@ -543,49 +540,6 @@ describe('deleteJourney', () => { const row = await one(Journeys, { id: journey.id }); expect(row).toBeDefined(); }); - - it('JOURNEY-SVC-022b: deleting a journey drops the photo rows only it held and releases their files', async () => { - const { user } = createUser(testDb); - const journey = await svc.createJourney(user.id, { title: 'J' }); - const [photo, video] = await svc.uploadGalleryPhotos(journey.id, user.id, [ - { path: 'journey/a.jpg' }, - { path: 'journey/b.mp4', thumbnail: 'journey/b-poster.jpg', mediaType: 'video' }, - ]); - release.releaseValues.mockClear(); - - expect(await svc.deleteJourney(journey.id, user.id)).toBe(true); - - expect(await one(TrekPhotos, { id: { $in: [photo.photo_id, video.photo_id] } })).toBeUndefined(); - expect(release.releaseValues).toHaveBeenCalledTimes(1); - const [values, options] = release.releaseValues.mock.calls[0] as unknown as [Array, unknown]; - expect(values.filter(Boolean).sort()).toEqual(['journey/a.jpg', 'journey/b-poster.jpg', 'journey/b.mp4']); - expect(options).toEqual({ bare: 'journey' }); - }); - - it('JOURNEY-SVC-022c: a photo another journey or a trip still links keeps its row through the delete', async () => { - const { user } = createUser(testDb); - const journey = await svc.createJourney(user.id, { title: 'J' }); - const other = await svc.createJourney(user.id, { title: 'Other' }); - const trip = createTrip(testDb, user.id); - const [shared, inTrip, alone] = await svc.uploadGalleryPhotos(journey.id, user.id, [ - { path: 'journey/shared.jpg' }, - { path: 'journey/trip.jpg' }, - { path: 'journey/alone.jpg' }, - ]); - // The same file uploaded to a second journey reuses its photo row. - const [again] = await svc.uploadGalleryPhotos(other.id, user.id, [{ path: 'journey/shared.jpg' }]); - expect(again.photo_id).toBe(shared.photo_id); - testDb - .prepare('INSERT INTO trip_photos (trip_id, user_id, photo_id) VALUES (?, ?, ?)') - .run(trip.id, user.id, inTrip.photo_id); - - expect(await svc.deleteJourney(journey.id, user.id)).toBe(true); - - expect(await one(TrekPhotos, { id: shared.photo_id })).toBeDefined(); - expect(await one(TrekPhotos, { id: inTrip.photo_id })).toBeDefined(); - expect(await one(TrekPhotos, { id: alone.photo_id })).toBeUndefined(); - expect(await one(JourneyPhotos, { journey: other.id, photo: shared.photo_id })).toBeDefined(); - }); }); // -- Trip management ---------------------------------------------------------- diff --git a/server/tests/unit/nest/trips.service.test.ts b/server/tests/unit/nest/trips.service.test.ts index 767dafa93..7798db050 100644 --- a/server/tests/unit/nest/trips.service.test.ts +++ b/server/tests/unit/nest/trips.service.test.ts @@ -264,8 +264,8 @@ beforeAll(async () => { await createTestJourneysRepo(testDb), await createTestJourneyContributorsRepo(testDb), await createTestJourneyTripsRepo(testDb), await createTestJourneyEntriesRepo(testDb), await createTestTripsRepo(testDb), // Plan 3g Task 2 constructor-ripple: JourneyPhotosRepository/JourneyEntryPhotosRepository/PlacesRepository. - await createTestJourneyPhotosRepo(testDb), await createTestJourneyEntryPhotosRepo(testDb), await createTestPlacesRepo(testDb), - { releaseValues: async () => 0 } as never, // StorageReleaseService + await createTestJourneyPhotosRepo(testDb), await createTestJourneyEntryPhotosRepo(testDb), + await createTestPlacesRepo(testDb), { releaseValues: async () => 0 } as never, // StorageReleaseService ), makeStorageFixture('').storage, await accommodationsOver(testDb, realtime), await createTestUnitOfWork(testDb), diff --git a/shared/src/budget/cost-category.spec.ts b/shared/src/budget/cost-category.spec.ts index c7150cf69..4f58244b7 100644 --- a/shared/src/budget/cost-category.spec.ts +++ b/shared/src/budget/cost-category.spec.ts @@ -1,7 +1,13 @@ -// COST-CATEGORY-001 to COST-CATEGORY-007: a typed category read as one of the fixed keys. +// COST-CATEGORY-001 to COST-CATEGORY-008: a typed category read as one of the fixed keys. import { RESERVATION_TYPES } from '../reservation/reservation-types'; import { COST_CATEGORIES } from './budget.schema'; -import { COST_CATEGORY_HINT, costCategoryOf, storedCostCategory, typeToCostCategory } from './cost-category'; +import { + COST_CATEGORY_HINT, + costCategoryOf, + isDerivedCostCategory, + storedCostCategory, + typeToCostCategory, +} from './cost-category'; import { describe, expect, it } from 'vitest'; @@ -58,4 +64,13 @@ describe('costCategoryOf', () => { expect(typeToCostCategory(null)).toBe('other'); expect(typeToCostCategory(undefined)).toBe('other'); }); + + it('COST-CATEGORY-008: an expense moves with its booking type only while it carries the derived category', () => { + expect(isDerivedCostCategory('flights', 'flight')).toBe(true); + expect(isDerivedCostCategory('Flight', 'flight')).toBe(true); + expect(isDerivedCostCategory('other', 'event')).toBe(true); + expect(isDerivedCostCategory('activities', 'event')).toBe(true); + expect(isDerivedCostCategory('other', 'flight')).toBe(false); + expect(isDerivedCostCategory('food', 'train')).toBe(false); + }); }); diff --git a/shared/src/budget/cost-category.ts b/shared/src/budget/cost-category.ts index 48fa1ee92..0fe4d7723 100644 --- a/shared/src/budget/cost-category.ts +++ b/shared/src/budget/cost-category.ts @@ -92,5 +92,27 @@ export function storedCostCategory(category: string | null | undefined): string return costCategoryOf(category) ?? (category || 'other'); } +/** The booking types whose cost the type map filed under `other` before 5.1.1. */ +const FILED_AS_OTHER_BEFORE = new Set([ + 'cable_car', + 'event', + 'tour', + 'cruise', + 'bicycle', + 'transit', + 'transport_other', +]); + +/** + * Whether a booking's expense still carries the category derived from its type, so it + * moves with a type change; one picked by hand stays. Read through costCategoryOf, so a + * label stored before the fixed keys ("Flight") counts as the key it stands for, and an + * `other` on a type the old map filed there still counts as derived. + */ +export function isDerivedCostCategory(category: string | null | undefined, type: string): boolean { + if (costCategoryOf(category) === typeToCostCategory(type)) return true; + return category === 'other' && FILED_AS_OTHER_BEFORE.has(type); +} + /** What the MCP tells an assistant about the category field. */ export const COST_CATEGORY_HINT = `One of the Costs categories: ${COST_CATEGORIES.join(', ')}. Another case or a common name (Hotel, Flight, Food) is stored as its key; any other text is kept as given and shows as other`;