fix(server): plan 3g close-out — transactional book first-save, skeleton reconcile and share-link create; unknown-key entry patches are no-ops again; parity and authorization pins for the journey repositories

This commit is contained in:
jubnl
2026-09-24 00:49:55 +02:00
parent aad7605071
commit a5665b5d2d
13 changed files with 892 additions and 320 deletions
@@ -428,8 +428,11 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
async listCachedCountriesForPlaceIds(placeIds: number[]): Promise<{ place_id: number; country_code: string | null }[]> {
const out: { place_id: number; country_code: string | null }[] = [];
for (let i = 0; i < placeIds.length; i += 400) {
// M4 (task-5-review.md) — `chunk` can never be empty here: the loop
// guard `i < placeIds.length` guarantees at least one element remains
// to slice, so a dead `if (!chunk.length) continue;` used to sit here
// (an uncovered branch the coverage gate flagged, worse than base).
const chunk = placeIds.slice(i, i + 400);
if (!chunk.length) continue;
const rows = await this.kysely<PlaceRegionsKyselyDB>()
.selectFrom('place_regions')
.select(['place_id', 'country_code'])
@@ -1,7 +1,4 @@
import type { Platform } from '@mikro-orm/core';
import type { ExpressionBuilder } from 'kysely';
import type { JourneyEntry } from '../../types';
import { concatKysely, unixEpochToIsoKysely } from '../dialect/sql-functions';
import type { JourneyShareTokens } from '../entities/JourneyShareTokens.entity';
import { TrekRepository } from './_shared/trek-repository';
@@ -168,42 +165,18 @@ interface JourneyPublicKyselyDB {
};
}
/**
* R1's SECOND `GALLERY_CHRONOLOGICAL_ORDER` consumer (`getPublicJourney`'s
* gallery read, JS15) — Task 0's worked example (`task-0-report.md`), pasted
* verbatim against this file's own `JourneyPublicKyselyDB` shape rather than
* re-derived. Fixed to the `gp`/`tp` alias contract `.selectFrom('journey_photos
* as gp').innerJoin('trek_photos as tp', ...)` produces, same as the
* `publicStayExists`/SQLF-070 precedent: a table's alias is a property of the
* QUERY, not of the `DB` interface, so this is not generic over an arbitrary
* caller `DB`/`TB`.
*/
function galleryChronologicalOrderExpr(
platform: Platform,
eb: ExpressionBuilder<JourneyPublicKyselyDB & { gp: JourneyPublicKyselyDB['journey_photos']; tp: JourneyPublicKyselyDB['trek_photos'] }, 'gp' | 'tp'>,
) {
return eb.fn.coalesce(
eb.fn<string | null>('nullif', [eb.ref('tp.taken_at'), eb.val('')]),
eb
.selectFrom('journey_entry_photos as jep')
.innerJoin('journey_entries as je', 'je.id', 'jep.entry_id')
.select((eb2) =>
eb2.fn
.min<string | null>(
concatKysely(
platform,
eb2,
{ column: 'je.entry_date' },
{ value: 'T' },
{ expression: eb2.fn.coalesce(eb2.fn<string | null>('nullif', [eb2.ref('je.entry_time'), eb2.val('')]), eb2.val('00:00')) },
),
)
.as('min_dt'),
)
.whereRef('jep.journey_photo_id', '=', 'gp.id'),
unixEpochToIsoKysely(platform, eb, 'gp.created_at'),
);
}
// L2 — `galleryChronologicalOrderExpr`/`listGalleryForPublicJourney` (JS15)
// used to be a byte-identical duplicate of `JourneyPhotosRepository`'s own
// `galleryChronologicalOrderExpr`/`galleryRead` (same `GALLERY_COLUMNS`
// select list, same ORDER BY, differing only in which local `DB` interface
// the builder is typed against). `JourneyShareService.getPublicJourney` now
// calls `JourneyPhotosRepository.galleryRead` directly instead — one gallery
// ORDER BY builder, one gallery query, per the whole-plan review (M5/L2).
// `JourneyPublicGalleryRow` stays exported: it is still the accurate shape
// of what that query returns (`GalleryPhoto`, the type `galleryRead` is
// declared against, is a narrower public-API type missing `taken_at`/`lat`/
// `lng`/`media_type`/`duration_ms`), and tests keep using it to type the
// public gallery response.
/**
* `journey_share_tokens` — public share links (Plan 3g Task 3, R4). Six of
@@ -354,27 +327,6 @@ export class JourneyShareTokensRepository extends TrekRepository<JourneyShareTok
.execute();
}
/**
* JS15 — `getPublicJourney`'s gallery read (R1's second
* `GALLERY_CHRONOLOGICAL_ORDER` site). The select list is byte-for-byte
* `GALLERY_SELECT` (`journey-domain.service.ts`), hand-duplicated here the
* same way the legacy statement hand-duplicated it (that module const is
* not imported by `journey-share.service.ts` at HEAD either).
*/
async listGalleryForPublicJourney(journeyId: number): Promise<JourneyPublicGalleryRow[]> {
const platform = this.getEntityManager().getPlatform();
return await this.kysely<JourneyPublicKyselyDB>()
.selectFrom('journey_photos as gp')
.innerJoin('trek_photos as tp', 'tp.id', 'gp.photo_id')
.select([
'gp.id', 'gp.journey_id', 'gp.photo_id', 'gp.caption', 'gp.shared', 'gp.sort_order', 'gp.created_at',
'tp.provider', 'tp.asset_id', 'tp.owner_id', 'tp.file_path', 'tp.thumbnail_path', 'tp.width', 'tp.height',
'tp.media_type', 'tp.duration_ms', 'tp.taken_at', 'tp.lat', 'tp.lng',
])
.where('gp.journey_id', '=', journeyId)
.orderBy((eb) => galleryChronologicalOrderExpr(platform, eb), 'asc')
.orderBy('gp.sort_order', 'asc')
.orderBy('gp.id', 'asc')
.execute();
}
// JS15 — `getPublicJourney`'s gallery read moved to
// `JourneyPhotosRepository.galleryRead` (L2, above).
}
@@ -67,7 +67,8 @@ export class TripPhotosRepository extends TrekRepository<TripPhotos> {
/**
* PH10's non-journey half — `SELECT 1 FROM trip_photos WHERE photo_id = ?
* LIMIT 1`, used by `TrekPhotoRegistrationService.deleteIfOrphan` alongside
* the still-raw `journey_photos` existence check (`// PH10 — Plan 3g`).
* the `journey_photos` half of the same orphan check, converted onto
* {@link JourneyPhotosRepository.existsForPhoto} (Plan 3g Task 4).
*/
async existsForPhoto(photo_id: number): Promise<boolean> {
const row = await this.findOne({ photo: photo_id }, { fields: ['id'] });
+45 -29
View File
@@ -3,6 +3,7 @@ import { InjectRepository } from '@mikro-orm/nestjs';
import type { BookRecord, BookSummary } from '@trek/shared';
import { normalizeBookDocument } from '@trek/shared';
import { JourneyDomainService } from './journey-domain.service';
import { UnitOfWork } from '../database/unit-of-work';
import { JourneyBooks } from '../../db/entities/JourneyBooks.entity';
import type { JourneyBookRow, JourneyBooksRepository } from '../../db/repositories/JourneyBooks.repository';
@@ -33,6 +34,9 @@ export class JourneyBookService {
constructor(
private readonly journey: JourneyDomainService,
@InjectRepository(JourneyBooks) private readonly booksRepo: JourneyBooksRepository,
// M1 (task-5-review.md) — `saveBook`'s first-save read-then-insert
// needs the connection mutex to serialize two concurrent first saves.
private readonly uow: UnitOfWork,
) {}
/** Null when the journey does not exist or the user cannot reach it. */
@@ -117,38 +121,50 @@ export class JourneyBookService {
if (!(await this.canWrite(journeyId, userId))) return null;
const document = JSON.stringify(normalizeBookDocument(input.document));
// JB3.
const existing = await this.booksRepo.findFirstForJourney(journeyId);
if (!existing) {
// JB4.
const id = await this.booksRepo.insertBook(journeyId, input.title, document, userId);
return { record: (await this.byId(id))! };
}
// M1 (rule 11/24) — JB3's existing-link read and JB4's insert are
// separate awaits, so two concurrent first saves of the same journey's
// book could both read "no book yet" and both insert, leaving one
// editor's save silently orphaned behind `getBook`'s `ORDER BY id LIMIT
// 1` (there is no unique index on `journey_id`). Wrapped whole: every
// statement below is DB-only, and the mutex serializes a second
// caller's read behind the first's commit, so it finds the row the
// first just created and takes the JB5 CAS-update path instead, the
// same outcome the synchronous legacy code always had.
return this.uow.transactional(async () => {
// JB3.
const existing = await this.booksRepo.findFirstForJourney(journeyId);
/*
* The version goes in the WHERE clause rather than being checked first.
* Read-then-write leaves a window between the two in which another save can
* land, and SQLite gives no guarantee across two statements — one UPDATE
* that matches on the version cannot lose that race with itself.
*
* A save with no base version is a first write from a client that has not
* loaded one; it is allowed to take the current version, since refusing it
* would break "open Studio and start editing" for the second person to
* arrive.
*/
const base = input.baseVersion ?? existing.version;
// JB5 (R2) — one conditional UPDATE, returning the affected-row count.
const changes = await this.booksRepo.casUpdate(existing.id, base, {
title: input.title,
document,
updatedBy: userId,
if (!existing) {
// JB4.
const id = await this.booksRepo.insertBook(journeyId, input.title, document, userId);
return { record: (await this.byId(id))! };
}
/*
* The version goes in the WHERE clause rather than being checked first.
* Read-then-write leaves a window between the two in which another save can
* land, and SQLite gives no guarantee across two statements — one UPDATE
* that matches on the version cannot lose that race with itself.
*
* A save with no base version is a first write from a client that has not
* loaded one; it is allowed to take the current version, since refusing it
* would break "open Studio and start editing" for the second person to
* arrive.
*/
const base = input.baseVersion ?? existing.version;
// JB5 (R2) — one conditional UPDATE, returning the affected-row count.
const changes = await this.booksRepo.casUpdate(existing.id, base, {
title: input.title,
document,
updatedBy: userId,
});
if (changes === 0) {
return { conflict: (await this.byId(existing.id))! };
}
return { record: (await this.byId(existing.id))! };
});
if (changes === 0) {
return { conflict: (await this.byId(existing.id))! };
}
return { record: (await this.byId(existing.id))! };
}
async deleteBook(journeyId: number, userId: number): Promise<boolean | null> {
+214 -186
View File
@@ -460,43 +460,51 @@ export class JourneyDomainService {
// ── Sync engine ──────────────────────────────────────────────────────────
async syncTripPlaces(journeyId: number, tripId: number, authorId: number) {
const places = await this.journeyTripsRepo.listAssignedPlacesForTrip(tripId);
// M2 (rule 11/24) — the existence read and the skeleton insert are
// separate awaits now that the sync engine is async, so two concurrent
// syncs for the same trip could both miss the same place and each insert
// a skeleton for it. Wrapped whole: every statement inside is DB-only
// (repository calls), and the connection mutex serializes a second
// caller's statements behind this one until it commits.
await this.uow.transactional(async () => {
const places = await this.journeyTripsRepo.listAssignedPlacesForTrip(tripId);
const now = this.ts();
const existing = await this.entriesRepo.listSourceKeysForTrip(journeyId, tripId);
const existingKeys = new Set(existing.map((e) => skeletonKey(e.source_place_id, e.source_assignment_id)));
const now = this.ts();
const existing = await this.entriesRepo.listSourceKeysForTrip(journeyId, tripId);
const existingKeys = new Set(existing.map((e) => skeletonKey(e.source_place_id, e.source_assignment_id)));
// Track next sort_order per date so synced skeletons get unique, sequential positions.
const dateMaxOrder = new Map<string, number>();
const maxRows = await this.entriesRepo.dateSortOrderMaxima(journeyId);
for (const row of maxRows) dateMaxOrder.set(row.entry_date, row.m);
// Track next sort_order per date so synced skeletons get unique, sequential positions.
const dateMaxOrder = new Map<string, number>();
const maxRows = await this.entriesRepo.dateSortOrderMaxima(journeyId);
for (const row of maxRows) dateMaxOrder.set(row.entry_date, row.m);
for (const place of places) {
const key = skeletonKey(place.id, place.assignment_id);
if (existingKeys.has(key)) continue;
existingKeys.add(key);
for (const place of places) {
const key = skeletonKey(place.id, place.assignment_id);
if (existingKeys.has(key)) continue;
existingKeys.add(key);
const entryDate = place.day_date || new Date().toISOString().split('T')[0];
const entryTime = place.assignment_time || place.place_time || null;
const nextOrder = (dateMaxOrder.get(entryDate) ?? -1) + 1;
dateMaxOrder.set(entryDate, nextOrder);
const entryDate = place.day_date || new Date().toISOString().split('T')[0];
const entryTime = place.assignment_time || place.place_time || null;
const nextOrder = (dateMaxOrder.get(entryDate) ?? -1) + 1;
dateMaxOrder.set(entryDate, nextOrder);
await this.insertSkeletonEntry({
journeyId,
tripId,
placeId: place.id,
assignmentId: place.assignment_id ?? null,
authorId,
title: place.name,
entryDate,
entryTime,
locationName: place.address || place.name,
lat: place.lat || null,
lng: place.lng || null,
sortOrder: nextOrder,
now,
});
}
await this.insertSkeletonEntry({
journeyId,
tripId,
placeId: place.id,
assignmentId: place.assignment_id ?? null,
authorId,
title: place.name,
entryDate,
entryTime,
locationName: place.address || place.name,
lat: place.lat || null,
lng: place.lng || null,
sortOrder: nextOrder,
now,
});
}
});
}
// called when a trip place is created
@@ -511,38 +519,44 @@ export class JourneyDomainService {
if (!assignments.length) return; // not assigned to a day yet — skip
const now = this.ts();
for (const journeyId of links) {
// JG40 — same text as JG2/JG54, resolved through `findOwnerId`. No
// undefined-guard here (matching the legacy statement's own unchecked
// `as { user_id: number }` cast): `journey_trips` cascades on the
// owning journey's delete, so a linked journey can never be missing.
const ownerId = (await this.journeysRepo.findOwnerId(journeyId)) as number;
// M2 (rule 11/24) — same fix as syncTripPlaces: the existence check
// (`existsForPlaceAssignment`) and the insert are separate awaits, so a
// concurrent reconcile racing this callback could both find nothing and
// both insert. Wrapped whole; DB-only, no broadcast inside.
await this.uow.transactional(async () => {
for (const journeyId of links) {
// JG40 — same text as JG2/JG54, resolved through `findOwnerId`. No
// undefined-guard here (matching the legacy statement's own unchecked
// `as { user_id: number }` cast): `journey_trips` cascades on the
// owning journey's delete, so a linked journey can never be missing.
const ownerId = (await this.journeysRepo.findOwnerId(journeyId)) as number;
for (const place of assignments) {
const already = await this.entriesRepo.existsForPlaceAssignment(journeyId, placeId, place.assignment_id ?? null);
if (already) continue;
for (const place of assignments) {
const already = await this.entriesRepo.existsForPlaceAssignment(journeyId, placeId, place.assignment_id ?? null);
if (already) continue;
const entryDate = place.day_date as string;
const maxOrder = await this.entriesRepo.maxSortOrderForDate(journeyId, entryDate);
const nextOrder = (maxOrder ?? -1) + 1;
const entryDate = place.day_date as string;
const maxOrder = await this.entriesRepo.maxSortOrderForDate(journeyId, entryDate);
const nextOrder = (maxOrder ?? -1) + 1;
await this.insertSkeletonEntry({
journeyId,
tripId,
placeId,
assignmentId: place.assignment_id ?? null,
authorId: ownerId,
title: place.name,
entryDate,
entryTime: place.assignment_time || place.place_time || null,
locationName: place.address || place.name,
lat: place.lat || null,
lng: place.lng || null,
sortOrder: nextOrder,
now,
});
await this.insertSkeletonEntry({
journeyId,
tripId,
placeId,
assignmentId: place.assignment_id ?? null,
authorId: ownerId,
title: place.name,
entryDate,
entryTime: place.assignment_time || place.place_time || null,
locationName: place.address || place.name,
lat: place.lat || null,
lng: place.lng || null,
sortOrder: nextOrder,
now,
});
}
}
}
});
}
// called when a trip place is updated
@@ -695,137 +709,148 @@ export class JourneyDomainService {
const now = this.ts();
for (const journeyId of links) {
const ownerId = await this.journeysRepo.findOwnerId(journeyId);
if (ownerId === undefined) continue;
// M2 (rule 11/24) — the existence read (`listForTripReconcile`) and the
// upsert/delete writes below are separate awaits, so two concurrent
// reconciles for the same trip (or a reconcile racing `onPlaceCreated`)
// could both read "not there yet" and both insert. Wrapped whole per
// journey: every statement inside is DB-only, and the mutex serializes
// a second caller's statements behind this one until it commits — the
// broadcast (non-DB I/O) stays outside, after commit, per rule 24.
const changed = await this.uow.transactional(async () => {
const ownerId = await this.journeysRepo.findOwnerId(journeyId);
if (ownerId === undefined) return false;
let changed = false;
// JG55 — a wider column set than JG35 (`listSourceKeysForTrip`), not a dup.
const existing = await this.entriesRepo.listForTripReconcile(journeyId, tripId);
const existingByKey = new Map<string, (typeof existing)[number]>();
// Rows from before the assignment link existed, and any the backfill could not
// resolve. The place's earliest assignment claims one below, rather than the row
// being read as "no longer in the plan" and annotated out from under its author.
const unclaimed = new Map<number, (typeof existing)[number][]>();
for (const e of existing) {
if (e.source_place_id == null) continue;
if (e.source_assignment_id == null) {
const pool = unclaimed.get(e.source_place_id);
if (pool) pool.push(e);
else unclaimed.set(e.source_place_id, [e]);
} else {
existingByKey.set(skeletonKey(e.source_place_id, e.source_assignment_id), e);
}
}
// Next sort_order per date for freshly inserted skeletons.
const dateMaxOrder = new Map<string, number>();
const maxRows = await this.entriesRepo.dateSortOrderMaxima(journeyId);
for (const row of maxRows) dateMaxOrder.set(row.entry_date, row.m);
// 1) Upsert a skeleton for every current day assignment.
for (const place of places) {
const entryDate = place.day_date || new Date().toISOString().split('T')[0];
const entryTime = place.assignment_time || place.place_time || null;
const locationName = place.address || place.name;
const lat = place.lat || null;
const lng = place.lng || null;
let found = existingByKey.get(skeletonKey(place.id, place.assignment_id));
if (!found) {
// `places` is ordered by day, so the earliest assignment claims it.
const adopted = unclaimed.get(place.id)?.shift();
if (adopted) {
await this.entriesRepo.claimAssignment(adopted.id, place.assignment_id ?? null);
adopted.source_assignment_id = place.assignment_id ?? null;
existingByKey.set(skeletonKey(place.id, place.assignment_id), adopted);
found = adopted;
let didChange = false;
// JG55 — a wider column set than JG35 (`listSourceKeysForTrip`), not a dup.
const existing = await this.entriesRepo.listForTripReconcile(journeyId, tripId);
const existingByKey = new Map<string, (typeof existing)[number]>();
// Rows from before the assignment link existed, and any the backfill could not
// resolve. The place's earliest assignment claims one below, rather than the row
// being read as "no longer in the plan" and annotated out from under its author.
const unclaimed = new Map<number, (typeof existing)[number][]>();
for (const e of existing) {
if (e.source_place_id == null) continue;
if (e.source_assignment_id == null) {
const pool = unclaimed.get(e.source_place_id);
if (pool) pool.push(e);
else unclaimed.set(e.source_place_id, [e]);
} else {
existingByKey.set(skeletonKey(e.source_place_id, e.source_assignment_id), e);
}
}
if (!found) {
const nextOrder = (dateMaxOrder.get(entryDate) ?? -1) + 1;
dateMaxOrder.set(entryDate, nextOrder);
await this.insertSkeletonEntry({
journeyId,
tripId,
placeId: place.id,
assignmentId: place.assignment_id ?? null,
authorId: ownerId,
title: place.name,
entryDate,
entryTime,
locationName,
lat,
lng,
sortOrder: nextOrder,
now,
});
changed = true;
} else if (found.type === 'skeleton') {
// Skeletons follow the place's day/time/location snapshot.
const stale =
found.title !== place.name ||
found.entry_date !== entryDate ||
found.entry_time !== entryTime ||
found.location_name !== locationName ||
found.location_lat !== lat ||
found.location_lng !== lng;
if (stale) {
await this.entriesRepo.updateSkeletonSnapshot(found.id, {
// Next sort_order per date for freshly inserted skeletons.
const dateMaxOrder = new Map<string, number>();
const maxRows = await this.entriesRepo.dateSortOrderMaxima(journeyId);
for (const row of maxRows) dateMaxOrder.set(row.entry_date, row.m);
// 1) Upsert a skeleton for every current day assignment.
for (const place of places) {
const entryDate = place.day_date || new Date().toISOString().split('T')[0];
const entryTime = place.assignment_time || place.place_time || null;
const locationName = place.address || place.name;
const lat = place.lat || null;
const lng = place.lng || null;
let found = existingByKey.get(skeletonKey(place.id, place.assignment_id));
if (!found) {
// `places` is ordered by day, so the earliest assignment claims it.
const adopted = unclaimed.get(place.id)?.shift();
if (adopted) {
await this.entriesRepo.claimAssignment(adopted.id, place.assignment_id ?? null);
adopted.source_assignment_id = place.assignment_id ?? null;
existingByKey.set(skeletonKey(place.id, place.assignment_id), adopted);
found = adopted;
}
}
if (!found) {
const nextOrder = (dateMaxOrder.get(entryDate) ?? -1) + 1;
dateMaxOrder.set(entryDate, nextOrder);
await this.insertSkeletonEntry({
journeyId,
tripId,
placeId: place.id,
assignmentId: place.assignment_id ?? null,
authorId: ownerId,
title: place.name,
entry_date: entryDate,
entry_time: entryTime,
location_name: locationName,
location_lat: lat,
location_lng: lng,
country_code: this.countryFor(lat, lng),
updated_at: now,
entryDate,
entryTime,
locationName,
lat,
lng,
sortOrder: nextOrder,
now,
});
changed = true;
}
} else {
// Filled entries keep the user's date/story; only location follows the place.
const stale =
found.location_name !== locationName || found.location_lat !== lat || found.location_lng !== lng;
if (stale) {
await this.entriesRepo.updateLocationOnly(found.id, {
location_name: locationName,
location_lat: lat,
location_lng: lng,
country_code: this.countryFor(lat, lng),
updated_at: now,
});
changed = true;
didChange = true;
} else if (found.type === 'skeleton') {
// Skeletons follow the place's day/time/location snapshot.
const stale =
found.title !== place.name ||
found.entry_date !== entryDate ||
found.entry_time !== entryTime ||
found.location_name !== locationName ||
found.location_lat !== lat ||
found.location_lng !== lng;
if (stale) {
await this.entriesRepo.updateSkeletonSnapshot(found.id, {
title: place.name,
entry_date: entryDate,
entry_time: entryTime,
location_name: locationName,
location_lat: lat,
location_lng: lng,
country_code: this.countryFor(lat, lng),
updated_at: now,
});
didChange = true;
}
} else {
// Filled entries keep the user's date/story; only location follows the place.
const stale =
found.location_name !== locationName || found.location_lat !== lat || found.location_lng !== lng;
if (stale) {
await this.entriesRepo.updateLocationOnly(found.id, {
location_name: locationName,
location_lat: lat,
location_lng: lng,
country_code: this.countryFor(lat, lng),
updated_at: now,
});
didChange = true;
}
}
}
}
// 2) Drop skeletons whose assignment is gone. One still waiting to be claimed is
// spared while its place is on the plan somewhere: having no link yet is not
// the same as the stop having left.
for (const e of existing) {
if (e.source_place_id == null) continue;
if (e.source_assignment_id == null && assignedPlaceIds.has(e.source_place_id)) continue;
if (e.source_assignment_id != null && assignedKeys.has(skeletonKey(e.source_place_id, e.source_assignment_id))) {
continue;
}
if (e.type === 'skeleton') {
const hasPhotos = await this.entriesRepo.existsPhotoForEntry(e.id);
if (!hasPhotos && !e.story) {
await this.entriesRepo.deleteById(e.id);
changed = true;
// 2) Drop skeletons whose assignment is gone. One still waiting to be claimed is
// spared while its place is on the plan somewhere: having no link yet is not
// the same as the stop having left.
for (const e of existing) {
if (e.source_place_id == null) continue;
if (e.source_assignment_id == null && assignedPlaceIds.has(e.source_place_id)) continue;
if (e.source_assignment_id != null && assignedKeys.has(skeletonKey(e.source_place_id, e.source_assignment_id))) {
continue;
}
if (e.type === 'skeleton') {
const hasPhotos = await this.entriesRepo.existsPhotoForEntry(e.id);
if (!hasPhotos && !e.story) {
await this.entriesRepo.deleteById(e.id);
didChange = true;
continue;
}
}
const note = '\n\n> _Note: the original trip place was removed from the trip plan_';
const newStory = (e.story || '') + note;
await this.entriesRepo.detachAndAnnotate(e.id, {
type: e.type === 'skeleton' ? 'entry' : e.type,
story: newStory,
updated_at: now,
});
didChange = true;
}
const note = '\n\n> _Note: the original trip place was removed from the trip plan_';
const newStory = (e.story || '') + note;
await this.entriesRepo.detachAndAnnotate(e.id, {
type: e.type === 'skeleton' ? 'entry' : e.type,
story: newStory,
updated_at: now,
});
changed = true;
}
return didChange;
});
if (changed) await this.broadcastJourneyEvent(journeyId, 'journey:trip:synced', { tripId }, sid);
}
@@ -1273,13 +1298,16 @@ export class JourneyDomainService {
updated_at: [true, this.ts()],
});
// The legacy no-op check (`fields.length === 0`) fires exactly when NO
// allow-listed key of `data` carries a defined value — the country
// recompute and the type-promotion push are both themselves gated on
// keys already in that same set (`location_lat`/`location_lng`/`story`),
// so "any key of `data` is defined" is the identical condition.
const anyFieldProvided = Object.values(data).some((v) => v !== undefined);
if (!anyFieldProvided) return decodeEntryRow(entry);
// M3 (parity) — the legacy no-op check (`fields.length === 0`) fires
// exactly when NO allow-listed key made it into the dynamic SET list.
// `Object.values(data).some(v => v !== undefined)` is the WRONG mirror
// of that: `data` is `journeyEntryUpdateRequestSchema`'s `z.looseObject`,
// so a PATCH body carrying only non-allow-listed keys (`{"foo":1}`) has
// a defined value there and this used to write and broadcast anyway.
// `patch` (built above by `presenceSet`) always carries `updated_at`
// unconditionally, so its length is 1 exactly when nothing allow-listed
// was provided — the same condition the legacy field-count check tested.
if (Object.keys(patch).length === 1) return decodeEntryRow(entry);
await this.entriesRepo.updateFields(entryId, patch);
@@ -4,6 +4,7 @@ import crypto from 'crypto';
import { JourneyDomainService } from './journey-domain.service';
import { decodeEntryRow } from './journey-entry-row';
import { SettingsService } from '../settings/settings.service';
import { UnitOfWork } from '../database/unit-of-work';
import { Journeys } from '../../db/entities/Journeys.entity';
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity';
@@ -11,6 +12,8 @@ import type {
JourneyPublicEntryPhotoRow,
JourneyShareTokensRepository,
} from '../../db/repositories/JourneyShareTokens.repository';
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
import type { JourneyPhotosRepository } from '../../db/repositories/JourneyPhotos.repository';
interface JourneySharePermissions {
share_timeline?: boolean;
@@ -47,6 +50,17 @@ export class JourneyShareService {
// already-stable `JourneysRepository.findById` (the JG5 dup group) rather
// than a second, hand-kept copy of the same statement.
@InjectRepository(Journeys) private readonly journeysRepo: JourneysRepository,
// Fix-wave additions (task-5-review.md):
// - `uow` (L1): `createOrUpdateJourneyShareLink`'s existing-link read and
// its insert are separate awaits now, so two concurrent first-creates
// for the same journey could both read "no link yet" and both insert —
// the second hits `UNIQUE(journey_id)` and 500s instead of returning
// `{created:false}` like the legacy synchronous path always did.
// - `photosRepo` (L2): `getPublicJourney`'s gallery read (JS15) reuses
// `JourneyPhotosRepository.galleryRead` instead of carrying its own
// byte-identical copy of the ORDER BY builder and the gallery query.
private readonly uow: UnitOfWork,
@InjectRepository(JourneyPhotos) private readonly photosRepo: JourneyPhotosRepository,
) {}
async createOrUpdateJourneyShareLink(
@@ -58,45 +72,55 @@ export class JourneyShareService {
// able to publish the journey or change which screens are shared.
if (!(await this.journey.isOwner(journeyId, createdBy))) return null;
// JS1 — `JourneyShareTokensRepository.findFlagsByJourneyId`.
const existing = await this.shareTokensRepo.findFlagsByJourneyId(journeyId);
// L1 (rule 11/24) — the existing-link read and the insert below are
// separate awaits, so two concurrent first-creates for the same journey
// could both read "no link yet" and both try to insert: the loser hits
// `UNIQUE(journey_id)` and throws (a 500 over HTTP) instead of the
// legacy's `{created:false}` outcome. Wrapped whole, DB-only, same fix
// as M1: the mutex serializes the second caller's read behind the
// first's commit, so it finds the row the first just created and takes
// the UPDATE branch instead, exactly like the synchronous legacy path.
return this.uow.transactional(async () => {
// JS1 — `JourneyShareTokensRepository.findFlagsByJourneyId`.
const existing = await this.shareTokensRepo.findFlagsByJourneyId(journeyId);
if (existing) {
// An update only changes the flags it was actually given. Falling back to
// the create-time defaults here would silently re-publish a gallery or map
// the owner had switched off, at the unchanged token.
const share_timeline = permissions.share_timeline ?? !!existing.share_timeline;
const share_gallery = permissions.share_gallery ?? !!existing.share_gallery;
const share_map = permissions.share_map ?? !!existing.share_map;
const newest_first = permissions.newest_first ?? !!existing.newest_first;
// JS2 — the SERVICE resolves the final value of every flag (above); the
// repository writes exactly those four already-resolved booleans, a
// plain 4-column UPDATE, not a presence-sentinel one.
await this.shareTokensRepo.updateFlags(journeyId, {
if (existing) {
// An update only changes the flags it was actually given. Falling back to
// the create-time defaults here would silently re-publish a gallery or map
// the owner had switched off, at the unchanged token.
const share_timeline = permissions.share_timeline ?? !!existing.share_timeline;
const share_gallery = permissions.share_gallery ?? !!existing.share_gallery;
const share_map = permissions.share_map ?? !!existing.share_map;
const newest_first = permissions.newest_first ?? !!existing.newest_first;
// JS2 — the SERVICE resolves the final value of every flag (above); the
// repository writes exactly those four already-resolved booleans, a
// plain 4-column UPDATE, not a presence-sentinel one.
await this.shareTokensRepo.updateFlags(journeyId, {
share_timeline: share_timeline ? 1 : 0,
share_gallery: share_gallery ? 1 : 0,
share_map: share_map ? 1 : 0,
newest_first: newest_first ? 1 : 0,
});
return { token: existing.token, created: false };
}
const {
share_timeline = true,
share_gallery = true,
share_map = true,
newest_first = false,
} = permissions;
const token = crypto.randomBytes(24).toString('base64url');
// JS3.
await this.shareTokensRepo.insertLink(journeyId, token, createdBy, {
share_timeline: share_timeline ? 1 : 0,
share_gallery: share_gallery ? 1 : 0,
share_map: share_map ? 1 : 0,
newest_first: newest_first ? 1 : 0,
});
return { token: existing.token, created: false };
}
const {
share_timeline = true,
share_gallery = true,
share_map = true,
newest_first = false,
} = permissions;
const token = crypto.randomBytes(24).toString('base64url');
// JS3.
await this.shareTokensRepo.insertLink(journeyId, token, createdBy, {
share_timeline: share_timeline ? 1 : 0,
share_gallery: share_gallery ? 1 : 0,
share_map: share_map ? 1 : 0,
newest_first: newest_first ? 1 : 0,
return { token, created: true };
});
return { token, created: true };
}
/**
@@ -194,8 +218,10 @@ export class JourneyShareService {
(photosByEntry[p.entry_id] ||= []).push(p);
}
// JS15 (R1's second `GALLERY_CHRONOLOGICAL_ORDER` site).
const gallery = await this.shareTokensRepo.listGalleryForPublicJourney(row.journey_id);
// JS15 (R1's second `GALLERY_CHRONOLOGICAL_ORDER` site) — L2: reuses
// `JourneyPhotosRepository.galleryRead` (same `GALLERY_COLUMNS`, same
// ORDER BY) rather than a second, hand-kept copy of the same query.
const gallery = await this.photosRepo.galleryRead(row.journey_id);
const enrichedEntries = entries
.map(e => ({