feat(places): tags on places, owned by the trip

A place keeps its one category, which decides its marker, and can now carry
any number of tags as extra labels to filter by.

- Tags belong to the trip (tags.trip_id): every member sees the same list and
  whoever may edit the trip's places adds, renames and deletes. Personal tags
  stay what they were.
- The place form picks them on desktop and mobile through one shared hook,
  usePlaceTags, and can add a new tag to the trip on the spot.
- The existing category filter of the places list lists the tags as well.
- Tags show on the place (inspector pills, phone place sheet); the marker is
  untouched.
- MCP: create_place, create_and_assign_place and update_place take `tags`,
  and list/create/update/delete_trip_tag manage a trip's tags.
- /api/trips/:tripId/tags and the tripTags:changed event keep every client
  of the trip in step.
This commit is contained in:
Mariano
2026-11-17 06:35:09 +00:00
committed by Maurice
parent e952586f60
commit 33d074c786
108 changed files with 3634 additions and 118 deletions
+5
View File
@@ -3,6 +3,7 @@ import { TagsRepository } from '../repositories/Tags.repository';
import { DbTimestampType } from '../types';
import { CollectionPlaces } from './CollectionPlaces.entity';
import { Places } from './Places.entity';
import { Trips } from './Trips.entity';
import { Users } from './Users.entity';
export class Tags {
@@ -13,6 +14,8 @@ export class Tags {
name!: string;
color?: string | null = '#10b981';
created_at?: string | null;
trip?: Ref<Trips> | null;
trip_id?: number | null;
collection_place_tags_inverse = new Collection<CollectionPlaces>(this);
place_tags_inverse = new Collection<Places>(this);
}
@@ -27,6 +30,8 @@ export const TagsSchema = defineEntity({
name: p.text(),
color: p.text().nullable(),
created_at: p.type(DbTimestampType).nullable().defaultRaw(`CURRENT_TIMESTAMP`),
trip: () => p.manyToOne(Trips).ref().deleteRule('cascade').nullable().hidden().index('idx_tags_trip_id'),
trip_id: p.integer().nullable().persist(false).index('idx_tags_trip_id'),
collection_place_tags_inverse: () => p.manyToMany(CollectionPlaces).mappedBy('collection_place_tags').hidden(),
place_tags_inverse: () => p.manyToMany(Places).mappedBy('place_tags').hidden(),
},
+3
View File
@@ -31,6 +31,7 @@ import { Reservations } from './Reservations.entity';
import { RoadtripDayBoundaries } from './RoadtripDayBoundaries.entity';
import { RoadtripPreferences } from './RoadtripPreferences.entity';
import { ShareTokens } from './ShareTokens.entity';
import { Tags } from './Tags.entity';
import { TodoCategoryAssignees } from './TodoCategoryAssignees.entity';
import { TodoItems } from './TodoItems.entity';
import { TourDrafts } from './TourDrafts.entity';
@@ -93,6 +94,7 @@ export class Trips {
roadtrip_day_boundaries_collection = new Collection<RoadtripDayBoundaries>(this);
roadtrip_preferences_collection = new Collection<RoadtripPreferences>(this);
share_tokens_collection = new Collection<ShareTokens>(this);
tags_collection = new Collection<Tags>(this);
todo_category_assignees_collection = new Collection<TodoCategoryAssignees>(this);
todo_items_collection = new Collection<TodoItems>(this);
tour_drafts_collection = new Collection<TourDrafts>(this);
@@ -171,6 +173,7 @@ export const TripsSchema = defineEntity({
roadtrip_day_boundaries_collection: () => p.oneToMany(RoadtripDayBoundaries).mappedBy('trip').hidden(),
roadtrip_preferences_collection: () => p.oneToMany(RoadtripPreferences).mappedBy('trip').hidden(),
share_tokens_collection: () => p.oneToMany(ShareTokens).mappedBy('trip').hidden(),
tags_collection: () => p.oneToMany(Tags).mappedBy('trip').hidden(),
todo_category_assignees_collection: () => p.oneToMany(TodoCategoryAssignees).mappedBy('trip').hidden(),
todo_items_collection: () => p.oneToMany(TodoItems).mappedBy('trip').hidden(),
tour_drafts_collection: () => p.oneToMany(TourDrafts).mappedBy('trip').hidden(),
+1
View File
@@ -8,4 +8,5 @@ export interface TagsTable {
name: string;
color: InsertOptional<string | null>;
created_at: InsertOptional<string | null>;
trip_id: InsertOptional<number | null>;
}
@@ -0,0 +1,21 @@
import { addColumnIfMissing } from '../migration-utils';
import { Migration } from '@mikro-orm/migrations';
/**
* A tag can belong to a trip. Every tag used to be one person's: a place of a
* shared trip carried labels only their owner could list, pick again or rename,
* and a co-traveller had to make their own tag of the same name.
*
* A tag with `trip_id` set is the trip's own. Every member reads it, anyone who
* may edit the trip's places may change it, and it goes when the trip goes.
* `user_id` keeps who created it. The column stays null on every existing row,
* which leaves those what they were: personal tags.
*/
export class Migration20200101046440_a_trip_owns_its_tags extends Migration {
override name = 'Migration20200101046440_a_trip_owns_its_tags';
override async up(): Promise<void> {
await addColumnIfMissing(this, 'tags', 'trip_id', 'trip_id INTEGER REFERENCES trips(id) ON DELETE CASCADE');
this.addSql('CREATE INDEX IF NOT EXISTS idx_tags_trip_id ON tags (trip_id)');
}
}
+44 -16
View File
@@ -4,13 +4,14 @@ import { findOwnedByUser, listForOwner } from './_shared/owned-lookup';
import { toRow, type AssertRowKeys } from './_shared/rows';
import { TrekRepository } from './_shared/trek-repository';
/** A `tags` row as the API emits it. */
/** A `tags` row as the API emits it. `trip_id` is null on a personal tag and names the trip on one of its own. */
export interface TagRow {
id: number;
user_id: number;
name: string;
color: string | null;
created_at: string | null;
trip_id: number | null;
}
const _tagRowKeys: AssertRowKeys<TagRow, Tags> = true;
@@ -45,6 +46,9 @@ export interface TagForPlaceRow {
*/
type PlaceTagsKyselyDB = Pick<DB, 'place_tags'>;
/** `tags` alone, for the reads that name their columns. */
type TagsKyselyDB = Pick<DB, 'tags'>;
/**
* `place_tags` joined to `places` for TP46 (`trips.service.ts::copy`'s
* place-tags read). The `trip_id` the caller passes stays `number | string`
@@ -97,11 +101,18 @@ export class TagsRepository extends TrekRepository<Tags> {
* `id` and the `defaultRaw` `created_at` the same way a legacy
* INSERT-then-reselect pair did.
*/
async createTag(input: { user_id: number; name: string; color: string }): Promise<TagRow> {
async createTag(input: {
user_id: number;
name: string;
color: string | null;
/** The trip the tag is for; left out, it is `user_id`'s personal one. */
trip_id?: number;
}): Promise<TagRow> {
const id = await this.insert({
user: input.user_id,
name: input.name,
color: input.color,
...(input.trip_id === undefined ? {} : { trip: input.trip_id }),
});
const inserted = await this.findOne({ id });
if (!inserted) {
@@ -193,22 +204,39 @@ export class TagsRepository extends TrekRepository<Tags> {
// ---------------------------------------------------------------------------
/**
* PL2 (`PlacesService.tagsOnTrip`) — `` SELECT id, user_id FROM tags WHERE
* id IN (${…}) ``, the ownership half of tag scoping: the caller
* (`tagsOnTrip`) intersects these rows' `user_id` against the trip's
* roster, and an id belonging to nobody on the roster drops silently.
* `$in` for the dynamic list (rule 17b).
* PL2 (`PlacesService.tagsOnTrip`) — `` SELECT id, user_id, trip_id FROM tags
* WHERE id IN (${…}) ``, what decides whether a trip may put a tag on a
* place: the caller keeps a trip's own tag for that trip and a personal one
* (`trip_id` null) while its `user_id` is on the roster, and every other id
* drops silently.
*/
async findByIds(ids: number[]): Promise<{ id: number; user_id: number }[]> {
async findByIds(ids: number[]): Promise<{ id: number; user_id: number; trip_id: number | null }[]> {
if (ids.length === 0) return [];
// `t.user` (unaliased, not separately joined) resolves to the physical
// `user_id` column and comes back keyed as `user_id` on the raw driver
// row — `TripsRepository.findAccessible`'s `.select(['t.id', 't.user',
// 't.currency'])` establishes the same shape.
return this.qb('t')
.select(['t.id', 't.user'])
.where({ id: { $in: ids } })
.execute<{ id: number; user_id: number }[]>('all', false);
return await this.kysely<TagsKyselyDB>()
.selectFrom('tags')
.select(['id', 'user_id', 'trip_id'])
.where('id', 'in', ids)
.execute();
}
// ---------------------------------------------------------------------------
// A trip's own tags (`trip_id` set): one list for everybody on the trip.
// ---------------------------------------------------------------------------
/** `SELECT * FROM tags WHERE trip_id = ? ORDER BY name ASC`: the trip's own tags, whoever created them. */
async listByTrip(tripId: number): Promise<TagRow[]> {
const tags = await this.find({ trip: tripId }, { orderBy: { name: 'asc' } });
return tags.map((tag) => toRow(tag) as TagRow);
}
/**
* `SELECT * FROM tags WHERE id = ? AND trip_id = ?`: one tag of the trip, or
* null for a personal tag and for another trip's, so a write scoped to a trip
* cannot reach either.
*/
async findByIdAndTrip(id: number, tripId: number): Promise<TagRow | null> {
const tag = await this.findOne({ id, trip: tripId });
return tag ? (toRow(tag) as TagRow) : null;
}
// ---------------------------------------------------------------------------
@@ -658,18 +658,18 @@ export class CollectionsService {
// -------------------------------------------------------------------------
/**
* A tag has no list of its own, only a `user_id`, so "belongs here" resolves
* through the people on the list — the same shape places.service uses against
* a trip roster. Off-list tag ids drop silently rather than being stored and
* read straight back out: the tag read-back ships `tags.user_id`, so an
* unfiltered id answers who owns a tag the caller cannot otherwise see.
* A personal tag has no list of its own, only a `user_id`, so "belongs here" resolves
* through the people on the list — the same shape places.service uses against a trip
* roster. Every other id drops silently, a trip's own tag included (it labels that
* trip's places only), rather than being stored and read straight back out: the
* read-back ships `tags.user_id`, so it answers who owns a tag the caller cannot see.
*/
private async attachTags(collectionPlaceId: number, tagIds: number[] | undefined): Promise<void> {
if (!tagIds || tagIds.length === 0) return;
const unique = [...new Set(tagIds)];
const eligible = await this.collectionMemberIds(await this.collectionIdOfPlace(collectionPlaceId));
const owned = await this.tags.findByIds(unique);
const eligibleTagIds = owned.filter(t => eligible.has(t.user_id)).map(t => t.id);
const eligibleTagIds = owned.filter(t => t.trip_id === null && eligible.has(t.user_id)).map(t => t.id);
await this.collectionPlaces.attachTags(collectionPlaceId, eligibleTagIds);
}
+13 -9
View File
@@ -11,6 +11,7 @@ import {
placeImportListRequestSchema,
placeEmailField,
placeOpeningHoursSchema,
placeTagIdsSchema,
placeWebsiteSchema,
roadtripStopTypeSchema,
type PlaceOpeningHours,
@@ -100,23 +101,24 @@ export class PlacesMcp {
price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
stop_type: roadtripStopTypeSchema.optional().describe('Marks the place as a stop on a drive rather than a destination: fuel, charging, rest_area, campsite, restaurant, sights or hotel. A service stop is left out of the stop count for the day, so a day with a charger between four places still reads as four stops. Leave unset for an ordinary place. calculate_roadtrip reports the same value on a stop as stopType; this field is stop_type.'),
tags: placeTagIdsSchema.optional().describe('Ids of the tags to put on the place: tags of this trip (list_trip_tags, create_trip_tag) or personal tags of someone on it (list_tags). Any other id is ignored'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
access: { group: 'places', mode: 'write' },
})
async createPlace(
{ tripId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours, image_url, price, currency, stop_type }: {
{ tripId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours, image_url, price, currency, stop_type, tags }: {
tripId: number; name: string; description?: string; lat?: number; lng?: number; address?: string;
category_id?: number; google_place_id?: string; google_ftid?: string; osm_id?: string; amap_poi_id?: string;
notes?: string; website?: string; phone?: string; email?: string | null; opening_hours?: PlaceOpeningHours | null;
image_url?: string; price?: number; currency?: string;
stop_type?: RoadtripStopType;
stop_type?: RoadtripStopType; tags?: number[];
},
ctx: McpContext,
) {
if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type });
const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type, tags });
this.guards.safeBroadcast(tripId, 'place:created', { place });
await this.origins.record(place.id, null, AGENT);
// The journey hook the REST route and the plugin RPC run after the same write.
@@ -150,17 +152,18 @@ export class PlacesMcp {
price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
currency: z.string().length(3).optional().describe('ISO 4217 currency code (e.g. "EUR", "USD")'),
stop_type: roadtripStopTypeSchema.optional().describe('Marks the place as a stop on a drive rather than a destination: fuel, charging, rest_area, campsite, restaurant, sights or hotel. A service stop is left out of the stop count for the day, so a day with a charger between four places still reads as four stops. Leave unset for an ordinary place. calculate_roadtrip reports the same value on a stop as stopType; this field is stop_type.'),
tags: placeTagIdsSchema.optional().describe('Ids of the tags to put on the place: tags of this trip (list_trip_tags, create_trip_tag) or personal tags of someone on it (list_tags). Any other id is ignored'),
},
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
access: { group: 'places', mode: 'write' },
})
async createAndAssignPlace(
{ tripId, dayId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, place_notes, website, phone, email, opening_hours, image_url, assignment_notes, price, currency, stop_type }: {
{ tripId, dayId, name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, place_notes, website, phone, email, opening_hours, image_url, assignment_notes, price, currency, stop_type, tags }: {
tripId: number; dayId: number; name: string; description?: string; lat?: number; lng?: number; address?: string;
category_id?: number; google_place_id?: string; google_ftid?: string; osm_id?: string; amap_poi_id?: string;
place_notes?: string; website?: string; phone?: string; email?: string | null; opening_hours?: PlaceOpeningHours | null;
image_url?: string; assignment_notes?: string;
price?: number; currency?: string; stop_type?: RoadtripStopType;
price?: number; currency?: string; stop_type?: RoadtripStopType; tags?: number[];
},
ctx: McpContext,
) {
@@ -169,7 +172,7 @@ export class PlacesMcp {
if (!(await this.assignments.dayExists(dayId, tripId))) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
try {
const result = await this.uow.transactional(async () => {
const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes: place_notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type });
const place = await this.places.create(String(tripId), { name, description, lat, lng, address, category_id, google_place_id, google_ftid, osm_id, amap_poi_id, notes: place_notes, website, phone, email, opening_hours: hoursText(opening_hours), image_url, price, currency, stop_type, tags });
const assignment = await this.assignments.createAssignment(dayId, place.id, assignment_notes ?? null);
return { place, assignment };
});
@@ -213,12 +216,13 @@ export class PlacesMcp {
amap_poi_id: z.string().optional().describe('Amap (高德地图) POI ID, amap:-prefixed (e.g. "amap:B000A83M61")'),
stop_type: roadtripStopTypeSchema.nullable().optional().describe('What kind of stop on a drive this is: fuel, charging, rest_area, campsite, restaurant, sights or hotel. Pass null to turn a service stop back into an ordinary place. calculate_roadtrip reports the same value on a stop as stopType; this field is stop_type.'),
fill_percent: z.number().int().min(1).max(100).nullable().optional().describe('How full THIS stop fills the tank, 1-100. A motorway rapid charger is worth about 80 %, the one at the hotel 100 %. Pass null to follow whatever the traveller set as their default fill.'),
tags: placeTagIdsSchema.optional().describe('The whole set of tag ids the place should carry afterwards: tags of this trip (list_trip_tags, create_trip_tag) or personal tags of someone on it (list_tags). Send the ids it keeps along with the new ones, and an empty list to clear them. Leave out to keep its tags as they are'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
access: { group: 'places', mode: 'write' },
})
async updatePlace(
{ tripId, placeId, name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours, image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent }: {
{ tripId, placeId, name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours, image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent, tags }: {
tripId: number; placeId: number; name?: string; description?: string; lat?: number; lng?: number;
address?: string; category_id?: number; price?: number; currency?: string; place_time?: string | null;
end_time?: string | null; duration_minutes?: number | null; notes?: string; website?: string; phone?: string;
@@ -226,14 +230,14 @@ export class PlacesMcp {
image_url?: string | null;
transport_mode?: 'walking' | 'driving' | 'cycling' | 'transit' | 'flight'; osm_id?: string;
google_place_id?: string; google_ftid?: string; amap_poi_id?: string; stop_type?: RoadtripStopType | null;
fill_percent?: number | null;
fill_percent?: number | null; tags?: number[];
},
ctx: McpContext,
) {
if (!(await this.tripsRepo.findAccessible(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('place_edit', tripId, ctx.userId))) return permissionDenied();
const before = await this.origins.valuesBefore(placeId);
const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours: opening_hours === undefined ? undefined : hoursText(opening_hours), image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent });
const place = await this.places.update(String(tripId), String(placeId), { name, description, lat, lng, address, category_id, price, currency, place_time, end_time, duration_minutes, notes, website, phone, email, opening_hours: opening_hours === undefined ? undefined : hoursText(opening_hours), image_url, transport_mode, osm_id, google_place_id, google_ftid, amap_poi_id, stop_type, fill_percent, tags });
// No base version is sent, so the update never answers a conflict; the guard only narrows the type.
if (!place || isUpdateConflict(place)) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
this.guards.safeBroadcast(tripId, 'place:updated', { place });
+12 -12
View File
@@ -210,16 +210,16 @@ export class PlacesService {
}
/**
* The subset of `tagIds` that someone on this trip owns. A tag has no trip of
* its own, only a `user_id`, so "belongs to this trip" resolves through the
* roster — which keeps the shared case working: a member tags a place, another
* member re-saves it and sends the id back, and the tag survives because its
* owner is still on the trip. Scoping to the caller instead would quietly strip
* a co-traveller's tag on every foreign edit.
* The subset of `tagIds` this trip may put on a place: the tags it owns, and the
* personal tags of anybody on its roster. A personal tag has no trip, only a
* `user_id`, so it resolves through the roster, which keeps the shared case
* working: a member tags a place, another re-saves it and sends the id back, and
* the tag survives because its owner is still on the trip. Scoping to the caller
* instead would quietly strip a co-traveller's tag on every foreign edit.
*
* Off-roster ids drop silently. The place body is an open record, so an id can
* arrive from an older client that had no business knowing it existed, and the
* read-back join hands `tags.user_id` straight to the caller.
* Every other id drops silently, another trip's tag included. The place body is an
* open record, so an id can arrive from a client that had no business knowing it
* existed, and the read-back join hands the tag straight to the caller.
*/
private async tagsOnTrip(tripId: string | number, tagIds: number[]): Promise<number[]> {
const unique = [...new Set(tagIds)];
@@ -229,9 +229,9 @@ export class PlacesService {
// precedent: each domain converts its own `DatabaseService`-delegated
// callers as it lands.
const roster = await this.tripMembersRepo.rosterUserIds(tripId);
// PL2 — `SELECT id, user_id FROM tags WHERE id IN (${…})`.
const owned = await this.tagsRepo.findByIds(unique);
return owned.filter(t => roster.has(t.user_id)).map(t => t.id);
// PL2 — `SELECT id, user_id, trip_id FROM tags WHERE id IN (${…})`.
const rows = await this.tagsRepo.findByIds(unique);
return rows.filter(t => (t.trip_id === null ? roster.has(t.user_id) : t.trip_id === Number(tripId))).map(t => t.id);
}
broadcast<E extends TrekWsTripEventName>(tripId: string, event: E, payload: TrekWsPayload<E>, socketId: string | undefined): void {
@@ -325,7 +325,9 @@ export const PLUGIN_ENTITY_CONTRACT = {
tag: {
table: 'tags',
columns: ['id', 'user_id', 'name', 'color', 'created_at'],
withheld: [],
// Which trip a tag belongs to is the host's own scoping: tags.* answers the acting
// user's personal tags, and a trip's own reach a plugin on that trip's places.
withheld: ['trip_id'],
wholeRow: true,
derived: [],
},
+9
View File
@@ -1,3 +1,5 @@
import { tripTagCreateRequestSchema, tripTagUpdateRequestSchema } from '@trek/shared';
import { createZodDto } from 'nestjs-zod';
import { z } from 'zod';
@@ -23,3 +25,10 @@ const tagBody = z.looseObject({ name: z.unknown().optional(), color: z.unknown()
export class TagCreateDto extends createZodDto(tagBody) {}
export class TagUpdateDto extends createZodDto(tagBody) {}
/**
* The trip tag routes are new, so they take the shared contracts as written: the
* pipe trims the name, refuses an empty one and a colour that is not hex.
*/
export class TripTagCreateDto extends createZodDto(tripTagCreateRequestSchema) {}
export class TripTagUpdateDto extends createZodDto(tripTagUpdateRequestSchema) {}
+21 -4
View File
@@ -1,10 +1,16 @@
import { Tags } from '../../db/entities/Tags.entity';
import { McpSharedModule } from '../mcp-shared/mcp-shared.module';
import { PermissionsModule } from '../permissions/permissions.module';
import { RealtimeModule } from '../realtime/realtime.module';
import { TripMembershipModule } from '../trip-membership/trip-membership.module';
import { TagWritesService } from './tag-writes.service';
import { TagsController } from './tags.controller';
import { TagsMcp } from './tags.mcp';
import { TagsRpc } from './tags.rpc';
import { TagsService } from './tags.service';
import { TripTagsController } from './trip-tags.controller';
import { TripTagsMcp } from './trip-tags.mcp';
import { TripTagsService } from './trip-tags.service';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { Module } from '@nestjs/common';
@@ -15,15 +21,26 @@ import { Module } from '@nestjs/common';
* @InjectRepository(Tags) in the service — the forFeature +
* @InjectRepository wiring pattern every domain copies (settings.module.ts's
* precedent comment).
*
* Two surfaces over the one table: a user's personal tags (TagsController,
* TagsMcp, TagsRpc) and the tags a trip owns (TripTagsController, TripTagsMcp),
* which take the trip's access and `place_edit` instead of an owner.
*/
@Module({
// RealtimeModule for TagWritesService, which tells a user's other tabs that their tags changed.
imports: [RealtimeModule, MikroOrmModule.forFeature([Tags])],
controllers: [TagsController],
// RealtimeModule for the two write services, which tell the other tabs that the tags changed;
// TripMembershipModule and PermissionsModule for the trip gate, McpSharedModule for the tools' writer.
imports: [
RealtimeModule,
TripMembershipModule,
PermissionsModule,
McpSharedModule,
MikroOrmModule.forFeature([Tags]),
],
controllers: [TagsController, TripTagsController],
// TagsRpc must stay in providers: the plugin RPC registry discovers marked
// PROVIDERS only, and a missing entry here would leave tags.* answering
// PERMISSION_DENIED with no other symptom.
providers: [TagsService, TagWritesService, TagsMcp, TagsRpc],
providers: [TagsService, TagWritesService, TripTagsService, TagsMcp, TripTagsMcp, TagsRpc],
// For in-container consumers (TagsRpc).
exports: [TagsService],
})
+9 -2
View File
@@ -12,6 +12,11 @@ import type { Tag } from '@trek/shared';
* here, exactly as they did over raw SQL, while the SQL itself lives in the
* repository. All consumers are in-container — the plugin RPC surface
* injects this class into TagsRpc.
*
* This is the personal surface: a user's own tags. A tag that belongs to a trip
* (`trip_id` set) names its creator in `user_id` as well, but it is the trip's,
* so `list` leaves it out and `getByIdAndUser` does not find it; TripTagsService
* reads and writes those under the trip's own rights.
*/
@Injectable()
export class TagsService {
@@ -24,7 +29,8 @@ export class TagsService {
// either) — these casts keep that same trust boundary at the service layer
// instead of inside a raw-SQL call.
async list(userId: number): Promise<Tag[]> {
return (await this.tags.listByUser(userId)) as unknown as Tag[];
const own = (await this.tags.listByUser(userId)).filter((tag) => tag.trip_id === null);
return own as unknown as Tag[];
}
async getByIdAndUser(id: string | number, userId: number): Promise<Tag | undefined> {
@@ -39,7 +45,8 @@ export class TagsService {
const rowId = toRowId(id);
if (rowId === null) return undefined;
const tag = await this.tags.findByIdAndUser(rowId, userId);
return (tag as unknown as Tag | null) ?? undefined;
if (!tag || tag.trip_id !== null) return undefined;
return tag as unknown as Tag;
}
async create(userId: number, name: string, color?: string): Promise<Tag> {
@@ -0,0 +1,71 @@
import type { User } from '../../types';
import { CurrentUser } from '../auth-core/current-user.decorator';
import { JwtAuthGuard } from '../auth-core/jwt-auth.guard';
import { ResponseContract } from '../common/response-contract';
import { RequirePermission, TripAccessGuard } from '../permissions/trip-access.guard';
import { TripTagCreateDto, TripTagUpdateDto } from './tags.dto';
import { TripTagsService } from './trip-tags.service';
import { Body, Controller, Delete, Get, Headers, Param, Post, Put, UseGuards } from '@nestjs/common';
import { successResponseSchema, tripTagListResponseSchema, tripTagResponseSchema } from '@trek/shared';
/**
* /api/trips/:tripId/tags — the tags a trip owns, shared by everybody on it.
*
* Reading takes trip access (404 otherwise); the writes add the `place_edit`
* permission (403), the one a tag is put on a place with. Bodies validate against
* the @trek/shared trip tag contracts through the Zod pipe. Create answers 201 with
* the tag of that name, which is the trip's existing one when it has it already;
* a rename onto another tag's name is a 409. Every write tells the trip's other
* sockets `tripTags:changed`.
*/
@Controller('api/trips/:tripId/tags')
@UseGuards(JwtAuthGuard, TripAccessGuard)
export class TripTagsController {
constructor(private readonly tripTags: TripTagsService) {}
@Get()
@ResponseContract(tripTagListResponseSchema)
async list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { tags: await this.tripTags.list(tripId, user.id) };
}
@RequirePermission('place_edit')
@Post()
@ResponseContract(tripTagResponseSchema)
async create(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: TripTagCreateDto,
@Headers('x-socket-id') socketId?: string,
) {
const writer = this.tripTags.restWriter(tripId, user, socketId);
return { tag: await this.tripTags.create(tripId, { name: body.name, color: body.color }, writer) };
}
@RequirePermission('place_edit')
@Put(':id')
@ResponseContract(tripTagResponseSchema)
async update(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Body() body: TripTagUpdateDto,
@Headers('x-socket-id') socketId?: string,
) {
const writer = this.tripTags.restWriter(tripId, user, socketId);
return { tag: await this.tripTags.update(tripId, id, { name: body.name, color: body.color }, writer) };
}
@RequirePermission('place_edit')
@Delete(':id')
@ResponseContract(successResponseSchema)
async remove(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
) {
await this.tripTags.remove(tripId, id, this.tripTags.restWriter(tripId, user, socketId));
return { success: true };
}
}
+97
View File
@@ -0,0 +1,97 @@
import {
McpController,
Tool,
type McpContext,
TOOL_ANNOTATIONS_DELETE,
TOOL_ANNOTATIONS_READONLY,
TOOL_ANNOTATIONS_WRITE,
ok,
} from '../../nest-mcp';
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
import { TripTagsService } from './trip-tags.service';
import { hexColorSchema, idSchema, tripTagNameSchema } from '@trek/shared';
/**
* The tags a trip owns, as MCP tools: adapters over TripTagsService, the same
* use cases the /api/trips/:tripId/tags routes run. The service holds the trip
* gate and sends `tripTags:changed`, so a refusal reads the same on both
* surfaces and a tag an assistant adds shows up for every member at once.
*
* In the `places` scope group like the personal tag tools, since a tag only
* ever labels places. The ids go into `tags` on create_place and update_place.
*/
@McpController()
export class TripTagsMcp {
constructor(
private readonly tripTags: TripTagsService,
private readonly guards: McpToolGuardsService,
) {}
@Tool({
name: 'list_trip_tags',
description:
'List the tags a trip owns: the labels every member of the trip sees, filters its places by and can put on them. Pass their ids as `tags` to create_place, create_and_assign_place and update_place. list_tags answers the personal tags of the current user instead.',
inputSchema: {
tripId: idSchema,
},
annotations: TOOL_ANNOTATIONS_READONLY,
access: { group: 'places', mode: 'read' },
})
async listTripTags({ tripId }: { tripId: number }, ctx: McpContext) {
return ok({ tags: await this.tripTags.list(tripId, ctx.userId) });
}
@Tool({
name: 'create_trip_tag',
description:
"Add a tag to a trip, shared by everybody on it. A name stands once per trip, whatever its case: asking for a name the trip already has answers that tag instead of making a second one, so call this freely before tagging places. Needs the right to edit the trip's places.",
inputSchema: {
tripId: idSchema,
name: tripTagNameSchema,
color: hexColorSchema.optional().describe('Hex color string e.g. #6366f1'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
access: { group: 'places', mode: 'write' },
})
async createTripTag({ tripId, name, color }: { tripId: number; name: string; color?: string }, ctx: McpContext) {
const tag = await this.tripTags.create(tripId, { name, color }, await this.guards.tripWriter(tripId, ctx.userId));
return ok({ tag });
}
@Tool({
name: 'update_trip_tag',
description:
"Rename or recolour a tag of a trip. Every place that carries it shows the change, for every member. A name another tag of the trip already has is refused. Needs the right to edit the trip's places.",
inputSchema: {
tripId: idSchema,
tagId: idSchema,
name: tripTagNameSchema.optional(),
color: hexColorSchema.optional().describe('Hex color string e.g. #6366f1'),
},
annotations: TOOL_ANNOTATIONS_WRITE,
access: { group: 'places', mode: 'write' },
})
async updateTripTag(
{ tripId, tagId, name, color }: { tripId: number; tagId: number; name?: string; color?: string },
ctx: McpContext,
) {
const writer = await this.guards.tripWriter(tripId, ctx.userId);
return ok({ tag: await this.tripTags.update(tripId, tagId, { name, color }, writer) });
}
@Tool({
name: 'delete_trip_tag',
description:
"Delete a tag of a trip. It comes off every place of the trip that carried it, for every member; the places themselves stay. Needs the right to edit the trip's places.",
inputSchema: {
tripId: idSchema,
tagId: idSchema,
},
annotations: TOOL_ANNOTATIONS_DELETE,
access: { group: 'places', mode: 'write' },
})
async deleteTripTag({ tripId, tagId }: { tripId: number; tagId: number }, ctx: McpContext) {
await this.tripTags.remove(tripId, tagId, await this.guards.tripWriter(tripId, ctx.userId));
return ok({ success: true });
}
}
+118
View File
@@ -0,0 +1,118 @@
import { Tags } from '../../db/entities/Tags.entity';
import type { TagRow, TagsRepository } from '../../db/repositories/Tags.repository';
import type { User } from '../../types';
import { conflict, DomainError } from '../common/domain-error';
import { toRowId } from '../common/row-id';
import { requireTripWrite, restTripWriter, tripNotFound, type TripWriter } from '../common/trip-writer';
import { UnitOfWork } from '../database/unit-of-work';
import { PermissionsService } from '../permissions/permissions.service';
import { RealtimeService } from '../realtime/realtime.service';
import { TripAccessService } from '../trip-membership/trip-access.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { Injectable } from '@nestjs/common';
import type { Tag } from '@trek/shared';
/** The colour a tag gets when its creator names none, the same as a personal tag's. */
const DEFAULT_TAG_COLOR = '#10b981';
const tagNotFound = () => new DomainError(404, 'Tag not found', { mcpMessage: 'Tag not found.' });
const nameTaken = () => conflict('A tag with this name already exists');
/** Two names are one tag when they read the same, whatever their case. */
const sameName = (a: string, b: string): boolean => a.trim().toLowerCase() === b.trim().toLowerCase();
/** A stored row as the contract types it; the columns the contract narrows are always set on a trip's tag. */
const asTag = (row: TagRow): Tag => row as unknown as Tag;
/**
* A trip's own tags, one method per use case, for REST and MCP alike.
*
* A tag of a trip belongs to the trip, not to the member who created it: every
* member reads the same list, and anyone who may edit the trip's places
* (`place_edit`, the right a tag is put on a place with) may add to it, rename
* and delete. Each write holds the trip gate, its checks, the write and the
* `tripTags:changed` it sends, so both surfaces tell the trip the same thing.
*
* A name stands once per trip, whatever its case: asking for one the trip has
* answers that tag, and renaming onto another tag's name is refused. Two members
* tagging the same idea end up on one tag, which is what a shared filter needs.
*/
@Injectable()
export class TripTagsService {
constructor(
@InjectRepository(Tags) private readonly tags: TagsRepository,
private readonly access: TripAccessService,
private readonly permissions: PermissionsService,
private readonly realtime: RealtimeService,
private readonly uow: UnitOfWork,
) {}
/** The REST caller of a tag write: its event skips the socket that made the request. */
restWriter(tripId: string, user: User, socketId: string | undefined): TripWriter {
return restTripWriter(this.realtime, tripId, user, socketId);
}
/** The trip's tags by name, for anybody who can see the trip. */
async list(tripId: string | number, userId: number): Promise<Tag[]> {
const tid = toRowId(tripId);
if (tid === null || !(await this.access.findAccessible(tid, userId))) throw tripNotFound();
return (await this.tags.listByTrip(tid)).map(asTag);
}
/** The tag of that name on the trip, created when the trip has none yet. */
async create(tripId: string | number, input: { name: string; color?: string }, writer: TripWriter): Promise<Tag> {
const tid = await this.gate(tripId, writer);
const name = input.name.trim();
const { tag, created } = await this.uow.transactional(async () => {
const existing = (await this.tags.listByTrip(tid)).find((row) => sameName(row.name, name));
if (existing) return { tag: existing, created: false };
const color = input.color ?? DEFAULT_TAG_COLOR;
return { tag: await this.tags.createTag({ user_id: writer.userId, trip_id: tid, name, color }), created: true };
});
if (created) writer.events.emit('tripTags:changed', {});
return asTag(tag);
}
/** Rename or recolour a tag of the trip; a field that is left out keeps its value. */
async update(
tripId: string | number,
tagId: string | number,
changes: { name?: string; color?: string },
writer: TripWriter,
): Promise<Tag> {
const tid = await this.gate(tripId, writer);
const id = toRowId(tagId);
const name = changes.name?.trim();
const tag = await this.uow.transactional(async () => {
const onTrip = await this.tags.listByTrip(tid);
const current = onTrip.find((row) => row.id === id);
if (!current) throw tagNotFound();
if (name && onTrip.some((row) => row.id !== current.id && sameName(row.name, name))) throw nameTaken();
const patched = await this.tags.patch(current.id, {
...(name ? { name } : {}),
...(changes.color ? { color: changes.color } : {}),
});
// Read in this transaction a statement ago, so the patch finds the row.
return patched as TagRow;
});
writer.events.emit('tripTags:changed', {});
return asTag(tag);
}
/** Delete a tag of the trip; it comes off every place that carried it. */
async remove(tripId: string | number, tagId: string | number, writer: TripWriter): Promise<void> {
const tid = await this.gate(tripId, writer);
const id = toRowId(tagId);
if (id === null || !(await this.tags.findByIdAndTrip(id, tid))) throw tagNotFound();
await this.tags.remove(id);
writer.events.emit('tripTags:changed', {});
}
/** The gate of every write: the writer sees the trip (404) and may edit its places (403). */
private async gate(tripId: string | number, writer: TripWriter): Promise<number> {
const tid = toRowId(tripId);
if (tid === null) throw tripNotFound();
await requireTripWrite({ access: this.access, permissions: this.permissions }, 'place_edit', tid, writer);
return tid;
}
}
+7 -1
View File
@@ -48,6 +48,7 @@ import { StorageReleaseService } from '../storage/storage-release.service';
import { SettingsService } from '../settings/settings.service';
import { escapeLikePattern } from '../places/places.helpers';
import { NotFoundError, ValidationError } from '../common/domain-errors';
import { inOrder } from '../common/in-order';
import { UnitOfWork } from '../database/unit-of-work';
import { legacyBoundIntegerText } from '../common/row-id';
import { appClock } from '../common/timezoneService';
@@ -712,10 +713,15 @@ export class TripsService {
if (newDayId && newPlaceId) await this.roadtripDayTracksRepo.upsertTrack(newDayId, newPlaceId, t.stray_km); // TP45
}
// The trip's own tags are written again as the copy's; a personal tag stays its owner's one row.
const tagMap = new Map<number, number>();
await inOrder(await this.tagsRepo.listByTrip(Number(sourceTripId)), async ({ id, name, color }) => {
tagMap.set(id, (await this.tagsRepo.createTag({ user_id: newOwnerId, trip_id: newTripId, name, color })).id);
});
const oldTags = await this.tagsRepo.listPlaceTagsForTrip(sourceTripId); // TP46
for (const t of oldTags) {
const newPlaceId = placeMap.get(t.place_id);
if (newPlaceId) await this.tagsRepo.insertIgnore(newPlaceId, [t.tag_id]); // TP47
if (newPlaceId) await this.tagsRepo.insertIgnore(newPlaceId, [tagMap.get(t.tag_id) ?? t.tag_id]); // TP47
}
// The `tours` facet goes first: the import record, obstacle decisions, packing link and waypoints need it.