mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-27 07:07:31 +00:00
Trip members can rate a place 1-5 stars; the place shows the average, with a who-voted custom tooltip and a star-sort toggle in the places sidebar. Saved collection places are ratable too (plus a min-rating filter), and ratings travel with a place copied between a trip and a collection — carrying only the votes of users who belong to both sides. Adds a full Collections MCP surface (list/get, CRUD lists + places, status, rate_collection_place, labels, sharing, copy-to-trip) under a new collections:read/collections:write scope, plus rate_place for trip places; rating aggregates flow through the existing place outputs. Mobile trip + collection place sheets gain the rating row. New UI strings translated across all 22 locales.
This commit is contained in:
@@ -96,6 +96,9 @@ interface PlaceWithCategory extends Place {
|
||||
interface PlaceWithTags extends Place {
|
||||
category: { id: number; name: string; color: string; icon: string } | null;
|
||||
tags: Tag[];
|
||||
ratings: { user_id: number; username: string; avatar: string | null; rating: number }[];
|
||||
rating_avg: number | null;
|
||||
rating_count: number;
|
||||
}
|
||||
|
||||
function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
|
||||
@@ -114,6 +117,14 @@ function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
|
||||
WHERE pt.place_id = ?
|
||||
`).all(placeId) as Tag[];
|
||||
|
||||
// Collaborative ratings (#1435): every voter with username/avatar for the
|
||||
// who-voted tooltip; the displayed value is the average.
|
||||
const ratings = db.prepare(`
|
||||
SELECT pr.user_id, u.username, u.avatar, pr.rating FROM place_ratings pr
|
||||
JOIN users u ON pr.user_id = u.id
|
||||
WHERE pr.place_id = ? ORDER BY pr.created_at
|
||||
`).all(placeId) as { user_id: number; username: string; avatar: string | null; rating: number }[];
|
||||
|
||||
return {
|
||||
...place,
|
||||
category: place.category_id ? {
|
||||
@@ -123,6 +134,9 @@ function getPlaceWithTags(placeId: number | string): PlaceWithTags | null {
|
||||
icon: place.category_icon!,
|
||||
} : null,
|
||||
tags,
|
||||
ratings,
|
||||
rating_avg: ratings.length > 0 ? ratings.reduce((s, r) => s + r.rating, 0) / ratings.length : null,
|
||||
rating_count: ratings.length,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -3727,6 +3727,33 @@ function runMigrations(db: Database.Database): void {
|
||||
`);
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_vacay_shares_user ON vacay_shares (user_id);');
|
||||
},
|
||||
// Collaborative place ratings (#1435): every trip member can rate a trip
|
||||
// place 1-5, every collection member a saved place; the displayed value is
|
||||
// the average. One row per user and place, mirroring collab_poll_votes.
|
||||
() => {
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS place_ratings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
rating INTEGER NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(place_id, user_id)
|
||||
);
|
||||
`);
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_place_ratings_place ON place_ratings (place_id);');
|
||||
db.exec(`
|
||||
CREATE TABLE IF NOT EXISTS collection_place_ratings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
rating INTEGER NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(collection_place_id, user_id)
|
||||
);
|
||||
`);
|
||||
db.exec('CREATE INDEX IF NOT EXISTS idx_collection_place_ratings_place ON collection_place_ratings (collection_place_id);');
|
||||
},
|
||||
];
|
||||
|
||||
if (currentVersion < migrations.length) {
|
||||
|
||||
@@ -155,6 +155,15 @@ function createTables(db: Database.Database): void {
|
||||
PRIMARY KEY (place_id, tag_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS place_ratings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
place_id INTEGER NOT NULL REFERENCES places(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
rating INTEGER NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(place_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS day_assignments (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
day_id INTEGER NOT NULL REFERENCES days(id) ON DELETE CASCADE,
|
||||
@@ -425,6 +434,15 @@ function createTables(db: Database.Database): void {
|
||||
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS collection_place_ratings (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
|
||||
user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
rating INTEGER NOT NULL,
|
||||
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
UNIQUE(collection_place_id, user_id)
|
||||
);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS collection_place_tags (
|
||||
collection_place_id INTEGER NOT NULL REFERENCES collection_places(id) ON DELETE CASCADE,
|
||||
tag_id INTEGER NOT NULL REFERENCES tags(id) ON DELETE CASCADE,
|
||||
|
||||
@@ -9,6 +9,8 @@ export const SCOPES = {
|
||||
TRIPS_SHARE: 'trips:share',
|
||||
PLACES_READ: 'places:read',
|
||||
PLACES_WRITE: 'places:write',
|
||||
COLLECTIONS_READ: 'collections:read',
|
||||
COLLECTIONS_WRITE: 'collections:write',
|
||||
ATLAS_READ: 'atlas:read',
|
||||
ATLAS_WRITE: 'atlas:write',
|
||||
PACKING_READ: 'packing:read',
|
||||
@@ -49,6 +51,8 @@ export const SCOPE_INFO: Record<Scope, ScopeInfo> = {
|
||||
'trips:share': { label: 'Manage share links', description: 'Create, update, and revoke public share links for trips', group: 'Trips' },
|
||||
'places:read': { label: 'View places & map data', description: 'Read places, day assignments, tags, and categories', group: 'Places' },
|
||||
'places:write': { label: 'Manage places', description: 'Create, update, and delete places, assignments, and tags', group: 'Places' },
|
||||
'collections:read': { label: 'View collections', description: 'Read saved-place collections, their places, ratings, labels, and members', group: 'Collections' },
|
||||
'collections:write': { label: 'Manage collections', description: 'Create/edit collections, save, rate, label and copy places, and share lists', group: 'Collections' },
|
||||
'atlas:read': { label: 'View Atlas', description: 'Read visited countries, regions, and bucket list', group: 'Atlas' },
|
||||
'atlas:write': { label: 'Manage Atlas', description: 'Mark countries and regions visited, manage bucket list', group: 'Atlas' },
|
||||
'packing:read': { label: 'View packing lists', description: 'Read packing items, bags, and category assignees', group: 'Packing' },
|
||||
|
||||
@@ -8,6 +8,7 @@ import { registerMapsWeatherTools } from './tools/mapsWeather';
|
||||
import { registerNotificationTools } from './tools/notifications';
|
||||
import { registerAtlasTools } from './tools/atlas';
|
||||
import { registerPlaceTools } from './tools/places';
|
||||
import { registerCollectionTools } from './tools/collections';
|
||||
import { registerDayTools } from './tools/days';
|
||||
import { registerBudgetTools } from './tools/budget';
|
||||
import { registerPackingTools } from './tools/packing';
|
||||
@@ -23,6 +24,8 @@ export function registerTools(server: McpServer, userId: number, scopes: string[
|
||||
|
||||
registerPlaceTools(server, userId, scopes);
|
||||
|
||||
registerCollectionTools(server, userId, scopes);
|
||||
|
||||
registerBudgetTools(server, userId, scopes);
|
||||
|
||||
registerPackingTools(server, userId, scopes);
|
||||
|
||||
@@ -0,0 +1,398 @@
|
||||
import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import { z } from 'zod';
|
||||
import { db } from '../../db/database';
|
||||
import { isDemoUser } from '../../services/authService';
|
||||
import * as collections from '../../services/collectionsService';
|
||||
import {
|
||||
TOOL_ANNOTATIONS_READONLY, TOOL_ANNOTATIONS_WRITE, TOOL_ANNOTATIONS_DELETE,
|
||||
TOOL_ANNOTATIONS_NON_IDEMPOTENT, demoDenied, ok,
|
||||
} from './_shared';
|
||||
import { canRead, canWrite } from '../scopes';
|
||||
import {
|
||||
collectionCreateRequestSchema, collectionUpdateRequestSchema,
|
||||
collectionSavePlaceRequestSchema, collectionPlaceUpdateRequestSchema,
|
||||
collectionCopyToTripRequestSchema, collectionLabelCreateRequestSchema,
|
||||
collectionLabelUpdateRequestSchema, collectionLabelAssignRequestSchema,
|
||||
collectionInviteRequestSchema, COLLECTION_STATUSES, COLLECTION_ROLES,
|
||||
} from '@trek/shared';
|
||||
|
||||
/** Convert a thrown service error (httpError carries `.message`) into MCP error text. */
|
||||
function errText(err: unknown): string {
|
||||
if (err instanceof Error) return err.message;
|
||||
if (typeof err === 'string') return err;
|
||||
return 'Operation failed';
|
||||
}
|
||||
function fail(err: unknown) {
|
||||
return { content: [{ type: 'text' as const, text: errText(err) }], isError: true };
|
||||
}
|
||||
|
||||
/**
|
||||
* Collections MCP surface (#1435) — the full set of actions a member can take on
|
||||
* a saved-places list: browse, CRUD lists + places, status, collaborative star
|
||||
* ratings, per-list labels, sharing, and copy-into-a-trip. Every service call
|
||||
* enforces the caller's membership/role, so the tools stay thin wrappers. Place
|
||||
* outputs carry the `ratings`/`rating_avg`/`rating_count` aggregate.
|
||||
*/
|
||||
export function registerCollectionTools(server: McpServer, userId: number, scopes: string[] | null): void {
|
||||
const R = canRead(scopes, 'collections');
|
||||
const W = canWrite(scopes, 'collections');
|
||||
|
||||
const denyDemo = () => (isDemoUser(userId) ? demoDenied() : null);
|
||||
|
||||
// ── Read ──────────────────────────────────────────────────────────────
|
||||
|
||||
if (R) server.registerTool(
|
||||
'list_collections',
|
||||
{
|
||||
description: 'List all saved-place collections (lists) the user owns or has accepted a share for, plus any pending incoming invites. Use get_collection for a list\'s places.',
|
||||
inputSchema: {},
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
},
|
||||
async () => {
|
||||
try { return ok(collections.listCollections(userId)); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (R) server.registerTool(
|
||||
'get_collection',
|
||||
{
|
||||
description: 'Get one collection with its members, labels, and all saved places. Each place includes rating_avg / rating_count and the per-member ratings (#1435) so you can plan around highly-rated spots.',
|
||||
inputSchema: { collectionId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
},
|
||||
async ({ collectionId }) => {
|
||||
try { return ok(collections.getCollection(userId, collectionId)); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (R) server.registerTool(
|
||||
'available_collection_users',
|
||||
{
|
||||
description: 'List users who can still be invited to a collection (excludes current members and guests). Use the returned ids with invite_to_collection.',
|
||||
inputSchema: { collectionId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_READONLY,
|
||||
},
|
||||
async ({ collectionId }) => {
|
||||
try {
|
||||
// Owner-only, mirroring the REST gate — availableUsers() itself does no
|
||||
// access check, so without this any token could enumerate the user list.
|
||||
collections.assertAccess(userId, collectionId);
|
||||
if (!collections.isOwner(userId, collectionId)) {
|
||||
return { content: [{ type: 'text' as const, text: 'Only the collection owner can view invitable users.' }], isError: true };
|
||||
}
|
||||
return ok({ users: collections.availableUsers(userId, collectionId) });
|
||||
} catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
// ── Collections CRUD ─────────────────────────────────────────────────
|
||||
|
||||
if (W) server.registerTool(
|
||||
'create_collection',
|
||||
{
|
||||
description: 'Create a new saved-place collection (list) owned by the user.',
|
||||
inputSchema: collectionCreateRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
},
|
||||
async (body) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok({ collection: collections.createCollection(userId, body) }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'update_collection',
|
||||
{
|
||||
description: 'Update a collection\'s name, description, colour, icon, cover, links, or sort order. Owner/admin only.',
|
||||
inputSchema: { collectionId: z.number().int().positive(), ...collectionUpdateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ collectionId, ...body }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok({ collection: collections.updateCollection(userId, collectionId, body) }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'delete_collection',
|
||||
{
|
||||
description: 'Permanently delete a collection and all its saved places. Owner only. This cannot be undone.',
|
||||
inputSchema: { collectionId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
},
|
||||
async ({ collectionId }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { collections.deleteCollection(userId, collectionId); return ok({ success: true }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'reorder_collections',
|
||||
{
|
||||
description: 'Reorder the user\'s collections. Pass every collection id in the desired order.',
|
||||
inputSchema: { orderedIds: z.array(z.number().int().positive()).min(1) },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ orderedIds }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { collections.reorderCollections(userId, orderedIds); return ok({ success: true }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
// ── Places ────────────────────────────────────────────────────────────
|
||||
|
||||
if (W) server.registerTool(
|
||||
'save_place_to_collection',
|
||||
{
|
||||
description: 'Save a place into a collection from a raw payload (name required; set google_place_id/osm_id from search_place for rich details). Returns a duplicate marker instead of saving when a similar place already exists, unless force is true.',
|
||||
inputSchema: collectionSavePlaceRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
},
|
||||
async (body) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok(collections.savePlace(userId, body)); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'save_trip_places_to_collection',
|
||||
{
|
||||
description: 'Copy one or more existing trip places into a collection (the server reads each place). Their star ratings (#1435) travel along for members shared on both. Duplicates are skipped unless force is true.',
|
||||
inputSchema: {
|
||||
collectionId: z.number().int().positive(),
|
||||
tripId: z.number().int().positive(),
|
||||
placeIds: z.array(z.number().int().positive()).min(1).max(1000),
|
||||
force: z.boolean().optional(),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
},
|
||||
async ({ collectionId, tripId, placeIds, force }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok(collections.saveFromTripPlaces(userId, collectionId, tripId, placeIds, force)); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'update_collection_place',
|
||||
{
|
||||
description: 'Update a saved place\'s name, description, notes, status, category, links, tags, labels, image, or move it to another collection (set collection_id).',
|
||||
inputSchema: { placeId: z.number().int().positive(), ...collectionPlaceUpdateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ placeId, ...body }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok({ place: collections.updatePlace(userId, placeId, body) }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'set_collection_place_status',
|
||||
{
|
||||
description: 'Set a saved place\'s status: idea, want, or visited.',
|
||||
inputSchema: { placeId: z.number().int().positive(), status: z.enum(COLLECTION_STATUSES) },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ placeId, status }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok({ place: collections.setStatus(userId, placeId, status) }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'rate_collection_place',
|
||||
{
|
||||
description: "Set or clear the current user's 1-5 star rating on a saved collection place (#1435). Every member rates independently; the place shows the average. Pass null (or omit rating) to remove the user's vote. Ratings a member casts here follow the place into any trip it is later copied to. Use the ratings to capture the user's preferences.",
|
||||
inputSchema: {
|
||||
placeId: z.number().int().positive(),
|
||||
rating: z.number().int().min(1).max(5).nullable().optional().describe('1-5 stars; null/omitted clears the vote'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ placeId, rating }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok({ place: collections.setRating(userId, placeId, rating ?? null) }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'delete_collection_place',
|
||||
{
|
||||
description: 'Remove a saved place from its collection. Requires delete permission on the list.',
|
||||
inputSchema: { placeId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
},
|
||||
async ({ placeId }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { collections.deletePlace(userId, placeId); return ok({ success: true }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'copy_collection_places_to_trip',
|
||||
{
|
||||
description: 'Copy one or more saved collection places into a trip (dedup precheck on the server). Ratings (#1435) travel into the trip; trip members keep voting there. Requires edit access to the target trip.',
|
||||
inputSchema: collectionCopyToTripRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
},
|
||||
async (body) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok(collections.copyToTrip(userId, body)); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
// ── Labels ────────────────────────────────────────────────────────────
|
||||
|
||||
if (W) server.registerTool(
|
||||
'create_collection_label',
|
||||
{
|
||||
description: 'Create a custom per-collection label (name + optional hex colour) for grouping/filtering places.',
|
||||
inputSchema: collectionLabelCreateRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
},
|
||||
async ({ collection_id, name, color }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok({ label: collections.createLabel(userId, collection_id, name, color) }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'update_collection_label',
|
||||
{
|
||||
description: 'Rename or recolour a collection label, or change its sort order.',
|
||||
inputSchema: { labelId: z.number().int().positive(), ...collectionLabelUpdateRequestSchema.shape },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ labelId, ...body }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok({ label: collections.updateLabel(userId, labelId, body) }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'delete_collection_label',
|
||||
{
|
||||
description: 'Delete a collection label; its assignments on places are cleared.',
|
||||
inputSchema: { labelId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
},
|
||||
async ({ labelId }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { collections.deleteLabel(userId, labelId); return ok({ success: true }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'assign_collection_labels',
|
||||
{
|
||||
description: 'Add (or with remove=true, take away) one or more labels across a set of saved places. Only labels belonging to each place\'s own list are applied.',
|
||||
inputSchema: { ...collectionLabelAssignRequestSchema.shape, remove: z.boolean().optional() },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ label_ids, place_ids, remove }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { return ok(collections.assignLabels(userId, label_ids, place_ids, remove ?? false)); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
// ── Sharing ───────────────────────────────────────────────────────────
|
||||
|
||||
if (W) server.registerTool(
|
||||
'invite_to_collection',
|
||||
{
|
||||
description: 'Invite a user (by id, from available_collection_users) to collaborate on a collection, with a role of viewer, editor, or admin (default editor). Owner only.',
|
||||
inputSchema: collectionInviteRequestSchema.shape,
|
||||
annotations: TOOL_ANNOTATIONS_NON_IDEMPOTENT,
|
||||
},
|
||||
async ({ collection_id, user_id, role }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
const me = db.prepare('SELECT username, email FROM users WHERE id = ?').get(userId) as { username: string; email: string } | undefined;
|
||||
const res = collections.sendInvite(collection_id, userId, me?.username ?? '', me?.email ?? '', user_id, role);
|
||||
if (res.error) return { content: [{ type: 'text' as const, text: res.error }], isError: true };
|
||||
return ok({ success: true });
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'set_collection_member_role',
|
||||
{
|
||||
description: 'Change an accepted member\'s permission role (viewer, editor, or admin). Owner only.',
|
||||
inputSchema: {
|
||||
collectionId: z.number().int().positive(),
|
||||
userId: z.number().int().positive(),
|
||||
role: z.enum(COLLECTION_ROLES),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ collectionId, userId: targetUserId, role }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { collections.setMemberRole(userId, collectionId, targetUserId, role); return ok({ success: true }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'remove_collection_member',
|
||||
{
|
||||
description: 'Remove an accepted member from a shared collection (a kick). Owner only.',
|
||||
inputSchema: { collectionId: z.number().int().positive(), userId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_DELETE,
|
||||
},
|
||||
async ({ collectionId, userId: targetUserId }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { collections.removeMember(userId, collectionId, targetUserId); return ok({ success: true }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'cancel_collection_invite',
|
||||
{
|
||||
description: 'Cancel a pending invite you sent to a user for a collection. Owner only.',
|
||||
inputSchema: { collectionId: z.number().int().positive(), userId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ collectionId, userId: targetUserId }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { collections.cancelInvite(collectionId, userId, targetUserId); return ok({ success: true }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'accept_collection_invite',
|
||||
{
|
||||
description: 'Accept a pending invite to join a shared collection.',
|
||||
inputSchema: { collectionId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ collectionId }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
const res = collections.acceptInvite(userId, collectionId, undefined);
|
||||
if (res.error) return { content: [{ type: 'text' as const, text: res.error }], isError: true };
|
||||
return ok({ success: true });
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'decline_collection_invite',
|
||||
{
|
||||
description: 'Decline a pending invite to a shared collection.',
|
||||
inputSchema: { collectionId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ collectionId }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { collections.declineInvite(userId, collectionId, undefined); return ok({ success: true }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'leave_collection',
|
||||
{
|
||||
description: 'Leave a shared collection you are a member of. The owner cannot leave (delete the list instead).',
|
||||
inputSchema: { collectionId: z.number().int().positive() },
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ collectionId }) => {
|
||||
const demo = denyDemo(); if (demo) return demo;
|
||||
try { collections.leaveCollection(userId, collectionId, undefined); return ok({ success: true }); } catch (err) { return fail(err); }
|
||||
}
|
||||
);
|
||||
}
|
||||
@@ -2,7 +2,7 @@ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp';
|
||||
import { z } from 'zod';
|
||||
import { canAccessTrip, db } from '../../db/database';
|
||||
import { isDemoUser } from '../../services/authService';
|
||||
import { deletePlacesMany, updatePlacesMany, importGoogleList, importNaverList, listPlaces, createPlace, updatePlace, deletePlace } from '../../services/placeService';
|
||||
import { deletePlacesMany, updatePlacesMany, importGoogleList, importNaverList, listPlaces, createPlace, updatePlace, deletePlace, ratePlace } from '../../services/placeService';
|
||||
import { createAssignment, dayExists } from '../../services/assignmentService';
|
||||
import { onPlaceDeleted, reconcileTripSkeletons } from '../../services/journeyService';
|
||||
import { listCategories } from '../../services/categoryService';
|
||||
@@ -139,6 +139,28 @@ export function registerPlaceTools(server: McpServer, userId: number, scopes: st
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'rate_place',
|
||||
{
|
||||
description: "Set or clear the current user's 1-5 star rating on a trip place (#1435). Every trip member rates independently; the place shows the average. Omit rating (or pass null) to remove the user's vote. Use the ratings to capture the user's preferences and shape the itinerary around highly-rated places.",
|
||||
inputSchema: {
|
||||
tripId: z.number().int().positive(),
|
||||
placeId: z.number().int().positive(),
|
||||
rating: z.number().int().min(1).max(5).nullable().optional().describe('1-5 stars; null/omitted clears the vote'),
|
||||
},
|
||||
annotations: TOOL_ANNOTATIONS_WRITE,
|
||||
},
|
||||
async ({ tripId, placeId, rating }) => {
|
||||
if (isDemoUser(userId)) return demoDenied();
|
||||
// Rating is a personal vote — any trip member may cast one, place_edit not required.
|
||||
if (!canAccessTrip(tripId, userId)) return noAccess();
|
||||
const place = ratePlace(String(tripId), String(placeId), userId, rating ?? null);
|
||||
if (!place) return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
|
||||
safeBroadcast(tripId, 'place:updated', { place });
|
||||
return ok({ place });
|
||||
}
|
||||
);
|
||||
|
||||
if (W) server.registerTool(
|
||||
'delete_place',
|
||||
{
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
Param,
|
||||
Patch,
|
||||
Post,
|
||||
Put,
|
||||
Query,
|
||||
UploadedFile,
|
||||
UseGuards,
|
||||
@@ -37,6 +38,7 @@ import {
|
||||
collectionSaveFromTripManyRequestSchema,
|
||||
collectionPlaceUpdateRequestSchema,
|
||||
collectionSetStatusRequestSchema,
|
||||
placeRatingRequestSchema,
|
||||
collectionCopyToTripRequestSchema,
|
||||
collectionInviteRequestSchema,
|
||||
collectionInviteActionRequestSchema,
|
||||
@@ -56,6 +58,7 @@ import {
|
||||
type CollectionSaveFromTripManyRequest,
|
||||
type CollectionPlaceUpdateRequest,
|
||||
type CollectionSetStatusRequest,
|
||||
type PlaceRatingRequest,
|
||||
type CollectionCopyToTripRequest,
|
||||
type CollectionInviteRequest,
|
||||
type CollectionInviteActionRequest,
|
||||
@@ -168,6 +171,21 @@ export class CollectionsController {
|
||||
return this.collections.setStatus(user.id, Number(pid), body.status, socketId);
|
||||
}
|
||||
|
||||
@Put('places/:pid/rating')
|
||||
setRating(
|
||||
@CurrentUser() user: User,
|
||||
@Param('pid') pid: string,
|
||||
@Body(new ZodValidationPipe(placeRatingRequestSchema)) body: PlaceRatingRequest,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
return this.collections.setRating(user.id, Number(pid), body.rating, socketId);
|
||||
}
|
||||
|
||||
@Delete('places/:pid/rating')
|
||||
clearRating(@CurrentUser() user: User, @Param('pid') pid: string, @Headers('x-socket-id') socketId?: string) {
|
||||
return this.collections.setRating(user.id, Number(pid), null, socketId);
|
||||
}
|
||||
|
||||
@Post('places/:pid/image')
|
||||
@HttpCode(200)
|
||||
@UseInterceptors(FileInterceptor('image', PLACE_IMAGE_UPLOAD))
|
||||
|
||||
@@ -33,6 +33,7 @@ export class CollectionsService {
|
||||
}
|
||||
updatePlace(userId: number, placeId: number, body: CollectionPlaceUpdateRequest, socketId?: string) { return svc.updatePlace(userId, placeId, body, socketId); }
|
||||
setStatus(userId: number, placeId: number, status: CollectionStatus, socketId?: string) { return svc.setStatus(userId, placeId, status, socketId); }
|
||||
setRating(userId: number, placeId: number, rating: number | null, socketId?: string) { return svc.setRating(userId, placeId, rating, socketId); }
|
||||
setPlaceImage(userId: number, placeId: number, imageUrl: string | null, socketId?: string) { return svc.setPlaceImage(userId, placeId, imageUrl, socketId); }
|
||||
deletePlace(userId: number, placeId: number, socketId?: string) { return svc.deletePlace(userId, placeId, socketId); }
|
||||
deletePlacesMany(userId: number, ids: number[], socketId?: string) { return svc.deletePlacesMany(userId, ids, socketId); }
|
||||
|
||||
@@ -24,6 +24,8 @@ import { CurrentUser } from '../auth/current-user.decorator';
|
||||
import { PLACE_IMAGE_UPLOAD } from '../common/place-image-upload';
|
||||
import { placeImageUrl } from '../../services/placeImage';
|
||||
import { isDemoEmail } from '../../services/demo';
|
||||
import { ZodValidationPipe } from '../common/zod-validation.pipe';
|
||||
import { placeRatingRequestSchema, type PlaceRatingRequest } from '@trek/shared';
|
||||
|
||||
const STRING_LIMITS: Record<string, number> = { name: 200, description: 2000, address: 500, notes: 2000 };
|
||||
const UPLOAD = { storage: memoryStorage(), limits: { fileSize: 10 * 1024 * 1024 } };
|
||||
@@ -299,6 +301,36 @@ export class PlacesController {
|
||||
return { place };
|
||||
}
|
||||
|
||||
@Put(':id/rating')
|
||||
rate(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('id') id: string,
|
||||
@Body(new ZodValidationPipe(placeRatingRequestSchema)) body: PlaceRatingRequest,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
// Deliberately no place_edit check: every trip member may cast their own
|
||||
// vote (#1435), even when an admin restricts place editing.
|
||||
this.requireTrip(tripId, user);
|
||||
const place = this.places.rate(tripId, id, user.id, body.rating);
|
||||
if (!place) {
|
||||
throw new HttpException({ error: 'Place not found' }, 404);
|
||||
}
|
||||
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
|
||||
return { place };
|
||||
}
|
||||
|
||||
@Delete(':id/rating')
|
||||
unrate(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string, @Headers('x-socket-id') socketId?: string) {
|
||||
this.requireTrip(tripId, user);
|
||||
const place = this.places.rate(tripId, id, user.id, null);
|
||||
if (!place) {
|
||||
throw new HttpException({ error: 'Place not found' }, 404);
|
||||
}
|
||||
this.places.broadcast(tripId, 'place:updated', { place }, socketId);
|
||||
return { place };
|
||||
}
|
||||
|
||||
@Get(':id/image')
|
||||
async image(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('id') id: string) {
|
||||
this.requireTrip(tripId, user);
|
||||
|
||||
@@ -80,6 +80,10 @@ export class PlacesService {
|
||||
return svc.searchPlaceImage(tripId, id, userId);
|
||||
}
|
||||
|
||||
rate(tripId: string, id: string, userId: number, rating: number | null) {
|
||||
return svc.ratePlace(tripId, id, userId, rating);
|
||||
}
|
||||
|
||||
// Journey hooks — non-fatal, mirroring the route's try/catch wrappers.
|
||||
onCreated(tripId: string, placeId: number): void { try { onPlaceCreated(Number(tripId), placeId); } catch { /* non-fatal */ } }
|
||||
onUpdated(placeId: number): void { try { onPlaceUpdated(placeId); } catch { /* non-fatal */ } }
|
||||
|
||||
@@ -171,12 +171,32 @@ function loadLabelIdsByPlaceIds(placeIds: number[]): Record<number, number[]> {
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Per-voter rating rows (#1435), batched (mirrors loadTagsByCollectionPlaceIds). */
|
||||
function loadRatingsByCollectionPlaceIds(placeIds: number[]): Record<number, { user_id: number; username: string; avatar: string | null; rating: number }[]> {
|
||||
const out: Record<number, { user_id: number; username: string; avatar: string | null; rating: number }[]> = {};
|
||||
if (placeIds.length === 0) return out;
|
||||
const rows = db.prepare(`
|
||||
SELECT cpr.collection_place_id AS pid, cpr.user_id, u.username, u.avatar, cpr.rating
|
||||
FROM collection_place_ratings cpr
|
||||
JOIN users u ON u.id = cpr.user_id
|
||||
WHERE cpr.collection_place_id IN (${placeIds.map(() => '?').join(',')})
|
||||
ORDER BY cpr.created_at
|
||||
`).all(...placeIds) as { pid: number; user_id: number; username: string; avatar: string | null; rating: number }[];
|
||||
for (const { pid, ...rest } of rows) {
|
||||
if (!out[pid]) out[pid] = [];
|
||||
out[pid].push(rest);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function hydratePlaces(rows: PlaceRow[]): CollectionPlace[] {
|
||||
const ids = rows.map(r => r.id);
|
||||
const tagsByPlace = loadTagsByCollectionPlaceIds(ids);
|
||||
const labelsByPlace = loadLabelIdsByPlaceIds(ids);
|
||||
const ratingsByPlace = loadRatingsByCollectionPlaceIds(ids);
|
||||
return rows.map(r => {
|
||||
const { category_name, category_color, category_icon, ...rest } = r;
|
||||
const ratings = ratingsByPlace[r.id] || [];
|
||||
return {
|
||||
...rest,
|
||||
links: parseLinks((r as { links?: unknown }).links),
|
||||
@@ -185,6 +205,9 @@ function hydratePlaces(rows: PlaceRow[]): CollectionPlace[] {
|
||||
: undefined,
|
||||
tags: tagsByPlace[r.id] || [],
|
||||
label_ids: labelsByPlace[r.id] || [],
|
||||
ratings,
|
||||
rating_avg: ratings.length > 0 ? ratings.reduce((s, x) => s + x.rating, 0) / ratings.length : null,
|
||||
rating_count: ratings.length,
|
||||
} as CollectionPlace;
|
||||
});
|
||||
}
|
||||
@@ -419,6 +442,28 @@ function attachTags(collectionPlaceId: number, tagIds: number[] | undefined): vo
|
||||
for (const tid of tagIds) stmt.run(collectionPlaceId, tid);
|
||||
}
|
||||
|
||||
/** Owner + accepted members — the users whose votes may live in this list. */
|
||||
function collectionMemberIds(collectionId: number): Set<number> {
|
||||
const ids = new Set<number>([ownerOf(collectionId)]);
|
||||
const rows = db.prepare("SELECT user_id FROM collection_members WHERE collection_id = ? AND status = 'accepted'").all(collectionId) as { user_id: number }[];
|
||||
rows.forEach(r => ids.add(r.user_id));
|
||||
return ids;
|
||||
}
|
||||
|
||||
/**
|
||||
* Carry star votes (#1435) from a trip place into a freshly saved collection
|
||||
* place. Only votes by members of the target collection come along (the saver
|
||||
* is always a member) — other trip members' opinions stay in the trip.
|
||||
*/
|
||||
function copyTripRatings(sourcePlaceId: number, collectionPlaceId: number, collectionId: number): void {
|
||||
const eligible = collectionMemberIds(collectionId);
|
||||
const rows = db.prepare('SELECT user_id, rating FROM place_ratings WHERE place_id = ?').all(sourcePlaceId) as { user_id: number; rating: number }[];
|
||||
const ins = db.prepare('INSERT OR IGNORE INTO collection_place_ratings (collection_place_id, user_id, rating) VALUES (?, ?, ?)');
|
||||
for (const r of rows) {
|
||||
if (eligible.has(r.user_id)) ins.run(collectionPlaceId, r.user_id, r.rating);
|
||||
}
|
||||
}
|
||||
|
||||
export function savePlace(userId: number, body: CollectionSavePlaceRequest, socketId?: string): CollectionSaveResult {
|
||||
assertCanEdit(userId, body.collection_id);
|
||||
|
||||
@@ -446,6 +491,18 @@ export function savePlace(userId: number, body: CollectionSavePlaceRequest, sock
|
||||
|
||||
const placeId = Number(result.lastInsertRowid);
|
||||
attachTags(placeId, body.tag_ids);
|
||||
// Carry trip ratings ONLY when the caller can actually see the source place.
|
||||
// source_place_id/source_trip_id are raw client input, so verify trip access +
|
||||
// that the place lives in that trip before reading place_ratings — otherwise a
|
||||
// member could harvest co-members' votes on places in trips they cannot access
|
||||
// (mirrors the canAccessTrip gate in saveFromTripPlace).
|
||||
if (
|
||||
body.source_place_id && body.source_trip_id &&
|
||||
canAccessTrip(body.source_trip_id, userId) &&
|
||||
db.prepare('SELECT 1 FROM places WHERE id = ? AND trip_id = ?').get(body.source_place_id, body.source_trip_id)
|
||||
) {
|
||||
copyTripRatings(body.source_place_id, placeId, body.collection_id);
|
||||
}
|
||||
notifyCollectionUsers(body.collection_id, socketId, 'collections:updated');
|
||||
return { place: getPlaceById(placeId) };
|
||||
}
|
||||
@@ -511,7 +568,7 @@ export function saveFromTripPlaces(
|
||||
skipped.push({ id: placeId, name });
|
||||
continue;
|
||||
}
|
||||
insert.run(
|
||||
const res = insert.run(
|
||||
collectionId, ownerId, userId,
|
||||
name, (p.description as string | null) ?? null, lat, lng, (p.address as string | null) ?? null,
|
||||
(p.category_id as number | null) ?? null, (p.price as number | null) ?? null, (p.currency as string | null) ?? null, (p.notes as string | null) ?? null,
|
||||
@@ -519,6 +576,7 @@ export function saveFromTripPlaces(
|
||||
(p.osm_id as string | null) ?? null, (p.website as string | null) ?? null, (p.phone as string | null) ?? null,
|
||||
tripId, placeId,
|
||||
);
|
||||
copyTripRatings(placeId, Number(res.lastInsertRowid), collectionId);
|
||||
copied++;
|
||||
}
|
||||
if (copied > 0) notifyCollectionUsers(collectionId, undefined, 'collections:updated');
|
||||
@@ -586,6 +644,26 @@ export function setStatus(userId: number, placeId: number, status: CollectionSta
|
||||
return getPlaceById(placeId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Set (1-5) or clear (null) the user's own star vote on a saved place (#1435).
|
||||
* Gated on assertAccess, not assertCanEdit — a vote is the member's personal
|
||||
* opinion, so read-only viewers get to cast one too.
|
||||
*/
|
||||
export function setRating(userId: number, placeId: number, rating: number | null, socketId?: string): CollectionPlace {
|
||||
const collectionId = collectionIdOfPlace(placeId);
|
||||
assertAccess(userId, collectionId);
|
||||
if (rating === null) {
|
||||
db.prepare('DELETE FROM collection_place_ratings WHERE collection_place_id = ? AND user_id = ?').run(placeId, userId);
|
||||
} else {
|
||||
db.prepare(`
|
||||
INSERT INTO collection_place_ratings (collection_place_id, user_id, rating) VALUES (?, ?, ?)
|
||||
ON CONFLICT(collection_place_id, user_id) DO UPDATE SET rating = excluded.rating
|
||||
`).run(placeId, userId, rating);
|
||||
}
|
||||
notifyCollectionUsers(collectionId, socketId, 'collections:updated');
|
||||
return getPlaceById(placeId);
|
||||
}
|
||||
|
||||
export function deletePlace(userId: number, placeId: number, socketId?: string): void {
|
||||
const collectionId = collectionIdOfPlace(placeId);
|
||||
assertCanDelete(userId, collectionId);
|
||||
@@ -635,6 +713,14 @@ export function copyToTrip(userId: number, body: CollectionCopyToTripRequest): {
|
||||
httpError(403, 'Not allowed to edit this trip');
|
||||
}
|
||||
|
||||
// Votes only travel for users who are members of THIS trip (owner + members),
|
||||
// so copying never surfaces a collection member with no tie to the trip.
|
||||
// Symmetric with copyTripRatings' collection-member filter (#1435).
|
||||
const tripMemberIds = new Set<number>([trip.user_id]);
|
||||
for (const r of db.prepare('SELECT user_id FROM trip_members WHERE trip_id = ?').all(body.trip_id) as { user_id: number }[]) {
|
||||
tripMemberIds.add(r.user_id);
|
||||
}
|
||||
|
||||
// Visibility on every SOURCE place — no cross-user exfiltration via copy.
|
||||
const sources: Array<{ id: number; name: string; description: string | null; lat: number | null; lng: number | null;
|
||||
address: string | null; category_id: number | null; price: number | null; currency: string | null;
|
||||
@@ -665,6 +751,7 @@ export function copyToTrip(userId: number, body: CollectionCopyToTripRequest): {
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
`);
|
||||
const insertTag = db.prepare('INSERT OR IGNORE INTO place_tags (place_id, tag_id) VALUES (?, ?)');
|
||||
const insertRating = db.prepare('INSERT OR IGNORE INTO place_ratings (place_id, user_id, rating) VALUES (?, ?, ?)');
|
||||
|
||||
let copied = 0;
|
||||
const skipped: { id: number; name: string }[] = [];
|
||||
@@ -680,6 +767,11 @@ export function copyToTrip(userId: number, body: CollectionCopyToTripRequest): {
|
||||
const newPlaceId = Number(res.lastInsertRowid);
|
||||
const tagIds = db.prepare('SELECT tag_id FROM collection_place_tags WHERE collection_place_id = ?').all(s.id) as { tag_id: number }[];
|
||||
for (const t of tagIds) insertTag.run(newPlaceId, t.tag_id);
|
||||
// Ratings travel into the trip too (#1435), but only for trip members — a
|
||||
// collection voter who isn't on the trip stays out of it. Trip members keep
|
||||
// voting there; nothing is mirrored back.
|
||||
const votes = db.prepare('SELECT user_id, rating FROM collection_place_ratings WHERE collection_place_id = ?').all(s.id) as { user_id: number; rating: number }[];
|
||||
for (const v of votes) if (tripMemberIds.has(v.user_id)) insertRating.run(newPlaceId, v.user_id, v.rating);
|
||||
|
||||
if (s.name) dedup.names.add(s.name.trim().toLowerCase());
|
||||
else if (s.lat != null && s.lng != null) dedup.coords.push({ lat: s.lat, lng: s.lng });
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { XMLParser, XMLValidator } from 'fast-xml-parser';
|
||||
import unzipper from 'unzipper';
|
||||
import { db, getPlaceWithTags } from '../db/database';
|
||||
import { loadTagsByPlaceIds } from './queryHelpers';
|
||||
import { loadTagsByPlaceIds, loadRatingsByPlaceIds, ratingAggregate } from './queryHelpers';
|
||||
import { checkSsrf, safeFetchFollow, SsrfBlockedError } from '../utils/ssrfGuard';
|
||||
import { Place } from '../types';
|
||||
import {
|
||||
@@ -97,6 +97,7 @@ export function listPlaces(
|
||||
|
||||
const placeIds = places.map(p => p.id);
|
||||
const tagsByPlaceId = loadTagsByPlaceIds(placeIds);
|
||||
const ratingsByPlaceId = loadRatingsByPlaceIds(placeIds);
|
||||
|
||||
return places.map(p => ({
|
||||
...p,
|
||||
@@ -107,6 +108,8 @@ export function listPlaces(
|
||||
icon: p.category_icon,
|
||||
} : null,
|
||||
tags: tagsByPlaceId[p.id] || [],
|
||||
ratings: ratingsByPlaceId[p.id] || [],
|
||||
...ratingAggregate(ratingsByPlaceId[p.id]),
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -994,3 +997,27 @@ export async function searchPlaceImage(tripId: string, placeId: string, userId:
|
||||
|
||||
return searchUnsplashPhotos(place.name + (place.address ? ' ' + place.address : ''), 5, getUnsplashKey(userId));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Collaborative ratings (#1435)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/**
|
||||
* Set (rating 1-5) or clear (rating null) the user's own vote on a trip place.
|
||||
* Ratings live in their own table so voting never bumps places.updated_at —
|
||||
* a vote must not 409 another member's offline edit. Returns the refreshed
|
||||
* place (with the new aggregate) or null when the place isn't in the trip.
|
||||
*/
|
||||
export function ratePlace(tripId: string, placeId: string, userId: number, rating: number | null): ReturnType<typeof getPlaceWithTags> | null {
|
||||
const place = db.prepare('SELECT id FROM places WHERE id = ? AND trip_id = ?').get(placeId, tripId);
|
||||
if (!place) return null;
|
||||
if (rating === null) {
|
||||
db.prepare('DELETE FROM place_ratings WHERE place_id = ? AND user_id = ?').run(placeId, userId);
|
||||
} else {
|
||||
db.prepare(`
|
||||
INSERT INTO place_ratings (place_id, user_id, rating) VALUES (?, ?, ?)
|
||||
ON CONFLICT(place_id, user_id) DO UPDATE SET rating = excluded.rating
|
||||
`).run(placeId, userId, rating);
|
||||
}
|
||||
return getPlaceWithTags(placeId);
|
||||
}
|
||||
|
||||
@@ -37,6 +37,40 @@ function loadTagsByPlaceIds(placeIds: number[], { compact }: { compact?: boolean
|
||||
return tagsByPlaceId;
|
||||
}
|
||||
|
||||
export interface PlaceRatingRow {
|
||||
user_id: number;
|
||||
username: string;
|
||||
avatar: string | null;
|
||||
rating: number;
|
||||
}
|
||||
|
||||
/** Batch-load collaborative ratings (#1435) for multiple places in one query, indexed by place ID. */
|
||||
function loadRatingsByPlaceIds(placeIds: number[]): Record<number, PlaceRatingRow[]> {
|
||||
const ratingsByPlaceId: Record<number, PlaceRatingRow[]> = {};
|
||||
if (placeIds.length > 0) {
|
||||
const rows = db.prepare(`
|
||||
SELECT pr.place_id, pr.user_id, u.username, u.avatar, pr.rating FROM place_ratings pr
|
||||
JOIN users u ON pr.user_id = u.id
|
||||
WHERE pr.place_id IN (${placeIds.map(() => '?').join(',')})
|
||||
ORDER BY pr.created_at
|
||||
`).all(...placeIds) as (PlaceRatingRow & { place_id: number })[];
|
||||
for (const { place_id, ...rest } of rows) {
|
||||
if (!ratingsByPlaceId[place_id]) ratingsByPlaceId[place_id] = [];
|
||||
ratingsByPlaceId[place_id].push(rest);
|
||||
}
|
||||
}
|
||||
return ratingsByPlaceId;
|
||||
}
|
||||
|
||||
/** avg/count aggregate for a place's rating rows. */
|
||||
function ratingAggregate(ratings: PlaceRatingRow[] | undefined) {
|
||||
const rows = ratings || [];
|
||||
return {
|
||||
rating_avg: rows.length > 0 ? rows.reduce((s, r) => s + r.rating, 0) / rows.length : null,
|
||||
rating_count: rows.length,
|
||||
};
|
||||
}
|
||||
|
||||
/** Batch-load participants for multiple day-assignments in a single query, indexed by assignment ID. */
|
||||
function loadParticipantsByAssignmentIds(assignmentIds: number[]): Record<number, Participant[]> {
|
||||
const participantsByAssignment: Record<number, Participant[]> = {};
|
||||
@@ -95,4 +129,4 @@ function formatAssignmentWithPlace(a: AssignmentRow, tags: Partial<Tag>[], parti
|
||||
};
|
||||
}
|
||||
|
||||
export { loadTagsByPlaceIds, loadParticipantsByAssignmentIds, formatAssignmentWithPlace };
|
||||
export { loadTagsByPlaceIds, loadParticipantsByAssignmentIds, formatAssignmentWithPlace, loadRatingsByPlaceIds, ratingAggregate };
|
||||
|
||||
Reference in New Issue
Block a user