mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
Merge branch 'origin/dev' into feat/storage-driver
Both sides appended a migration to the same schema_version slot: dev's reservation_day_positions cross-trip cleanup keeps its published index, the storage slice-2 trip_files prefix strip moves after it. The trailing- migration guard now rewinds two versions and asserts both. Dev's new places image_url/website tests gain the StorageService constructor arg and async update() handling from the storage slices.
This commit is contained in:
@@ -3891,6 +3891,24 @@ function runMigrations(db: Database.Database): void {
|
||||
db.exec('ALTER TABLE budget_items ADD COLUMN place_id INTEGER REFERENCES places(id) ON DELETE SET NULL DEFAULT NULL');
|
||||
}
|
||||
},
|
||||
// A reservation_day_positions row only makes sense when its reservation and
|
||||
// its day are on the same trip. The table carries no trip_id and its two
|
||||
// foreign keys only ask that the ids exist, so pairs that never belonged
|
||||
// together could accumulate; the writer refuses them now, and this clears
|
||||
// whatever an older build let through. This slot keeps the index it shipped
|
||||
// with on dev — the array is index-addressed against schema_version.
|
||||
() => {
|
||||
db.exec(`
|
||||
DELETE FROM reservation_day_positions
|
||||
WHERE rowid IN (
|
||||
SELECT rdp.rowid
|
||||
FROM reservation_day_positions rdp
|
||||
JOIN reservations r ON r.id = rdp.reservation_id
|
||||
JOIN days d ON d.id = rdp.day_id
|
||||
WHERE d.trip_id <> r.trip_id
|
||||
)
|
||||
`);
|
||||
},
|
||||
// Storage slice 2 — collab note attachments historically stored 'files/<name>'
|
||||
// in trip_files.filename while the file manager stored bare names in the same
|
||||
// column; the storage layer addresses objects as category + bare name, so
|
||||
|
||||
@@ -113,9 +113,14 @@ export class DayAssignmentsController {
|
||||
/**
|
||||
* /api/trips/:tripId/assignments/:id/* — per-assignment ops (move, time,
|
||||
* participants), independent of the day path. Same parity rules as above.
|
||||
*
|
||||
* Same guard pair as the day controller, and for the same reason: TripAccessGuard
|
||||
* is what resolves :tripId and what reads @RequirePermission. The per-handler
|
||||
* getAssignmentForTrip calls answer a different question — whether the assignment
|
||||
* sits on the trip in the URL, not whether the caller may be on that trip.
|
||||
*/
|
||||
@Controller('api/trips/:tripId/assignments')
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@UseGuards(JwtAuthGuard, TripAccessGuard)
|
||||
export class AssignmentOpsController {
|
||||
constructor(private readonly assignments: AssignmentsService) {}
|
||||
|
||||
@@ -142,6 +147,9 @@ export class AssignmentOpsController {
|
||||
|
||||
@Get(':id/participants')
|
||||
participants(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) {
|
||||
if (!this.assignments.getAssignmentForTrip(id, tripId)) {
|
||||
throw new HttpException({ error: 'Assignment not found' }, 404);
|
||||
}
|
||||
return { participants: this.assignments.getParticipants(id) };
|
||||
}
|
||||
|
||||
@@ -191,7 +199,10 @@ export class AssignmentOpsController {
|
||||
@Body() body: AssignmentParticipantsDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const participants = this.assignments.setParticipants(id, body.user_ids);
|
||||
if (!this.assignments.getAssignmentForTrip(id, tripId)) {
|
||||
throw new HttpException({ error: 'Assignment not found' }, 404);
|
||||
}
|
||||
const participants = this.assignments.setParticipants(id, body.user_ids, tripId);
|
||||
this.assignments.broadcast(tripId, 'assignment:participants', { assignmentId: Number(id), participants }, socketId);
|
||||
return { participants };
|
||||
}
|
||||
|
||||
@@ -187,7 +187,7 @@ export class AssignmentsMcp {
|
||||
if (!this.assignments.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('day_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
if (!this.assignments.getAssignmentForTrip(assignmentId, tripId)) return errorResult('Assignment not found.');
|
||||
const participants = this.assignments.setParticipants(assignmentId, userIds);
|
||||
const participants = this.assignments.setParticipants(assignmentId, userIds, tripId);
|
||||
this.guards.safeBroadcast(tripId, 'assignment:participants', { assignmentId, participants });
|
||||
return ok({ participants });
|
||||
}
|
||||
|
||||
@@ -283,12 +283,21 @@ export class AssignmentsService {
|
||||
return this.getAssignmentWithPlace(Number(id));
|
||||
}
|
||||
|
||||
setParticipants(assignmentId: string | number, userIds: number[]) {
|
||||
/**
|
||||
* Both callers have already proven the assignment sits on `tripId`; this
|
||||
* settles the other half, that the ids in the body do too. Off-roster ids drop
|
||||
* silently rather than 400, matching bag members and reservation travellers —
|
||||
* the participants box sends the whole list back on every edit, so rejecting
|
||||
* the request would strand a trip whose membership changed underneath it.
|
||||
*/
|
||||
setParticipants(assignmentId: string | number, userIds: number[], tripId: string | number) {
|
||||
const roster = this.dbs.rosterUserIds(tripId);
|
||||
const scoped = userIds.filter(id => roster.has(id));
|
||||
this.dbs.transaction(() => {
|
||||
this.dbs.run('DELETE FROM assignment_participants WHERE assignment_id = ?', assignmentId);
|
||||
if (userIds.length > 0) {
|
||||
if (scoped.length > 0) {
|
||||
const insert = this.dbs.prepare('INSERT OR IGNORE INTO assignment_participants (assignment_id, user_id) VALUES (?, ?)');
|
||||
for (const userId of userIds) insert.run(assignmentId, userId);
|
||||
for (const userId of scoped) insert.run(assignmentId, userId);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -94,6 +94,11 @@ export class BudgetController {
|
||||
{ from_user_id: body.from_user_id, to_user_id: body.to_user_id, amount: body.amount, currency: body.currency },
|
||||
user.id,
|
||||
);
|
||||
// A party who is not on this trip gets the same answer as a settlement that
|
||||
// does not exist, so the endpoint cannot be used to probe for user ids.
|
||||
if (!settlement) {
|
||||
throw new HttpException({ error: 'Settlement not found' }, 404);
|
||||
}
|
||||
this.budget.broadcast(tripId, 'budget:settlement-created', { settlement }, socketId);
|
||||
return { settlement };
|
||||
}
|
||||
|
||||
@@ -330,6 +330,7 @@ export class BudgetMcp {
|
||||
// Freeze-then-write composite, same as the REST path (no-op while the
|
||||
// schema has no currency input — see the #1445 note in the class doc).
|
||||
const settlement = await this.budget.createSettlement(tripId, { from_user_id, to_user_id, amount }, ctx.userId);
|
||||
if (!settlement) return errorResult('Settlement not found.');
|
||||
this.guards.safeBroadcast(tripId, 'budget:settlement-created', { settlement });
|
||||
return ok({ settlement });
|
||||
}
|
||||
|
||||
@@ -126,21 +126,25 @@ export class BudgetService {
|
||||
return rows.map(p => ({ ...p, avatar_url: avatarUrl(p) }));
|
||||
}
|
||||
|
||||
private knownUserIds(userIds: number[]): Set<number> {
|
||||
const unique = [...new Set(userIds)];
|
||||
if (unique.length === 0) return new Set();
|
||||
const rows = this.db.all<{ id: number }>(
|
||||
`SELECT id FROM users WHERE id IN (${unique.map(() => '?').join(',')})`,
|
||||
...unique,
|
||||
);
|
||||
return new Set(rows.map(r => r.id));
|
||||
/**
|
||||
* The subset of `userIds` that is actually on this trip. Used to be a plain
|
||||
* existence check against `users`, which let any id on the instance become a
|
||||
* payer or a split member and come back out through the read-back join with a
|
||||
* name and an avatar attached. Off-roster ids drop silently, the way the
|
||||
* packing and reservations assignee paths handle them.
|
||||
*/
|
||||
private rosterMemberIds(tripId: string | number, userIds: number[]): Set<number> {
|
||||
const unique = new Set(userIds);
|
||||
if (unique.size === 0) return new Set();
|
||||
const roster = this.db.rosterUserIds(tripId);
|
||||
return new Set([...unique].filter(id => roster.has(id)));
|
||||
}
|
||||
|
||||
/** Replace the payer rows of an item and keep total_price = sum of payer amounts. */
|
||||
private writeItemPayers(itemId: number | string, payers: { user_id: number; amount: number }[]) {
|
||||
private writeItemPayers(itemId: number | string, tripId: string | number, payers: { user_id: number; amount: number }[]) {
|
||||
this.db.run('DELETE FROM budget_item_payers WHERE budget_item_id = ?', itemId);
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_payers (budget_item_id, user_id, amount) VALUES (?, ?, ?)');
|
||||
const known = this.knownUserIds(payers.map(p => p.user_id));
|
||||
const known = this.rosterMemberIds(tripId, payers.map(p => p.user_id));
|
||||
let total = 0;
|
||||
for (const p of payers) {
|
||||
if (!(p.amount > 0) || !known.has(p.user_id)) continue;
|
||||
@@ -347,9 +351,9 @@ export class BudgetService {
|
||||
const payerTotal = (data.payers || []).reduce((a, p) => a + (p.amount > 0 ? p.amount : 0), 0);
|
||||
const total = data.payers && data.payers.length > 0 ? payerTotal : (data.total_price || 0);
|
||||
|
||||
const knownMembers = data.members ? this.knownUserIds(data.members.map(m => m.user_id)) : null;
|
||||
const knownMembers = data.members ? this.rosterMemberIds(tripId, data.members.map(m => m.user_id)) : null;
|
||||
const members = data.members && knownMembers ? data.members.filter(m => knownMembers.has(m.user_id)) : undefined;
|
||||
const knownIds = data.member_ids ? this.knownUserIds(data.member_ids) : null;
|
||||
const knownIds = data.member_ids ? this.rosterMemberIds(tripId, data.member_ids) : null;
|
||||
const memberIds = data.member_ids && knownIds ? data.member_ids.filter(uid => knownIds.has(uid)) : undefined;
|
||||
|
||||
const { note, ticket } = splitLegacyTicketNote(data.note, data.ticket_json);
|
||||
@@ -373,7 +377,7 @@ export class BudgetService {
|
||||
);
|
||||
|
||||
const itemId = result.lastInsertRowid as number;
|
||||
if (data.payers && data.payers.length > 0) this.writeItemPayers(itemId, data.payers);
|
||||
if (data.payers && data.payers.length > 0) this.writeItemPayers(itemId, tripId, data.payers);
|
||||
if (members && members.length > 0) {
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, ?)');
|
||||
for (const m of members) insert.run(itemId, m.user_id, m.amount !== undefined && m.amount !== null ? m.amount : null);
|
||||
@@ -461,7 +465,7 @@ export class BudgetService {
|
||||
|
||||
// Optional inline payer/member replacement (the edit modal saves all at once).
|
||||
if (data.payers !== undefined) {
|
||||
this.writeItemPayers(id, data.payers);
|
||||
this.writeItemPayers(id, tripId, data.payers);
|
||||
// writeItemPayers derives total_price from the payer sum (0 for no payers).
|
||||
// A "recorded total, nobody assigned" expense clears payers but still carries
|
||||
// an explicit total_price — re-apply it so it isn't clobbered to 0.
|
||||
@@ -470,14 +474,14 @@ export class BudgetService {
|
||||
}
|
||||
}
|
||||
if (data.members !== undefined) {
|
||||
const known = this.knownUserIds(data.members.map(m => m.user_id));
|
||||
const known = this.rosterMemberIds(tripId, data.members.map(m => m.user_id));
|
||||
const members = data.members.filter(m => known.has(m.user_id));
|
||||
this.db.run('DELETE FROM budget_item_members WHERE budget_item_id = ?', id);
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, ?)');
|
||||
for (const m of members) insert.run(id, m.user_id, m.amount !== undefined && m.amount !== null ? m.amount : null);
|
||||
this.db.run('UPDATE budget_items SET persons = ? WHERE id = ?', members.length || null, id);
|
||||
} else if (data.member_ids !== undefined) {
|
||||
const known = this.knownUserIds(data.member_ids);
|
||||
const known = this.rosterMemberIds(tripId, data.member_ids);
|
||||
const memberIds = data.member_ids.filter(uid => known.has(uid));
|
||||
this.db.run('DELETE FROM budget_item_members WHERE budget_item_id = ?', id);
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, NULL)');
|
||||
@@ -510,7 +514,7 @@ export class BudgetService {
|
||||
return this.db.transaction(() => {
|
||||
const item = this.db.get('SELECT id FROM budget_items WHERE id = ? AND trip_id = ?', id, tripId);
|
||||
if (!item) return null;
|
||||
this.writeItemPayers(id, payers);
|
||||
this.writeItemPayers(id, tripId, payers);
|
||||
const updated = this.db.get<BudgetItem>('SELECT * FROM budget_items WHERE id = ?', id)!;
|
||||
updated.members = this.loadItemMembers(id);
|
||||
updated.payers = this.loadItemPayers(id);
|
||||
@@ -540,7 +544,7 @@ export class BudgetService {
|
||||
|
||||
this.db.run('DELETE FROM budget_item_members WHERE budget_item_id = ?', id);
|
||||
|
||||
const known = this.knownUserIds(userIds);
|
||||
const known = this.rosterMemberIds(tripId, userIds);
|
||||
const memberIds = userIds.filter(uid => known.has(uid));
|
||||
if (memberIds.length > 0) {
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid) VALUES (?, ?, ?)');
|
||||
@@ -949,7 +953,21 @@ export class BudgetService {
|
||||
return this.setItemPayers(id, tripId, payers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unlike a split member, a settlement cannot drop an off-roster id: it has
|
||||
* exactly two named parties and both columns are NOT NULL, so a stranger in
|
||||
* either slot makes the row meaningless rather than merely wider. Refuse the
|
||||
* whole write. Returning null lands on the caller's existing "Settlement not
|
||||
* found" 404, which is also what keeps the endpoint from confirming whether
|
||||
* an id it rejected exists at all.
|
||||
*/
|
||||
private settlementPartiesOnTrip(tripId: string | number, data: { from_user_id: number; to_user_id: number }): boolean {
|
||||
const roster = this.db.rosterUserIds(tripId);
|
||||
return roster.has(data.from_user_id) && roster.has(data.to_user_id);
|
||||
}
|
||||
|
||||
async createSettlement(tripId: string | number, data: { from_user_id: number; to_user_id: number; amount: number; currency?: string | null }, userId: number) {
|
||||
if (!this.settlementPartiesOnTrip(tripId, data)) return null;
|
||||
// Freeze the FX rate for the display currency the amount was entered in so the
|
||||
// transfer keeps cancelling its expense when live rates drift (#1445).
|
||||
await this.freezeForeignRate(tripId, data);
|
||||
@@ -960,6 +978,7 @@ export class BudgetService {
|
||||
// Pass the settlement's stored currency so an edit that doesn't change it keeps
|
||||
// the already-frozen rate (#1445) — otherwise a live-rate drift would re-open a
|
||||
// settled position on an unrelated edit.
|
||||
if (!this.settlementPartiesOnTrip(tripId, data)) return null;
|
||||
const existing = this.getSettlement(id, tripId);
|
||||
await this.freezeForeignRate(tripId, data, undefined, existing?.currency ?? null);
|
||||
return this.applySettlementUpdate(id, tripId, data);
|
||||
|
||||
@@ -446,10 +446,23 @@ export class CollectionsService {
|
||||
// Saved places CRUD
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
private attachTags(collectionPlaceId: number, tagIds: number[] | undefined): void {
|
||||
if (!tagIds || tagIds.length === 0) return;
|
||||
const unique = [...new Set(tagIds)];
|
||||
const eligible = this.collectionMemberIds(this.collectionIdOfPlace(collectionPlaceId));
|
||||
const owned = this.db.all<{ id: number; user_id: number }>(
|
||||
`SELECT id, user_id FROM tags WHERE id IN (${unique.map(() => '?').join(',')})`,
|
||||
...unique,
|
||||
);
|
||||
const stmt = this.db.prepare('INSERT OR IGNORE INTO collection_place_tags (collection_place_id, tag_id) VALUES (?, ?)');
|
||||
for (const tid of tagIds) stmt.run(collectionPlaceId, tid);
|
||||
for (const t of owned) if (eligible.has(t.user_id)) stmt.run(collectionPlaceId, t.id);
|
||||
}
|
||||
|
||||
/** Owner + accepted members — the users whose votes may live in this list. */
|
||||
|
||||
@@ -56,6 +56,25 @@ export class DatabaseService {
|
||||
return isOwner(tripId, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
* The user ids a trip may refer to: its members plus the owner. Guests count —
|
||||
* a guest is a credential-less users row joined into trip_members, and #1362
|
||||
* makes it assignable everywhere a real member is.
|
||||
*
|
||||
* This is canAccessTrip's question asked as a set rather than a predicate, so
|
||||
* it lives beside it. Domains that accept user ids in a write body intersect
|
||||
* against it: holding the permission says you may edit the trip, not that any
|
||||
* id you name belongs to it. Runs on the connection rather than delegating to
|
||||
* db/database, because it has no legacy export to stay parity with.
|
||||
*/
|
||||
rosterUserIds(tripId: number | string): Set<number> {
|
||||
const rows = this.all<{ user_id: number }>(
|
||||
'SELECT user_id FROM trip_members WHERE trip_id = ? UNION SELECT user_id FROM trips WHERE id = ?',
|
||||
tripId, tripId,
|
||||
);
|
||||
return new Set(rows.map(r => r.user_id));
|
||||
}
|
||||
|
||||
getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
|
||||
return getPlaceWithTags(placeId);
|
||||
}
|
||||
|
||||
@@ -231,7 +231,8 @@ export class PackingService {
|
||||
// "Shared with specific people" — record the recipients it covers.
|
||||
if (data.visibility === 'shared' && Array.isArray(data.recipient_ids)) {
|
||||
const ins = this.db.prepare('INSERT OR IGNORE INTO packing_item_recipients (item_id, user_id) VALUES (?, ?)');
|
||||
for (const uid of data.recipient_ids) if (uid !== ownerId) ins.run(id, uid);
|
||||
const roster = this.tripRosterIds(tripId);
|
||||
for (const uid of data.recipient_ids) if (uid !== ownerId && roster.has(uid)) ins.run(id, uid);
|
||||
}
|
||||
return id;
|
||||
});
|
||||
@@ -350,7 +351,8 @@ export class PackingService {
|
||||
if (visibility === 'shared') {
|
||||
const ins = this.db.prepare('INSERT OR IGNORE INTO packing_item_recipients (item_id, user_id) VALUES (?, ?)');
|
||||
const owner = item.owner_id ?? actingUserId;
|
||||
for (const uid of recipientIds) if (uid !== owner) ins.run(id, uid);
|
||||
const roster = this.tripRosterIds(tripId);
|
||||
for (const uid of recipientIds) if (uid !== owner && roster.has(uid)) ins.run(id, uid);
|
||||
}
|
||||
// Leaving the Common tier drops any co-contributors (they only apply to Common).
|
||||
if (visibility !== 'common') this.db.run('DELETE FROM packing_item_contributors WHERE item_id = ?', id);
|
||||
@@ -479,10 +481,14 @@ export class PackingService {
|
||||
}));
|
||||
}
|
||||
|
||||
/** Owner + collaborators of a trip — the only user ids that may be assigned to a bag. */
|
||||
/**
|
||||
* Owner + collaborators of a trip, guests included — the only user ids
|
||||
* assignable anywhere on it, not just to a bag. The wording used to say
|
||||
* "assigned to a bag", which is why the category and recipient writes below
|
||||
* grew up without it.
|
||||
*/
|
||||
private tripRosterIds(tripId: string | number): Set<number> {
|
||||
const rows = this.db.all<{ user_id: number }>('SELECT user_id FROM trip_members WHERE trip_id = ? UNION SELECT user_id FROM trips WHERE id = ?', tripId, tripId);
|
||||
return new Set(rows.map(r => r.user_id));
|
||||
return this.db.rosterUserIds(tripId);
|
||||
}
|
||||
|
||||
setBagMembers(tripId: string | number, bagId: string | number, userIds: number[]) {
|
||||
@@ -665,7 +671,9 @@ export class PackingService {
|
||||
|
||||
if (Array.isArray(userIds) && userIds.length > 0) {
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO packing_category_assignees (trip_id, category_name, user_id) VALUES (?, ?, ?)');
|
||||
for (const uid of userIds) insert.run(tripId, categoryName, uid);
|
||||
// Same rule as setBagMembers: only people on this trip may be assigned.
|
||||
const roster = this.tripRosterIds(tripId);
|
||||
for (const uid of userIds) if (roster.has(uid)) insert.run(tripId, categoryName, uid);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -20,7 +20,7 @@ import type { Response } from 'express';
|
||||
import { isDemoWriteBlocked, DEMO_WRITE_ERROR } from '../common/demo-write';
|
||||
import { RuntimeEnvService } from '../app-config/runtime-env.service';
|
||||
import { memoryStorage } from 'multer';
|
||||
import { hexColorSchema } from '@trek/shared';
|
||||
import { hexColorSchema, placeImageUrlSchema, placeWebsiteSchema } from '@trek/shared';
|
||||
import type { User } from '../../types';
|
||||
import { PlacesService } from './places.service';
|
||||
import { isUpdateConflict } from '../common/conflictResult';
|
||||
@@ -64,6 +64,25 @@ function validateRouteColor(body: Record<string, unknown>): void {
|
||||
}
|
||||
}
|
||||
|
||||
// Same reason as route_color: these two leave the database for a renderer that
|
||||
// treats them as a URL — the thumbnail into marker HTML, the homepage into
|
||||
// window.open — and the open record means the pipe never sees them.
|
||||
function validateUrlFields(body: Record<string, unknown>): void {
|
||||
const image = body.image_url;
|
||||
if (image !== undefined && image !== null) {
|
||||
if (typeof image !== 'string' || !placeImageUrlSchema.safeParse(image).success) {
|
||||
throw new HttpException({ error: 'image_url must be an uploaded path, a photo-proxy path, an inline image or an https URL' }, 400);
|
||||
}
|
||||
}
|
||||
const website = body.website;
|
||||
// '' is how the UI clears the field; treat it like an absent value.
|
||||
if (website !== undefined && website !== null && website !== '') {
|
||||
if (typeof website !== 'string' || !placeWebsiteSchema.safeParse(website).success) {
|
||||
throw new HttpException({ error: 'website must be an http or https URL' }, 400);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function parseBool(v: unknown, defaultVal: boolean): boolean {
|
||||
return v === undefined || v === null ? defaultVal : String(v) === 'true';
|
||||
}
|
||||
@@ -133,6 +152,7 @@ export class PlacesController {
|
||||
const trip = this.requireTrip(tripId, user);
|
||||
validateLengths(body);
|
||||
validateRouteColor(body);
|
||||
validateUrlFields(body);
|
||||
this.requireEdit(trip, user);
|
||||
const place = this.places.create(tripId, body as never);
|
||||
this.places.broadcast(tripId, 'place:created', { place }, socketId);
|
||||
@@ -433,6 +453,7 @@ export class PlacesController {
|
||||
const trip = this.requireTrip(tripId, user);
|
||||
validateLengths(body);
|
||||
validateRouteColor(body);
|
||||
validateUrlFields(body);
|
||||
this.requireEdit(trip, user);
|
||||
const result = await this.places.update(tripId, id, body as never, ifMatch);
|
||||
if (!result) {
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
demoDenied, ok,
|
||||
} from '@trek/nest-mcp';
|
||||
import { McpToolGuardsService } from '../mcp-shared/mcp-tool-guards.service';
|
||||
import { placeWebsiteSchema } from '@trek/shared';
|
||||
import { z } from 'zod';
|
||||
import { AuthService } from '../auth/auth.service';
|
||||
import { AssignmentsService } from '../assignments/assignments.service';
|
||||
@@ -63,7 +64,7 @@ export class PlacesMcp {
|
||||
google_ftid: z.string().optional().describe('Google Maps feature ID from search_place — enables direct Google Maps links'),
|
||||
osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345") — enables opening hours if no Google ID'),
|
||||
notes: z.string().max(2000).optional(),
|
||||
website: z.string().max(500).optional(),
|
||||
website: placeWebsiteSchema.optional(),
|
||||
phone: z.string().max(50).optional(),
|
||||
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")'),
|
||||
@@ -103,7 +104,7 @@ export class PlacesMcp {
|
||||
google_ftid: z.string().optional().describe('Google Maps feature ID from search_place — enables direct Google Maps links'),
|
||||
osm_id: z.string().optional().describe('OpenStreetMap ID from search_place (e.g. "way:12345")'),
|
||||
place_notes: z.string().max(2000).optional().describe('Notes for the place'),
|
||||
website: z.string().max(500).optional(),
|
||||
website: placeWebsiteSchema.optional(),
|
||||
phone: z.string().max(50).optional(),
|
||||
assignment_notes: z.string().max(500).optional().describe('Notes for this day assignment'),
|
||||
price: z.number().nonnegative().optional().describe('Cost of this place/activity (e.g. ticket price, entry fee)'),
|
||||
@@ -158,7 +159,7 @@ export class PlacesMcp {
|
||||
end_time: z.string().max(50).optional().describe('End time (e.g. "11:00")'),
|
||||
duration_minutes: z.number().int().positive().optional(),
|
||||
notes: z.string().max(2000).optional(),
|
||||
website: z.string().max(500).optional(),
|
||||
website: placeWebsiteSchema.optional(),
|
||||
phone: z.string().max(50).optional(),
|
||||
transport_mode: z.enum(['walking', 'driving', 'cycling', 'transit', 'flight']).optional(),
|
||||
osm_id: z.string().optional().describe('OpenStreetMap ID (e.g. "way:12345")'),
|
||||
@@ -366,7 +367,7 @@ export class PlacesMcp {
|
||||
end_time: z.string().max(50).optional().describe('End time (e.g. "11:00")'),
|
||||
duration_minutes: z.number().int().positive().optional(),
|
||||
notes: z.string().max(2000).optional(),
|
||||
website: z.string().max(500).optional(),
|
||||
website: placeWebsiteSchema.optional(),
|
||||
phone: z.string().max(50).optional(),
|
||||
description: z.string().max(2000).optional(),
|
||||
},
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { placeCreateRequestSchema, placeUpdateRequestSchema } from '@trek/shared';
|
||||
import { placeCreateRequestSchema, placeImageUrlSchema, placeUpdateRequestSchema, placeWebsiteSchema } from '@trek/shared';
|
||||
import { PluginController, PluginMethod } from '../plugins/host/rpc-kit/decorators';
|
||||
import { PluginGuards } from '../plugins/host/plugin-guards.service';
|
||||
import { BadParams, ForbiddenResource } from '../plugins/host/rpc-errors';
|
||||
@@ -18,6 +18,23 @@ const PLACE_EDIT_ACTION = 'place_edit';
|
||||
*/
|
||||
const PLACE_STR_LIMITS: Record<string, number> = { name: 200, description: 2000, address: 500, notes: 2000 };
|
||||
|
||||
/**
|
||||
* The two URL fields the REST controller pins in validateUrlFields. Same reason
|
||||
* they are checked there rather than in the contract: the write schemas are open
|
||||
* records, so a plugin could otherwise store a thumbnail or a homepage the web
|
||||
* app refuses — and both end up somewhere that treats them as a URL.
|
||||
*/
|
||||
function capUrls(input: Record<string, unknown>): void {
|
||||
const image = input.image_url;
|
||||
if (image !== undefined && image !== null && !placeImageUrlSchema.safeParse(image).success) {
|
||||
throw new BadParams('invalid place: image_url must be an uploaded path, a photo-proxy path, an inline image or an https URL');
|
||||
}
|
||||
const website = input.website;
|
||||
if (website !== undefined && website !== null && website !== '' && !placeWebsiteSchema.safeParse(website).success) {
|
||||
throw new BadParams('invalid place: website must be an http or https URL');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The place surface a plugin may reach (#plugins).
|
||||
*
|
||||
@@ -41,6 +58,7 @@ export class PlacesRpc {
|
||||
const parsed = placeCreateRequestSchema.safeParse(params.input);
|
||||
if (!parsed.success) throw new BadParams(`invalid place: ${schemaMessage(parsed.error)}`);
|
||||
this.guards.capStrings(parsed.data as Record<string, unknown>, PLACE_STR_LIMITS);
|
||||
capUrls(parsed.data as Record<string, unknown>);
|
||||
this.guards.requireTripEdit(tripId, actor, PLACE_EDIT_ACTION);
|
||||
const place = this.places.create(String(tripId), parsed.data as unknown as PlaceCreateInput);
|
||||
this.realtime.broadcast(tripId, 'place:created', { place });
|
||||
@@ -56,6 +74,7 @@ export class PlacesRpc {
|
||||
const parsed = placeUpdateRequestSchema.safeParse(params.input);
|
||||
if (!parsed.success) throw new BadParams(`invalid place: ${schemaMessage(parsed.error)}`);
|
||||
this.guards.capStrings(parsed.data as Record<string, unknown>, PLACE_STR_LIMITS);
|
||||
capUrls(parsed.data as Record<string, unknown>);
|
||||
this.guards.requireTripEdit(tripId, actor, PLACE_EDIT_ACTION);
|
||||
const place = this.places.update(String(tripId), String(placeId), parsed.data as PlaceUpdateInput);
|
||||
if (place === null) throw new ForbiddenResource(`no place ${placeId} on trip ${tripId}`);
|
||||
|
||||
@@ -124,6 +124,29 @@ export class PlacesService {
|
||||
return this.permissions.checkPermission('place_edit', user.role, trip.user_id, user.id, trip.user_id !== user.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
private tagsOnTrip(tripId: string | number, tagIds: number[]): number[] {
|
||||
const unique = [...new Set(tagIds)];
|
||||
if (unique.length === 0) return [];
|
||||
const roster = this.dbs.rosterUserIds(tripId);
|
||||
const owned = this.dbs.all<{ id: number; user_id: number }>(
|
||||
`SELECT id, user_id FROM tags WHERE id IN (${unique.map(() => '?').join(',')})`,
|
||||
...unique,
|
||||
);
|
||||
return owned.filter(t => roster.has(t.user_id)).map(t => t.id);
|
||||
}
|
||||
|
||||
broadcast<E extends TrekWsTripEventName>(tripId: string, event: E, payload: TrekWsPayload<E>, socketId: string | undefined): void {
|
||||
this.realtime.broadcast(tripId, event, payload, socketId);
|
||||
}
|
||||
@@ -225,7 +248,7 @@ export class PlacesService {
|
||||
|
||||
if (tags && tags.length > 0) {
|
||||
const insertTag = this.dbs.prepare('INSERT OR IGNORE INTO place_tags (place_id, tag_id) VALUES (?, ?)');
|
||||
for (const tagId of tags) {
|
||||
for (const tagId of this.tagsOnTrip(tripId, tags)) {
|
||||
insertTag.run(placeId, tagId);
|
||||
}
|
||||
}
|
||||
@@ -342,7 +365,7 @@ export class PlacesService {
|
||||
this.dbs.run('DELETE FROM place_tags WHERE place_id = ?', placeId);
|
||||
if (tags.length > 0) {
|
||||
const insertTag = this.dbs.prepare('INSERT OR IGNORE INTO place_tags (place_id, tag_id) VALUES (?, ?)');
|
||||
for (const tagId of tags) {
|
||||
for (const tagId of this.tagsOnTrip(tripId, tags)) {
|
||||
insertTag.run(placeId, tagId);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -468,6 +468,13 @@ export class ReservationsMcp {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId)) return permissionDenied();
|
||||
|
||||
// The service scopes the write to the trip on its own, so a foreign id is
|
||||
// already harmless — say so rather than reporting a success that moved
|
||||
// nothing, the way the sibling tools above do.
|
||||
if (dayId && !this.days.getDay(dayId, tripId))
|
||||
return errorResult('dayId does not belong to this trip.');
|
||||
|
||||
this.reservations.updatePositions(tripId, positions, dayId);
|
||||
this.guards.safeBroadcast(tripId, 'reservation:positions', { positions, dayId });
|
||||
return ok({ success: true });
|
||||
|
||||
@@ -527,13 +527,26 @@ export class ReservationsService {
|
||||
return { reservation, accommodationCreated };
|
||||
}
|
||||
|
||||
updatePositions(tripId: string | number, positions: { id: number; day_plan_position: number }[], dayId?: number | string | null) {
|
||||
updatePositions(tripId: string | number, positions: { id: number; day_plan_position?: number }[], dayId?: number | string | null) {
|
||||
if (dayId) {
|
||||
// Per-day positions for multi-day reservations
|
||||
const stmt = this.db.prepare('INSERT OR REPLACE INTO reservation_day_positions (reservation_id, day_id, position) VALUES (?, ?, ?)');
|
||||
// Per-day positions for multi-day reservations, scoped the way the legacy
|
||||
// branch below already scopes its update. The table carries no trip_id and
|
||||
// its two foreign keys only ask that the ids exist, so the trip has to come
|
||||
// from the join: the row materialises only when the reservation and the day
|
||||
// agree on it. Doing that in the statement rather than as a pre-check also
|
||||
// makes a stale id a quiet no-op instead of a foreign-key error surfacing
|
||||
// as a 500.
|
||||
const stmt = this.db.prepare(`
|
||||
INSERT OR REPLACE INTO reservation_day_positions (reservation_id, day_id, position)
|
||||
SELECT r.id, d.id, ?
|
||||
FROM reservations r
|
||||
JOIN days d ON d.trip_id = r.trip_id
|
||||
WHERE r.id = ? AND d.id = ? AND r.trip_id = ?
|
||||
`);
|
||||
this.db.transaction(() => {
|
||||
for (const item of positions) {
|
||||
stmt.run(item.id, dayId, item.day_plan_position);
|
||||
// position is NOT NULL while the wire contract leaves the value optional.
|
||||
stmt.run(item.day_plan_position ?? 0, item.id, dayId, tripId);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
|
||||
@@ -136,7 +136,12 @@ export class TodoService {
|
||||
|
||||
if (Array.isArray(userIds) && userIds.length > 0) {
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO todo_category_assignees (trip_id, category_name, user_id) VALUES (?, ?, ?)');
|
||||
for (const uid of userIds) insert.run(tripId, categoryName, uid);
|
||||
// Only people on this trip may be assigned, the way packing filters bag
|
||||
// members and reservations filter travellers. Dropped rather than
|
||||
// rejected: a copied trip carries assignee ids across before its members
|
||||
// exist, and a 400 would make the picker unusable there.
|
||||
const roster = this.db.rosterUserIds(tripId);
|
||||
for (const uid of userIds) if (roster.has(uid)) insert.run(tripId, categoryName, uid);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
Reference in New Issue
Block a user