mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-05 18:34:09 +00:00
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:
@@ -3,7 +3,7 @@
|
||||
"scripts/generate-entities.ts": 2259,
|
||||
"src/db/repositories/Places.repository.ts": 1432,
|
||||
"src/db/repositories/Reservations.repository.ts": 1538,
|
||||
"src/db/repositories/Trips.repository.ts": 1120,
|
||||
"src/db/repositories/Trips.repository.ts": 1101,
|
||||
"src/db/repositories/Users.repository.ts": 1403,
|
||||
"src/nest/atlas/atlas.service.ts": 1166,
|
||||
"src/nest/auth/auth.service.ts": 1114,
|
||||
|
||||
@@ -65,6 +65,7 @@ export class Trips {
|
||||
updated_at?: string | null;
|
||||
reminder_sent_for?: string | null;
|
||||
costs_mode: TTripsCostsMode & Opt = TripsCostsMode.SPLIT;
|
||||
tags_json?: string | null;
|
||||
assistant_attachments_collection = new Collection<AssistantAttachments>(this);
|
||||
assistant_threads_collection = new Collection<AssistantThreads>(this);
|
||||
budget_category_order_collection = new Collection<BudgetCategoryOrder>(this);
|
||||
@@ -146,6 +147,7 @@ export const TripsSchema = defineEntity({
|
||||
updated_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
|
||||
reminder_sent_for: p.text().nullable(),
|
||||
costs_mode: p.enum(() => TripsCostsMode).default('split'),
|
||||
tags_json: p.text().nullable(),
|
||||
assistant_attachments_collection: () => p.oneToMany(AssistantAttachments).mappedBy('trip').hidden(),
|
||||
assistant_threads_collection: () => p.oneToMany(AssistantThreads).mappedBy('trip').hidden(),
|
||||
budget_category_order_collection: () => p.oneToMany(BudgetCategoryOrder).mappedBy('trip').hidden(),
|
||||
|
||||
@@ -18,4 +18,5 @@ export interface TripsTable {
|
||||
updated_at: InsertOptional<string | null>;
|
||||
reminder_sent_for: InsertOptional<string | null>;
|
||||
costs_mode: InsertOptional<string>;
|
||||
tags_json: InsertOptional<string | null>;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { engineDdl } from '../migration-utils';
|
||||
import { Migration } from '@mikro-orm/migrations';
|
||||
|
||||
export class Migration20200101046650_trips_can_carry_custom_tags extends Migration {
|
||||
override name = 'Migration20200101046650_trips_can_carry_custom_tags';
|
||||
|
||||
override up(): void {
|
||||
engineDdl(this, {
|
||||
sqlite: ['ALTER TABLE trips ADD COLUMN tags_json TEXT'],
|
||||
postgres: ['ALTER TABLE "trips" ADD COLUMN "tags_json" text'],
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,9 @@ import { TrekRepository } from './_shared/trek-repository';
|
||||
import { tripAccessExpr } from './_shared/trip-access';
|
||||
import type { DB } from '../kysely/db';
|
||||
import { toRowId } from '../row-id';
|
||||
import { decodeTags, encodeTags, type TripDatabaseRow, type TripRawRow } from './tripRows';
|
||||
|
||||
export type { TripRawRow } from './tripRows';
|
||||
|
||||
/** What a trip-scoped request learns about the trip once access is verified. */
|
||||
export interface TripAccess {
|
||||
@@ -14,34 +17,6 @@ export interface TripAccess {
|
||||
currency: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* `SELECT * FROM trips WHERE id = ?`, every scalar column — the row
|
||||
* `TripReadModelService.getTripSummary` (TR-B) and, once Task 7 lands,
|
||||
* `TripsService.getRaw` (TP22) both need, `feed_token` included: the
|
||||
* `withoutFeedToken()` JS strip that guards the credential stays in the
|
||||
* SERVICE (TR-B's ruling), so this repository method must hand the column
|
||||
* back intact for that strip to have something to delete.
|
||||
*/
|
||||
export interface TripRawRow {
|
||||
id: number;
|
||||
user_id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
start_date: string | null;
|
||||
end_date: string | null;
|
||||
currency: string | null;
|
||||
cover_image: string | null;
|
||||
is_archived: number | null;
|
||||
reminder_days: number | null;
|
||||
feed_token: string | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
reminder_sent_for: string | null;
|
||||
costs_mode: TTripsCostsMode;
|
||||
}
|
||||
|
||||
const _tripRawRowKeys: AssertRowKeys<TripRawRow, Trips> = true;
|
||||
|
||||
/**
|
||||
* `TRIP_SELECT`'s output row (inventory §11a) — every `TripRawRow` column
|
||||
* plus the four computed/joined columns the projection adds. `feed_token`
|
||||
@@ -350,8 +325,8 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
const row = await this.qb('t')
|
||||
.select(['t.*'])
|
||||
.where('t.id = ?', [id])
|
||||
.execute<TripRawRow | undefined>('get', false);
|
||||
return row ?? null;
|
||||
.execute<TripDatabaseRow | undefined>('get', false);
|
||||
return row ? decodeTags(row) : null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
@@ -405,7 +380,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
const id = toRowId(trip_id);
|
||||
if (id === null) return undefined;
|
||||
const row = await this.tripSelectQuery(user_id).where('t.id', '=', id).executeTakeFirst();
|
||||
return row as TripSelectRow | undefined;
|
||||
return row ? decodeTags(row) as TripSelectRow : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -432,7 +407,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
.where('t.id', '=', id)
|
||||
.where((eb) => tripAccessExpr(eb, 't.user_id', 'm.user_id', user_id))
|
||||
.executeTakeFirst();
|
||||
return row as TripSelectRow | undefined;
|
||||
return row ? decodeTags(row) as TripSelectRow : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -447,7 +422,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
.where((eb) => tripAccessExpr(eb, 't.user_id', 'm.user_id', user_id));
|
||||
if (archived !== null) query = query.where('t.is_archived', '=', archived);
|
||||
const rows = await query.orderBy('t.created_at', 'desc').execute();
|
||||
return rows as TripSelectRow[];
|
||||
return rows.map(decodeTags) as TripSelectRow[];
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -525,6 +500,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
user_id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
tags?: string[];
|
||||
start_date: string | null;
|
||||
end_date: string | null;
|
||||
currency: string;
|
||||
@@ -534,6 +510,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
user: input.user_id,
|
||||
title: input.title,
|
||||
description: input.description,
|
||||
...encodeTags(input.tags),
|
||||
start_date: input.start_date,
|
||||
end_date: input.end_date,
|
||||
currency: input.currency,
|
||||
@@ -562,6 +539,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
user_id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
tags?: string[];
|
||||
start_date: string | null;
|
||||
end_date: string | null;
|
||||
currency: string | null;
|
||||
@@ -573,6 +551,7 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
user: input.user_id,
|
||||
title: input.title,
|
||||
description: input.description,
|
||||
...encodeTags(input.tags),
|
||||
start_date: input.start_date,
|
||||
end_date: input.end_date,
|
||||
currency: input.currency,
|
||||
@@ -605,11 +584,12 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
*/
|
||||
async updateTripRow(
|
||||
id: number,
|
||||
data: Pick<TripRawRow, 'title' | 'description' | 'start_date' | 'end_date' | 'is_archived' | 'cover_image' | 'costs_mode'>
|
||||
& { currency: string; reminder_days: number },
|
||||
data: Partial<Pick<TripRawRow, 'title' | 'description' | 'start_date' | 'end_date' | 'is_archived' | 'cover_image' | 'costs_mode'>
|
||||
& { currency: string; reminder_days: number; tags: string[] }>,
|
||||
): Promise<void> {
|
||||
const platform = this.getEntityManager().getPlatform();
|
||||
await this.nativeUpdate({ id }, { ...data, updated_at: currentTimestamp(platform) });
|
||||
const { tags, ...fields } = data;
|
||||
await this.nativeUpdate({ id }, { ...fields, ...encodeTags(tags), updated_at: currentTimestamp(platform) });
|
||||
}
|
||||
|
||||
/** TP35 (`trips.service.ts::updateCoverImage`) — `UPDATE trips SET cover_image=?, updated_at=CURRENT_TIMESTAMP WHERE id=?`. */
|
||||
@@ -910,10 +890,11 @@ export class TripsRepository extends TrekRepository<Trips> {
|
||||
* the join can never fan a `t` row out to more than one result row.
|
||||
*/
|
||||
async listOwnedOrMember(user_id: number): Promise<TripRawRow[]> {
|
||||
return await this.accessibleTripsQuery(user_id)
|
||||
const rows = await this.accessibleTripsQuery(user_id)
|
||||
.select(['t.*'])
|
||||
.orderBy({ 't.start_date': 'desc' })
|
||||
.execute<TripRawRow[]>('all', false);
|
||||
.execute<TripDatabaseRow[]>('all', false);
|
||||
return rows.map(decodeTags);
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import type { TTripsCostsMode, Trips } from '../entities/Trips.entity';
|
||||
import type { AssertRowKeys } from './_shared/rows';
|
||||
import { tripTagNamesSchema, uniqueTripTags } from '@trek/shared';
|
||||
|
||||
/**
|
||||
* `SELECT * FROM trips WHERE id = ?`, every scalar column — the row
|
||||
* `TripReadModelService.getTripSummary` (TR-B) and, once Task 7 lands,
|
||||
* `TripsService.getRaw` (TP22) both need, `feed_token` included: the
|
||||
* `withoutFeedToken()` JS strip that guards the credential stays in the
|
||||
* SERVICE (TR-B's ruling), so this repository method must hand the column
|
||||
* back intact for that strip to have something to delete.
|
||||
*/
|
||||
export interface TripDatabaseRow {
|
||||
id: number;
|
||||
user_id: number;
|
||||
title: string;
|
||||
description: string | null;
|
||||
tags_json: string | null;
|
||||
start_date: string | null;
|
||||
end_date: string | null;
|
||||
currency: string | null;
|
||||
cover_image: string | null;
|
||||
is_archived: number | null;
|
||||
reminder_days: number | null;
|
||||
feed_token: string | null;
|
||||
created_at: string | null;
|
||||
updated_at: string | null;
|
||||
reminder_sent_for: string | null;
|
||||
costs_mode: TTripsCostsMode;
|
||||
}
|
||||
|
||||
const _tripRawRowKeys: AssertRowKeys<TripDatabaseRow, Trips> = true;
|
||||
|
||||
export type TripRawRow = Omit<TripDatabaseRow, 'tags_json'> & { tags?: string[] };
|
||||
|
||||
export function decodeTags<T extends { tags_json: string | null }>({ tags_json, ...row }: T) {
|
||||
let tags: string[] = [];
|
||||
if (tags_json) {
|
||||
try {
|
||||
const parsed = tripTagNamesSchema.safeParse(JSON.parse(tags_json));
|
||||
if (parsed.success) tags = parsed.data;
|
||||
} catch {
|
||||
// Older import tools may have written invalid JSON. Keep the trip readable.
|
||||
}
|
||||
}
|
||||
return { ...row, tags };
|
||||
}
|
||||
|
||||
export function encodeTags(tags: string[] | undefined): { tags_json?: string | null } {
|
||||
if (tags === undefined) return {};
|
||||
const unique = uniqueTripTags(tags);
|
||||
return { tags_json: unique.length ? JSON.stringify(unique) : null };
|
||||
}
|
||||
@@ -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',
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
+2
-4
@@ -31,11 +31,9 @@ export interface User {
|
||||
}
|
||||
|
||||
/**
|
||||
* A trips row as the database holds it, derived from the generated table type
|
||||
* so it cannot drift from the schema (currency, is_archived and reminder_days
|
||||
* are nullable columns, and feed_token and reminder_sent_for exist).
|
||||
* A trip row with its custom tags decoded from storage.
|
||||
*/
|
||||
export type Trip = Selectable<TripsTable>;
|
||||
export type Trip = Omit<Selectable<TripsTable>, 'tags_json'> & { tags?: string[] };
|
||||
|
||||
export interface Day {
|
||||
id: number;
|
||||
|
||||
@@ -130,6 +130,7 @@ const UNNUMBERED = [
|
||||
'Migration20200101046620_a_journey_link_can_ask_for_a_password_and_run_out',
|
||||
'Migration20200101046630_a_journey_gathers_comments_and_followers',
|
||||
'Migration20200101046640_bahrain_flights_keep_bahrain_time',
|
||||
'Migration20200101046650_trips_can_carry_custom_tags',
|
||||
];
|
||||
// The last step the positional runner ever had; planLegacyBaseline refuses a
|
||||
// schema_version past it.
|
||||
|
||||
@@ -98,7 +98,9 @@ describe('ReservationsRepository — CL1 (findRaw, existing method reused by cal
|
||||
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
|
||||
const legacy = testDb.prepare('SELECT * FROM trips WHERE id = ?').get(trip.id);
|
||||
|
||||
expect(typed).toEqual(legacy);
|
||||
const { tags_json, ...tripFields } = legacy as Record<string, unknown>;
|
||||
expect(tags_json).toBeNull();
|
||||
expect(typed).toEqual({ ...tripFields, tags: [] });
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -13,6 +13,10 @@ import type { EntityData } from '@mikro-orm/core';
|
||||
|
||||
import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest';
|
||||
|
||||
function expectedTrip({ tags_json, ...fields }: Record<string, unknown>) {
|
||||
return { ...fields, tags: typeof tags_json === 'string' ? JSON.parse(tags_json) : [] };
|
||||
}
|
||||
|
||||
const testDb = createSnapshotTestDb();
|
||||
let t: TestOrm;
|
||||
let trips: TripsRepository;
|
||||
@@ -238,7 +242,7 @@ describe('TripsRepository — TripMembersService / TripReadModelService (Plan 3c
|
||||
// test-sql-allow: the legacy statement is the oracle the repository read is held to.
|
||||
const legacyRow = testDb.prepare('SELECT * FROM trips WHERE id = ?').get(trip.id);
|
||||
const row = await trips.findRaw(trip.id);
|
||||
expect(row).toEqual(legacyRow);
|
||||
expect(row).toEqual(expectedTrip(legacyRow as Record<string, unknown>));
|
||||
expect(row?.feed_token).toBe('secret-token');
|
||||
});
|
||||
|
||||
@@ -329,7 +333,7 @@ describe('TripsRepository.findForViewer / listForUser / activeTrip (Plan 3c Task
|
||||
)
|
||||
.get({ userId: owner.id, tripId: trip.id });
|
||||
const row = await trips.findForViewer(trip.id, owner.id);
|
||||
expect(row).toEqual(legacyOwner);
|
||||
expect(row).toEqual(expectedTrip(legacyOwner as Record<string, unknown>));
|
||||
// createTrip's own start_date/end_date span already generates 5 days;
|
||||
// the two explicit createDay calls above add 2 more, for 7 total.
|
||||
expect(row).toMatchObject({
|
||||
@@ -356,7 +360,7 @@ describe('TripsRepository.findForViewer / listForUser / activeTrip (Plan 3c Task
|
||||
)
|
||||
.get({ userId: member.id, tripId: trip.id });
|
||||
const memberRow = await trips.findForViewer(trip.id, member.id);
|
||||
expect(memberRow).toEqual(legacyMember);
|
||||
expect(memberRow).toEqual(expectedTrip(legacyMember as Record<string, unknown>));
|
||||
expect(memberRow).toMatchObject({ is_owner: 0, day_count: 7, place_count: 3, shared_count: 1 });
|
||||
});
|
||||
|
||||
@@ -376,7 +380,7 @@ describe('TripsRepository.findForViewer / listForUser / activeTrip (Plan 3c Task
|
||||
)
|
||||
.get({ userId: owner.id, tripId: trip.id });
|
||||
const row = await trips.findForViewer(trip.id, owner.id);
|
||||
expect(row).toEqual(legacy);
|
||||
expect(row).toEqual(expectedTrip(legacy as Record<string, unknown>));
|
||||
expect(row).toMatchObject({
|
||||
description: null,
|
||||
start_date: null,
|
||||
@@ -429,7 +433,7 @@ describe('TripsRepository.findForViewer / listForUser / activeTrip (Plan 3c Task
|
||||
)
|
||||
.all({ userId: owner.id });
|
||||
const rows = await trips.listForUser(owner.id, null);
|
||||
expect(rows).toEqual(legacy);
|
||||
expect(rows).toEqual(legacy.map((row) => expectedTrip(row as Record<string, unknown>)));
|
||||
expect(rows.map((r) => r.id).sort()).toEqual([owned.id, shared.id, archived.id].sort());
|
||||
});
|
||||
|
||||
@@ -450,7 +454,9 @@ describe('TripsRepository.findForViewer / listForUser / activeTrip (Plan 3c Task
|
||||
`,
|
||||
)
|
||||
.all({ userId: owner.id, archived: 1 });
|
||||
expect(await trips.listForUser(owner.id, 1)).toEqual(legacyArchived);
|
||||
expect(await trips.listForUser(owner.id, 1)).toEqual(
|
||||
legacyArchived.map((row) => expectedTrip(row as Record<string, unknown>)),
|
||||
);
|
||||
expect((await trips.listForUser(owner.id, 1)).map((r) => r.id)).toEqual([archived.id]);
|
||||
expect((await trips.listForUser(owner.id, 0)).map((r) => r.id)).toEqual([active.id]);
|
||||
});
|
||||
@@ -1082,7 +1088,7 @@ describe('TripsRepository.listOwnedOrMember — AT1 parity with the legacy state
|
||||
const legacy = testDb.prepare(LEGACY_OWNED_OR_MEMBER).all(caller.id, caller.id, caller.id);
|
||||
const rows = await trips.listOwnedOrMember(caller.id);
|
||||
|
||||
expect(rows).toEqual(legacy);
|
||||
expect(rows).toEqual(legacy.map((row) => expectedTrip(row as Record<string, unknown>)));
|
||||
expect(rows.map((r) => r.id)).toEqual([memberOf.id, owned.id]);
|
||||
});
|
||||
|
||||
|
||||
@@ -298,6 +298,26 @@ describe('Tool: update_trip', () => {
|
||||
});
|
||||
});
|
||||
|
||||
it('updates dashboard tags by name while preserving unrelated tags', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id, { title: 'Weekend' });
|
||||
await withHarness(user.id, async (h) => {
|
||||
await h.client.callTool({ name: 'update_trip', arguments: { tripId: trip.id, tags: ['Work', 'Family'] } });
|
||||
const result = await h.client.callTool({
|
||||
name: 'update_trip',
|
||||
arguments: { tripId: trip.id, remove_tags: ['work'], add_tags: [' FAMILY ', 'City break'] },
|
||||
});
|
||||
expect(parseToolResult(result)).toMatchObject({ trip: { title: 'Weekend', tags: ['Family', 'City break'] } });
|
||||
expect(broadcastMock).toHaveBeenCalledWith(
|
||||
trip.id,
|
||||
'trip:updated',
|
||||
expect.objectContaining({
|
||||
trip: expect.objectContaining({ tags: ['Family', 'City break'] }),
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('broadcasts trip:updated event', async () => {
|
||||
const { user } = await makeUser(orm);
|
||||
const trip = await makeTrip(orm, user.id);
|
||||
|
||||
@@ -66,8 +66,8 @@ describe('the contract table', () => {
|
||||
expect(fields).toEqual([...contract.columns, ...contract.derived]);
|
||||
});
|
||||
|
||||
it('OUTCONTRACT-UNIT-004 a trip withholds its feed token and a user exposes four fields', () => {
|
||||
expect(contractOf('trip').withheld).toEqual(['feed_token']);
|
||||
it('OUTCONTRACT-UNIT-004 a trip withholds its feed token and stored tag data', () => {
|
||||
expect(contractOf('trip').withheld).toEqual(['feed_token', 'tags_json']);
|
||||
expect(pluginEntityFields('user')).toEqual(['id', 'username', 'display_name', 'avatar']);
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user