feat(journey): entry updates and reorders answer what they replaced

update_journey_entry now answers previous, the entry's earlier values of
exactly the fields it names (a suggestion written up goes back to being
one), and reorder_journey_entries answers previous_order, the ids in the
order they stood in before. Both come from the service the REST routes
use, which now builds an entry's patch in one pure helper; the routes'
bodies are unchanged. The tools' inline zod moves into strict schemas in
@trek/shared.
This commit is contained in:
Maurice
2026-10-24 21:46:43 +02:00
parent 48ff1b3a98
commit 5160bd23d5
8 changed files with 340 additions and 186 deletions
+31 -101
View File
@@ -27,9 +27,9 @@ import { Trips } from '../../db/entities/Trips.entity';
import type { TripsRepository } from '../../db/repositories/Trips.repository';
import { Places } from '../../db/entities/Places.entity';
import type { PlacesRepository } from '../../db/repositories/Places.repository';
import { presenceSet } from '../../db/repositories/_shared/presence-set';
import { parseRouteGeometry } from './journey-geometry';
import { journeySettingsPatch, type JourneySettingsInput } from './journey-settings.helpers';
import { entryPrevious, entryUpdatePatch, type JourneyEntryPrevious, type JourneyEntryUpdateInput } from './journey-entry-patch.helpers';
/**
* What makes a journal skeleton unique: the place *and* the day assignment it
@@ -1158,107 +1158,30 @@ export class JourneyDomainService {
return created;
}
async updateEntry(
async updateEntry(entryId: number, userId: number, data: JourneyEntryUpdateInput, sid?: string): Promise<JourneyEntryWire | null> {
return (await this.updateEntryWithPrevious(entryId, userId, data, sid))?.entry ?? null;
}
/** The update every surface makes, with what it replaced (journey-entry-patch.helpers.ts), for the assistant's undo. */
async updateEntryWithPrevious(
entryId: number,
userId: number,
data: Partial<{
type: string;
title: string;
story: string;
entry_date: string;
entry_time: string;
location_name: string;
location_lat: number;
location_lng: number;
mood: string;
weather: string;
tags: string[];
pros_cons: { pros: string[]; cons: string[] };
visibility: string;
sort_order: number;
stats_excluded: boolean;
dismissed: boolean;
is_draft: boolean;
}>,
data: JourneyEntryUpdateInput,
sid?: string,
): Promise<JourneyEntryWire | null> {
): Promise<{ entry: JourneyEntryWire; previous: JourneyEntryPrevious } | null> {
// JG77 — same text as JG76.
const entry = await this.entriesRepo.findById(entryId);
if (!entry) return null;
if (!(await this.canEdit(entry.journey_id, userId))) return null;
// JG78 — R6's `presenceSet` conversion, the SECOND consumer of this
// pattern (JG24's `updateJourney`, Task 1's, is the first — same shape,
// not re-derived). The SERVICE resolves every field to its final bound
// value first: `tags`/`pros_cons` JSON-encoded, `stats_excluded`/
// `dismissed` boolean-coerced to 0/1 (better-sqlite3 refuses a JS
// boolean bind), `country_code` recomputed whenever EITHER half of the
// lat/lng pair is present in the patch — including when explicitly
// `null`, which means "take this entry off the map" and must clear the
// country rather than fall back to the old one, hence `!== undefined`,
// never `??` — before handing any of it to the repository.
//
// The skeleton→entry promotion preserves a real legacy nuance: the
// original dynamic-SET-list pushed a SECOND `type = ?` binding when a
// story was added to a skeleton, even when the caller's own `data.type`
// had already pushed one — SQLite's `SET col = a, col = b` keeps the
// LAST assignment, so the promotion always won over an explicit
// `data.type` whenever both applied. `presenceSet` takes one value per
// key, so that "last one wins" resolution happens here instead, in the
// same effective order the legacy statement's own field list built it.
const promoteToEntry = entry.type === 'skeleton' && !!data.story && data.story.trim().length > 0;
const patch = presenceSet<{
type: string;
title: string | null;
story: string | null;
entry_date: string;
entry_time: string | null;
location_name: string | null;
location_lat: number | null;
location_lng: number | null;
mood: string | null;
weather: string | null;
tags: string | null;
pros_cons: string | null;
visibility: string;
sort_order: number;
stats_excluded: number;
dismissed: number;
is_draft: number;
country_code: string | null;
updated_at: number;
}>({
type: [data.type !== undefined || promoteToEntry, promoteToEntry ? 'entry' : (data.type as string)],
title: [data.title !== undefined, data.title as string],
story: [data.story !== undefined, data.story as string],
entry_date: [data.entry_date !== undefined, data.entry_date as string],
entry_time: [data.entry_time !== undefined, data.entry_time as string],
location_name: [data.location_name !== undefined, data.location_name as string],
location_lat: [data.location_lat !== undefined, data.location_lat as number | null],
location_lng: [data.location_lng !== undefined, data.location_lng as number | null],
mood: [data.mood !== undefined, data.mood as string],
weather: [data.weather !== undefined, data.weather as string],
// `Array.isArray(val) ? JSON.stringify(val) : val` (legacy) — a caller
// sending `tags: null`/`pros_cons: null` explicitly (to CLEAR the
// field, not touch it) must write SQL NULL, not the JSON string
// `"null"` (`JSON.stringify(null)`) — caught live by
// `tools-journey.test.ts`'s own "clears a field on null" case.
tags: [data.tags !== undefined, Array.isArray(data.tags) ? JSON.stringify(data.tags) : null],
pros_cons: [data.pros_cons !== undefined, data.pros_cons && typeof data.pros_cons === 'object' ? JSON.stringify(data.pros_cons) : null],
visibility: [data.visibility !== undefined, data.visibility as string],
sort_order: [data.sort_order !== undefined, data.sort_order as number],
stats_excluded: [data.stats_excluded !== undefined, data.stats_excluded ? 1 : 0],
dismissed: [data.dismissed !== undefined, data.dismissed ? 1 : 0],
is_draft: [data.is_draft !== undefined, data.is_draft ? 1 : 0],
country_code: [
data.location_lat !== undefined || data.location_lng !== undefined,
this.countryFor(
data.location_lat !== undefined ? data.location_lat : entry.location_lat,
data.location_lng !== undefined ? data.location_lng : entry.location_lng,
),
],
updated_at: [true, this.ts()],
});
// JG78 — the patch is built in one place for every surface; the country is recomputed whenever
// EITHER half of the lat/lng pair is named, including as null, so it clears rather than falls back.
const country = this.countryFor(
data.location_lat !== undefined ? data.location_lat : entry.location_lat,
data.location_lng !== undefined ? data.location_lng : entry.location_lng,
);
const patch = entryUpdatePatch(entry, data, country, this.ts());
const previous = entryPrevious(entry, data);
// M3 (parity) — the legacy no-op check (`fields.length === 0`) fires
// exactly when NO allow-listed key made it into the dynamic SET list.
@@ -1266,10 +1189,10 @@ export class JourneyDomainService {
// 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`
// `patch` (built above by `entryUpdatePatch`) 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);
if (Object.keys(patch).length === 1) return { entry: decodeEntryRow(entry), previous: {} };
await this.uow.transactional(async () => {
await placeMovedEntry(this.entriesRepo, entry, patch, this.ts());
@@ -1280,19 +1203,26 @@ export class JourneyDomainService {
// JG80 — same text as JG76.
const updated = decodeEntryRow((await this.entriesRepo.findById(entryId)) as JourneyEntry);
await this.broadcastJourneyEvent(entry.journey_id, 'journey:entry:updated', { entry: updated }, sid);
return updated;
return { entry: updated, previous };
}
// Reorder entries (typically within a single day). Caller passes the new
// desired order of ids; each entry's sort_order is set to its index in the
// array. Only entries owned by this journey are accepted.
async reorderEntries(journeyId: number, userId: number, orderedIds: number[], sid?: string): Promise<boolean> {
if (!(await this.canEdit(journeyId, userId))) return false;
if (!orderedIds.length) return true;
return (await this.reorderEntriesWithPrevious(journeyId, userId, orderedIds, sid)) !== null;
}
/** The reorder every surface makes, with the order the ids stood in before it (the journal's reading order). */
async reorderEntriesWithPrevious(journeyId: number, userId: number, orderedIds: number[], sid?: string): Promise<{ previousOrder: number[] } | null> {
if (!(await this.canEdit(journeyId, userId))) return null;
if (!orderedIds.length) return { previousOrder: [] };
// JG81 — ownership verification.
const matchedIds = await this.entriesRepo.listIdsIn(journeyId, orderedIds);
if (matchedIds.length !== orderedIds.length) return false;
if (matchedIds.length !== orderedIds.length) return null;
const named = new Set(orderedIds);
const previousOrder = (await this.entriesRepo.listForJourney(journeyId)).map((e) => e.id).filter((id) => named.has(id));
const now = this.ts();
// JG82/JG83 (the fourth `uow.transactional` block) — the legacy
@@ -1311,7 +1241,7 @@ export class JourneyDomainService {
});
await this.broadcastJourneyEvent(journeyId, 'journey:entries:reordered', { orderedIds }, sid);
return true;
return { previousOrder };
}
/**
@@ -0,0 +1,132 @@
import { presenceSet } from '../../db/repositories/_shared/presence-set';
import type { JourneyEntry } from '../../types';
import { decodeEntryRow } from './journey-entry-row';
/**
* An update of a journal entry as every surface hands it in (the REST route,
* the MCP tool, the plugin RPC), the columns it writes, and what it replaced.
* Pure: the service resolves the entry's country from its coordinates and
* the clock, and hands both in.
*/
export type JourneyEntryUpdateInput = Partial<{
type: string;
title: string;
story: string;
entry_date: string;
entry_time: string;
location_name: string;
location_lat: number;
location_lng: number;
mood: string;
weather: string;
tags: string[];
pros_cons: { pros: string[]; cons: string[] };
visibility: string;
sort_order: number;
stats_excluded: boolean;
dismissed: boolean;
is_draft: boolean;
}>;
/** The columns an update writes, as they are stored. */
export interface JourneyEntryColumns {
type: string;
title: string | null;
story: string | null;
entry_date: string;
entry_time: string | null;
location_name: string | null;
location_lat: number | null;
location_lng: number | null;
mood: string | null;
weather: string | null;
tags: string | null;
pros_cons: string | null;
visibility: string;
sort_order: number;
stats_excluded: number;
dismissed: number;
is_draft: number;
country_code: string | null;
updated_at: number;
}
/**
* JG78: the columns an update of `entry` with `data` writes, each resolved to
* its bound value (`tags`/`pros_cons` JSON-encoded, the flags 0/1, the
* country recomputed whenever either half of the coordinates is named,
* including as null, which takes the entry off the map). The skeleton to
* entry promotion keeps the legacy nuance: a story written onto a skeleton
* makes it an entry even over an explicit `data.type`, as the legacy SET
* list's last assignment did. `updated_at` is always written.
*/
export function entryUpdatePatch(
entry: JourneyEntry,
data: JourneyEntryUpdateInput,
country: string | null,
now: number,
): Partial<JourneyEntryColumns> {
const promoteToEntry = entry.type === 'skeleton' && !!data.story && data.story.trim().length > 0;
const proscons = data.pros_cons && typeof data.pros_cons === 'object' ? JSON.stringify(data.pros_cons) : null;
return presenceSet<JourneyEntryColumns>({
type: [data.type !== undefined || promoteToEntry, promoteToEntry ? 'entry' : (data.type as string)],
title: [data.title !== undefined, data.title as string],
story: [data.story !== undefined, data.story as string],
entry_date: [data.entry_date !== undefined, data.entry_date as string],
entry_time: [data.entry_time !== undefined, data.entry_time as string],
location_name: [data.location_name !== undefined, data.location_name as string],
location_lat: [data.location_lat !== undefined, data.location_lat as number | null],
location_lng: [data.location_lng !== undefined, data.location_lng as number | null],
mood: [data.mood !== undefined, data.mood as string],
weather: [data.weather !== undefined, data.weather as string],
// A caller sending `tags: null`/`pros_cons: null` to CLEAR the field must write SQL NULL, never the
// JSON string "null" (tools-journey.test.ts, "clears a field on null").
tags: [data.tags !== undefined, Array.isArray(data.tags) ? JSON.stringify(data.tags) : null],
pros_cons: [data.pros_cons !== undefined, proscons],
visibility: [data.visibility !== undefined, data.visibility as string],
sort_order: [data.sort_order !== undefined, data.sort_order as number],
stats_excluded: [data.stats_excluded !== undefined, data.stats_excluded ? 1 : 0],
dismissed: [data.dismissed !== undefined, data.dismissed ? 1 : 0],
is_draft: [data.is_draft !== undefined, data.is_draft ? 1 : 0],
country_code: [data.location_lat !== undefined || data.location_lng !== undefined, country],
updated_at: [true, now],
});
}
/** The fields an update can write back, as the MCP tool takes them. */
const RESTORABLE = [
'title',
'story',
'entry_date',
'entry_time',
'location_name',
'location_lat',
'location_lng',
'mood',
'weather',
'tags',
'pros_cons',
'visibility',
'type',
'stats_excluded',
'dismissed',
'is_draft',
] as const;
/** What an entry update replaced: the fields `data` names, as the entry held them on the wire, decoded. */
export type JourneyEntryPrevious = Partial<Record<(typeof RESTORABLE)[number], unknown>>;
/**
* The entry's values, as read before the update, of exactly the fields the
* update names (the sort order aside, which reorder takes back): what writing
* the change back sets again. JSON columns decoded, flags as booleans.
*/
export function entryPrevious(entry: JourneyEntry, data: JourneyEntryUpdateInput): JourneyEntryPrevious {
const wire = decodeEntryRow(entry) as unknown as Record<string, unknown>;
const previous: JourneyEntryPrevious = {};
for (const key of RESTORABLE) if (data[key] !== undefined) previous[key] = wire[key] ?? null;
// A story written onto a suggestion makes it an entry: going back makes it a suggestion again.
if (entry.type === 'skeleton' && typeof data.story === 'string' && data.story.trim()) previous.type = 'skeleton';
return previous;
}
+22 -83
View File
@@ -22,6 +22,8 @@ import {
idSchema,
journeyCreateToolSchema,
journeyEntriesRangeSchema,
journeyEntryUpdateToolSchema,
journeyReorderEntriesToolSchema,
journeyEntryProsConsSchema,
journeyEntryTypeSchema,
journeyEntryVisibilitySchema,
@@ -29,7 +31,9 @@ import {
journeyUpdateToolSchema,
type JourneyCreateTool,
type JourneyEntryType,
type JourneyEntryUpdateTool,
type JourneyEntryVisibility,
type JourneyReorderEntriesTool,
type JourneyUpdateTool,
} from '@trek/shared';
@@ -428,87 +432,21 @@ export class JourneyMcp {
@Tool({
name: 'update_journey_entry',
description:
'Update an existing journey entry: its text, date, place, coordinates, weather, tags, verdict, visibility, whether it is a draft, or whether it counts as a stop. Fields left out keep their value; pass null to clear one. To move an entry within its day use reorder_journey_entries rather than setting sort_order here.',
inputSchema: {
entryId: idSchema,
title: z.string().max(300).nullable().optional(),
story: z.string().nullable().optional(),
entry_date: z
.string()
.regex(/^\d{4}-\d{2}-\d{2}$/)
.optional(),
entry_time: z.string().nullable().optional(),
location_name: z.string().nullable().optional(),
location_lat: z
.number()
.min(-90)
.max(90)
.nullable()
.optional()
.describe('Latitude, or null to take the entry off the journey map'),
location_lng: z.number().min(-180).max(180).nullable().optional(),
mood: z.string().nullable().optional(),
weather: z.string().max(100).nullable().optional(),
tags: z.array(z.string()).nullable().optional(),
pros_cons: PROS_CONS.nullable().optional().describe('Replaces the whole verdict; null clears it'),
visibility: ENTRY_VISIBILITY.optional(),
type: ENTRY_TYPE.optional().describe(
'Promote a trip-derived "skeleton" to a real "entry" once it has been written up',
),
sort_order: z.number().int().min(0).optional(),
stats_excluded: z
.boolean()
.optional()
.describe(
'True leaves the entry in the journal but takes it off the journey route and out of its distance, countries and step count (see get_journey_stats); false puts it back. For the home airport, a stopover, the place the trip was planned from',
),
dismissed: z
.boolean()
.optional()
.describe(
'True waves a trip-derived suggestion away: it leaves the journey without being deleted, so the trip sync does not offer it again. restore_journey_suggestions brings every dismissed one back',
),
is_draft: z
.boolean()
.optional()
.describe('True turns the entry into a draft that the journey share link leaves out; false publishes it'),
},
'Update an existing journey entry: its text, date, place, coordinates, weather, tags, verdict, visibility, whether it is a draft, or whether it counts as a stop. Fields left out keep their value; pass null to clear one. To move an entry within its day use reorder_journey_entries rather than setting sort_order here. Answers with the entry and, under previous, what the changed fields held before.',
inputSchema: { entryId: idSchema, ...journeyEntryUpdateToolSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: journeyAddonOn,
access: { group: 'journey', mode: 'write' },
})
async updateJourneyEntry(
{
entryId,
...data
}: {
entryId: number;
title?: string | null;
story?: string | null;
entry_date?: string;
entry_time?: string | null;
location_name?: string | null;
location_lat?: number | null;
location_lng?: number | null;
mood?: string | null;
weather?: string | null;
tags?: string[] | null;
pros_cons?: { pros: string[]; cons: string[] } | null;
visibility?: JourneyEntryVisibility;
type?: JourneyEntryType;
sort_order?: number;
stats_excluded?: boolean;
dismissed?: boolean;
is_draft?: boolean;
},
ctx: McpContext,
) {
const entry = await this.journey.updateEntry(entryId, ctx.userId, data, undefined);
if (!entry) return notFound('Entry not found or access denied.');
async updateJourneyEntry({ entryId, ...data }: JourneyEntryUpdateTool & { entryId: number }, ctx: McpContext) {
// The update PATCH /api/journeys/entries/:entryId makes, with what it replaced.
const updated = await this.journey.updateEntryWithPrevious(entryId, ctx.userId, data, undefined);
if (!updated) return notFound('Entry not found or access denied.');
const { entry, previous } = updated;
// Return through the listEntries enrichment (parsed tags/pros_cons, photos), matching create_journey_entry.
const enriched =
(await this.journey.listEntries(entry.journey_id, ctx.userId))?.find((e) => e.id === entry.id) ?? entry;
return ok({ entry: enriched });
return ok({ entry: enriched, previous });
}
@Tool({
@@ -527,19 +465,20 @@ export class JourneyMcp {
@Tool({
name: 'reorder_journey_entries',
description: 'Reorder entries within a journey by providing the desired order of entry IDs.',
inputSchema: {
journeyId: idSchema,
orderedIds: z.array(idSchema),
},
description:
'Reorder entries within a journey by providing the desired order of entry IDs. Answers with previous_order, the same ids in the order they stood in before.',
inputSchema: { journeyId: idSchema, ...journeyReorderEntriesToolSchema.shape },
annotations: TOOL_ANNOTATIONS_WRITE,
when: journeyAddonOn,
access: { group: 'journey', mode: 'write' },
})
async reorderJourneyEntries({ journeyId, orderedIds }: { journeyId: number; orderedIds: number[] }, ctx: McpContext) {
const success = await this.journey.reorderEntries(journeyId, ctx.userId, orderedIds, undefined);
if (!success) return notFound('Journey not found, access denied, or entry IDs do not belong to this journey.');
return ok({ success: true });
async reorderJourneyEntries(
{ journeyId, orderedIds }: JourneyReorderEntriesTool & { journeyId: number },
ctx: McpContext,
) {
const reordered = await this.journey.reorderEntriesWithPrevious(journeyId, ctx.userId, orderedIds, undefined);
if (!reordered) return notFound('Journey not found, access denied, or entry IDs do not belong to this journey.');
return ok({ success: true, previous_order: reordered.previousOrder });
}
@Tool({