mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 05:21:15 +00:00
refactor(journey, oidc, place-enrichment, tokens, trip-members): async DB-touching methods; transactions through UnitOfWork
This commit is contained in:
@@ -84,7 +84,11 @@ export class AssignmentsService {
|
||||
* the journey stays in sync. Non-fatal, like the route's try/catch.
|
||||
*/
|
||||
reconcile(tripId: string | number, socketId?: string): void {
|
||||
try { this.journey.reconcileTripSkeletons(Number(tripId), socketId); } catch { /* non-fatal */ }
|
||||
// R1.5: reconcile() is called fire-and-forget from a dozen sync call sites across
|
||||
// this domain; reconcileTripSkeletons is now async, so the rejection is caught here
|
||||
// instead of escaping as an unhandled promise rejection — same "non-fatal" contract
|
||||
// the try/catch gave it before the sweep.
|
||||
void this.journey.reconcileTripSkeletons(Number(tripId), socketId).catch(() => { /* non-fatal */ });
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -291,18 +291,18 @@ export class DawarichSuggestionsService {
|
||||
* arrival time fills the entry's time — the two fields a person would
|
||||
* otherwise copy off the suggestion by hand.
|
||||
*/
|
||||
private acceptAsJournalEntry(
|
||||
private async acceptAsJournalEntry(
|
||||
userId: number,
|
||||
row: SuggestionRow,
|
||||
body: DawarichAccept,
|
||||
sid?: string,
|
||||
): DawarichAcceptResult {
|
||||
): Promise<DawarichAcceptResult> {
|
||||
if (body.journalId === undefined) {
|
||||
throw new AcceptError('journal_required', 'A journey is required to create an entry', 400);
|
||||
}
|
||||
// canEdit is the journey domain's own answer, and createEntry asks it again.
|
||||
// Asking here too is what turns "silently did nothing" into a 403.
|
||||
if (!this.journey.canEdit(body.journalId, userId)) {
|
||||
if (!(await this.journey.canEdit(body.journalId, userId))) {
|
||||
throw new AcceptError('journal_forbidden', 'Journey not found', 404);
|
||||
}
|
||||
|
||||
@@ -314,8 +314,8 @@ export class DawarichSuggestionsService {
|
||||
// that one notification can still outrun a rollback. Moving it out means
|
||||
// changing that domain's contract, which this integration has no business
|
||||
// doing; the write itself is what had to stop being two.
|
||||
const entry = this.db.transaction(() => {
|
||||
const created = this.journey.createEntry(
|
||||
const entry = await this.uow.transactional(async () => {
|
||||
const created = await this.journey.createEntry(
|
||||
body.journalId,
|
||||
userId,
|
||||
{
|
||||
|
||||
@@ -63,7 +63,7 @@ export class JournalRpc {
|
||||
await this.requireJourneyAddon();
|
||||
// listEntries self-gates via canAccessJourney and returns null when the user
|
||||
// cannot see it.
|
||||
const entries = this.journey.listEntries(journeyId, userId);
|
||||
const entries = await this.journey.listEntries(journeyId, userId);
|
||||
if (entries === null) throw new ForbiddenResource(`no access to journey ${journeyId}`);
|
||||
return entries;
|
||||
}
|
||||
@@ -75,7 +75,7 @@ export class JournalRpc {
|
||||
if (typeof input.entry_date !== 'string' || input.entry_date === '') throw new BadParams('entry_date is required');
|
||||
const journeyId = num(params.journeyId, 'journeyId');
|
||||
await this.requireJourneyAddon();
|
||||
const entry = this.journey.createEntry(journeyId, userId, input as never);
|
||||
const entry = await this.journey.createEntry(journeyId, userId, input as never);
|
||||
if (!entry) throw new ForbiddenResource(`no editable journey ${journeyId} for this user`);
|
||||
return entry;
|
||||
}
|
||||
@@ -85,7 +85,7 @@ export class JournalRpc {
|
||||
const userId = this.requireJournalUser(ctx, 'writes');
|
||||
const entryId = num(params.entryId, 'entryId');
|
||||
await this.requireJourneyAddon();
|
||||
const entry = this.journey.updateEntry(entryId, userId, asPayload(params.input) as never);
|
||||
const entry = await this.journey.updateEntry(entryId, userId, asPayload(params.input) as never);
|
||||
if (!entry) throw new ForbiddenResource(`no editable journal entry ${entryId} for this user`);
|
||||
return entry;
|
||||
}
|
||||
@@ -95,7 +95,7 @@ export class JournalRpc {
|
||||
const userId = this.requireJournalUser(ctx, 'writes');
|
||||
const entryId = num(params.entryId, 'entryId');
|
||||
await this.requireJourneyAddon();
|
||||
if (!this.journey.deleteEntry(entryId, userId)) {
|
||||
if (!(await this.journey.deleteEntry(entryId, userId))) {
|
||||
throw new ForbiddenResource(`no editable journal entry ${entryId} for this user`);
|
||||
}
|
||||
return { deleted: true };
|
||||
@@ -192,7 +192,7 @@ export class JournalRpc {
|
||||
const userId = this.requireJournalUser(ctx, 'writes');
|
||||
const journeyId = num(params.journeyId, 'journeyId');
|
||||
await this.requireJourneyAddon();
|
||||
if (!this.journey.deleteJourney(journeyId, userId)) {
|
||||
if (!(await this.journey.deleteJourney(journeyId, userId))) {
|
||||
throw new ForbiddenResource(`no deletable journal ${journeyId} for this user`);
|
||||
}
|
||||
return { deleted: true };
|
||||
|
||||
@@ -34,8 +34,8 @@ export class JourneyBookService {
|
||||
) {}
|
||||
|
||||
/** Null when the journey does not exist or the user cannot reach it. */
|
||||
private canAccess(journeyId: number, userId: number): boolean {
|
||||
return !!this.journey.canAccessJourney(journeyId, userId);
|
||||
private async canAccess(journeyId: number, userId: number): Promise<boolean> {
|
||||
return !!(await this.journey.canAccessJourney(journeyId, userId));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -43,7 +43,7 @@ export class JourneyBookService {
|
||||
* same owner-or-editor check the entry and photo writes take. canAccess also
|
||||
* covers role 'viewer', who may read the book but must not overwrite it.
|
||||
*/
|
||||
private canWrite(journeyId: number, userId: number): boolean {
|
||||
private async canWrite(journeyId: number, userId: number): Promise<boolean> {
|
||||
return this.journey.canEdit(journeyId, userId);
|
||||
}
|
||||
|
||||
@@ -53,7 +53,7 @@ export class JourneyBookService {
|
||||
* Public so the controller can tell "no book yet" from "no journey" without
|
||||
* running a query built for something else.
|
||||
*/
|
||||
canOpen(journeyId: number, userId: number): boolean {
|
||||
async canOpen(journeyId: number, userId: number): Promise<boolean> {
|
||||
return this.canAccess(journeyId, userId);
|
||||
}
|
||||
|
||||
@@ -72,8 +72,8 @@ export class JourneyBookService {
|
||||
};
|
||||
}
|
||||
|
||||
listBooks(journeyId: number, userId: number): BookSummary[] | null {
|
||||
if (!this.canAccess(journeyId, userId)) return null;
|
||||
async listBooks(journeyId: number, userId: number): Promise<BookSummary[] | null> {
|
||||
if (!(await this.canAccess(journeyId, userId))) return null;
|
||||
const rows = this.db
|
||||
.prepare(`
|
||||
SELECT id, journey_id, title, version, updated_at, updated_by
|
||||
@@ -99,8 +99,8 @@ export class JourneyBookService {
|
||||
* the same trip is an obvious thing to want and adding a column later is
|
||||
* harder than not needing to.
|
||||
*/
|
||||
getBook(journeyId: number, userId: number): BookRecord | null {
|
||||
if (!this.canAccess(journeyId, userId)) return null;
|
||||
async getBook(journeyId: number, userId: number): Promise<BookRecord | null> {
|
||||
if (!(await this.canAccess(journeyId, userId))) return null;
|
||||
const row = this.db
|
||||
.prepare(`
|
||||
SELECT id, journey_id, title, document, version, updated_at, updated_by
|
||||
@@ -120,12 +120,12 @@ export class JourneyBookService {
|
||||
* moved. Throwing would be the obvious shape and the wrong one: a conflict is
|
||||
* an ordinary outcome of two people working, not an exception.
|
||||
*/
|
||||
saveBook(
|
||||
async saveBook(
|
||||
journeyId: number,
|
||||
userId: number,
|
||||
input: { title: string; document: unknown; baseVersion?: number },
|
||||
): { record: BookRecord } | { conflict: BookRecord } | null {
|
||||
if (!this.canWrite(journeyId, userId)) return null;
|
||||
): Promise<{ record: BookRecord } | { conflict: BookRecord } | null> {
|
||||
if (!(await this.canWrite(journeyId, userId))) return null;
|
||||
|
||||
const document = JSON.stringify(normalizeBookDocument(input.document));
|
||||
const existing = this.db
|
||||
@@ -139,7 +139,7 @@ export class JourneyBookService {
|
||||
VALUES (?, ?, ?, 1, ?, ?, CURRENT_TIMESTAMP)
|
||||
`)
|
||||
.run(journeyId, input.title, document, userId, userId);
|
||||
return { record: this.byId(Number(result.lastInsertRowid))! };
|
||||
return { record: (await this.byId(Number(result.lastInsertRowid)))! };
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -164,13 +164,13 @@ export class JourneyBookService {
|
||||
.run(input.title, document, userId, existing.id, base);
|
||||
|
||||
if (result.changes === 0) {
|
||||
return { conflict: this.byId(existing.id)! };
|
||||
return { conflict: (await this.byId(existing.id))! };
|
||||
}
|
||||
return { record: this.byId(existing.id)! };
|
||||
return { record: (await this.byId(existing.id))! };
|
||||
}
|
||||
|
||||
deleteBook(journeyId: number, userId: number): boolean | null {
|
||||
if (!this.canWrite(journeyId, userId)) return null;
|
||||
async deleteBook(journeyId: number, userId: number): Promise<boolean | null> {
|
||||
if (!(await this.canWrite(journeyId, userId))) return null;
|
||||
const result = this.db
|
||||
.prepare('DELETE FROM journey_books WHERE journey_id = ?')
|
||||
.run(journeyId);
|
||||
@@ -188,8 +188,8 @@ export class JourneyBookService {
|
||||
* The saver is excluded by socket id, the same way every other TREK mutation
|
||||
* does it, so the client that just saved does not process its own change.
|
||||
*/
|
||||
broadcastSaved(journeyId: number, userId: number, record: BookRecord, socketId?: string) {
|
||||
this.journey.broadcastJourneyEvent(
|
||||
async broadcastSaved(journeyId: number, userId: number, record: BookRecord, socketId?: string) {
|
||||
await this.journey.broadcastJourneyEvent(
|
||||
journeyId,
|
||||
'journey:book:saved',
|
||||
{ version: record.version, savedBy: userId },
|
||||
@@ -197,7 +197,7 @@ export class JourneyBookService {
|
||||
);
|
||||
}
|
||||
|
||||
private byId(id: number): BookRecord | null {
|
||||
private async byId(id: number): Promise<BookRecord | null> {
|
||||
const row = this.db
|
||||
.prepare(`
|
||||
SELECT id, journey_id, title, document, version, updated_at, updated_by
|
||||
|
||||
@@ -4,6 +4,7 @@ import type { Journey, JourneyEntry, JourneyPhoto, JourneyContributor } from '..
|
||||
import { decodeEntryRow, type JourneyEntryWire } from './journey-entry-row';
|
||||
import { GALLERY_CHRONOLOGICAL_ORDER } from './journey-gallery-order';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
import type { JourneyStats, JourneyTrack, TrekWsUserEventName } from '@trek/shared';
|
||||
import { TrekPhotosRepository } from '../photos/trek-photos.repository';
|
||||
@@ -94,6 +95,7 @@ export class JourneyDomainService {
|
||||
private readonly db: DatabaseService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly photos: TrekPhotosRepository,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
private ts(): number {
|
||||
@@ -109,7 +111,7 @@ export class JourneyDomainService {
|
||||
* journey is one question with one answer, and a second copy of this walk
|
||||
* over contributors and owner would be a second answer waiting to disagree.
|
||||
*/
|
||||
broadcastJourneyEvent(
|
||||
async broadcastJourneyEvent(
|
||||
journeyId: number,
|
||||
// Typed against the shared WS registry rather than left as `string`: the
|
||||
// legacy broadcastToUser took anything, so a typo'd event name shipped as a
|
||||
@@ -117,7 +119,7 @@ export class JourneyDomainService {
|
||||
event: TrekWsUserEventName,
|
||||
data: Record<string, unknown>,
|
||||
excludeSocketId?: string | number,
|
||||
) {
|
||||
): Promise<void> {
|
||||
const contributors = this.db.prepare('SELECT user_id FROM journey_contributors WHERE journey_id = ?').all(journeyId) as {
|
||||
user_id: number;
|
||||
}[];
|
||||
@@ -135,7 +137,7 @@ export class JourneyDomainService {
|
||||
|
||||
// ── Access control ───────────────────────────────────────────────────────
|
||||
|
||||
canAccessJourney(journeyId: number, userId: number): Journey | null {
|
||||
async canAccessJourney(journeyId: number, userId: number): Promise<Journey | null> {
|
||||
const own = this.db.prepare('SELECT * FROM journeys WHERE id = ? AND user_id = ?').get(journeyId, userId) as
|
||||
| Journey
|
||||
| undefined;
|
||||
@@ -147,12 +149,12 @@ export class JourneyDomainService {
|
||||
return null;
|
||||
}
|
||||
|
||||
isOwner(journeyId: number, userId: number): boolean {
|
||||
async isOwner(journeyId: number, userId: number): Promise<boolean> {
|
||||
return !!this.db.prepare('SELECT 1 FROM journeys WHERE id = ? AND user_id = ?').get(journeyId, userId);
|
||||
}
|
||||
|
||||
canEdit(journeyId: number, userId: number): boolean {
|
||||
if (this.isOwner(journeyId, userId)) return true;
|
||||
async canEdit(journeyId: number, userId: number): Promise<boolean> {
|
||||
if (await this.isOwner(journeyId, userId)) return true;
|
||||
const c = this.db
|
||||
.prepare('SELECT role FROM journey_contributors WHERE journey_id = ? AND user_id = ?')
|
||||
.get(journeyId, userId) as { role: string } | undefined;
|
||||
@@ -161,7 +163,7 @@ export class JourneyDomainService {
|
||||
|
||||
// ── Journey CRUD ─────────────────────────────────────────────────────────
|
||||
|
||||
listJourneys(userId: number) {
|
||||
async listJourneys(userId: number) {
|
||||
return this.db
|
||||
.prepare(
|
||||
`
|
||||
@@ -186,14 +188,14 @@ export class JourneyDomainService {
|
||||
})[];
|
||||
}
|
||||
|
||||
createJourney(
|
||||
async createJourney(
|
||||
userId: number,
|
||||
data: {
|
||||
title: string;
|
||||
subtitle?: string;
|
||||
trip_ids?: number[];
|
||||
},
|
||||
): Journey {
|
||||
): Promise<Journey> {
|
||||
const now = this.ts();
|
||||
const res = this.db
|
||||
.prepare(
|
||||
@@ -221,7 +223,7 @@ export class JourneyDomainService {
|
||||
// trip_ids[0] would otherwise leak an arbitrary trip's cover image cross-tenant.
|
||||
let coverTripId: number | undefined;
|
||||
for (const tripId of data.trip_ids) {
|
||||
if (this.addTripToJourney(journeyId, tripId, userId) && coverTripId === undefined) coverTripId = tripId;
|
||||
if ((await this.addTripToJourney(journeyId, tripId, userId)) && coverTripId === undefined) coverTripId = tripId;
|
||||
}
|
||||
|
||||
if (coverTripId !== undefined) {
|
||||
@@ -239,8 +241,8 @@ export class JourneyDomainService {
|
||||
return this.db.prepare('SELECT * FROM journeys WHERE id = ?').get(journeyId) as Journey;
|
||||
}
|
||||
|
||||
getJourneyFull(journeyId: number, userId: number) {
|
||||
const journey = this.canAccessJourney(journeyId, userId);
|
||||
async getJourneyFull(journeyId: number, userId: number) {
|
||||
const journey = await this.canAccessJourney(journeyId, userId);
|
||||
if (!journey) return null;
|
||||
|
||||
const entries = this.db
|
||||
@@ -342,7 +344,7 @@ export class JourneyDomainService {
|
||||
};
|
||||
}
|
||||
|
||||
updateJourney(
|
||||
async updateJourney(
|
||||
journeyId: number,
|
||||
userId: number,
|
||||
data: Partial<{
|
||||
@@ -356,10 +358,10 @@ export class JourneyDomainService {
|
||||
show_mood: boolean | number;
|
||||
show_weather: boolean | number;
|
||||
}>,
|
||||
): Journey | null {
|
||||
): Promise<Journey | null> {
|
||||
// Journey-level settings (title, cover, status) are owner-only — editors
|
||||
// may only edit entries and photos, not reshape the journey itself.
|
||||
if (!this.isOwner(journeyId, userId)) return null;
|
||||
if (!(await this.isOwner(journeyId, userId))) return null;
|
||||
|
||||
const ALLOWED_STATUSES = ['draft', 'active', 'completed', 'archived'];
|
||||
const allowed = [
|
||||
@@ -394,8 +396,8 @@ export class JourneyDomainService {
|
||||
return this.db.prepare('SELECT * FROM journeys WHERE id = ?').get(journeyId) as Journey;
|
||||
}
|
||||
|
||||
updateJourneyPreferences(journeyId: number, userId: number, data: { hide_skeletons?: boolean }) {
|
||||
if (!this.canAccessJourney(journeyId, userId)) return null;
|
||||
async updateJourneyPreferences(journeyId: number, userId: number, data: { hide_skeletons?: boolean }) {
|
||||
if (!(await this.canAccessJourney(journeyId, userId))) return null;
|
||||
if (data.hide_skeletons !== undefined) {
|
||||
this.db.prepare('UPDATE journey_contributors SET hide_skeletons = ? WHERE journey_id = ? AND user_id = ?').run(
|
||||
data.hide_skeletons ? 1 : 0,
|
||||
@@ -417,24 +419,24 @@ export class JourneyDomainService {
|
||||
* things you have already said you did not want is not a screen worth
|
||||
* building. The count comes back so the caller can say what happened.
|
||||
*/
|
||||
restoreDismissedSuggestions(journeyId: number, userId: number): { restored: number } | null {
|
||||
if (!this.canEdit(journeyId, userId)) return null;
|
||||
async restoreDismissedSuggestions(journeyId: number, userId: number): Promise<{ restored: number } | null> {
|
||||
if (!(await this.canEdit(journeyId, userId))) return null;
|
||||
const res = this.db
|
||||
.prepare('UPDATE journey_entries SET dismissed = 0 WHERE journey_id = ? AND dismissed = 1')
|
||||
.run(journeyId);
|
||||
if (res.changes > 0) this.broadcastJourneyEvent(journeyId, 'journey:entry:updated', { restored: res.changes });
|
||||
if (res.changes > 0) await this.broadcastJourneyEvent(journeyId, 'journey:entry:updated', { restored: res.changes });
|
||||
return { restored: res.changes };
|
||||
}
|
||||
|
||||
deleteJourney(journeyId: number, userId: number): boolean {
|
||||
if (!this.isOwner(journeyId, userId)) return false;
|
||||
async deleteJourney(journeyId: number, userId: number): Promise<boolean> {
|
||||
if (!(await this.isOwner(journeyId, userId))) return false;
|
||||
this.db.prepare('DELETE FROM journeys WHERE id = ?').run(journeyId);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ── Trip management ──────────────────────────────────────────────────────
|
||||
|
||||
addTripToJourney(journeyId: number, tripId: number, userId: number): boolean {
|
||||
async addTripToJourney(journeyId: number, tripId: number, userId: number): Promise<boolean> {
|
||||
// Only attach a trip the caller can actually access — otherwise a journey
|
||||
// owner could pull an arbitrary trip's places + photos into their journey
|
||||
// (cross-tenant leak). Mirrors the trip-access gate every other trip-scoped
|
||||
@@ -443,7 +445,7 @@ export class JourneyDomainService {
|
||||
// And a journey the caller can actually reach. Without this, any logged-in user
|
||||
// could link a trip of theirs into a stranger's journey and seed entries and
|
||||
// photos there — the MCP tool has always checked this, the REST route never did.
|
||||
if (!this.canAccessJourney(journeyId, userId)) return false;
|
||||
if (!(await this.canAccessJourney(journeyId, userId))) return false;
|
||||
const now = this.ts();
|
||||
try {
|
||||
this.db.prepare('INSERT OR IGNORE INTO journey_trips (journey_id, trip_id, added_at) VALUES (?, ?, ?)').run(
|
||||
@@ -456,19 +458,19 @@ export class JourneyDomainService {
|
||||
}
|
||||
|
||||
// sync skeleton entries for all places in this trip
|
||||
this.syncTripPlaces(journeyId, tripId, userId);
|
||||
await this.syncTripPlaces(journeyId, tripId, userId);
|
||||
// Trip photos are deliberately NOT pulled in any more (#1614). Photos live in
|
||||
// journeys now: the trip-photo surface lost its UI in 3.1.0, nothing writes to
|
||||
// it on an install newer than that, and copying rows between the two was what
|
||||
// let a photo one member had chosen not to share reach a journey at all. The
|
||||
// table and its (unreferenced) routes stay for one more release rather than
|
||||
// being dropped in an append-only migration.
|
||||
this.broadcastJourneyEvent(journeyId, 'journey:trip:synced', { tripId });
|
||||
await this.broadcastJourneyEvent(journeyId, 'journey:trip:synced', { tripId });
|
||||
return true;
|
||||
}
|
||||
|
||||
removeTripFromJourney(journeyId: number, tripId: number, userId: number): boolean {
|
||||
if (!this.isOwner(journeyId, userId)) return false;
|
||||
async removeTripFromJourney(journeyId: number, tripId: number, userId: number): Promise<boolean> {
|
||||
if (!(await this.isOwner(journeyId, userId))) return false;
|
||||
|
||||
// remove skeleton entries that haven't been filled in
|
||||
this.db.prepare(
|
||||
@@ -492,7 +494,7 @@ export class JourneyDomainService {
|
||||
|
||||
// ── Sync engine ──────────────────────────────────────────────────────────
|
||||
|
||||
syncTripPlaces(journeyId: number, tripId: number, authorId: number) {
|
||||
async syncTripPlaces(journeyId: number, tripId: number, authorId: number) {
|
||||
const places = this.db
|
||||
.prepare(
|
||||
`
|
||||
@@ -531,7 +533,7 @@ export class JourneyDomainService {
|
||||
const nextOrder = (dateMaxOrder.get(entryDate) ?? -1) + 1;
|
||||
dateMaxOrder.set(entryDate, nextOrder);
|
||||
|
||||
this.insertSkeletonEntry({
|
||||
await this.insertSkeletonEntry({
|
||||
journeyId,
|
||||
tripId,
|
||||
placeId: place.id,
|
||||
@@ -550,7 +552,7 @@ export class JourneyDomainService {
|
||||
}
|
||||
|
||||
// called when a trip place is created
|
||||
onPlaceCreated(tripId: number, placeId: number) {
|
||||
async onPlaceCreated(tripId: number, placeId: number) {
|
||||
const links = this.db.prepare('SELECT journey_id FROM journey_trips WHERE trip_id = ?').all(tripId) as {
|
||||
journey_id: number;
|
||||
}[];
|
||||
@@ -589,7 +591,7 @@ export class JourneyDomainService {
|
||||
.get(link.journey_id, entryDate) as { m: number | null };
|
||||
const nextOrder = (maxOrder?.m ?? -1) + 1;
|
||||
|
||||
this.insertSkeletonEntry({
|
||||
await this.insertSkeletonEntry({
|
||||
journeyId: link.journey_id,
|
||||
tripId,
|
||||
placeId,
|
||||
@@ -609,7 +611,7 @@ export class JourneyDomainService {
|
||||
}
|
||||
|
||||
// called when a trip place is updated
|
||||
onPlaceUpdated(placeId: number) {
|
||||
async onPlaceUpdated(placeId: number) {
|
||||
const entries = this.db.prepare('SELECT * FROM journey_entries WHERE source_place_id = ?').all(placeId) as JourneyEntry[];
|
||||
if (!entries.length) return;
|
||||
|
||||
@@ -673,7 +675,7 @@ export class JourneyDomainService {
|
||||
}
|
||||
|
||||
// called when a trip place is deleted
|
||||
onPlaceDeleted(placeId: number) {
|
||||
async onPlaceDeleted(placeId: number) {
|
||||
const entries = this.db.prepare('SELECT * FROM journey_entries WHERE source_place_id = ?').all(placeId) as JourneyEntry[];
|
||||
|
||||
for (const entry of entries) {
|
||||
@@ -711,7 +713,7 @@ export class JourneyDomainService {
|
||||
}
|
||||
}
|
||||
|
||||
private insertSkeletonEntry(p: {
|
||||
private async insertSkeletonEntry(p: {
|
||||
journeyId: number;
|
||||
tripId: number;
|
||||
placeId: number;
|
||||
@@ -757,7 +759,7 @@ export class JourneyDomainService {
|
||||
// only detached + annotated, mirroring onPlaceDeleted. Idempotent: a second call with
|
||||
// no underlying change is a no-op (no writes, no broadcast). Called from every
|
||||
// assignment mutation path.
|
||||
reconcileTripSkeletons(tripId: number, sid?: string | number) {
|
||||
async reconcileTripSkeletons(tripId: number, sid?: string | number) {
|
||||
const links = this.db.prepare('SELECT journey_id FROM journey_trips WHERE trip_id = ?').all(tripId) as {
|
||||
journey_id: number;
|
||||
}[];
|
||||
@@ -857,7 +859,7 @@ export class JourneyDomainService {
|
||||
if (!found) {
|
||||
const nextOrder = (dateMaxOrder.get(entryDate) ?? -1) + 1;
|
||||
dateMaxOrder.set(entryDate, nextOrder);
|
||||
this.insertSkeletonEntry({
|
||||
await this.insertSkeletonEntry({
|
||||
journeyId: journey_id,
|
||||
tripId,
|
||||
placeId: place.id,
|
||||
@@ -926,7 +928,7 @@ export class JourneyDomainService {
|
||||
changed = true;
|
||||
}
|
||||
|
||||
if (changed) this.broadcastJourneyEvent(journey_id, 'journey:trip:synced', { tripId }, sid);
|
||||
if (changed) await this.broadcastJourneyEvent(journey_id, 'journey:trip:synced', { tripId }, sid);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -941,8 +943,8 @@ export class JourneyDomainService {
|
||||
* Only places that actually carry geometry are returned, so a journey whose trips
|
||||
* have no tracks answers with an empty list rather than a wall of null points.
|
||||
*/
|
||||
journeyTracks(journeyId: number, userId: number): JourneyTrack[] | null {
|
||||
if (!this.canAccessJourney(journeyId, userId)) return null;
|
||||
async journeyTracks(journeyId: number, userId: number): Promise<JourneyTrack[] | null> {
|
||||
if (!(await this.canAccessJourney(journeyId, userId))) return null;
|
||||
|
||||
const rows = this.db.prepare(`
|
||||
SELECT DISTINCT p.id AS place_id, p.trip_id, p.name, p.route_color, p.route_geometry
|
||||
@@ -1025,8 +1027,8 @@ export class JourneyDomainService {
|
||||
* (discussion #2064). It is still named, under `excluded`, because the only
|
||||
* way to switch a stop back on is to be able to see it.
|
||||
*/
|
||||
journeyStats(journeyId: number, userId: number): JourneyStats | null {
|
||||
if (!this.canAccessJourney(journeyId, userId)) return null;
|
||||
async journeyStats(journeyId: number, userId: number): Promise<JourneyStats | null> {
|
||||
if (!(await this.canAccessJourney(journeyId, userId))) return null;
|
||||
|
||||
const entryRows = this.db.prepare(`
|
||||
SELECT id, title, location_name, location_lat, location_lng, entry_date, source_trip_id,
|
||||
@@ -1245,8 +1247,8 @@ export class JourneyDomainService {
|
||||
});
|
||||
}
|
||||
|
||||
listEntries(journeyId: number, userId: number) {
|
||||
if (!this.canAccessJourney(journeyId, userId)) return null;
|
||||
async listEntries(journeyId: number, userId: number) {
|
||||
if (!(await this.canAccessJourney(journeyId, userId))) return null;
|
||||
|
||||
const entries = this.db
|
||||
.prepare('SELECT * FROM journey_entries WHERE journey_id = ? AND dismissed = 0 ORDER BY entry_date ASC, sort_order ASC, id ASC')
|
||||
@@ -1273,7 +1275,7 @@ export class JourneyDomainService {
|
||||
}));
|
||||
}
|
||||
|
||||
createEntry(
|
||||
async createEntry(
|
||||
journeyId: number,
|
||||
userId: number,
|
||||
data: {
|
||||
@@ -1293,8 +1295,8 @@ export class JourneyDomainService {
|
||||
sort_order?: number;
|
||||
},
|
||||
sid?: string,
|
||||
): JourneyEntryWire | null {
|
||||
if (!this.canEdit(journeyId, userId)) return null;
|
||||
): Promise<JourneyEntryWire | null> {
|
||||
if (!(await this.canEdit(journeyId, userId))) return null;
|
||||
|
||||
const now = this.ts();
|
||||
const maxOrder = this.db
|
||||
@@ -1340,11 +1342,11 @@ export class JourneyDomainService {
|
||||
.prepare('SELECT * FROM journey_entries WHERE id = ?')
|
||||
.get(Number(res.lastInsertRowid)) as JourneyEntry,
|
||||
);
|
||||
this.broadcastJourneyEvent(journeyId, 'journey:entry:created', { entry: created }, sid);
|
||||
await this.broadcastJourneyEvent(journeyId, 'journey:entry:created', { entry: created }, sid);
|
||||
return created;
|
||||
}
|
||||
|
||||
updateEntry(
|
||||
async updateEntry(
|
||||
entryId: number,
|
||||
userId: number,
|
||||
data: Partial<{
|
||||
@@ -1366,10 +1368,10 @@ export class JourneyDomainService {
|
||||
dismissed: boolean;
|
||||
}>,
|
||||
sid?: string,
|
||||
): JourneyEntryWire | null {
|
||||
): Promise<JourneyEntryWire | null> {
|
||||
const entry = this.db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined;
|
||||
if (!entry) return null;
|
||||
if (!this.canEdit(entry.journey_id, userId)) return null;
|
||||
if (!(await this.canEdit(entry.journey_id, userId))) return null;
|
||||
|
||||
const fields: string[] = [];
|
||||
const values: unknown[] = [];
|
||||
@@ -1445,15 +1447,15 @@ export class JourneyDomainService {
|
||||
const updated = decodeEntryRow(
|
||||
this.db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry,
|
||||
);
|
||||
this.broadcastJourneyEvent(entry.journey_id, 'journey:entry:updated', { entry: updated }, sid);
|
||||
await this.broadcastJourneyEvent(entry.journey_id, 'journey:entry:updated', { entry: updated }, sid);
|
||||
return updated;
|
||||
}
|
||||
|
||||
// Reorder entries (typically within a single day). Caller passes the new
|
||||
// desired order of ids; each entry's sort_order is set to its index in the
|
||||
// array. Only entries owned by this journey are accepted.
|
||||
reorderEntries(journeyId: number, userId: number, orderedIds: number[], sid?: string): boolean {
|
||||
if (!this.canEdit(journeyId, userId)) return false;
|
||||
async reorderEntries(journeyId: number, userId: number, orderedIds: number[], sid?: string): Promise<boolean> {
|
||||
if (!(await this.canEdit(journeyId, userId))) return false;
|
||||
if (!orderedIds.length) return true;
|
||||
|
||||
const placeholders = orderedIds.map(() => '?').join(',');
|
||||
@@ -1464,20 +1466,19 @@ export class JourneyDomainService {
|
||||
|
||||
const now = this.ts();
|
||||
const update = this.db.prepare('UPDATE journey_entries SET sort_order = ?, updated_at = ? WHERE id = ?');
|
||||
const tx = this.db.connection.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
orderedIds.forEach((id, index) => update.run(index, now, id));
|
||||
this.db.prepare('UPDATE journeys SET updated_at = ? WHERE id = ?').run(now, journeyId);
|
||||
});
|
||||
tx();
|
||||
|
||||
this.broadcastJourneyEvent(journeyId, 'journey:entries:reordered', { orderedIds }, sid);
|
||||
await this.broadcastJourneyEvent(journeyId, 'journey:entries:reordered', { orderedIds }, sid);
|
||||
return true;
|
||||
}
|
||||
|
||||
deleteEntry(entryId: number, userId: number, sid?: string): boolean {
|
||||
async deleteEntry(entryId: number, userId: number, sid?: string): Promise<boolean> {
|
||||
const entry = this.db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined;
|
||||
if (!entry) return false;
|
||||
if (!this.canEdit(entry.journey_id, userId)) return false;
|
||||
if (!(await this.canEdit(entry.journey_id, userId))) return false;
|
||||
|
||||
if (entry.source_trip_id && entry.source_place_id && entry.type !== 'skeleton') {
|
||||
// Revert filled entry back to skeleton instead of deleting
|
||||
@@ -1489,10 +1490,10 @@ export class JourneyDomainService {
|
||||
WHERE id = ?
|
||||
`,
|
||||
).run(this.ts(), entryId);
|
||||
this.broadcastJourneyEvent(entry.journey_id, 'journey:entry:updated', { entryId }, sid);
|
||||
await this.broadcastJourneyEvent(entry.journey_id, 'journey:entry:updated', { entryId }, sid);
|
||||
} else {
|
||||
this.db.prepare('DELETE FROM journey_entries WHERE id = ?').run(entryId);
|
||||
this.broadcastJourneyEvent(entry.journey_id, 'journey:entry:deleted', { entryId }, sid);
|
||||
await this.broadcastJourneyEvent(entry.journey_id, 'journey:entry:deleted', { entryId }, sid);
|
||||
}
|
||||
|
||||
return true;
|
||||
@@ -1503,13 +1504,13 @@ export class JourneyDomainService {
|
||||
// Promote a skeleton suggestion to a concrete entry. Called whenever the user
|
||||
// adds content (photo upload, provider photo, gallery link) — a suggestion
|
||||
// with photos is no longer just a suggestion.
|
||||
private promoteSkeletonIfNeeded(entry: JourneyEntry): void {
|
||||
private async promoteSkeletonIfNeeded(entry: JourneyEntry): Promise<void> {
|
||||
if (entry.type !== 'skeleton') return;
|
||||
this.db.prepare('UPDATE journey_entries SET type = ?, updated_at = ? WHERE id = ?').run('entry', this.ts(), entry.id);
|
||||
}
|
||||
|
||||
// Ensure a trek_photo_id is in the journey gallery; return its gallery row id.
|
||||
private ensureInGallery(journeyId: number, trekPhotoId: number, caption?: string, shared?: number): number {
|
||||
private async ensureInGallery(journeyId: number, trekPhotoId: number, caption?: string, shared?: number): Promise<number> {
|
||||
const now = this.ts();
|
||||
const maxOrderRow = this.db
|
||||
.prepare('SELECT MAX(sort_order) as m FROM journey_photos WHERE journey_id = ?')
|
||||
@@ -1527,7 +1528,7 @@ export class JourneyDomainService {
|
||||
}
|
||||
|
||||
// Link a gallery photo to an entry (idempotent). Returns the junction JP_SELECT row.
|
||||
private linkGalleryPhotoToEntry(galleryId: number, entryId: number): JourneyPhoto | null {
|
||||
private async linkGalleryPhotoToEntry(galleryId: number, entryId: number): Promise<JourneyPhoto | null> {
|
||||
const now = this.ts();
|
||||
const maxOrderRow = this.db
|
||||
.prepare('SELECT MAX(sort_order) as m FROM journey_entry_photos WHERE entry_id = ?')
|
||||
@@ -1562,7 +1563,7 @@ export class JourneyDomainService {
|
||||
): Promise<JourneyPhoto | null> {
|
||||
const entry = this.db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined;
|
||||
if (!entry) return null;
|
||||
if (!this.canEdit(entry.journey_id, userId)) return null;
|
||||
if (!(await this.canEdit(entry.journey_id, userId))) return null;
|
||||
|
||||
const trekPhotoId = await this.photos.getOrCreateLocal(
|
||||
filePath,
|
||||
@@ -1572,9 +1573,9 @@ export class JourneyDomainService {
|
||||
media?.mediaType || 'image',
|
||||
media?.durationMs ?? null,
|
||||
);
|
||||
const galleryId = this.db.connection.transaction(() => this.ensureInGallery(entry.journey_id, trekPhotoId, caption))();
|
||||
const result = this.linkGalleryPhotoToEntry(galleryId, entryId);
|
||||
this.promoteSkeletonIfNeeded(entry);
|
||||
const galleryId = await this.uow.transactional(async () => await this.ensureInGallery(entry.journey_id, trekPhotoId, caption));
|
||||
const result = await this.linkGalleryPhotoToEntry(galleryId, entryId);
|
||||
await this.promoteSkeletonIfNeeded(entry);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1589,7 +1590,7 @@ export class JourneyDomainService {
|
||||
): Promise<JourneyPhoto | null> {
|
||||
const entry = this.db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined;
|
||||
if (!entry) return null;
|
||||
if (!this.canEdit(entry.journey_id, userId)) return null;
|
||||
if (!(await this.canEdit(entry.journey_id, userId))) return null;
|
||||
|
||||
const trekPhotoId = await this.photos.getOrCreate(provider, assetId, userId, passphrase, mediaType);
|
||||
|
||||
@@ -1605,17 +1606,17 @@ export class JourneyDomainService {
|
||||
.get(entryId, trekPhotoId);
|
||||
if (alreadyLinked) return null;
|
||||
|
||||
const galleryId = this.db.connection.transaction(() => this.ensureInGallery(entry.journey_id, trekPhotoId, caption))();
|
||||
const result = this.linkGalleryPhotoToEntry(galleryId, entryId);
|
||||
this.promoteSkeletonIfNeeded(entry);
|
||||
const galleryId = await this.uow.transactional(async () => await this.ensureInGallery(entry.journey_id, trekPhotoId, caption));
|
||||
const result = await this.linkGalleryPhotoToEntry(galleryId, entryId);
|
||||
await this.promoteSkeletonIfNeeded(entry);
|
||||
return result;
|
||||
}
|
||||
|
||||
// Link a gallery photo (by its journey_photos.id) to an entry — idempotent.
|
||||
linkPhotoToEntry(entryId: number, journeyPhotoId: number, userId: number): JourneyPhoto | null {
|
||||
async linkPhotoToEntry(entryId: number, journeyPhotoId: number, userId: number): Promise<JourneyPhoto | null> {
|
||||
const entry = this.db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined;
|
||||
if (!entry) return null;
|
||||
if (!this.canEdit(entry.journey_id, userId)) return null;
|
||||
if (!(await this.canEdit(entry.journey_id, userId))) return null;
|
||||
|
||||
// Verify the gallery photo belongs to this journey
|
||||
const galleryRow = this.db.prepare('SELECT id, journey_id FROM journey_photos WHERE id = ?').get(journeyPhotoId) as
|
||||
@@ -1623,8 +1624,8 @@ export class JourneyDomainService {
|
||||
| undefined;
|
||||
if (!galleryRow || galleryRow.journey_id !== entry.journey_id) return null;
|
||||
|
||||
const result = this.linkGalleryPhotoToEntry(galleryRow.id, entryId);
|
||||
this.promoteSkeletonIfNeeded(entry);
|
||||
const result = await this.linkGalleryPhotoToEntry(galleryRow.id, entryId);
|
||||
await this.promoteSkeletonIfNeeded(entry);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -1634,7 +1635,7 @@ export class JourneyDomainService {
|
||||
userId: number,
|
||||
filePaths: { path: string; thumbnail?: string; mediaType?: string; durationMs?: number | null }[],
|
||||
): Promise<JourneyPhoto[]> {
|
||||
if (!this.canEdit(journeyId, userId)) return [];
|
||||
if (!(await this.canEdit(journeyId, userId))) return [];
|
||||
const results: any[] = [];
|
||||
const now = this.ts();
|
||||
const maxOrderRow = this.db
|
||||
@@ -1668,17 +1669,17 @@ export class JourneyDomainService {
|
||||
passphrase?: string,
|
||||
mediaType: string = 'image',
|
||||
): Promise<any | null> {
|
||||
if (!this.canEdit(journeyId, userId)) return null;
|
||||
if (!(await this.canEdit(journeyId, userId))) return null;
|
||||
const trekPhotoId = await this.photos.getOrCreate(provider, assetId, userId, passphrase, mediaType);
|
||||
const galleryId = this.db.connection.transaction(() => this.ensureInGallery(journeyId, trekPhotoId, caption))();
|
||||
const galleryId = await this.uow.transactional(async () => await this.ensureInGallery(journeyId, trekPhotoId, caption));
|
||||
return this.db.prepare(`SELECT ${GALLERY_SELECT} FROM ${GALLERY_JOIN} WHERE gp.id = ?`).get(galleryId) ?? null;
|
||||
}
|
||||
|
||||
// Unlink a photo from a specific entry; gallery row is preserved.
|
||||
unlinkPhotoFromEntry(entryId: number, journeyPhotoId: number, userId: number): boolean {
|
||||
async unlinkPhotoFromEntry(entryId: number, journeyPhotoId: number, userId: number): Promise<boolean> {
|
||||
const entry = this.db.prepare('SELECT * FROM journey_entries WHERE id = ?').get(entryId) as JourneyEntry | undefined;
|
||||
if (!entry) return false;
|
||||
if (!this.canEdit(entry.journey_id, userId)) return false;
|
||||
if (!(await this.canEdit(entry.journey_id, userId))) return false;
|
||||
|
||||
const result = this.db
|
||||
.prepare('DELETE FROM journey_entry_photos WHERE entry_id = ? AND journey_photo_id = ?')
|
||||
@@ -1695,7 +1696,7 @@ export class JourneyDomainService {
|
||||
| { id: number; journey_id: number; photo_id: number }
|
||||
| undefined;
|
||||
if (!row) return null;
|
||||
if (!this.canEdit(row.journey_id, userId)) return null;
|
||||
if (!(await this.canEdit(row.journey_id, userId))) return null;
|
||||
|
||||
const trekRow = this.db.prepare('SELECT file_path, thumbnail_path, provider FROM trek_photos WHERE id = ?').get(row.photo_id) as
|
||||
| { file_path?: string; thumbnail_path?: string; provider?: string }
|
||||
@@ -1724,17 +1725,17 @@ export class JourneyDomainService {
|
||||
);
|
||||
}
|
||||
|
||||
updatePhoto(
|
||||
async updatePhoto(
|
||||
photoId: number,
|
||||
userId: number,
|
||||
data: { caption?: string; sort_order?: number },
|
||||
): JourneyPhoto | null {
|
||||
): Promise<JourneyPhoto | null> {
|
||||
// photoId = journey_photos.id (gallery row)
|
||||
const row = this.db.prepare('SELECT id, journey_id FROM journey_photos WHERE id = ?').get(photoId) as
|
||||
| { id: number; journey_id: number }
|
||||
| undefined;
|
||||
if (!row) return null;
|
||||
if (!this.canEdit(row.journey_id, userId)) return null;
|
||||
if (!(await this.canEdit(row.journey_id, userId))) return null;
|
||||
|
||||
// caption lives on the gallery row; sort_order lives on the junction table
|
||||
// (JP_SELECT reads jep.sort_order, so updating journey_photos.sort_order
|
||||
@@ -1760,7 +1761,7 @@ export class JourneyDomainService {
|
||||
| { id: number; journey_id: number; photo_id: number }
|
||||
| undefined;
|
||||
if (!row) return null;
|
||||
if (!this.canEdit(row.journey_id, userId)) return null;
|
||||
if (!(await this.canEdit(row.journey_id, userId))) return null;
|
||||
|
||||
const trekRow = this.db.prepare('SELECT file_path, thumbnail_path, provider FROM trek_photos WHERE id = ?').get(row.photo_id) as
|
||||
| { file_path?: string; thumbnail_path?: string; provider?: string }
|
||||
@@ -1774,43 +1775,43 @@ export class JourneyDomainService {
|
||||
|
||||
// ── Contributors ─────────────────────────────────────────────────────────
|
||||
|
||||
addContributor(
|
||||
async addContributor(
|
||||
journeyId: number,
|
||||
userId: number,
|
||||
targetUserId: number,
|
||||
role: 'editor' | 'viewer',
|
||||
): boolean {
|
||||
if (!this.isOwner(journeyId, userId)) return false;
|
||||
): Promise<boolean> {
|
||||
if (!(await this.isOwner(journeyId, userId))) return false;
|
||||
if (targetUserId === userId) return false;
|
||||
try {
|
||||
this.db.prepare(
|
||||
'INSERT OR REPLACE INTO journey_contributors (journey_id, user_id, role, added_at) VALUES (?, ?, ?, ?)',
|
||||
).run(journeyId, targetUserId, role, this.ts());
|
||||
this.broadcastJourneyEvent(journeyId, 'journey:contributor:changed', { targetUserId, role });
|
||||
await this.broadcastJourneyEvent(journeyId, 'journey:contributor:changed', { targetUserId, role });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
updateContributorRole(
|
||||
async updateContributorRole(
|
||||
journeyId: number,
|
||||
userId: number,
|
||||
targetUserId: number,
|
||||
role: 'editor' | 'viewer',
|
||||
): boolean {
|
||||
if (!this.isOwner(journeyId, userId)) return false;
|
||||
): Promise<boolean> {
|
||||
if (!(await this.isOwner(journeyId, userId))) return false;
|
||||
this.db.prepare('UPDATE journey_contributors SET role = ? WHERE journey_id = ? AND user_id = ?').run(
|
||||
role,
|
||||
journeyId,
|
||||
targetUserId,
|
||||
);
|
||||
this.broadcastJourneyEvent(journeyId, 'journey:contributor:changed', { targetUserId, role });
|
||||
await this.broadcastJourneyEvent(journeyId, 'journey:contributor:changed', { targetUserId, role });
|
||||
return true;
|
||||
}
|
||||
|
||||
removeContributor(journeyId: number, userId: number, targetUserId: number): boolean {
|
||||
if (!this.isOwner(journeyId, userId)) return false;
|
||||
async removeContributor(journeyId: number, userId: number, targetUserId: number): Promise<boolean> {
|
||||
if (!(await this.isOwner(journeyId, userId))) return false;
|
||||
this.db.prepare("DELETE FROM journey_contributors WHERE journey_id = ? AND user_id = ? AND role != 'owner'").run(
|
||||
journeyId,
|
||||
targetUserId,
|
||||
@@ -1820,7 +1821,7 @@ export class JourneyDomainService {
|
||||
|
||||
// ── Suggestions ──────────────────────────────────────────────────────────
|
||||
|
||||
getSuggestions(userId: number) {
|
||||
async getSuggestions(userId: number) {
|
||||
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0];
|
||||
return this.db
|
||||
.prepare(
|
||||
@@ -1842,7 +1843,7 @@ export class JourneyDomainService {
|
||||
|
||||
// ── User trips (for trip picker) ─────────────────────────────────────────
|
||||
|
||||
listUserTrips(userId: number) {
|
||||
async listUserTrips(userId: number) {
|
||||
return this.db
|
||||
.prepare(
|
||||
`
|
||||
|
||||
@@ -43,7 +43,7 @@ export class JourneyPublicController {
|
||||
|
||||
@Get(':token/photos/:photoId/:kind')
|
||||
async photo(@Param('token') token: string, @Param('photoId') photoId: string, @Param('kind') kind: string, @Res() res: Response): Promise<void> {
|
||||
const valid = this.journey.validateShareTokenForPhoto(token, Number(photoId));
|
||||
const valid = await this.journey.validateShareTokenForPhoto(token, Number(photoId));
|
||||
if (!valid) {
|
||||
throw new HttpException({ error: 'Not found' }, 404);
|
||||
}
|
||||
@@ -58,7 +58,7 @@ export class JourneyPublicController {
|
||||
@Param('kind') kind: string,
|
||||
@Res() res: Response,
|
||||
): Promise<void> {
|
||||
const valid = this.journey.validateShareTokenForAsset(token, assetId);
|
||||
const valid = await this.journey.validateShareTokenForAsset(token, assetId);
|
||||
if (!valid) {
|
||||
throw new HttpException({ error: 'Not found' }, 404);
|
||||
}
|
||||
|
||||
@@ -39,14 +39,14 @@ export class JourneyShareService {
|
||||
private readonly settings: SettingsService,
|
||||
) {}
|
||||
|
||||
createOrUpdateJourneyShareLink(
|
||||
async createOrUpdateJourneyShareLink(
|
||||
journeyId: number,
|
||||
createdBy: number,
|
||||
permissions: JourneySharePermissions
|
||||
): { token: string; created: boolean } | null {
|
||||
): Promise<{ token: string; created: boolean } | null> {
|
||||
// Public sharing is an owner-only action — editors/viewers must not be
|
||||
// able to publish the journey or change which screens are shared.
|
||||
if (!this.journey.isOwner(journeyId, createdBy)) return null;
|
||||
if (!(await this.journey.isOwner(journeyId, createdBy))) return null;
|
||||
|
||||
const existing = this.db.prepare('SELECT token, share_timeline, share_gallery, share_map, newest_first FROM journey_share_tokens WHERE journey_id = ?')
|
||||
.get(journeyId) as { token: string; share_timeline: number; share_gallery: number; share_map: number; newest_first: number } | undefined;
|
||||
@@ -87,15 +87,15 @@ export class JourneyShareService {
|
||||
* unpublished puts a "create link" button in front of somebody it will then
|
||||
* refuse. Both the REST route and the MCP tool read the link through here.
|
||||
*/
|
||||
readJourneyShareLink(
|
||||
async readJourneyShareLink(
|
||||
journeyId: number,
|
||||
userId: number,
|
||||
): { allowed: false } | { allowed: true; link: JourneyShareTokenInfo | null } {
|
||||
if (!this.journey.isOwner(journeyId, userId)) return { allowed: false };
|
||||
return { allowed: true, link: this.getJourneyShareLink(journeyId) };
|
||||
): Promise<{ allowed: false } | { allowed: true; link: JourneyShareTokenInfo | null }> {
|
||||
if (!(await this.journey.isOwner(journeyId, userId))) return { allowed: false };
|
||||
return { allowed: true, link: await this.getJourneyShareLink(journeyId) };
|
||||
}
|
||||
|
||||
getJourneyShareLink(journeyId: number): JourneyShareTokenInfo | null {
|
||||
async getJourneyShareLink(journeyId: number): Promise<JourneyShareTokenInfo | null> {
|
||||
const row = this.db.prepare('SELECT * FROM journey_share_tokens WHERE journey_id = ?').get(journeyId) as any;
|
||||
if (!row) return null;
|
||||
return {
|
||||
@@ -108,13 +108,13 @@ export class JourneyShareService {
|
||||
};
|
||||
}
|
||||
|
||||
deleteJourneyShareLink(journeyId: number, userId: number): boolean {
|
||||
if (!this.journey.isOwner(journeyId, userId)) return false;
|
||||
async deleteJourneyShareLink(journeyId: number, userId: number): Promise<boolean> {
|
||||
if (!(await this.journey.isOwner(journeyId, userId))) return false;
|
||||
this.db.prepare('DELETE FROM journey_share_tokens WHERE journey_id = ?').run(journeyId);
|
||||
return true;
|
||||
}
|
||||
|
||||
validateShareTokenForPhoto(token: string, photoId: number): { journeyId: number; ownerId: number } | null {
|
||||
async validateShareTokenForPhoto(token: string, photoId: number): Promise<{ journeyId: number; ownerId: number } | null> {
|
||||
const row = this.db.prepare('SELECT journey_id, share_gallery FROM journey_share_tokens WHERE token = ?').get(token) as any;
|
||||
if (!row) return null;
|
||||
// Photos only ever surface (inline or in the gallery) when share_gallery is on,
|
||||
@@ -133,7 +133,7 @@ export class JourneyShareService {
|
||||
return journey ? { journeyId: row.journey_id, ownerId: photo.owner_id || journey.user_id } : null;
|
||||
}
|
||||
|
||||
validateShareTokenForAsset(token: string, assetId: string): { ownerId: number } | null {
|
||||
async validateShareTokenForAsset(token: string, assetId: string): Promise<{ ownerId: number } | null> {
|
||||
const row = this.db.prepare('SELECT journey_id, share_gallery FROM journey_share_tokens WHERE token = ?').get(token) as any;
|
||||
if (!row) return null;
|
||||
// Same as the unified photo proxy: no asset bytes leave the host unless the
|
||||
|
||||
@@ -192,8 +192,8 @@ export class JourneyController {
|
||||
|
||||
// ── Static prefix routes (before /:id) ──────────────────────────────────
|
||||
@Get()
|
||||
list(@CurrentUser() user: User) {
|
||||
return { journeys: this.journey.listJourneys(user.id) };
|
||||
async list(@CurrentUser() user: User) {
|
||||
return { journeys: await this.journey.listJourneys(user.id) };
|
||||
}
|
||||
|
||||
@Post()
|
||||
@@ -211,19 +211,19 @@ export class JourneyController {
|
||||
}
|
||||
|
||||
@Get('suggestions')
|
||||
suggestions(@CurrentUser() user: User) {
|
||||
return { trips: this.journey.getSuggestions(user.id) };
|
||||
async suggestions(@CurrentUser() user: User) {
|
||||
return { trips: await this.journey.getSuggestions(user.id) };
|
||||
}
|
||||
|
||||
@Get('available-trips')
|
||||
availableTrips(@CurrentUser() user: User) {
|
||||
return { trips: this.journey.listUserTrips(user.id) };
|
||||
async availableTrips(@CurrentUser() user: User) {
|
||||
return { trips: await this.journey.listUserTrips(user.id) };
|
||||
}
|
||||
|
||||
// ── Entries (prefix /entries — before /:id) ─────────────────────────────
|
||||
@Patch('entries/:entryId')
|
||||
updateEntry(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: JourneyEntryUpdateDto, @Headers('x-socket-id') socketId?: string) {
|
||||
const result = this.journey.updateEntry(Number(entryId), user.id, body, socketId);
|
||||
async updateEntry(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: JourneyEntryUpdateDto, @Headers('x-socket-id') socketId?: string) {
|
||||
const result = await this.journey.updateEntry(Number(entryId), user.id, body, socketId);
|
||||
if (!result) {
|
||||
throw new HttpException({ error: 'Entry not found' }, 404);
|
||||
}
|
||||
@@ -231,8 +231,8 @@ export class JourneyController {
|
||||
}
|
||||
|
||||
@Delete('entries/:entryId')
|
||||
deleteEntry(@CurrentUser() user: User, @Param('entryId') entryId: string, @Headers('x-socket-id') socketId?: string) {
|
||||
if (!this.journey.deleteEntry(Number(entryId), user.id, socketId)) {
|
||||
async deleteEntry(@CurrentUser() user: User, @Param('entryId') entryId: string, @Headers('x-socket-id') socketId?: string) {
|
||||
if (!(await this.journey.deleteEntry(Number(entryId), user.id, socketId))) {
|
||||
throw new HttpException({ error: 'Entry not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
@@ -258,7 +258,7 @@ export class JourneyController {
|
||||
continue;
|
||||
}
|
||||
// Mirror to Immich only when the user explicitly opted in (#730).
|
||||
if (this.journey.immichAutoUploadEnabled(user.id)) {
|
||||
if (await this.journey.immichAutoUploadEnabled(user.id)) {
|
||||
try {
|
||||
const immichId = await this.journey.uploadToImmich(user.id, relativePath, file.originalname);
|
||||
if (immichId) {
|
||||
@@ -357,12 +357,12 @@ export class JourneyController {
|
||||
}
|
||||
|
||||
@Post('entries/:entryId/link-photo')
|
||||
linkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: JourneyLinkPhotoDto) {
|
||||
async linkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Body() body: JourneyLinkPhotoDto) {
|
||||
const journeyPhotoId = body.journey_photo_id ?? body.photo_id;
|
||||
if (!journeyPhotoId) {
|
||||
throw new HttpException({ error: 'journey_photo_id required' }, 400);
|
||||
}
|
||||
const result = this.journey.linkPhotoToEntry(Number(entryId), Number(journeyPhotoId), user.id);
|
||||
const result = await this.journey.linkPhotoToEntry(Number(entryId), Number(journeyPhotoId), user.id);
|
||||
if (!result) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
@@ -371,15 +371,15 @@ export class JourneyController {
|
||||
|
||||
@Delete('entries/:entryId/photos/:journeyPhotoId')
|
||||
@HttpCode(204)
|
||||
unlinkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Param('journeyPhotoId') journeyPhotoId: string): void {
|
||||
if (!this.journey.unlinkPhotoFromEntry(Number(entryId), Number(journeyPhotoId), user.id)) {
|
||||
async unlinkPhoto(@CurrentUser() user: User, @Param('entryId') entryId: string, @Param('journeyPhotoId') journeyPhotoId: string): Promise<void> {
|
||||
if (!(await this.journey.unlinkPhotoFromEntry(Number(entryId), Number(journeyPhotoId), user.id))) {
|
||||
throw new HttpException({ error: 'Not found or not allowed' }, 404);
|
||||
}
|
||||
}
|
||||
|
||||
@Patch('photos/:photoId')
|
||||
updatePhoto(@CurrentUser() user: User, @Param('photoId') photoId: string, @Body() body: JourneyPhotoUpdateDto) {
|
||||
const result = this.journey.updatePhoto(Number(photoId), user.id, body);
|
||||
async updatePhoto(@CurrentUser() user: User, @Param('photoId') photoId: string, @Body() body: JourneyPhotoUpdateDto) {
|
||||
const result = await this.journey.updatePhoto(Number(photoId), user.id, body);
|
||||
if (!result) {
|
||||
throw new HttpException({ error: 'Photo not found' }, 404);
|
||||
}
|
||||
@@ -527,8 +527,8 @@ export class JourneyController {
|
||||
|
||||
// ── Journeys /:id ───────────────────────────────────────────────────────
|
||||
@Get(':id')
|
||||
get(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const data = this.journey.getJourneyFull(Number(id), user.id);
|
||||
async get(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const data = await this.journey.getJourneyFull(Number(id), user.id);
|
||||
if (!data) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
@@ -536,8 +536,8 @@ export class JourneyController {
|
||||
}
|
||||
|
||||
@Patch(':id')
|
||||
update(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyUpdateDto) {
|
||||
const result = this.journey.updateJourney(Number(id), user.id, body);
|
||||
async update(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyUpdateDto) {
|
||||
const result = await this.journey.updateJourney(Number(id), user.id, body);
|
||||
if (!result) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
@@ -552,7 +552,7 @@ export class JourneyController {
|
||||
throw new HttpException({ error: 'No file uploaded' }, 400);
|
||||
}
|
||||
await this.commitJourneyUploads([file]);
|
||||
const result = this.journey.updateJourney(Number(id), user.id, { cover_image: `journey/${file.filename}` });
|
||||
const result = await this.journey.updateJourney(Number(id), user.id, { cover_image: `journey/${file.filename}` });
|
||||
if (!result) {
|
||||
await this.discardJourneyUploads([file]);
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
@@ -561,8 +561,8 @@ export class JourneyController {
|
||||
}
|
||||
|
||||
@Delete(':id')
|
||||
remove(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
if (!this.journey.deleteJourney(Number(id), user.id)) {
|
||||
async remove(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
if (!(await this.journey.deleteJourney(Number(id), user.id))) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
@@ -571,19 +571,19 @@ export class JourneyController {
|
||||
// ── Journey trips ───────────────────────────────────────────────────────
|
||||
@Post(':id/trips')
|
||||
@HttpCode(200) // Express answers with res.json (200).
|
||||
addTrip(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyAddTripDto) {
|
||||
async addTrip(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyAddTripDto) {
|
||||
if (!body.trip_id) {
|
||||
throw new HttpException({ error: 'trip_id required' }, 400);
|
||||
}
|
||||
if (!this.journey.addTripToJourney(Number(id), Number(body.trip_id), user.id)) {
|
||||
if (!(await this.journey.addTripToJourney(Number(id), Number(body.trip_id), user.id))) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Delete(':id/trips/:tripId')
|
||||
removeTrip(@CurrentUser() user: User, @Param('id') id: string, @Param('tripId') tripId: string) {
|
||||
if (!this.journey.removeTripFromJourney(Number(id), Number(tripId), user.id)) {
|
||||
async removeTrip(@CurrentUser() user: User, @Param('id') id: string, @Param('tripId') tripId: string) {
|
||||
if (!(await this.journey.removeTripFromJourney(Number(id), Number(tripId), user.id))) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
return { success: true };
|
||||
@@ -591,8 +591,8 @@ export class JourneyController {
|
||||
|
||||
// ── Entries under journey ───────────────────────────────────────────────
|
||||
@Get(':id/entries')
|
||||
listEntries(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const entries = this.journey.listEntries(Number(id), user.id);
|
||||
async listEntries(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const entries = await this.journey.listEntries(Number(id), user.id);
|
||||
if (!entries) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
@@ -605,8 +605,8 @@ export class JourneyController {
|
||||
* planner is all it takes for it to show up here.
|
||||
*/
|
||||
@Get(':id/tracks')
|
||||
listTracks(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const tracks = this.journey.journeyTracks(Number(id), user.id);
|
||||
async listTracks(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const tracks = await this.journey.journeyTracks(Number(id), user.id);
|
||||
if (!tracks) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
@@ -623,8 +623,8 @@ export class JourneyController {
|
||||
* designing and never while printing.
|
||||
*/
|
||||
@Get(':id/stats')
|
||||
stats(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const stats = this.journey.journeyStats(Number(id), user.id);
|
||||
async stats(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const stats = await this.journey.journeyStats(Number(id), user.id);
|
||||
if (!stats) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
@@ -640,9 +640,9 @@ export class JourneyController {
|
||||
*/
|
||||
|
||||
@Get(':id/book')
|
||||
getBook(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const book = this.books.getBook(Number(id), user.id);
|
||||
if (book === null && !this.books.canOpen(Number(id), user.id)) {
|
||||
async getBook(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const book = await this.books.getBook(Number(id), user.id);
|
||||
if (book === null && !(await this.books.canOpen(Number(id), user.id))) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
// A journey with no book yet is not an error: Studio opens, lays one out
|
||||
@@ -653,19 +653,19 @@ export class JourneyController {
|
||||
|
||||
@Put(':id/book')
|
||||
@HttpCode(200)
|
||||
saveBook(
|
||||
async saveBook(
|
||||
@CurrentUser() user: User,
|
||||
@Param('id') id: string,
|
||||
@Body() body: BookSaveDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const result = this.books.saveBook(Number(id), user.id, {
|
||||
const result = await this.books.saveBook(Number(id), user.id, {
|
||||
title: body.title ?? '',
|
||||
document: body.document,
|
||||
baseVersion: body.baseVersion,
|
||||
});
|
||||
if (result === null) {
|
||||
throw this.bookRefusal(Number(id), user.id);
|
||||
throw await this.bookRefusal(Number(id), user.id);
|
||||
}
|
||||
if ('conflict' in result) {
|
||||
/*
|
||||
@@ -681,16 +681,16 @@ export class JourneyController {
|
||||
409,
|
||||
);
|
||||
}
|
||||
this.books.broadcastSaved(Number(id), user.id, result.record, socketId);
|
||||
await this.books.broadcastSaved(Number(id), user.id, result.record, socketId);
|
||||
return result.record;
|
||||
}
|
||||
|
||||
@Delete(':id/book')
|
||||
@HttpCode(204)
|
||||
deleteBook(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const removed = this.books.deleteBook(Number(id), user.id);
|
||||
async deleteBook(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const removed = await this.books.deleteBook(Number(id), user.id);
|
||||
if (removed === null) {
|
||||
throw this.bookRefusal(Number(id), user.id);
|
||||
throw await this.bookRefusal(Number(id), user.id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -702,18 +702,18 @@ export class JourneyController {
|
||||
* not exist. Someone who cannot see the journey at all still gets the 404 —
|
||||
* the status is not an existence oracle for them.
|
||||
*/
|
||||
private bookRefusal(journeyId: number, userId: number): HttpException {
|
||||
return this.books.canOpen(journeyId, userId)
|
||||
private async bookRefusal(journeyId: number, userId: number): Promise<HttpException> {
|
||||
return (await this.books.canOpen(journeyId, userId))
|
||||
? new HttpException({ error: 'Not allowed' }, 403)
|
||||
: new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
|
||||
@Post(':id/entries')
|
||||
createEntry(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyEntryCreateDto, @Headers('x-socket-id') socketId?: string) {
|
||||
async createEntry(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyEntryCreateDto, @Headers('x-socket-id') socketId?: string) {
|
||||
if (!body.entry_date) {
|
||||
throw new HttpException({ error: 'entry_date is required' }, 400);
|
||||
}
|
||||
const entry = this.journey.createEntry(Number(id), user.id, body, socketId);
|
||||
const entry = await this.journey.createEntry(Number(id), user.id, body, socketId);
|
||||
if (!entry) {
|
||||
throw new HttpException({ error: 'Journey not found' }, 404);
|
||||
}
|
||||
@@ -721,12 +721,12 @@ export class JourneyController {
|
||||
}
|
||||
|
||||
@Put(':id/entries/reorder')
|
||||
reorderEntries(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyReorderEntriesDto, @Headers('x-socket-id') socketId?: string) {
|
||||
async reorderEntries(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyReorderEntriesDto, @Headers('x-socket-id') socketId?: string) {
|
||||
const orderedIds = body.orderedIds;
|
||||
if (!Array.isArray(orderedIds) || !orderedIds.every((v) => Number.isFinite(Number(v)))) {
|
||||
throw new HttpException({ error: 'orderedIds must be an array of numbers' }, 400);
|
||||
}
|
||||
if (!this.journey.reorderEntries(Number(id), user.id, orderedIds.map(Number), socketId)) {
|
||||
if (!(await this.journey.reorderEntries(Number(id), user.id, orderedIds.map(Number), socketId))) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
return { success: true };
|
||||
@@ -734,27 +734,27 @@ export class JourneyController {
|
||||
|
||||
// ── Contributors ────────────────────────────────────────────────────────
|
||||
@Post(':id/contributors')
|
||||
addContributor(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyContributorAddDto) {
|
||||
async addContributor(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyContributorAddDto) {
|
||||
if (!body.user_id) {
|
||||
throw new HttpException({ error: 'user_id required' }, 400);
|
||||
}
|
||||
if (!this.journey.addContributor(Number(id), user.id, Number(body.user_id), (body.role as 'editor' | 'viewer') || 'viewer')) {
|
||||
if (!(await this.journey.addContributor(Number(id), user.id, Number(body.user_id), (body.role as 'editor' | 'viewer') || 'viewer'))) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Patch(':id/contributors/:userId')
|
||||
updateContributor(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body() body: JourneyContributorUpdateDto) {
|
||||
if (!this.journey.updateContributorRole(Number(id), user.id, Number(userId), body.role as 'editor' | 'viewer')) {
|
||||
async updateContributor(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body() body: JourneyContributorUpdateDto) {
|
||||
if (!(await this.journey.updateContributorRole(Number(id), user.id, Number(userId), body.role as 'editor' | 'viewer'))) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@Delete(':id/contributors/:userId')
|
||||
removeContributor(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
if (!this.journey.removeContributor(Number(id), user.id, Number(userId))) {
|
||||
async removeContributor(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
if (!(await this.journey.removeContributor(Number(id), user.id, Number(userId)))) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
return { success: true };
|
||||
@@ -763,8 +763,8 @@ export class JourneyController {
|
||||
// ── Suggestions ─────────────────────────────────────────────────────────
|
||||
@Post(':id/suggestions/restore')
|
||||
@HttpCode(200)
|
||||
restoreSuggestions(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const result = this.journey.restoreDismissedSuggestions(Number(id), user.id);
|
||||
async restoreSuggestions(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const result = await this.journey.restoreDismissedSuggestions(Number(id), user.id);
|
||||
if (!result) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
@@ -773,8 +773,8 @@ export class JourneyController {
|
||||
|
||||
// ── User Preferences ────────────────────────────────────────────────────
|
||||
@Patch(':id/preferences')
|
||||
preferences(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyPreferencesDto) {
|
||||
const result = this.journey.updateJourneyPreferences(Number(id), user.id, body);
|
||||
async preferences(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyPreferencesDto) {
|
||||
const result = await this.journey.updateJourneyPreferences(Number(id), user.id, body);
|
||||
if (!result) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
@@ -783,12 +783,12 @@ export class JourneyController {
|
||||
|
||||
// ── Share Link ──────────────────────────────────────────────────────────
|
||||
@Get(':id/share-link')
|
||||
getShareLink(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
async getShareLink(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
// Reading the token is owner-only. It refuses like its siblings rather than
|
||||
// answering with a null link: "not published" and "not yours to see" are
|
||||
// different answers, and a client told the first one offers a create button
|
||||
// that the POST below then refuses.
|
||||
const result = this.journey.getJourneyShareLink(Number(id), user.id);
|
||||
const result = await this.journey.getJourneyShareLink(Number(id), user.id);
|
||||
if (!result.allowed) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
@@ -797,8 +797,8 @@ export class JourneyController {
|
||||
|
||||
@Post(':id/share-link')
|
||||
@HttpCode(200) // Express answers with res.json (200).
|
||||
setShareLink(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyShareLinkDto) {
|
||||
const result = this.journey.createOrUpdateJourneyShareLink(Number(id), user.id, {
|
||||
async setShareLink(@CurrentUser() user: User, @Param('id') id: string, @Body() body: JourneyShareLinkDto) {
|
||||
const result = await this.journey.createOrUpdateJourneyShareLink(Number(id), user.id, {
|
||||
share_timeline: body.share_timeline as boolean | undefined,
|
||||
share_gallery: body.share_gallery as boolean | undefined,
|
||||
share_map: body.share_map as boolean | undefined,
|
||||
@@ -811,8 +811,8 @@ export class JourneyController {
|
||||
}
|
||||
|
||||
@Delete(':id/share-link')
|
||||
deleteShareLink(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
if (!this.journey.deleteJourneyShareLink(Number(id), user.id)) {
|
||||
async deleteShareLink(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
if (!(await this.journey.deleteJourneyShareLink(Number(id), user.id))) {
|
||||
throw new HttpException({ error: 'Not allowed' }, 403);
|
||||
}
|
||||
return { success: true };
|
||||
|
||||
@@ -123,8 +123,8 @@ export class JourneyMcp {
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
listJourneys(_args: unknown, ctx: McpContext) {
|
||||
return ok({ journeys: this.journey.listJourneys(ctx.userId) });
|
||||
async listJourneys(_args: unknown, ctx: McpContext) {
|
||||
return ok({ journeys: await this.journey.listJourneys(ctx.userId) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -135,8 +135,8 @@ export class JourneyMcp {
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
getJourney({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
const journey = this.journey.getJourneyFull(journeyId, ctx.userId);
|
||||
async getJourney({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
const journey = await this.journey.getJourneyFull(journeyId, ctx.userId);
|
||||
if (!journey) return notFound('Journey not found or access denied.');
|
||||
return ok({ journey });
|
||||
}
|
||||
@@ -152,8 +152,8 @@ export class JourneyMcp {
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
getJourneyStats({ journeyId, include_route }: { journeyId: number; include_route?: boolean }, ctx: McpContext) {
|
||||
const stats = this.journey.journeyStats(journeyId, ctx.userId);
|
||||
async getJourneyStats({ journeyId, include_route }: { journeyId: number; include_route?: boolean }, ctx: McpContext) {
|
||||
const stats = await this.journey.journeyStats(journeyId, ctx.userId);
|
||||
if (!stats) return notFound('Journey not found or access denied.');
|
||||
// Same payload as GET /api/journeys/:id/stats. The route is left out unless
|
||||
// it was asked for: 400 coordinate pairs answer a different question than
|
||||
@@ -171,9 +171,9 @@ export class JourneyMcp {
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
listJourneyEntries({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
if (!this.journey.canAccessJourney(journeyId, ctx.userId)) return notFound('Journey not found or access denied.');
|
||||
return ok({ entries: this.journey.listEntries(journeyId, ctx.userId) });
|
||||
async listJourneyEntries({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
if (!(await this.journey.canAccessJourney(journeyId, ctx.userId))) return notFound('Journey not found or access denied.');
|
||||
return ok({ entries: await this.journey.listEntries(journeyId, ctx.userId) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -184,8 +184,8 @@ export class JourneyMcp {
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
listJourneyContributors({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
const journey = this.journey.getJourneyFull(journeyId, ctx.userId);
|
||||
async listJourneyContributors({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
const journey = await this.journey.getJourneyFull(journeyId, ctx.userId);
|
||||
if (!journey) return notFound('Journey not found or access denied.');
|
||||
return ok({ contributors: (journey as { contributors?: JourneyContributor[] }).contributors ?? [] });
|
||||
}
|
||||
@@ -198,8 +198,8 @@ export class JourneyMcp {
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
getJourneySuggestions(_args: unknown, ctx: McpContext) {
|
||||
return ok({ trips: this.journey.getSuggestions(ctx.userId) });
|
||||
async getJourneySuggestions(_args: unknown, ctx: McpContext) {
|
||||
return ok({ trips: await this.journey.getSuggestions(ctx.userId) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -210,8 +210,8 @@ export class JourneyMcp {
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
listJourneyAvailableTrips(_args: unknown, ctx: McpContext) {
|
||||
return ok({ trips: this.journey.listUserTrips(ctx.userId) });
|
||||
async listJourneyAvailableTrips(_args: unknown, ctx: McpContext) {
|
||||
return ok({ trips: await this.journey.listUserTrips(ctx.userId) });
|
||||
}
|
||||
|
||||
// ── Write ───────────────────────────────────────────────────────────────
|
||||
@@ -233,10 +233,10 @@ export class JourneyMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const journey = this.journey.createJourney(ctx.userId, { title, subtitle, trip_ids });
|
||||
const journey = await this.journey.createJourney(ctx.userId, { title, subtitle, trip_ids });
|
||||
// Return the fully-hydrated journey (entries/contributors/trips/stats/my_role),
|
||||
// matching get_journey, rather than the bare row.
|
||||
return ok({ journey: this.journey.getJourneyFull(journey.id, ctx.userId) ?? journey });
|
||||
return ok({ journey: (await this.journey.getJourneyFull(journey.id, ctx.userId)) ?? journey });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -263,7 +263,7 @@ export class JourneyMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const journey = this.journey.updateJourney(journeyId, ctx.userId, data);
|
||||
const journey = await this.journey.updateJourney(journeyId, ctx.userId, data);
|
||||
if (!journey) return notFound('Journey not found or access denied.');
|
||||
return ok({ journey });
|
||||
}
|
||||
@@ -280,7 +280,7 @@ export class JourneyMcp {
|
||||
})
|
||||
async restoreJourneySuggestions({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const result = this.journey.restoreDismissedSuggestions(journeyId, ctx.userId);
|
||||
const result = await this.journey.restoreDismissedSuggestions(journeyId, ctx.userId);
|
||||
if (!result) return notFound('Journey not found or access denied.');
|
||||
return ok(result);
|
||||
}
|
||||
@@ -295,7 +295,7 @@ export class JourneyMcp {
|
||||
})
|
||||
async deleteJourney({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.journey.deleteJourney(journeyId, ctx.userId)) return notFound('Journey not found or access denied.');
|
||||
if (!(await this.journey.deleteJourney(journeyId, ctx.userId))) return notFound('Journey not found or access denied.');
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@@ -309,8 +309,8 @@ export class JourneyMcp {
|
||||
})
|
||||
async addJourneyTrip({ journeyId, tripId }: { journeyId: number; tripId: number }, ctx: McpContext) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.journey.canAccessJourney(journeyId, ctx.userId)) return notFound('Journey not found or access denied.');
|
||||
return ok({ success: this.journey.addTripToJourney(journeyId, tripId, ctx.userId) });
|
||||
if (!(await this.journey.canAccessJourney(journeyId, ctx.userId))) return notFound('Journey not found or access denied.');
|
||||
return ok({ success: await this.journey.addTripToJourney(journeyId, tripId, ctx.userId) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -323,7 +323,7 @@ export class JourneyMcp {
|
||||
})
|
||||
async removeJourneyTrip({ journeyId, tripId }: { journeyId: number; tripId: number }, ctx: McpContext) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const success = this.journey.removeTripFromJourney(journeyId, tripId, ctx.userId);
|
||||
const success = await this.journey.removeTripFromJourney(journeyId, tripId, ctx.userId);
|
||||
if (!success) return notFound('Journey not found or access denied.');
|
||||
return ok({ success });
|
||||
}
|
||||
@@ -362,10 +362,10 @@ export class JourneyMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const entry = this.journey.createEntry(journeyId, ctx.userId, data);
|
||||
const entry = await this.journey.createEntry(journeyId, ctx.userId, data);
|
||||
if (!entry) return notFound('Journey not found or access denied.');
|
||||
// Return through the listEntries enrichment (parsed tags/pros_cons, photos, source_trip_name).
|
||||
const enriched = this.journey.listEntries(journeyId, ctx.userId)?.find(e => e.id === entry.id) ?? entry;
|
||||
const enriched = (await this.journey.listEntries(journeyId, ctx.userId))?.find(e => e.id === entry.id) ?? entry;
|
||||
return ok({ entry: enriched });
|
||||
}
|
||||
|
||||
@@ -407,10 +407,10 @@ export class JourneyMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const entry = this.journey.updateEntry(entryId, ctx.userId, data, undefined);
|
||||
const entry = await this.journey.updateEntry(entryId, ctx.userId, data, undefined);
|
||||
if (!entry) return notFound('Entry not found or access denied.');
|
||||
// Return through the listEntries enrichment (parsed tags/pros_cons, photos), matching create_journey_entry.
|
||||
const enriched = this.journey.listEntries(entry.journey_id, ctx.userId)?.find(e => e.id === entry.id) ?? entry;
|
||||
const enriched = (await this.journey.listEntries(entry.journey_id, ctx.userId))?.find(e => e.id === entry.id) ?? entry;
|
||||
return ok({ entry: enriched });
|
||||
}
|
||||
|
||||
@@ -424,7 +424,7 @@ export class JourneyMcp {
|
||||
})
|
||||
async deleteJourneyEntry({ entryId }: { entryId: number }, ctx: McpContext) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.journey.deleteEntry(entryId, ctx.userId, undefined)) return notFound('Entry not found or access denied.');
|
||||
if (!(await this.journey.deleteEntry(entryId, ctx.userId, undefined))) return notFound('Entry not found or access denied.');
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@@ -441,7 +441,7 @@ export class JourneyMcp {
|
||||
})
|
||||
async reorderJourneyEntries({ journeyId, orderedIds }: { journeyId: number; orderedIds: number[] }, ctx: McpContext) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const success = this.journey.reorderEntries(journeyId, ctx.userId, orderedIds, undefined);
|
||||
const success = await this.journey.reorderEntries(journeyId, ctx.userId, orderedIds, undefined);
|
||||
if (!success) return notFound('Journey not found, access denied, or entry IDs do not belong to this journey.');
|
||||
return ok({ success: true });
|
||||
}
|
||||
@@ -463,7 +463,7 @@ export class JourneyMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.journey.addContributor(journeyId, ctx.userId, targetUserId, role)) return notFound('Journey not found or access denied.');
|
||||
if (!(await this.journey.addContributor(journeyId, ctx.userId, targetUserId, role))) return notFound('Journey not found or access denied.');
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@@ -484,7 +484,7 @@ export class JourneyMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.journey.updateContributorRole(journeyId, ctx.userId, targetUserId, role)) return notFound('Journey not found or access denied.');
|
||||
if (!(await this.journey.updateContributorRole(journeyId, ctx.userId, targetUserId, role))) return notFound('Journey not found or access denied.');
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@@ -501,7 +501,7 @@ export class JourneyMcp {
|
||||
})
|
||||
async removeJourneyContributor({ journeyId, targetUserId }: { journeyId: number; targetUserId: number }, ctx: McpContext) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.journey.removeContributor(journeyId, ctx.userId, targetUserId)) return notFound('Journey not found or access denied.');
|
||||
if (!(await this.journey.removeContributor(journeyId, ctx.userId, targetUserId))) return notFound('Journey not found or access denied.');
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@@ -521,7 +521,7 @@ export class JourneyMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const result = this.journey.updateJourneyPreferences(journeyId, ctx.userId, { hide_skeletons });
|
||||
const result = await this.journey.updateJourneyPreferences(journeyId, ctx.userId, { hide_skeletons });
|
||||
if (!result) return notFound('Journey not found or access denied.');
|
||||
// Return the service result ({ hide_skeletons }), matching the REST route.
|
||||
return ok(result);
|
||||
@@ -556,8 +556,8 @@ export class JourneyMcp {
|
||||
// access gets an empty 200. Checking up front instead turns that silence
|
||||
// into a sentence, and is what makes journeyId worth asking for: the entry
|
||||
// has to be shown to belong to it before anything is written.
|
||||
if (!this.journey.canEdit(journeyId, ctx.userId)) return notFound('Journey not found or access denied.');
|
||||
if (entryId !== undefined && !this.journey.listEntries(journeyId, ctx.userId)?.some(e => e.id === entryId)) {
|
||||
if (!(await this.journey.canEdit(journeyId, ctx.userId))) return notFound('Journey not found or access denied.');
|
||||
if (entryId !== undefined && !(await this.journey.listEntries(journeyId, ctx.userId))?.some(e => e.id === entryId)) {
|
||||
return notFound('Entry not found in this journey.');
|
||||
}
|
||||
|
||||
@@ -593,10 +593,10 @@ export class JourneyMcp {
|
||||
when: journeyAddonOn,
|
||||
access: { group: 'journey', mode: 'share' },
|
||||
})
|
||||
getJourneyShareLink({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
async getJourneyShareLink({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
// Same read the REST route uses, so the owner check cannot drift apart
|
||||
// between the two surfaces: handing out the token is handing out the journey.
|
||||
const result = this.share.readJourneyShareLink(journeyId, ctx.userId);
|
||||
const result = await this.share.readJourneyShareLink(journeyId, ctx.userId);
|
||||
if (!result.allowed) return notFound('Journey not found or access denied.');
|
||||
return ok({ shareLink: result.link });
|
||||
}
|
||||
@@ -617,7 +617,7 @@ export class JourneyMcp {
|
||||
})
|
||||
async createJourneyShareLink({ journeyId, ...permissions }: { journeyId: number; share_timeline?: boolean; share_gallery?: boolean; share_map?: boolean; newest_first?: boolean }, ctx: McpContext) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const shareLink = this.share.createOrUpdateJourneyShareLink(journeyId, ctx.userId, permissions);
|
||||
const shareLink = await this.share.createOrUpdateJourneyShareLink(journeyId, ctx.userId, permissions);
|
||||
if (!shareLink) return notFound('Journey not found or access denied.');
|
||||
return ok({ shareLink });
|
||||
}
|
||||
@@ -632,7 +632,7 @@ export class JourneyMcp {
|
||||
})
|
||||
async deleteJourneyShareLink({ journeyId }: { journeyId: number }, ctx: McpContext) {
|
||||
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.share.deleteJourneyShareLink(journeyId, ctx.userId)) return notFound('Journey not found or access denied.');
|
||||
if (!(await this.share.deleteJourneyShareLink(journeyId, ctx.userId))) return notFound('Journey not found or access denied.');
|
||||
return ok({ success: true });
|
||||
}
|
||||
|
||||
@@ -651,7 +651,7 @@ export class JourneyMcp {
|
||||
access: { group: 'journey', mode: 'read' },
|
||||
})
|
||||
async journeysResource(uri: URL, ctx: McpContext) {
|
||||
return jsonContent(uri.href, this.journey.listJourneys(ctx.userId));
|
||||
return jsonContent(uri.href, await this.journey.listJourneys(ctx.userId));
|
||||
}
|
||||
|
||||
@ResourceTemplate({
|
||||
@@ -665,7 +665,7 @@ export class JourneyMcp {
|
||||
async journeyDetailResource(uri: URL, { journeyId }: { journeyId: string | string[] }, ctx: McpContext) {
|
||||
const id = parseId(journeyId);
|
||||
if (id === null) return accessDenied(uri.href);
|
||||
const journey = this.journey.getJourneyFull(id, ctx.userId);
|
||||
const journey = await this.journey.getJourneyFull(id, ctx.userId);
|
||||
if (!journey) return accessDenied(uri.href);
|
||||
return jsonContent(uri.href, journey);
|
||||
}
|
||||
@@ -681,8 +681,8 @@ export class JourneyMcp {
|
||||
async journeyEntriesResource(uri: URL, { journeyId }: { journeyId: string | string[] }, ctx: McpContext) {
|
||||
const id = parseId(journeyId);
|
||||
if (id === null) return accessDenied(uri.href);
|
||||
if (!this.journey.canAccessJourney(id, ctx.userId)) return accessDenied(uri.href);
|
||||
return jsonContent(uri.href, this.journey.listEntries(id, ctx.userId));
|
||||
if (!(await this.journey.canAccessJourney(id, ctx.userId))) return accessDenied(uri.href);
|
||||
return jsonContent(uri.href, await this.journey.listEntries(id, ctx.userId));
|
||||
}
|
||||
|
||||
@ResourceTemplate({
|
||||
@@ -696,7 +696,7 @@ export class JourneyMcp {
|
||||
async journeyContributorsResource(uri: URL, { journeyId }: { journeyId: string | string[] }, ctx: McpContext) {
|
||||
const id = parseId(journeyId);
|
||||
if (id === null) return accessDenied(uri.href);
|
||||
const journey = this.journey.getJourneyFull(id, ctx.userId);
|
||||
const journey = await this.journey.getJourneyFull(id, ctx.userId);
|
||||
if (!journey) return accessDenied(uri.href);
|
||||
return jsonContent(uri.href, (journey as { contributors?: JourneyContributor[] }).contributors ?? []);
|
||||
}
|
||||
|
||||
@@ -87,7 +87,7 @@ export class JourneyService {
|
||||
deleteJourneyShareLink(id: number, userId: number) { return this.share.deleteJourneyShareLink(id, userId); }
|
||||
|
||||
// Immich mirror (only when the user opted in via integration settings)
|
||||
immichAutoUploadEnabled(userId: number): boolean {
|
||||
async immichAutoUploadEnabled(userId: number): Promise<boolean> {
|
||||
const prefs = this.db.prepare('SELECT immich_auto_upload FROM users WHERE id = ?').get(userId) as { immich_auto_upload?: number } | undefined;
|
||||
return !!prefs?.immich_auto_upload;
|
||||
}
|
||||
|
||||
@@ -45,7 +45,7 @@ export class OidcController {
|
||||
res.status(403).json({ error: 'SSO login is disabled.' });
|
||||
return;
|
||||
}
|
||||
const config = this.oidc.getOidcConfig();
|
||||
const config = await this.oidc.getOidcConfig();
|
||||
if (!config) {
|
||||
res.status(400).json({ error: 'OIDC not configured' });
|
||||
return;
|
||||
@@ -120,7 +120,7 @@ export class OidcController {
|
||||
const pending = this.oidc.consumeState(state);
|
||||
if (!pending) return f('/login?oidc_error=invalid_state');
|
||||
|
||||
const config = this.oidc.getOidcConfig();
|
||||
const config = await this.oidc.getOidcConfig();
|
||||
if (!config) return f('/login?oidc_error=not_configured');
|
||||
if (config.issuer && !config.issuer.startsWith('https://') && readEnv().app.isProduction) {
|
||||
return f('/login?oidc_error=issuer_not_https');
|
||||
@@ -181,11 +181,11 @@ export class OidcController {
|
||||
});
|
||||
}
|
||||
|
||||
this.oidc.touchLastLogin(result.user.id);
|
||||
await this.oidc.touchLastLogin(result.user.id);
|
||||
// Pass the flag through untouched: `undefined` must reach the token as
|
||||
// "absent", not `false`, or the sliding renewal would later downgrade the
|
||||
// default persistent cookie to a browser-session one (remember-me, #1927).
|
||||
const jwtToken = this.oidc.generateToken(result.user, pending.remember);
|
||||
const jwtToken = await this.oidc.generateToken(result.user, pending.remember);
|
||||
const { code: authCode, binding } = this.oidc.createAuthCode(jwtToken, pending.remember);
|
||||
// Bind the code to THIS browser, the way the state cookie binds the callback.
|
||||
// The code rides home in a URL, so it is readable from history, from a
|
||||
|
||||
@@ -306,7 +306,7 @@ export class OidcService implements OnModuleDestroy {
|
||||
// OIDC configuration (env + DB)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
getOidcConfig(): OidcConfig | null {
|
||||
async getOidcConfig(): Promise<OidcConfig | null> {
|
||||
const get = (key: string) =>
|
||||
(this.db.prepare("SELECT value FROM app_settings WHERE key = ?").get(key) as { value: string } | undefined)?.value || null;
|
||||
|
||||
@@ -445,7 +445,7 @@ export class OidcService implements OnModuleDestroy {
|
||||
return base + path;
|
||||
}
|
||||
|
||||
generateToken(user: { id: number }, remember?: boolean): string {
|
||||
async generateToken(user: { id: number }, remember?: boolean): Promise<string> {
|
||||
// Embed the current password_version so an OIDC-issued session is invalidated
|
||||
// by a password change/reset exactly like a password-login session (the auth
|
||||
// middleware compares this `pv` against users.password_version).
|
||||
@@ -768,7 +768,7 @@ export class OidcService implements OnModuleDestroy {
|
||||
// Update last_login timestamp
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
touchLastLogin(userId: number): void {
|
||||
async touchLastLogin(userId: number): Promise<void> {
|
||||
this.db.prepare('UPDATE users SET last_login = CURRENT_TIMESTAMP, login_count = login_count + 1 WHERE id = ?').run(userId);
|
||||
}
|
||||
|
||||
@@ -778,7 +778,7 @@ export class OidcService implements OnModuleDestroy {
|
||||
// settings write: removing the SSO config while password login is off would lock
|
||||
// every user out of the instance.
|
||||
|
||||
getOidcSettings() {
|
||||
async getOidcSettings() {
|
||||
const get = (key: string) =>
|
||||
this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', key)?.value || '';
|
||||
const secret = decrypt_api_key(get('oidc_client_secret'));
|
||||
@@ -811,7 +811,7 @@ export class OidcService implements OnModuleDestroy {
|
||||
this.db.run('INSERT OR REPLACE INTO app_settings (key, value) VALUES (?, ?)', key, val || '');
|
||||
// All five writes are one SSO config — a partial apply would leave the
|
||||
// instance with an issuer but no client id (or vice versa).
|
||||
this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
set('oidc_issuer', data.issuer ?? '');
|
||||
set('oidc_client_id', data.client_id ?? '');
|
||||
if (data.client_secret !== undefined) set('oidc_client_secret', maybe_encrypt_api_key(data.client_secret) ?? '');
|
||||
|
||||
@@ -318,13 +318,13 @@ export class PlaceEnrichmentService {
|
||||
* would mean backfilling a row for every existing install just to keep them
|
||||
* working, and there is nothing here that warrants a migration.
|
||||
*/
|
||||
enrichDisabled(): boolean {
|
||||
async enrichDisabled(): Promise<boolean> {
|
||||
const row = this.database.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', 'places_enrich_enabled');
|
||||
return row?.value === 'false';
|
||||
}
|
||||
|
||||
async enrich(userId: number, req: MapsPlaceEnrichmentRequest): Promise<MapsPlaceEnrichmentResult> {
|
||||
if (this.enrichDisabled()) return { photos: [], description: null, facts: [], disabled: true };
|
||||
if (await this.enrichDisabled()) return { photos: [], description: null, facts: [], disabled: true };
|
||||
|
||||
const placeId = req.placeId?.trim() || `coords:${req.lat}:${req.lng}`;
|
||||
const lang = req.lang;
|
||||
@@ -378,7 +378,7 @@ export class PlaceEnrichmentService {
|
||||
// A summary or a link the lookup here fetched itself is the map's and keeps.
|
||||
const fromCaller = req.details != null
|
||||
&& (description?.source === 'osm' || ownFacts.some((fact) => fact.url != null));
|
||||
if (!fromCaller) this.writeCache(placeId, lang, result);
|
||||
if (!fromCaller) await this.writeCache(placeId, lang, result);
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -842,7 +842,7 @@ export class PlaceEnrichmentService {
|
||||
}
|
||||
}
|
||||
|
||||
private writeCache(placeId: string, lang: string | undefined, value: CachedEnrichment): void {
|
||||
private async writeCache(placeId: string, lang: string | undefined, value: CachedEnrichment): Promise<void> {
|
||||
try {
|
||||
this.database.run(
|
||||
'INSERT OR REPLACE INTO place_details_cache (place_id, lang, expanded, payload_json, fetched_at) VALUES (?, ?, ?, ?, ?)',
|
||||
|
||||
@@ -153,7 +153,7 @@ export class PlacesMcp {
|
||||
});
|
||||
this.guards.safeBroadcast(tripId, 'place:created', { place: result.place });
|
||||
this.guards.safeBroadcast(tripId, 'assignment:created', { assignment: result.assignment });
|
||||
try { this.journey.reconcileTripSkeletons(tripId); } catch { /* non-fatal */ }
|
||||
try { await this.journey.reconcileTripSkeletons(tripId); } catch { /* non-fatal */ }
|
||||
return ok(result);
|
||||
} catch {
|
||||
return { content: [{ type: 'text' as const, text: 'Failed to create place and assignment.' }], isError: true };
|
||||
@@ -257,7 +257,7 @@ export class PlacesMcp {
|
||||
if (!this.places.get(String(tripId), String(placeId))) {
|
||||
return { content: [{ type: 'text' as const, text: 'Place not found.' }], isError: true };
|
||||
}
|
||||
try { this.journey.onPlaceDeleted(placeId); } catch { /* non-fatal */ } // sync journeys before the row is gone
|
||||
try { await this.journey.onPlaceDeleted(placeId); } catch { /* non-fatal */ } // sync journeys before the row is gone
|
||||
// The link is gone once the place is, so read it first (#1298).
|
||||
const expenseIds = this.places.linkedExpenseIds(tripId, [placeId]);
|
||||
const { deleted, cancelled } = await this.places.remove(String(tripId), String(placeId));
|
||||
@@ -433,7 +433,7 @@ export class PlacesMcp {
|
||||
// detach and left the entries as orphans.
|
||||
const scoped = this.places.scopedIds(String(tripId), placeIds);
|
||||
for (const id of scoped) {
|
||||
try { this.journey.onPlaceDeleted(id); } catch { /* non-fatal */ }
|
||||
try { await this.journey.onPlaceDeleted(id); } catch { /* non-fatal */ }
|
||||
}
|
||||
// The link is gone once the places are, so read it first (#1298).
|
||||
const expenseIds = this.places.linkedExpenseIds(tripId, scoped);
|
||||
|
||||
@@ -119,10 +119,16 @@ export class PlacesRpc {
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
/** Journey mirroring never fails a write that already succeeded. */
|
||||
private mirrorJourneys(run: () => void): void {
|
||||
/**
|
||||
* Journey mirroring never fails a write that already succeeded.
|
||||
*
|
||||
* R1.5: `run` wraps a now-async `this.journey.onPlace*` call; its rejection is
|
||||
* swallowed here (void + catch) rather than left unhandled — same "non-fatal"
|
||||
* contract the synchronous try/catch gave it before the sweep.
|
||||
*/
|
||||
private mirrorJourneys(run: () => Promise<void>): void {
|
||||
try {
|
||||
run();
|
||||
void run().catch(() => { /* non-fatal */ });
|
||||
} catch {
|
||||
/* non-fatal */
|
||||
}
|
||||
|
||||
@@ -1594,7 +1594,10 @@ export class PlacesService {
|
||||
}
|
||||
|
||||
// Journey hooks — non-fatal, mirroring the route's try/catch wrappers.
|
||||
onCreated(tripId: string, placeId: number): void { try { this.journey.onPlaceCreated(Number(tripId), placeId); } catch { /* non-fatal */ } }
|
||||
onUpdated(placeId: number): void { try { this.journey.onPlaceUpdated(placeId); } catch { /* non-fatal */ } }
|
||||
onDeleted(placeId: number): void { try { this.journey.onPlaceDeleted(placeId); } catch { /* non-fatal */ } }
|
||||
// R1.5: called fire-and-forget from several sync call sites; onPlace* are now async,
|
||||
// so the rejection is swallowed here (void + catch) rather than left unhandled —
|
||||
// same "non-fatal" contract the try/catch gave it before the sweep.
|
||||
onCreated(tripId: string, placeId: number): void { void this.journey.onPlaceCreated(Number(tripId), placeId).catch(() => { /* non-fatal */ }); }
|
||||
onUpdated(placeId: number): void { void this.journey.onPlaceUpdated(placeId).catch(() => { /* non-fatal */ }); }
|
||||
onDeleted(placeId: number): void { void this.journey.onPlaceDeleted(placeId).catch(() => { /* non-fatal */ }); }
|
||||
}
|
||||
|
||||
@@ -85,7 +85,7 @@ export class JournalEntryRowsController {
|
||||
|
||||
// The entry's journey must be one the caller can access — same gate as a read.
|
||||
const row = this.dbs.connection.prepare('SELECT journey_id FROM journey_entries WHERE id = ?').get(entryId) as { journey_id: number } | undefined;
|
||||
if (!row || !this.journey.canAccessJourney(row.journey_id, userId)) return { providers: [] };
|
||||
if (!row || !(await this.journey.canAccessJourney(row.journey_id, userId))) return { providers: [] };
|
||||
|
||||
const ids = this.hooks.providersOf('journalEntryProvider');
|
||||
const results = await Promise.all(
|
||||
|
||||
@@ -192,7 +192,7 @@ export class RealtimeGateway
|
||||
if (!user || !message?.journeyId) return undefined;
|
||||
|
||||
const journeyId = Number(message.journeyId);
|
||||
if (!Number.isFinite(journeyId) || !this.journeys.canAccessJourney(journeyId, user.id)) {
|
||||
if (!Number.isFinite(journeyId) || !(await this.journeys.canAccessJourney(journeyId, user.id))) {
|
||||
return { type: 'error', message: 'Access denied' };
|
||||
}
|
||||
|
||||
|
||||
@@ -47,12 +47,12 @@ export class TripMembersController {
|
||||
constructor(private readonly roster: TripMembersService, private readonly audit: AuditService) {}
|
||||
|
||||
@Get(':id/members')
|
||||
members(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const access = this.roster.canAccessTrip(id, user.id);
|
||||
async members(@CurrentUser() user: User, @Param('id') id: string) {
|
||||
const access = await this.roster.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
const { owner, members } = this.roster.listMembers(id, access.user_id);
|
||||
const { owner, members } = await this.roster.listMembers(id, access.user_id);
|
||||
return { owner, members, current_user_id: user.id };
|
||||
}
|
||||
|
||||
@@ -60,7 +60,7 @@ export class TripMembersController {
|
||||
@HttpCode(201)
|
||||
async addMember(@CurrentUser() user: User, @Param('id') id: string, @Body() body: TripAddMemberDto) {
|
||||
const { identifier } = body;
|
||||
const access = this.roster.canAccessTrip(id, user.id);
|
||||
const access = await this.roster.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
@@ -68,7 +68,7 @@ export class TripMembersController {
|
||||
throw new HttpException({ error: 'No permission to manage members' }, 403);
|
||||
}
|
||||
try {
|
||||
const result = this.roster.addMember(id, identifier, access.user_id, user.id);
|
||||
const result = await this.roster.addMember(id, identifier, access.user_id, user.id);
|
||||
this.roster.notifyInvite(id, user, result.targetUserId, result.tripTitle, result.member.email);
|
||||
return { member: result.member };
|
||||
} catch (e: unknown) {
|
||||
@@ -80,7 +80,7 @@ export class TripMembersController {
|
||||
|
||||
@Delete(':id/members/:userId')
|
||||
async removeMember(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
const access = this.roster.canAccessTrip(id, user.id);
|
||||
const access = await this.roster.canAccessTrip(id, user.id);
|
||||
if (!access) {
|
||||
throw new HttpException({ error: 'Trip not found' }, 404);
|
||||
}
|
||||
@@ -88,7 +88,7 @@ export class TripMembersController {
|
||||
if (targetId !== user.id && !(await this.roster.can('member_manage', user.role, access.user_id, user.id, access.user_id !== user.id))) {
|
||||
throw new HttpException({ error: 'No permission to remove members' }, 403);
|
||||
}
|
||||
this.roster.removeMember(id, targetId);
|
||||
await this.roster.removeMember(id, targetId);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -104,11 +104,11 @@ export class TripMembersController {
|
||||
) {
|
||||
const { newOwnerId } = body;
|
||||
try {
|
||||
const result = this.roster.transferOwnership(id, newOwnerId, user.id);
|
||||
const result = await this.roster.transferOwnership(id, newOwnerId, user.id);
|
||||
await this.audit.writeAudit({ userId: user.id, action: 'trip.transfer_ownership', ip: getClientIp(req), details: { tripId: Number(id), trip: result.tripTitle, from: result.fromEmail, to: result.toEmail } });
|
||||
// Nudge everyone viewing the trip to re-read it so the new ownership and the
|
||||
// recomputed permissions take effect live.
|
||||
const updatedTrip = this.roster.getTripForViewer(id, user.id);
|
||||
const updatedTrip = await this.roster.getTripForViewer(id, user.id);
|
||||
this.roster.broadcast(id, 'trip:updated', { trip: updatedTrip }, socketId);
|
||||
return { success: true };
|
||||
} catch (e: unknown) {
|
||||
@@ -122,12 +122,12 @@ export class TripMembersController {
|
||||
@HttpCode(201)
|
||||
@UseGuards(TripOwnerGuard)
|
||||
@RequireTripOwner('Only the owner can manage guests', { param: 'id' })
|
||||
createGuest(@CurrentUser() user: User, @Param('id') id: string, @Body() body: TripCreateGuestDto) {
|
||||
async createGuest(@CurrentUser() user: User, @Param('id') id: string, @Body() body: TripCreateGuestDto) {
|
||||
// Whitespace-only names still 400 with the legacy body — the service throws
|
||||
// ValidationError('Guest name is required') after trimming.
|
||||
try {
|
||||
// No notifyInvite: a guest has no inbox.
|
||||
return this.roster.createGuest(id, body.name, user.id);
|
||||
return await this.roster.createGuest(id, body.name, user.id);
|
||||
} catch (e: unknown) {
|
||||
if (e instanceof ValidationError) throw new HttpException({ error: e.message }, 400);
|
||||
throw e;
|
||||
@@ -137,9 +137,9 @@ export class TripMembersController {
|
||||
@Put(':id/guests/:userId')
|
||||
@UseGuards(TripOwnerGuard)
|
||||
@RequireTripOwner('Only the owner can manage guests', { param: 'id' })
|
||||
renameGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body() body: TripRenameGuestDto) {
|
||||
async renameGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string, @Body() body: TripRenameGuestDto) {
|
||||
try {
|
||||
if (!this.roster.renameGuest(id, Number.parseInt(userId), body.name)) {
|
||||
if (!(await this.roster.renameGuest(id, Number.parseInt(userId), body.name))) {
|
||||
throw new HttpException({ error: 'Guest not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
|
||||
@@ -74,7 +74,7 @@ export class TripMembersService {
|
||||
return this.dbs.connection;
|
||||
}
|
||||
|
||||
canAccessTrip(tripId: string | number, userId: number) {
|
||||
async canAccessTrip(tripId: string | number, userId: number) {
|
||||
return this.dbs.canAccessTrip(tripId, userId) as { user_id: number } | null | undefined;
|
||||
}
|
||||
|
||||
@@ -88,7 +88,7 @@ export class TripMembersService {
|
||||
|
||||
/** The trip in list shape, for the re-read a handover broadcasts. Same query the
|
||||
* trip routes use, imported rather than copied so the two cannot drift. */
|
||||
getTripForViewer(tripId: string | number, userId: number) {
|
||||
async getTripForViewer(tripId: string | number, userId: number) {
|
||||
return this.db.prepare(`${TRIP_SELECT} WHERE t.id = :tripId`).get({ userId, tripId });
|
||||
}
|
||||
|
||||
@@ -109,7 +109,7 @@ export class TripMembersService {
|
||||
|
||||
// ── Members ───────────────────────────────────────────────────────────────
|
||||
|
||||
listMembers(tripId: string | number, tripOwnerId: number) {
|
||||
async listMembers(tripId: string | number, tripOwnerId: number) {
|
||||
// u.is_guest rides along (#1362) so guests stay assignable everywhere a member is,
|
||||
// while the UI can badge them and suppress owner-only actions. The owner is never a guest.
|
||||
const members = this.db.prepare(`
|
||||
@@ -134,7 +134,7 @@ export class TripMembersService {
|
||||
};
|
||||
}
|
||||
|
||||
addMember(tripId: string | number, identifier: string, tripOwnerId: number, invitedByUserId: number): AddMemberResult {
|
||||
async addMember(tripId: string | number, identifier: string, tripOwnerId: number, invitedByUserId: number): Promise<AddMemberResult> {
|
||||
if (!identifier) throw new ValidationError('Email or username required');
|
||||
|
||||
// Guests (#1362) are not invitable accounts — exclude them so a trip-scoped guest
|
||||
@@ -162,7 +162,7 @@ export class TripMembersService {
|
||||
};
|
||||
}
|
||||
|
||||
removeMember(tripId: string | number, targetUserId: number): void {
|
||||
async removeMember(tripId: string | number, targetUserId: number): Promise<void> {
|
||||
this.db.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(tripId, targetUserId);
|
||||
}
|
||||
|
||||
@@ -172,11 +172,11 @@ export class TripMembersService {
|
||||
* becomes a regular member, so nobody loses access. Runs in a transaction so the
|
||||
* owner pointer and the membership rows never diverge.
|
||||
*/
|
||||
transferOwnership(
|
||||
async transferOwnership(
|
||||
tripId: string | number,
|
||||
newOwnerId: number,
|
||||
currentOwnerId: number,
|
||||
): TransferOwnershipResult {
|
||||
): Promise<TransferOwnershipResult> {
|
||||
const trip = this.db.prepare('SELECT id, title, user_id FROM trips WHERE id = ?').get(tripId) as { id: number; title: string; user_id: number } | undefined;
|
||||
if (!trip) throw new NotFoundError('Trip not found');
|
||||
if (trip.user_id !== currentOwnerId) throw new ValidationError('Only the owner can transfer ownership');
|
||||
@@ -192,14 +192,13 @@ export class TripMembersService {
|
||||
|
||||
const fromEmail = (this.db.prepare('SELECT email FROM users WHERE id = ?').get(currentOwnerId) as { email: string } | undefined)?.email || '';
|
||||
|
||||
const run = this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
this.db.prepare('UPDATE trips SET user_id = ? WHERE id = ?').run(newOwnerId, tripId);
|
||||
// The new owner is no longer a plain member…
|
||||
this.db.prepare('DELETE FROM trip_members WHERE trip_id = ? AND user_id = ?').run(tripId, newOwnerId);
|
||||
// …and the former owner keeps access as a member.
|
||||
this.db.prepare('INSERT OR IGNORE INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, currentOwnerId, newOwnerId);
|
||||
});
|
||||
run();
|
||||
|
||||
return { tripTitle: trip.title, fromEmail, toEmail: newOwner.email };
|
||||
}
|
||||
@@ -208,7 +207,7 @@ export class TripMembersService {
|
||||
|
||||
/** username is UNIQUE across all users — keep the typed name but disambiguate guests
|
||||
* that happen to share it (e.g. two "Anna"s) with a numeric suffix. */
|
||||
createGuest(tripId: string | number, name: string, invitedByUserId: number): { member: GuestMember } {
|
||||
async createGuest(tripId: string | number, name: string, invitedByUserId: number): Promise<{ member: GuestMember }> {
|
||||
const display = (name || '').trim();
|
||||
if (!display) throw new ValidationError('Guest name is required');
|
||||
if (display.length > 50) throw new ValidationError('Guest name must be 50 characters or fewer');
|
||||
@@ -219,31 +218,30 @@ export class TripMembersService {
|
||||
const email = `guest-${randomUUID()}@guests.invalid`;
|
||||
const username = `guest-${randomUUID()}`;
|
||||
|
||||
const create = this.db.transaction(() => {
|
||||
const guestId = await this.uow.transactional(async () => {
|
||||
const res = this.db.prepare(
|
||||
"INSERT INTO users (username, email, password_hash, role, is_guest, display_name) VALUES (?, ?, '', 'user', 1, ?)"
|
||||
).run(username, email, display);
|
||||
const guestId = Number(res.lastInsertRowid);
|
||||
this.db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, guestId, invitedByUserId);
|
||||
return guestId;
|
||||
const newGuestId = Number(res.lastInsertRowid);
|
||||
this.db.prepare('INSERT INTO trip_members (trip_id, user_id, invited_by) VALUES (?, ?, ?)').run(tripId, newGuestId, invitedByUserId);
|
||||
return newGuestId;
|
||||
});
|
||||
const guestId = create();
|
||||
|
||||
return { member: { id: guestId, username: display, email, role: 'member', is_guest: true, avatar_url: null } };
|
||||
}
|
||||
|
||||
/** Confirms a user id is a guest of THIS trip, so guest mutations stay trip-scoped. */
|
||||
private guestOfTrip(tripId: string | number, guestUserId: number): boolean {
|
||||
private async guestOfTrip(tripId: string | number, guestUserId: number): Promise<boolean> {
|
||||
return !!this.db.prepare(
|
||||
'SELECT u.id FROM users u JOIN trip_members m ON m.user_id = u.id WHERE u.id = ? AND m.trip_id = ? AND u.is_guest = 1'
|
||||
).get(guestUserId, tripId);
|
||||
}
|
||||
|
||||
renameGuest(tripId: string | number, guestUserId: number, name: string): boolean {
|
||||
async renameGuest(tripId: string | number, guestUserId: number, name: string): Promise<boolean> {
|
||||
const display = (name || '').trim();
|
||||
if (!display) throw new ValidationError('Guest name is required');
|
||||
if (display.length > 50) throw new ValidationError('Guest name must be 50 characters or fewer');
|
||||
if (!this.guestOfTrip(tripId, guestUserId)) return false;
|
||||
if (!(await this.guestOfTrip(tripId, guestUserId))) return false;
|
||||
|
||||
// Rename only the display name — no global-uniqueness dedup, so a rename to a name
|
||||
// another trip's guest already uses no longer produces "Name 2" (#1446).
|
||||
@@ -252,7 +250,7 @@ export class TripMembersService {
|
||||
}
|
||||
|
||||
async deleteGuest(tripId: string | number, guestUserId: number): Promise<boolean> {
|
||||
if (!this.guestOfTrip(tripId, guestUserId)) return false;
|
||||
if (!(await this.guestOfTrip(tripId, guestUserId))) return false;
|
||||
// A guest is still a user id a plugin may hold data for, so erase that too — the
|
||||
// host-side per-user tables + a durable own-db erasure per granted plugin — exactly
|
||||
// like a full account deletion (otherwise a deleted guest's plugin data lingers).
|
||||
|
||||
@@ -55,7 +55,7 @@ export class TripReadModelService {
|
||||
|
||||
const ownerRow = this.getOwner(tripId);
|
||||
if (!ownerRow) return null;
|
||||
const { owner, members } = this.members.listMembers(tripId, ownerRow.user_id);
|
||||
const { owner, members } = await this.members.listMembers(tripId, ownerRow.user_id);
|
||||
|
||||
const { days: rawDays } = await this.days.list(tripId);
|
||||
const days = rawDays.map(({ notes_items, ...day }) => ({ ...day, notes: notes_items }));
|
||||
@@ -99,7 +99,7 @@ export class TripReadModelService {
|
||||
/** Aggregates every trip sub-collection for offline caching (legacy /:id/bundle). */
|
||||
async bundle(tripId: string, trip: { user_id: number }, viewerId: number) {
|
||||
const { days } = await this.days.list(tripId);
|
||||
const { owner, members } = this.members.listMembers(tripId, trip.user_id);
|
||||
const { owner, members } = await this.members.listMembers(tripId, trip.user_id);
|
||||
return {
|
||||
trip,
|
||||
days,
|
||||
|
||||
@@ -335,7 +335,7 @@ export class TripsMcp {
|
||||
if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
const ownerRow = this.trips.getOwner(tripId);
|
||||
if (!ownerRow) return noAccess();
|
||||
const { owner, members } = this.members.listMembers(tripId, ownerRow.user_id);
|
||||
const { owner, members } = await this.members.listMembers(tripId, ownerRow.user_id);
|
||||
return ok({ owner, members });
|
||||
}
|
||||
|
||||
@@ -359,7 +359,7 @@ export class TripsMcp {
|
||||
// that setting (and the admin bypass inside checkPermission) where this did not.
|
||||
if (!(await this.guards.hasTripPermission('member_manage', tripId, ctx.userId))) return permissionDenied();
|
||||
try {
|
||||
const result = this.members.addMember(tripId, identifier, ownerRow.user_id, ctx.userId);
|
||||
const result = await this.members.addMember(tripId, identifier, ownerRow.user_id, ctx.userId);
|
||||
this.guards.safeBroadcast(tripId, 'member:added', { member: result.member });
|
||||
return ok({ member: result.member });
|
||||
} catch (err) {
|
||||
@@ -385,7 +385,7 @@ export class TripsMcp {
|
||||
// requirement: the same self-removal bypass DELETE /api/trips/:id/members/:userId has.
|
||||
if (memberId !== ctx.userId && !(await this.guards.hasTripPermission('member_manage', tripId, ctx.userId)))
|
||||
return permissionDenied();
|
||||
this.members.removeMember(tripId, memberId);
|
||||
await this.members.removeMember(tripId, memberId);
|
||||
this.guards.safeBroadcast(tripId, 'member:removed', { userId: memberId });
|
||||
return ok({ success: true });
|
||||
}
|
||||
@@ -408,7 +408,7 @@ export class TripsMcp {
|
||||
// owner calling this would get a success that changed nothing. Say so instead.
|
||||
if (ownerRow.user_id === ctx.userId)
|
||||
return errorResult('You own this trip, so you cannot leave it. Hand it to another member first, or delete it.');
|
||||
this.members.removeMember(tripId, ctx.userId);
|
||||
await this.members.removeMember(tripId, ctx.userId);
|
||||
this.guards.safeBroadcast(tripId, 'member:removed', { userId: ctx.userId });
|
||||
return ok({ success: true });
|
||||
}
|
||||
@@ -441,7 +441,7 @@ export class TripsMcp {
|
||||
return { content: [{ type: 'text' as const, text: 'Only the trip owner can manage guests.' }], isError: true };
|
||||
try {
|
||||
// No notifyInvite: a guest has no inbox.
|
||||
const { member } = this.members.createGuest(tripId, name, ctx.userId);
|
||||
const { member } = await this.members.createGuest(tripId, name, ctx.userId);
|
||||
this.guards.safeBroadcast(tripId, 'member:added', { member });
|
||||
return ok({ member });
|
||||
} catch (err) {
|
||||
@@ -468,7 +468,7 @@ export class TripsMcp {
|
||||
if (!ownerRow || ownerRow.user_id !== ctx.userId)
|
||||
return { content: [{ type: 'text' as const, text: 'Only the trip owner can manage guests.' }], isError: true };
|
||||
try {
|
||||
if (!this.members.renameGuest(tripId, guestId, name))
|
||||
if (!(await this.members.renameGuest(tripId, guestId, name)))
|
||||
return { content: [{ type: 'text' as const, text: 'Guest not found.' }], isError: true };
|
||||
} catch (err) {
|
||||
const msg = err instanceof ValidationError ? err.message : 'Failed to rename guest.';
|
||||
@@ -580,7 +580,7 @@ export class TripsMcp {
|
||||
if (id === null || !this.trips.canAccessTrip(id, ctx.userId)) return accessDenied(uri.href);
|
||||
const ownerRow = this.trips.getOwner(id);
|
||||
if (!ownerRow) return accessDenied(uri.href);
|
||||
const { owner, members } = this.members.listMembers(id, ownerRow.user_id);
|
||||
const { owner, members } = await this.members.listMembers(id, ownerRow.user_id);
|
||||
return jsonContent(uri.href, { owner, members });
|
||||
}
|
||||
|
||||
|
||||
@@ -187,7 +187,7 @@ export class TripsRpc {
|
||||
// Ownership transfer is a separate, deliberate action.
|
||||
const trip = this.db.prepare('SELECT user_id FROM trips WHERE id = ?').get(tripId) as { user_id: number } | undefined;
|
||||
if (trip && trip.user_id === targetUserId) throw new ForbiddenResource('cannot remove the trip owner');
|
||||
this.roster.removeMember(tripId, targetUserId);
|
||||
await this.roster.removeMember(tripId, targetUserId);
|
||||
return { removed: true };
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user