Merge pull request #3319 from liketrek/codex/trip-tags-desktop-polish

Add custom trip tags and refine the desktop interface
This commit is contained in:
Maurice
2026-12-05 13:26:40 +01:00
committed by GitHub
340 changed files with 3561 additions and 2540 deletions
@@ -67,10 +67,10 @@ export const PLUGIN_ENTITY_CONTRACT = {
'reminder_sent_for',
'costs_mode',
],
// The sole credential of the anonymous calendar feed.
withheld: ['feed_token'],
// Keep the calendar credential and internal tag serialization out of the plugin API.
withheld: ['feed_token', 'tags_json'],
wholeRow: true,
derived: ['day_count', 'place_count', 'is_owner', 'owner_username', 'shared_count'],
derived: ['day_count', 'place_count', 'is_owner', 'owner_username', 'shared_count', 'tags'],
},
place: {
table: 'places',
+2 -2
View File
@@ -136,7 +136,7 @@ export class TripsController {
throw new HttpException({ error: 'No permission to create trips' }, 403);
}
// Presence/shape validation happens in the ZodValidationPipe (tripCreateRequestSchema).
const { title, description, currency, reminder_days, day_count } = body;
const { title, description, tags, currency, reminder_days, day_count } = body;
const start_date: string | null = body.start_date || null;
const end_date: string | null = body.end_date || null;
if (start_date && end_date && new Date(end_date) < new Date(start_date)) {
@@ -145,7 +145,7 @@ export class TripsController {
const parsedDayCount = day_count ? Math.min(Math.max(Number(day_count) || 7, 1), MAX_TRIP_DAYS) : undefined;
try {
const { trip, tripId, reminderDays } = await this.tripWrites.create(
{ title, description, start_date, end_date, currency, reminder_days, day_count: parsedDayCount },
{ title, description, tags, start_date, end_date, currency, reminder_days, day_count: parsedDayCount },
{ userId: user.id, role: user.role, socketId },
);
await this.audit.writeAudit({
+42 -2
View File
@@ -1,5 +1,14 @@
import { ValidationError } from '../common/domain-errors';
import { addIsoDays, MAX_TRIP_DAYS, tripSpanDays, type PermissionKey } from '@trek/shared';
import {
addIsoDays,
MAX_TRIP_DAYS,
MAX_TRIP_TAGS,
tripSpanDays,
tripTagKey,
uniqueTripTags,
type PermissionKey,
type TripUpdateRequest,
} from '@trek/shared';
/**
* Pure helpers of the trips domain, moved out of trips.service.ts. Nothing
@@ -7,6 +16,28 @@ import { addIsoDays, MAX_TRIP_DAYS, tripSpanDays, type PermissionKey } from '@tr
* TripsService.
*/
export interface CreateTripData {
title: string;
description?: string | null;
tags?: string[];
start_date?: string | null;
end_date?: string | null;
currency?: string;
reminder_days?: number;
day_count?: number;
}
// The wire contract of PUT /api/trips/:id (tripUpdateRequestSchema), which
// update_trip hands on as well; nullable where it is, as null always arrived.
export type UpdateTripData = TripUpdateRequest & { add_tags?: string[]; remove_tags?: string[] };
export function patchTripTags(current: string[], add: string[] = [], remove: string[] = []): string[] {
const removed = new Set(remove.map((tag) => tripTagKey(tag)));
const tags = uniqueTripTags([...current.filter((tag) => !removed.has(tripTagKey(tag))), ...add]);
if (tags.length > MAX_TRIP_TAGS) throw new ValidationError(`A trip can have up to ${MAX_TRIP_TAGS} tags.`);
return tags;
}
/**
* The date range is refused, not cut short: generateDays used to clip the day
* rows at the limit while the trip kept its full end date, so everything past
@@ -35,7 +66,16 @@ export function withoutFeedToken<T>(row: T): T {
}
/** The fields of a trip update that count as an edit, as against archiving it or changing its cover. */
const TRIP_EDIT_FIELDS = ['title', 'description', 'start_date', 'end_date', 'currency', 'reminder_days', 'day_count'];
const TRIP_EDIT_FIELDS = [
'title',
'description',
'tags',
'start_date',
'end_date',
'currency',
'reminder_days',
'day_count',
];
/**
* The permissions a trip update needs, in the order PUT /api/trips/:id checks
+42 -5
View File
@@ -35,6 +35,9 @@ import {
MAX_TRIP_DAYS,
tripCalendarDayEventsSchema,
tripUpdateRequestSchema,
tripTagNamesSchema,
tripTagNameSchema,
tripTagKey,
type TripCostsMode,
} from '@trek/shared';
@@ -149,6 +152,7 @@ export class TripsMcp {
.max(30)
.optional()
.describe('How many days before departure the pre-trip reminder fires (default 3). 0 turns the reminder off.'),
tags: tripTagNamesSchema.optional().describe('Custom tags for the trip itself, such as City break or Work'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
access: { group: 'trips', mode: 'write' },
@@ -162,6 +166,7 @@ export class TripsMcp {
currency,
day_count,
reminder_days,
tags,
}: {
title: string;
description?: string;
@@ -170,6 +175,7 @@ export class TripsMcp {
currency?: string;
day_count?: number;
reminder_days?: number;
tags?: string[];
},
ctx: McpContext,
) {
@@ -191,7 +197,7 @@ export class TripsMcp {
}
try {
const { trip } = await this.tripWrites.create(
{ title, description, start_date, end_date, currency, day_count, reminder_days },
{ title, description, start_date, end_date, currency, day_count, reminder_days, ...(tags ? { tags } : {}) },
await this.listWriter(ctx.userId),
);
return ok({ trip });
@@ -256,6 +262,21 @@ export class TripsMcp {
costs_mode: tripUpdateRequestSchema.shape.costs_mode.describe(
'How the trip keeps its costs: split (who paid and who shares each expense, with settling up) or totals (what the trip costs, nothing split). Who paid and the shares stay stored either way. Needs the budget_edit permission rather than trip_edit',
),
tags: tripTagNamesSchema
.optional()
.describe(
'Replace all custom tags on the trip. Send an empty array to clear them. Cannot be combined with add_tags or remove_tags',
),
add_tags: tripTagNamesSchema
.optional()
.describe(
'Assign existing or new custom tags to the trip, keeping its other tags. Tag names are matched case-insensitively',
),
remove_tags: tripTagNamesSchema
.optional()
.describe(
'Remove these custom tags from this trip only. Other tags stay assigned. Removals apply before additions',
),
},
annotations: TOOL_ANNOTATIONS_WRITE,
access: { group: 'trips', mode: 'write' },
@@ -275,6 +296,9 @@ export class TripsMcp {
reminder_days,
date_shift_mode,
costs_mode,
tags,
add_tags,
remove_tags,
}: {
tripId: number;
title?: string;
@@ -289,6 +313,9 @@ export class TripsMcp {
reminder_days?: number;
date_shift_mode?: 'keep_bookings' | 'shift_all';
costs_mode?: TripCostsMode;
tags?: string[];
add_tags?: string[];
remove_tags?: string[];
},
ctx: McpContext,
) {
@@ -310,12 +337,17 @@ export class TripsMcp {
day_count,
reminder_days,
costs_mode,
...(tags ? { tags } : {}),
};
// The rights PUT /api/trips/:id asks for, field by field: archiving, the cover and the costs mode have their own.
const granted = await Promise.all(
tripUpdatePermissions(fields).map(({ action }) => this.guards.hasTripPermission(action, tripId, ctx.userId)),
tripUpdatePermissions({ ...fields, tags: tags ?? add_tags ?? remove_tags }).map(({ action }) =>
this.guards.hasTripPermission(action, tripId, ctx.userId),
),
);
if (granted.includes(false)) return permissionDenied();
if (tags !== undefined && (add_tags !== undefined || remove_tags !== undefined))
return errorResult('tags cannot be combined with add_tags or remove_tags.');
if (clear_dates && (start_date || end_date))
return errorResult('clear_dates cannot be combined with start_date or end_date.');
if (start_date) {
@@ -339,7 +371,7 @@ export class TripsMcp {
const { updatedTrip, removedDays, boundaries } = await this.trips.update(
tripId,
ctx.userId,
{ ...fields, date_shift_mode },
{ ...fields, date_shift_mode, add_tags, remove_tags },
role,
);
this.guards.safeBroadcast(tripId, 'trip:updated', { trip: updatedTrip });
@@ -399,12 +431,17 @@ export class TripsMcp {
'List all trips the current user owns or is a member of. Use this for trip discovery before calling get_trip_summary.',
inputSchema: {
include_archived: z.boolean().optional().describe('Include archived trips (default false)'),
tag: tripTagNameSchema.optional().describe('Only include trips with this custom tag, matched case-insensitively'),
},
annotations: TOOL_ANNOTATIONS_READONLY,
})
async listTrips({ include_archived }: { include_archived?: boolean }, ctx: McpContext) {
async listTrips({ include_archived, tag }: { include_archived?: boolean; tag?: string }, ctx: McpContext) {
const notice = ctx.getDeprecationNotice ? ctx.getDeprecationNotice() : null;
const trips = await this.trips.list(ctx.userId, include_archived ? null : 0);
const accessible = await this.trips.list(ctx.userId, include_archived ? null : 0);
const tagKey = tag ? tripTagKey(tag) : null;
const trips = tagKey
? accessible.filter((trip) => trip.tags?.some((name) => tripTagKey(name) === tagKey))
: accessible;
if (notice)
return {
isError: true as const,
+21 -20
View File
@@ -35,7 +35,7 @@ import {
type RoadtripDayBoundary,
type TrekWsPayload,
type TrekWsTripEventName,
type TripUpdateRequest,
uniqueTripTags,
} from '@trek/shared';
import { RealtimeService } from '../realtime/realtime.service';
import { PermissionsService } from '../permissions/permissions.service';
@@ -54,21 +54,7 @@ import { inOrder } from '../common/in-order';
import { UnitOfWork } from '../database/unit-of-work';
import { legacyBoundIntegerText } from '../common/row-id';
import { appClock } from '../common/timezoneService';
import { assertTripSpan, leaveStartFor } from './trips.helpers';
interface CreateTripData {
title: string;
description?: string | null;
start_date?: string | null;
end_date?: string | null;
currency?: string;
reminder_days?: number;
day_count?: number;
}
// The wire contract of PUT /api/trips/:id (tripUpdateRequestSchema), which
// update_trip hands on as well; nullable where it is, as null always arrived.
type UpdateTripData = TripUpdateRequest;
import { assertTripSpan, leaveStartFor, patchTripTags, type CreateTripData, type UpdateTripData } from './trips.helpers';
export interface UpdateTripResult {
updatedTrip: any;
@@ -366,6 +352,7 @@ export class TripsService {
user_id: userId,
title: data.title,
description: data.description || null,
...(data.tags === undefined ? {} : { tags: data.tags }),
start_date: startDate,
end_date: endDate,
currency,
@@ -422,7 +409,7 @@ export class TripsService {
/** TP22 — `TripsRepository.findRaw` (shared with `TripReadModelService.getTripSummary`, TR-B, per the inventory's own note that they are the identical statement). */
async getRaw(tripId: string | number): Promise<Trip | undefined> {
const row = await this.tripsRepo.findRaw(tripId);
return (row ?? undefined) as Trip | undefined;
return row ?? undefined;
}
async searchCoverImages(query: string, userId: number) {
@@ -442,10 +429,14 @@ export class TripsService {
* are one transaction, so a failing `generateDays` or booking resync leaves all of them as they were.
*/
async updateTrip(tripId: string | number, userId: number, data: UpdateTripData, userRole: string, rebase: CurrencyRebase | null = null): Promise<UpdateTripResult> {
const trip = await this.tripsRepo.findRaw(tripId) as (Trip & { reminder_days?: number }) | null; // TP24
const trip = await this.tripsRepo.findRaw(tripId); // TP24
if (!trip) throw new NotFoundError('Trip not found');
const { title, description, currency, is_archived, cover_image, reminder_days, costs_mode } = data;
const { add_tags, remove_tags, date_shift_mode, ...details } = data;
const patchTags = !!(add_tags?.length || remove_tags?.length);
const onlyPatchingTags = patchTags && Object.values(details).every(value => value === undefined);
let tags = data.tags === undefined ? undefined : uniqueTripTags(data.tags);
const { newStart, newEnd, dayCount, regenerate } = this.resolveRange(trip, data);
const newTitle = title || trip.title;
@@ -468,11 +459,19 @@ export class TripsService {
let boundaries: RoadtripDayBoundary[] | null = null; // the road trip day boundaries, when they moved with their days
let vacayId: number | undefined; // the vacay plan whose leave days moved along (#2604)
await this.uow.transactional(async () => {
if (patchTags) {
// Read within the serialized write transaction so concurrent tag edits
// merge against the latest tags and keep each other's changes.
const current = (await this.tripsRepo.findRaw(tripIdNum))?.tags ?? [];
tags = patchTripTags(current, add_tags, remove_tags);
}
// Before the row: the rebase reads the outgoing currency off it (#1543).
if (rebase) await this.budget.applyCurrencyRebase(tripId, rebase);
await this.tripsRepo.updateTripRow(tripIdNum, { // TP25
await this.tripsRepo.updateTripRow(tripIdNum, onlyPatchingTags ? { tags } : { // TP25
title: newTitle,
description: newDesc ?? null,
...(tags === undefined ? {} : { tags }),
start_date: newStart || null,
end_date: newEnd || null,
currency: newCurrency,
@@ -495,7 +494,7 @@ export class TripsService {
// Unless everything shifts, a range that still holds every day (one more day
// before the start or after the end) leaves each day, and all on it, on its
// date (#3119); only a moved or shorter range re-dates the days by position.
const shiftAll = data.date_shift_mode === 'shift_all';
const shiftAll = date_shift_mode === 'shift_all';
const grid = await this.generateDays(tripId, newStart || null, newEnd || null, dayCount, !shiftAll);
removedDays = grid.removed;
boundaries = grid.boundaries;
@@ -523,6 +522,7 @@ export class TripsService {
const changes: Record<string, unknown> = {};
if (title && title !== trip.title) changes.title = title;
if (tags && JSON.stringify(tags) !== JSON.stringify(trip.tags)) changes.tags = tags;
if (newStart !== trip.start_date) changes.start_date = newStart;
if (newEnd !== trip.end_date) changes.end_date = newEnd;
if (newReminder !== oldReminder) changes.reminder_days = newReminder === 0 ? 'none' : `${newReminder} days`;
@@ -637,6 +637,7 @@ export class TripsService {
user_id: newOwnerId,
title: newTitle,
description: src.description,
...(src.tags?.length ? { tags: src.tags } : {}),
start_date: src.start_date,
end_date: src.end_date,
currency: src.currency,