refactor(reservations, booking-import, calendar, integrations, roadtrip): async DB-touching methods; transactions through UnitOfWork

This commit is contained in:
jubnl
2026-09-22 06:11:41 +02:00
parent a1fbfe6d75
commit 869d139412
57 changed files with 1073 additions and 1050 deletions
@@ -35,7 +35,7 @@ export class BookingImportService {
return this.dbs.connection;
}
private resolveDayId(tripId: string, iso: string | null | undefined): number | null {
private async resolveDayId(tripId: string, iso: string | null | undefined): Promise<number | null> {
if (!iso) return null;
const date = iso.slice(0, 10);
if (!/^\d{4}-\d{2}-\d{2}$/.test(date)) return null;
@@ -284,8 +284,8 @@ export class BookingImportService {
// the accommodation row is actually inserted (createReservation gates on them).
let createAccommodation: { place_id?: number; start_day_id?: number; end_day_id?: number; check_in?: string; check_out?: string; confirmation?: string } | undefined;
if (item.type === 'hotel' && _accommodation) {
const startDayId = this.resolveDayId(tripId, _accommodation.check_in);
const endDayId = this.resolveDayId(tripId, _accommodation.check_out);
const startDayId = await this.resolveDayId(tripId, _accommodation.check_in);
const endDayId = await this.resolveDayId(tripId, _accommodation.check_out);
createAccommodation = {
place_id: placeId,
start_day_id: startDayId ?? undefined,
+4 -4
View File
@@ -144,7 +144,7 @@ export class CalendarService {
* because a user-supplied SUMMARY can legitimately contain the literal
* "END:VEVENT". Handing out the parts removes the need to reassemble them.
*/
buildTripCalendar(tripId: string | number): TripCalendar {
async buildTripCalendar(tripId: string | number): Promise<TripCalendar> {
const trip = this.db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as any;
if (!trip) throw new NotFoundError('Trip not found');
@@ -316,7 +316,7 @@ export class CalendarService {
// Transport/flight reservations carry no top-level reservation_time; their
// times live per endpoint (local_date + local_time) in reservation_endpoints.
const endpointsMap = this.reservations.loadEndpointsByTrip(tripId);
const endpointsMap = await this.reservations.loadEndpointsByTrip(tripId);
const isDate = (s: string | null | undefined) => !!s && /^\d{4}-\d{2}-\d{2}$/.test(s);
const isTime = (s: string | null | undefined) => !!s && /^\d{2}:\d{2}/.test(s);
@@ -746,8 +746,8 @@ export class CalendarService {
}
/** One trip's calendar as a finished, foldable VCALENDAR document. */
exportICS(tripId: string | number): { ics: string; filename: string } {
const cal = this.buildTripCalendar(tripId);
async exportICS(tripId: string | number): Promise<{ ics: string; filename: string }> {
const cal = await this.buildTripCalendar(tripId);
const ics =
CALENDAR_HEADER +
`X-WR-CALNAME:${cal.calName}\r\n` +
+4 -4
View File
@@ -42,8 +42,8 @@ export class FeedsPublicController {
constructor(private readonly feeds: FeedsService) {}
@Get('trip/:token.ics')
tripFeed(@Param('token') token: string, @Res() res: Response): void {
const result = this.feeds.buildTripIcs(token);
async tripFeed(@Param('token') token: string, @Res() res: Response): Promise<void> {
const result = await this.feeds.buildTripIcs(token);
if (!result) {
res.status(404).json({ error: 'Feed not found' });
return;
@@ -56,8 +56,8 @@ export class FeedsPublicController {
}
@Get('user/:token.ics')
userFeed(@Param('token') token: string, @Res() res: Response): void {
const result = this.feeds.buildUserIcs(token);
async userFeed(@Param('token') token: string, @Res() res: Response): Promise<void> {
const result = await this.feeds.buildUserIcs(token);
if (!result) {
res.status(404).json({ error: 'Feed not found' });
return;
+4 -4
View File
@@ -108,13 +108,13 @@ export class FeedsService {
// ── ICS generation ───────────────────────────────────────────────────────
buildTripIcs(token: string): { ics: string; filename: string } | null {
async buildTripIcs(token: string): Promise<{ ics: string; filename: string } | null> {
const row = this.db.prepare('SELECT id FROM trips WHERE feed_token = ?').get(token) as
| { id: number }
| undefined;
if (!row) return null;
try {
const cal = this.calendar.buildTripCalendar(row.id);
const cal = await this.calendar.buildTripCalendar(row.id);
// Same document as the one-time download, plus the subscription refresh
// hints so clients re-fetch hourly. Assembled from the calendar's parts
// rather than string-surgeried into the finished text.
@@ -132,7 +132,7 @@ export class FeedsService {
}
}
buildUserIcs(token: string): { ics: string; calName: string } | null {
async buildUserIcs(token: string): Promise<{ ics: string; calName: string } | null> {
const user = this.db.prepare('SELECT id, username FROM users WHERE feed_token = ?').get(token) as
| { id: number; username: string }
| undefined;
@@ -168,7 +168,7 @@ export class FeedsService {
let events = '';
for (const { id } of trips) {
try {
const cal = this.calendar.buildTripCalendar(id);
const cal = await this.calendar.buildTripCalendar(id);
for (const [tzid, block] of cal.timezones) {
if (!zones.has(tzid)) zones.set(tzid, block);
}
@@ -122,7 +122,7 @@ export class AirtrailImportService {
socketId: string | undefined,
connections: string[][] = [],
): Promise<AirtrailImportResult> {
const creds = this.airtrail.getAirtrailCredentials(userId);
const creds = await this.airtrail.getAirtrailCredentials(userId);
if (!creds) throw new AirtrailRequestError('AirTrail is not connected', 400);
const wanted = new Set(flightIds.map(String));
@@ -40,18 +40,18 @@ export class AirtrailLinkService {
return row?.value !== 'false';
}
broadcastUpdated(tripId: number, reservationId: number): void {
async broadcastUpdated(tripId: number, reservationId: number): Promise<void> {
try {
const reservation = this.reads.getReservationWithJoins(reservationId);
const reservation = await this.reads.getReservationWithJoins(reservationId);
if (reservation) this.realtime.broadcast(String(tripId), 'reservation:updated', { reservation } as never, undefined);
} catch {
/* broadcast failure is non-fatal */
}
}
detach(tripId: number, reservationId: number): void {
async detach(tripId: number, reservationId: number): Promise<void> {
this.db.run('UPDATE reservations SET sync_enabled = 0 WHERE id = ?', reservationId);
this.broadcastUpdated(tripId, reservationId);
await this.broadcastUpdated(tripId, reservationId);
}
/**
@@ -61,7 +61,7 @@ export class AirtrailLinkService {
* side: a pull flattens the layover chain back to from→to, a push rewrites the
* AirTrail flight to span the whole route (#1535).
*/
hasLocalMultiLegShape(reservationId: number, metadataJson: string | null | undefined): boolean {
async hasLocalMultiLegShape(reservationId: number, metadataJson: string | null | undefined): Promise<boolean> {
try {
const meta = metadataJson ? JSON.parse(metadataJson) : {};
if (Array.isArray(meta?.legs) && meta.legs.length > 1) return true;
@@ -96,21 +96,21 @@ export class AirtrailLinkService {
// 1:1 mapping to the AirTrail flight: pushing would rewrite that flight to the
// full span, and the next pull would flatten the layover again. Detach — the
// merge is a deliberate local restructuring, like a joined import (#1535).
const reservation = this.reads.getReservationWithJoins(row.id);
const reservation = await this.reads.getReservationWithJoins(row.id);
if (!reservation) return;
if (this.hasLocalMultiLegShape(row.id, (reservation as { metadata?: string | null }).metadata)) {
this.detach(tripId, row.id);
if (await this.hasLocalMultiLegShape(row.id, (reservation as { metadata?: string | null }).metadata)) {
await this.detach(tripId, row.id);
return;
}
// AirTrail is read-only by default (#1240). Only push when the flight's owner has
// explicitly opted in. A no-op skip (not a detach): the link stays active so the
// inbound, AirTrail-wins pull keeps the reservation up to date.
if (!row.external_owner_user_id || !this.airtrail.isAirtrailWriteEnabled(row.external_owner_user_id)) return;
if (!row.external_owner_user_id || !(await this.airtrail.isAirtrailWriteEnabled(row.external_owner_user_id))) return;
const creds: AirtrailCreds | null = this.airtrail.getAirtrailCredentials(row.external_owner_user_id);
const creds: AirtrailCreds | null = await this.airtrail.getAirtrailCredentials(row.external_owner_user_id);
if (!creds) {
this.detach(tripId, row.id); // owner disconnected — cannot push, so stop syncing
await this.detach(tripId, row.id); // owner disconnected — cannot push, so stop syncing
return;
}
@@ -118,12 +118,12 @@ export class AirtrailLinkService {
try {
existing = await this.client.getFlight(creds, Number(row.external_id));
} catch (err) {
if (err instanceof AirtrailAuthError) this.detach(tripId, row.id);
if (err instanceof AirtrailAuthError) await this.detach(tripId, row.id);
else logError(`AirTrail push: get failed for reservation ${row.id}: ${err instanceof Error ? err.message : err}`);
return;
}
if (!existing) {
this.detach(tripId, row.id); // gone in AirTrail → treat like a remote delete
await this.detach(tripId, row.id); // gone in AirTrail → treat like a remote delete
return;
}
@@ -19,7 +19,7 @@ export class AirtrailSyncJob implements OnApplicationBootstrap {
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
async onApplicationBootstrap(): Promise<void> {
if (!this.registrar.isEnabled()) return;
const value = this.db.get<{ value: string }>('SELECT value FROM app_settings WHERE key = ?', 'airtrail_poll_interval_minutes')?.value;
const raw = Number.parseInt(value || '5', 10);
@@ -52,7 +52,7 @@ export class AirtrailSyncService {
* flights are never auto-added to a trip. Returns how many rows changed.
*/
private async syncOwner(uid: number): Promise<number> {
const creds = this.airtrail.getAirtrailCredentials(uid);
const creds = await this.airtrail.getAirtrailCredentials(uid);
if (!creds) return 0; // owner disconnected — leave their linked rows as-is
let flights: AirtrailFlightRaw[];
@@ -73,7 +73,7 @@ export class AirtrailSyncService {
for (const row of linked) {
const flight = byId.get(String(row.external_id));
if (!flight) {
this.link.detach(row.trip_id, row.id); // deleted in AirTrail → keep row, stop syncing
await this.link.detach(row.trip_id, row.id); // deleted in AirTrail → keep row, stop syncing
changed++;
continue;
}
@@ -81,12 +81,12 @@ export class AirtrailSyncService {
const hash = canonicalHash(flight);
if (hash === row.external_hash) continue;
const current = this.reservations.getReservation(row.id, row.trip_id);
const current = await this.reservations.getReservation(row.id, row.trip_id);
if (!current) continue;
if (this.link.hasLocalMultiLegShape(row.id, (current as any).metadata)) {
if (await this.link.hasLocalMultiLegShape(row.id, (current as any).metadata)) {
// The user connected this flight into a multi-leg booking; applying the
// remote single-flight shape would flatten it. Stop syncing instead.
this.link.detach(row.trip_id, row.id);
await this.link.detach(row.trip_id, row.id);
changed++;
continue;
}
@@ -98,7 +98,7 @@ export class AirtrailSyncService {
new Date().toISOString(),
row.id,
);
this.link.broadcastUpdated(row.trip_id, row.id);
await this.link.broadcastUpdated(row.trip_id, row.id);
changed++;
} catch (err) {
logError(`AirTrail sync: failed to update reservation ${row.id}: ${err instanceof Error ? err.message : err}`);
@@ -38,7 +38,7 @@ export class AirtrailService {
private readonly client: AirtrailClient,
) {}
private readRow(userId: number): UserConnRow | undefined {
private async readRow(userId: number): Promise<UserConnRow | undefined> {
return this.db.get<UserConnRow>(
'SELECT airtrail_url, airtrail_api_key, airtrail_allow_insecure_tls, airtrail_write_enabled FROM users WHERE id = ?',
userId,
@@ -46,7 +46,7 @@ export class AirtrailService {
}
/** Has this user opted in to TREK writing their flight edits back to AirTrail? (#1240) */
isAirtrailWriteEnabled(userId: number): boolean {
async isAirtrailWriteEnabled(userId: number): Promise<boolean> {
const row = this.db.get<{ airtrail_write_enabled?: number | null }>(
'SELECT airtrail_write_enabled FROM users WHERE id = ?',
userId,
@@ -55,8 +55,8 @@ export class AirtrailService {
}
/** Decrypted creds for outbound calls, or null when the user has no connection. */
getAirtrailCredentials(userId: number): AirtrailCreds | null {
const row = this.readRow(userId);
async getAirtrailCredentials(userId: number): Promise<AirtrailCreds | null> {
const row = await this.readRow(userId);
if (!row?.airtrail_url || !row?.airtrail_api_key) return null;
const apiKey = decrypt_api_key(row.airtrail_api_key);
if (!apiKey) return null;
@@ -68,8 +68,8 @@ export class AirtrailService {
}
/** Settings as shown in the UI — the key is never echoed, only masked. */
getConnectionSettings(userId: number) {
const row = this.readRow(userId);
async getConnectionSettings(userId: number) {
const row = await this.readRow(userId);
return {
url: row?.airtrail_url || '',
apiKeyMasked: row?.airtrail_api_key ? KEY_MASK : '',
@@ -148,7 +148,7 @@ export class AirtrailService {
async getConnectionStatus(
userId: number,
): Promise<{ connected: boolean; flightCount?: number; error?: string }> {
const creds = this.getAirtrailCredentials(userId);
const creds = await this.getAirtrailCredentials(userId);
if (!creds) return { connected: false, error: 'Not configured' };
return this.probe(creds);
}
@@ -173,7 +173,7 @@ export class AirtrailService {
const trimmedUrl = (url || '').trim();
const provided = (apiKey || '').trim();
const stored = this.getAirtrailCredentials(userId);
const stored = await this.getAirtrailCredentials(userId);
const effectiveUrl = trimmedUrl || stored?.baseUrl;
const typedKey = provided && provided !== KEY_MASK ? provided : '';
@@ -199,7 +199,7 @@ export class AirtrailService {
/** The user's AirTrail flights, normalized for the import picker. */
async getFlightsForPicker(userId: number): Promise<AirtrailFlight[]> {
const creds = this.getAirtrailCredentials(userId);
const creds = await this.getAirtrailCredentials(userId);
if (!creds) throw new AirtrailRequestError('AirTrail is not connected', 400);
const raw = await this.client.listFlights(creds);
return raw.map(normalizeFlight);
@@ -64,8 +64,8 @@ export class DawarichSuggestionsService {
* someone's location history, and a forgotten filter over a wider read is how
* that leaks.
*/
list(userId: number, filter: { tripId?: number; state?: string }): DawarichSuggestionList {
this.reopenOrphaned(userId);
async list(userId: number, filter: { tripId?: number; state?: string }): Promise<DawarichSuggestionList> {
await this.reopenOrphaned(userId);
const clauses = ['s.user_id = ?'];
const params: unknown[] = [userId];
@@ -88,7 +88,7 @@ export class DawarichSuggestionsService {
...params,
);
const connection = this.dawarich.getConnection(userId);
const connection = await this.dawarich.getConnection(userId);
return {
suggestions: rows.map(toWire),
connected: connection.connected,
@@ -115,7 +115,7 @@ export class DawarichSuggestionsService {
* at read time, which would make the list say "back in review" while `accept`
* still refused the row as already accepted.
*/
private reopenOrphaned(userId: number): void {
private async reopenOrphaned(userId: number): Promise<void> {
this.db.run(
`UPDATE dawarich_visit_suggestions
SET state = 'new', target = NULL, accepted_hash = NULL,
@@ -136,7 +136,7 @@ export class DawarichSuggestionsService {
);
}
getOne(userId: number, id: number): DawarichSuggestion | null {
async getOne(userId: number, id: number): Promise<DawarichSuggestion | null> {
const row = this.db.get<SuggestionJoinRow>(
`SELECT s.*, t.title AS trip_title, b.name AS matched_bucket_name
FROM dawarich_visit_suggestions s
@@ -157,7 +157,7 @@ export class DawarichSuggestionsService {
* not offered — the place or entry it produced is a separate thing now, and
* "undo" would have to guess whether to delete it.
*/
setState(userId: number, id: number, state: 'new' | 'dismissed'): DawarichSuggestion | null {
async setState(userId: number, id: number, state: 'new' | 'dismissed'): Promise<DawarichSuggestion | null> {
const row = this.db.get<{ id: number; state: string }>(
'SELECT id, state FROM dawarich_visit_suggestions WHERE id = ? AND user_id = ?',
id,
@@ -256,7 +256,7 @@ export class DawarichSuggestionsService {
this.db.run("UPDATE places SET source = 'dawarich' WHERE id = ?", id);
const day = body.dayId !== undefined ? await this.assignments.createAssignment(body.dayId, id, null) : undefined;
this.markAccepted(row.id, 'place', { placeId: id });
await this.markAccepted(row.id, 'place', { placeId: id });
// Re-read, so what goes out on the wire carries the source: everyone else
// on the trip should see the Dawarich mark on it too, not only the person
// who accepted it.
@@ -277,7 +277,7 @@ export class DawarichSuggestionsService {
}
return {
suggestion: this.getOne(userId, row.id)!,
suggestion: (await this.getOne(userId, row.id))!,
createdPlaceId: placeId,
createdJournalEntryId: null,
bucketListItemId: null,
@@ -331,11 +331,11 @@ export class DawarichSuggestionsService {
sid,
);
if (!created) throw new AcceptError('journal_forbidden', 'Journey not found', 404);
this.markAccepted(row.id, 'journal', { journalEntryId: created.id });
await this.markAccepted(row.id, 'journal', { journalEntryId: created.id });
return created;
});
return {
suggestion: this.getOne(userId, row.id)!,
suggestion: (await this.getOne(userId, row.id))!,
createdPlaceId: null,
createdJournalEntryId: entry.id,
bucketListItemId: null,
@@ -343,7 +343,7 @@ export class DawarichSuggestionsService {
}
/** A stay ticks off a wish. The wish must be the caller's own. */
private acceptAsBucketTick(userId: number, row: SuggestionRow, body: DawarichAccept): DawarichAcceptResult {
private async acceptAsBucketTick(userId: number, row: SuggestionRow, body: DawarichAccept): Promise<DawarichAcceptResult> {
const itemId = body.bucketListItemId ?? row.matched_bucket_list_item_id;
if (!itemId) {
throw new AcceptError('bucket_required', 'A bucket-list entry is required', 400);
@@ -355,18 +355,18 @@ export class DawarichSuggestionsService {
);
if (!item) throw new AcceptError('not_found', 'Bucket-list entry not found', 404);
this.db.transaction(() => {
await this.uow.transactional(async () => {
this.db.run(
"UPDATE bucket_list SET visited_at = ?, visited_source = 'dawarich' WHERE id = ? AND user_id = ?",
row.started_at,
itemId,
userId,
);
this.markAccepted(row.id, 'bucket_list', { bucketItemId: itemId });
await this.markAccepted(row.id, 'bucket_list', { bucketItemId: itemId });
});
return {
suggestion: this.getOne(userId, row.id)!,
suggestion: (await this.getOne(userId, row.id))!,
createdPlaceId: null,
createdJournalEntryId: null,
bucketListItemId: itemId,
@@ -400,11 +400,11 @@ export class DawarichSuggestionsService {
* answerable at all: without it there is nothing to compare the current hash
* against, and the flag would either never fire or fire forever.
*/
private markAccepted(
private async markAccepted(
id: number,
target: 'place' | 'journal' | 'bucket_list',
ids: { placeId?: number; journalEntryId?: number; bucketItemId?: number },
): void {
): Promise<void> {
this.db.run(
`UPDATE dawarich_visit_suggestions
SET state = 'accepted', target = ?, accepted_place_id = ?,
@@ -435,7 +435,7 @@ export class DawarichSuggestionsService {
* eighty wishes must not be told their other thirty had no match.
*/
async scanBucketList(userId: number): Promise<DawarichBucketScan> {
const creds = this.dawarich.getCredentials(userId);
const creds = await this.dawarich.getCredentials(userId);
if (!creds) throw new AcceptError('not_connected', 'Dawarich is not connected', 400);
const items = this.db.all<BucketRow>(
@@ -515,17 +515,17 @@ export class DawarichSuggestionsService {
}
/** Tick off wishes the user confirmed after reading a scan. */
confirmBucketVisits(userId: number, itemIds: number[], visitedAt?: string): number {
async confirmBucketVisits(userId: number, itemIds: number[], visitedAt?: string): Promise<number> {
const now = new Date().toISOString();
let updated = 0;
this.db.transaction(() => {
await this.uow.transactional(async () => {
for (const itemId of itemIds) {
// The date is the one the wish was actually reached on. A wish somebody
// got to in 2023 ticked off with today's date is a wrong entry in a list
// people keep for years, so "now" is only the answer when nothing else
// knows better: the caller's own value first, then the stay this wish
// was matched to, then the clock.
const stamp = visitedAt ?? this.matchedStayStart(userId, itemId) ?? now;
const stamp = visitedAt ?? (await this.matchedStayStart(userId, itemId)) ?? now;
const result = this.db.run(
"UPDATE bucket_list SET visited_at = ?, visited_source = 'dawarich' WHERE id = ? AND user_id = ? AND visited_at IS NULL",
stamp,
@@ -539,7 +539,7 @@ export class DawarichSuggestionsService {
}
/** When the stay that claimed this wish began, if one did. */
private matchedStayStart(userId: number, itemId: number): string | null {
private async matchedStayStart(userId: number, itemId: number): Promise<string | null> {
const row = this.db.get<{ started_at: string }>(
`SELECT started_at FROM dawarich_visit_suggestions
WHERE user_id = ? AND matched_bucket_list_item_id = ?
@@ -551,7 +551,7 @@ export class DawarichSuggestionsService {
}
/** Undo a tick. Clears the source with it, so the entry reads as untouched again. */
clearBucketVisit(userId: number, itemId: number): boolean {
async clearBucketVisit(userId: number, itemId: number): Promise<boolean> {
const result = this.db.run(
'UPDATE bucket_list SET visited_at = NULL, visited_source = NULL WHERE id = ? AND user_id = ?',
itemId,
@@ -577,7 +577,7 @@ export class DawarichSuggestionsService {
* country the user went to, and silently losing it would be the worse bug.
*/
async atlasSuggestions(userId: number, from: Date, to: Date): Promise<DawarichAtlasSuggestions> {
const creds = this.dawarich.getCredentials(userId);
const creds = await this.dawarich.getCredentials(userId);
if (!creds) throw new AcceptError('not_connected', 'Dawarich is not connected', 400);
const countries = await this.client.listVisitedCities(creds, from, to);
@@ -25,7 +25,7 @@ export class DawarichSyncJob implements OnApplicationBootstrap {
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
async onApplicationBootstrap(): Promise<void> {
if (!this.registrar.isEnabled()) return;
const value = this.db.get<{ value: string }>(
'SELECT value FROM app_settings WHERE key = ?',
@@ -8,6 +8,7 @@ import {
} from '@trek/shared';
import { ADDON_IDS } from '../../addons';
import { DatabaseService } from '../database/database.service';
import { UnitOfWork } from '../database/unit-of-work';
import { AddonsService } from '../addons/addons.service';
import { logError, logInfo } from '../audit/audit-log.logger';
import { getCountryFromCoords } from '../atlas/atlas-geo';
@@ -70,6 +71,7 @@ export class DawarichSyncService {
private readonly addons: AddonsService,
private readonly client: DawarichClient,
private readonly dawarich: DawarichService,
private readonly uow: UnitOfWork,
) {}
/** The addon gate, evaluated per tick so an admin toggle lands without a restart. */
@@ -83,7 +85,7 @@ export class DawarichSyncService {
if (this.running) return;
this.running = true;
try {
const userIds = this.dawarich.listSyncableUserIds();
const userIds = await this.dawarich.listSyncableUserIds();
for (const userId of userIds) {
try {
await this.syncUser(userId);
@@ -133,21 +135,21 @@ export class DawarichSyncService {
/** The body of a sync, with the guard above already held. */
private async syncUserOnce(userId: number): Promise<DawarichSyncOutcome> {
if (!(await this.syncGloballyEnabled())) {
this.dawarich.recordSyncResult(userId, 'failed', 'addon_disabled');
await this.dawarich.recordSyncResult(userId, 'failed', 'addon_disabled');
return { state: 'failed', created: 0, updated: 0, missing: 0 };
}
const creds = this.dawarich.getCredentials(userId);
const creds = await this.dawarich.getCredentials(userId);
if (!creds) {
this.dawarich.recordSyncResult(userId, 'failed', 'not_connected');
await this.dawarich.recordSyncResult(userId, 'failed', 'not_connected');
return { state: 'failed', created: 0, updated: 0, missing: 0 };
}
const trips = this.listTripsToSync(userId);
const trips = await this.listTripsToSync(userId);
if (trips.length === 0) {
// Nothing to ask about is a successful sync, not a failure — otherwise a
// user with no dated trips sees a permanent red badge for doing nothing wrong.
this.dawarich.recordSyncResult(userId, 'ok', null);
await this.dawarich.recordSyncResult(userId, 'ok', null);
return { state: 'ok', created: 0, updated: 0, missing: 0 };
}
@@ -181,14 +183,14 @@ export class DawarichSyncService {
const state: DawarichSyncState =
failures === 0 ? 'ok' : failures === trips.length ? 'failed' : 'partial';
this.dawarich.recordSyncResult(userId, state, state === 'ok' ? null : lastError);
await this.dawarich.recordSyncResult(userId, state, state === 'ok' ? null : lastError);
// The probe is cheap next to the windows just fetched, and re-running it is
// how a Dawarich upgrade that finally ships `updated_at` starts being used
// without anyone reconnecting.
if (state !== 'failed') {
try {
this.dawarich.storeCapabilities(userId, await this.dawarich.probeCapabilities(creds));
await this.dawarich.storeCapabilities(userId, await this.dawarich.probeCapabilities(creds));
} catch {
// Capabilities are an optimisation; a failed probe is not a failed sync.
}
@@ -209,7 +211,7 @@ export class DawarichSyncService {
* generous rather than tight, because someone who connects Dawarich for the
* first time wants their last holiday filled in, not just today's.
*/
private listTripsToSync(userId: number): TripRow[] {
private async listTripsToSync(userId: number): Promise<TripRow[]> {
return this.db.all<TripRow>(
`SELECT DISTINCT t.id, t.start_date, t.end_date
FROM trips t
@@ -301,7 +303,7 @@ export class DawarichSyncService {
new Date().toISOString(),
);
created++;
this.matchBucketList(userId, visit.sourceVisitId, visit.lat, visit.lng, visit.durationMinutes);
await this.matchBucketList(userId, visit.sourceVisitId, visit.lat, visit.lng, visit.durationMinutes);
continue;
}
@@ -336,7 +338,7 @@ export class DawarichSyncService {
existing.id,
);
if (changed) updated++;
this.matchBucketList(userId, visit.sourceVisitId, visit.lat, visit.lng, visit.durationMinutes);
await this.matchBucketList(userId, visit.sourceVisitId, visit.lat, visit.lng, visit.durationMinutes);
continue;
}
@@ -355,7 +357,7 @@ export class DawarichSyncService {
if (changed) updated++;
}
const missing = this.flagMissing(userId, tripId, from, to, seenIds);
const missing = await this.flagMissing(userId, tripId, from, to, seenIds);
return { created, updated, missing };
}
@@ -368,13 +370,13 @@ export class DawarichSyncService {
* say "this is gone in Dawarich" next to an entry they wrote. Deleting that
* would delete their work.
*/
private flagMissing(
private async flagMissing(
userId: number,
tripId: number,
from: Date,
to: Date,
seenIds: Set<string>,
): number {
): Promise<number> {
// Bounded on `local_date`, not on `started_at`. Dawarich renders a visit's
// start as local wall-clock plus an offset (`2026-09-01T14:23:00+02:00`)
// while the window is UTC (`…Z`), and comparing those two shapes as strings
@@ -398,7 +400,7 @@ export class DawarichSyncService {
if (gone.length === 0) return 0;
const stamp = new Date().toISOString();
this.db.transaction(() => {
await this.uow.transactional(async () => {
for (const row of gone) {
if (row.state === 'new') {
this.db.run('DELETE FROM dawarich_visit_suggestions WHERE id = ?', row.id);
@@ -423,13 +425,13 @@ export class DawarichSyncService {
* from going past it. The link is only a hint; ticking the wish off still
* needs the user.
*/
private matchBucketList(
private async matchBucketList(
userId: number,
sourceVisitId: string,
lat: number | null,
lng: number | null,
durationMinutes: number,
): void {
): Promise<void> {
if (lat === null || lng === null) return;
if (durationMinutes < DAWARICH_BUCKET_MATCH_MIN_MINUTES) return;
@@ -456,7 +458,7 @@ export class DawarichSyncService {
}
if (!best) return;
this.claimWish(userId, sourceVisitId, best, lat, lng, durationMinutes);
await this.claimWish(userId, sourceVisitId, best, lat, lng, durationMinutes);
}
/**
@@ -473,14 +475,14 @@ export class DawarichSyncService {
* Every previous claim on the same wish is cleared, so re-running a sync after
* the recordings change cannot leave two stays holding it.
*/
private claimWish(
private async claimWish(
userId: number,
sourceVisitId: string,
wish: { id: number; lat: number; lng: number; distance: number },
lat: number,
lng: number,
durationMinutes: number,
): void {
): Promise<void> {
const holders = this.db.all<{
id: number;
source_visit_id: string;
@@ -505,7 +507,7 @@ export class DawarichSyncService {
if (holderWins) return;
}
this.db.transaction(() => {
await this.uow.transactional(async () => {
this.db.run(
'UPDATE dawarich_visit_suggestions SET matched_bucket_list_item_id = NULL WHERE user_id = ? AND matched_bucket_list_item_id = ?',
userId,
@@ -91,7 +91,7 @@ export class DawarichTracksService {
toIso: string,
offsetMinutes = offsetMinutesOf(fromIso),
): Promise<DawarichTrack> {
const creds = this.dawarich.getCredentials(userId);
const creds = await this.dawarich.getCredentials(userId);
if (!creds) return emptyTrack();
const from = new Date(fromIso);
@@ -129,7 +129,7 @@ export class DawarichTracksService {
to: Date,
offsetMinutes: number,
): Promise<DawarichTrack> {
const capabilities = this.dawarich.getCapabilities(userId);
const capabilities = await this.dawarich.getCapabilities(userId);
if (capabilities?.tracks !== false) {
try {
@@ -148,12 +148,12 @@ export class DawarichController {
@Put('suggestions/:id/state')
@HttpCode(200)
setSuggestionState(
async setSuggestionState(
@CurrentUser() user: User,
@Param('id') id: string,
@Body() body: DawarichSuggestionStateDto,
) {
const updated = this.suggestions.setState(user.id, parseId(id), body.state);
const updated = await this.suggestions.setState(user.id, parseId(id), body.state);
if (!updated) throw new HttpException({ error: 'Suggestion not found' }, 404);
return updated;
}
@@ -169,14 +169,14 @@ export class DawarichController {
@Post('bucket-list/confirm')
@HttpCode(200)
confirmBucketVisits(@CurrentUser() user: User, @Body() body: DawarichBucketConfirmDto) {
return { updated: this.suggestions.confirmBucketVisits(user.id, body.itemIds, body.visitedAt) };
async confirmBucketVisits(@CurrentUser() user: User, @Body() body: DawarichBucketConfirmDto) {
return { updated: await this.suggestions.confirmBucketVisits(user.id, body.itemIds, body.visitedAt) };
}
@Delete('bucket-list/:itemId/visit')
@HttpCode(200)
clearBucketVisit(@CurrentUser() user: User, @Param('itemId') itemId: string) {
const cleared = this.suggestions.clearBucketVisit(user.id, parseId(itemId));
async clearBucketVisit(@CurrentUser() user: User, @Param('itemId') itemId: string) {
const cleared = await this.suggestions.clearBucketVisit(user.id, parseId(itemId));
if (!cleared) throw new HttpException({ error: 'Bucket-list entry not found' }, 404);
return { success: true };
}
+5 -5
View File
@@ -70,11 +70,11 @@ export class DawarichMcp {
access: { group: 'journey', mode: 'read' },
when: dawarichAddonOn,
})
listSuggestions(
async listSuggestions(
{ tripId, state, limit }: { tripId?: number; state?: 'new' | 'accepted' | 'dismissed'; limit?: number },
ctx: McpContext,
) {
const all = this.suggestions.list(ctx.userId, { tripId, state });
const all = await this.suggestions.list(ctx.userId, { tripId, state });
const cap = limit ?? DEFAULT_LIMIT;
const page = all.suggestions.slice(0, cap);
return ok({
@@ -178,7 +178,7 @@ export class DawarichMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
const updated = this.suggestions.setState(ctx.userId, suggestionId, state ?? 'dismissed');
const updated = await this.suggestions.setState(ctx.userId, suggestionId, state ?? 'dismissed');
if (!updated) return errorResult('Suggestion not found');
return ok({ suggestion: updated });
}
@@ -229,9 +229,9 @@ export class DawarichMcp {
}
/** The MCP echo of the controller's error shaping: a refusal, not an exception. */
private run<T>(action: () => T) {
private async run<T>(action: () => Promise<T>) {
try {
return ok(action() as object);
return ok((await action()) as object);
} catch (err) {
if (err instanceof AcceptError) return errorResult(err.message);
throw err;
@@ -8,6 +8,7 @@ import {
} from '@trek/shared';
import { DatabaseService } from '../database/database.service';
import { AuditService } from '../audit/audit.service';
import { UnitOfWork } from '../database/unit-of-work';
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { checkSsrf } from '../../utils/ssrfGuard';
import { DawarichClient, DawarichError, type DawarichCreds } from './dawarich.client';
@@ -33,9 +34,10 @@ export class DawarichService {
private readonly db: DatabaseService,
private readonly audit: AuditService,
private readonly client: DawarichClient,
private readonly uow: UnitOfWork,
) {}
private readRow(userId: number): ConnRow | undefined {
private async readRow(userId: number): Promise<ConnRow | undefined> {
return this.db.get<ConnRow>(
`SELECT user_id, url, api_key, allow_insecure_tls, sync_enabled,
last_sync_at, last_sync_state, last_sync_error, capabilities
@@ -45,8 +47,8 @@ export class DawarichService {
}
/** Decrypted credentials for an outbound call, or null when nothing is connected. */
getCredentials(userId: number): DawarichCreds | null {
const row = this.readRow(userId);
async getCredentials(userId: number): Promise<DawarichCreds | null> {
const row = await this.readRow(userId);
if (!row?.url || !row?.api_key) return null;
const apiKey = decrypt_api_key(row.api_key);
if (!apiKey) return null;
@@ -54,13 +56,13 @@ export class DawarichService {
}
/** True when the user has both an address and a key on file. */
isConnected(userId: number): boolean {
const row = this.readRow(userId);
async isConnected(userId: number): Promise<boolean> {
const row = await this.readRow(userId);
return !!(row?.url && row?.api_key);
}
/** Every user whose connection is usable and whose background sync is on. */
listSyncableUserIds(): number[] {
async listSyncableUserIds(): Promise<number[]> {
const rows = this.db.all<{ user_id: number }>(
`SELECT user_id FROM dawarich_connections
WHERE sync_enabled = 1 AND url IS NOT NULL AND url <> '' AND api_key IS NOT NULL`,
@@ -69,8 +71,8 @@ export class DawarichService {
}
/** The connection as the settings card shows it. The key is a mask, always. */
getConnection(userId: number): DawarichConnection {
const row = this.readRow(userId);
async getConnection(userId: number): Promise<DawarichConnection> {
const row = await this.readRow(userId);
return {
url: row?.url || '',
apiKeyMasked: row?.api_key ? DAWARICH_KEY_MASK : '',
@@ -86,8 +88,8 @@ export class DawarichService {
};
}
getCapabilities(userId: number): DawarichCapabilities | null {
return parseCapabilities(this.readRow(userId)?.capabilities);
async getCapabilities(userId: number): Promise<DawarichCapabilities | null> {
return parseCapabilities((await this.readRow(userId))?.capabilities);
}
/**
@@ -145,7 +147,7 @@ export class DawarichService {
// All three writes or none: a row that took the new address but not the new
// key would point a credential minted for one instance at another one, and
// the next sync would send it there.
this.db.transaction(() => {
await this.uow.transactional(async () => {
this.db.run(
`INSERT INTO dawarich_connections (user_id, url, allow_insecure_tls, sync_enabled, updated_at)
VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)
@@ -236,7 +238,7 @@ export class DawarichService {
allowInsecureTls: boolean,
): Promise<DawarichStatus> {
const typedKey = (apiKey || '').trim();
const stored = this.getCredentials(userId);
const stored = await this.getCredentials(userId);
const baseUrl = (url || '').trim() || stored?.baseUrl || '';
const typed = typedKey && typedKey !== DAWARICH_KEY_MASK ? typedKey : '';
@@ -258,7 +260,7 @@ export class DawarichService {
const capabilities = await this.probeCapabilities(creds);
// Only persist against a connection that is actually stored — a test run
// from a half-filled form must not overwrite what is on file.
if (stored && baseUrl === stored.baseUrl) this.storeCapabilities(userId, capabilities);
if (stored && baseUrl === stored.baseUrl) await this.storeCapabilities(userId, capabilities);
return {
connected: true,
visitCount: capabilities.visits ? await this.countRecentVisits(creds) : 0,
@@ -335,7 +337,7 @@ export class DawarichService {
}
}
storeCapabilities(userId: number, capabilities: DawarichCapabilities): void {
async storeCapabilities(userId: number, capabilities: DawarichCapabilities): Promise<void> {
this.db.run(
'UPDATE dawarich_connections SET capabilities = ?, updated_at = CURRENT_TIMESTAMP WHERE user_id = ?',
JSON.stringify(capabilities),
@@ -343,7 +345,7 @@ export class DawarichService {
);
}
recordSyncResult(userId: number, state: DawarichSyncState, error: string | null): void {
async recordSyncResult(userId: number, state: DawarichSyncState, error: string | null): Promise<void> {
this.db.run(
`UPDATE dawarich_connections
SET last_sync_at = ?, last_sync_state = ?, last_sync_error = ?, updated_at = CURRENT_TIMESTAMP
@@ -22,7 +22,7 @@ export function toTraveler(r: { user_id: number; username: string; avatar: strin
export class ReservationsReadRepository {
constructor(private readonly db: DatabaseService) {}
getReservationWithJoins(id: string | number): ReservationRow | undefined {
async getReservationWithJoins(id: string | number): Promise<ReservationRow | undefined> {
const row = this.db.get<ReservationRow>(`
SELECT r.*, d.day_number, p.name as place_name, r.assignment_id,
ap.place_id as accommodation_place_id, acc_p.name as accommodation_name,
@@ -35,22 +35,22 @@ export class ReservationsReadRepository {
WHERE r.id = ?
`, id);
if (!row) return undefined;
row.endpoints = this.loadEndpoints(row.id);
row.travelers = this.loadTravelers(row.id);
row.endpoints = await this.loadEndpoints(row.id);
row.travelers = await this.loadTravelers(row.id);
// accommodation_id is a TEXT column; the integer FK reads back as a numeric
// string (e.g. "14.0"). Normalize to an int so clients can parse it.
row.accommodation_id = row.accommodation_id == null ? null : Math.trunc(Number(row.accommodation_id));
return row;
}
loadEndpoints(reservationId: number): ReservationEndpoint[] {
async loadEndpoints(reservationId: number): Promise<ReservationEndpoint[]> {
return this.db.all<ReservationEndpoint>(
'SELECT * FROM reservation_endpoints WHERE reservation_id = ? ORDER BY sequence',
reservationId
);
}
loadTravelers(reservationId: number | string): ReservationTraveler[] {
async loadTravelers(reservationId: number | string): Promise<ReservationTraveler[]> {
const rows = this.db.all<ReservationTraveler>(`
SELECT rt.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar, u.is_guest
FROM reservation_travelers rt
@@ -55,8 +55,8 @@ export class ReservationsController {
@Get()
list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { reservations: this.reservations.list(tripId) };
async list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
return { reservations: await this.reservations.list(tripId) };
}
@RequirePermission('reservation_edit')
@@ -75,13 +75,13 @@ export class ReservationsController {
}
await this.reservations.syncBudgetOnCreate(tripId, reservation.id, body.title, body.type, body.create_budget_entry, socketId);
this.reservations.broadcast(tripId, 'reservation:created', { reservation }, socketId);
this.reservations.notifyBookingChange(tripId, user.id, body.title, body.type ?? '');
await this.reservations.notifyBookingChange(tripId, user.id, body.title, body.type ?? '');
return { reservation };
}
@RequirePermission('reservation_edit')
@Put('positions')
updatePositions(
async updatePositions(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Body() body: ReservationPositionsDto,
@@ -89,7 +89,7 @@ export class ReservationsController {
) {
// The legacy signature declares day_plan_position required, but the wire
// contract tolerates absent values (bind NULL) — see the shared schema.
this.reservations.updatePositions(tripId, body.positions as { id: number; day_plan_position: number }[], body.day_id);
await this.reservations.updatePositions(tripId, body.positions as { id: number; day_plan_position: number }[], body.day_id);
this.reservations.broadcast(tripId, 'reservation:positions', { positions: body.positions, day_id: body.day_id }, socketId);
return { success: true };
}
@@ -104,7 +104,7 @@ export class ReservationsController {
@Headers('x-socket-id') socketId?: string,
) {
const body = rawBody as ReservationBody;
const current = this.reservations.getReservation(id, tripId);
const current = await this.reservations.getReservation(id, tripId);
if (!current) {
throw new HttpException({ error: 'Reservation not found' }, 404);
}
@@ -121,20 +121,20 @@ export class ReservationsController {
if ((reservation as any)?.external_source === 'airtrail' && (reservation as any)?.sync_enabled) {
void this.airtrailLink.pushReservationToAirtrail(Number((reservation as any).id), Number(tripId)).catch(() => {});
}
this.reservations.notifyBookingChange(tripId, user.id, body.title || cur.title, body.type || cur.type || '');
await this.reservations.notifyBookingChange(tripId, user.id, body.title || cur.title, body.type || cur.type || '');
return { reservation };
}
@RequirePermission('reservation_edit')
@Put(':id/travelers')
updateTravelers(
async updateTravelers(
@CurrentUser() user: User,
@Param('tripId') tripId: string,
@Param('id') id: string,
@Body() body: ReservationTravelersDto,
@Headers('x-socket-id') socketId?: string,
) {
const result = this.reservations.setTravelers(id, tripId, body.user_ids);
const result = await this.reservations.setTravelers(id, tripId, body.user_ids);
if (!result) {
throw new HttpException({ error: 'Reservation not found' }, 404);
}
@@ -161,7 +161,7 @@ export class ReservationsController {
this.reservations.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId }, socketId);
}
this.reservations.broadcast(tripId, 'reservation:deleted', { reservationId: Number(id) }, socketId);
this.reservations.notifyBookingChange(tripId, user.id, deleted.title, deleted.type || '');
await this.reservations.notifyBookingChange(tripId, user.id, deleted.title, deleted.type || '');
return { success: true };
}
@@ -181,7 +181,7 @@ export class ReservationsController {
* the wrong place.
*/
private async rejectForeignReferences(tripId: string, body: ReservationBody): Promise<void> {
const offenders = this.reservations.referencesOutsideTrip(tripId, body as never);
const offenders = await this.reservations.referencesOutsideTrip(tripId, body as never);
if (offenders.length > 0) {
throw new HttpException({ error: `Not part of this trip: ${offenders.join(', ')}` }, 400);
}
@@ -362,7 +362,7 @@ export class ReservationsMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.reservations.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
// Validate that all referenced IDs belong to this trip
@@ -438,9 +438,9 @@ export class ReservationsMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.reservations.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
const existing = this.reservations.getReservation(reservationId, tripId);
const existing = await this.reservations.getReservation(reservationId, tripId);
if (!existing) return errorResult('Reservation not found.');
if (place_id != null && !(await this.assignments.placeExists(place_id, tripId)))
@@ -469,7 +469,7 @@ export class ReservationsMcp {
})
async deleteReservation({ tripId, reservationId }: { tripId: number; reservationId: number }, ctx: McpContext) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.reservations.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
const { deleted, accommodationDeleted } = await this.reservations.remove(reservationId, tripId);
if (!deleted) return errorResult('Reservation not found.');
@@ -496,12 +496,12 @@ export class ReservationsMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.reservations.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
// The service filters the ids against the trip roster on its own, so an
// off-trip id cannot be attached; a missing booking is the only failure.
const result = this.reservations.setTravelers(String(reservationId), String(tripId), user_ids);
const result = await this.reservations.setTravelers(String(reservationId), String(tripId), user_ids);
if (!result) return errorResult('Reservation not found.');
this.guards.safeBroadcast(tripId, 'reservation:travelers-updated', { reservationId, travelers: result.travelers });
@@ -534,7 +534,7 @@ export class ReservationsMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.reservations.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
// The service scopes the write to the trip on its own, so a foreign id is
@@ -543,7 +543,7 @@ export class ReservationsMcp {
if (dayId && !(await this.days.getDay(dayId, tripId)))
return errorResult('dayId does not belong to this trip.');
this.reservations.updatePositions(tripId, positions, dayId);
await this.reservations.updatePositions(tripId, positions, dayId);
this.guards.safeBroadcast(tripId, 'reservation:positions', { positions, dayId });
return ok({ success: true });
}
@@ -571,9 +571,9 @@ export class ReservationsMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.reservations.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
const current = this.reservations.getReservation(reservationId, tripId);
const current = await this.reservations.getReservation(reservationId, tripId);
if (!current) return errorResult('Reservation not found.');
if (current.type !== 'hotel') return errorResult('Reservation is not of type hotel.');
@@ -617,7 +617,7 @@ export class ReservationsMcp {
access: { group: 'reservations', mode: 'read' },
})
async listUpcomingReservations({ limit }: { limit?: number }, ctx: McpContext) {
return ok({ reservations: this.reservations.listUpcoming(ctx.userId, limit) });
return ok({ reservations: await this.reservations.listUpcoming(ctx.userId, limit) });
}
@ResourceTemplate({
@@ -629,7 +629,7 @@ export class ReservationsMcp {
})
async tripReservationsResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
const id = parseId(tripId);
if (id === null || !this.reservations.verifyTripAccess(id, ctx.userId)) {
if (id === null || !(await this.reservations.verifyTripAccess(id, ctx.userId))) {
return {
contents: [{
uri: uri.href,
@@ -638,7 +638,7 @@ export class ReservationsMcp {
}],
};
}
const reservations = this.reservations.list(id);
const reservations = await this.reservations.list(id);
return {
contents: [{
uri: uri.href,
@@ -695,7 +695,7 @@ export class ReservationsMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.reservations.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
if (metadata && 'legs' in metadata) return errorResult(LEGS_IN_METADATA_ERROR);
@@ -803,12 +803,12 @@ export class ReservationsMcp {
ctx: McpContext,
) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.reservations.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
if (metadata && 'legs' in metadata) return errorResult(LEGS_IN_METADATA_ERROR);
const existing = this.reservations.getReservation(reservationId, tripId);
const existing = await this.reservations.getReservation(reservationId, tripId);
if (!existing) return errorResult('Transport not found.');
const resolvedType = type ?? existing.type;
@@ -841,7 +841,7 @@ export class ReservationsMcp {
type: resolvedType,
// Endpoints the caller did not replace stay the geometry the legs run
// over, so read them back (the row carries them) instead of guessing.
endpoints: resolvedEndpoints ?? (this.reservations.getReservationWithJoins(reservationId)?.endpoints ?? []).map(e => ({
endpoints: resolvedEndpoints ?? ((await this.reservations.getReservationWithJoins(reservationId))?.endpoints ?? []).map(e => ({
role: e.role, sequence: e.sequence, name: e.name, code: e.code,
lat: e.lat, lng: e.lng, timezone: e.timezone,
local_time: e.local_time, local_date: e.local_date,
@@ -899,7 +899,7 @@ export class ReservationsMcp {
})
async deleteTransport({ tripId, reservationId }: { tripId: number; reservationId: number }, ctx: McpContext) {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.reservations.verifyTripAccess(tripId, ctx.userId)) return noAccess();
if (!(await this.reservations.verifyTripAccess(tripId, ctx.userId))) return noAccess();
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
const { deleted } = await this.reservations.remove(reservationId, tripId);
if (!deleted) return errorResult('Transport not found.');
@@ -44,7 +44,7 @@ export class ReservationsRpc {
const i = input as { title?: string; type?: string; create_budget_entry?: unknown };
await this.reservations.syncBudgetOnCreate(String(tripId), reservation.id, i.title ?? '', i.type, i.create_budget_entry as never, undefined);
this.realtime.broadcast(tripId, 'reservation:created', { reservation }, undefined);
this.notifyBooking(actor, tripId, i.title ?? '', i.type ?? '');
await this.notifyBooking(actor, tripId, i.title ?? '', i.type ?? '');
return reservation;
}
@@ -58,7 +58,7 @@ export class ReservationsRpc {
const input = parsed.data as Record<string, unknown>;
this.requireValidEndpoints(input.endpoints);
await this.guards.requireTripEdit(tripId, actor, RESERVATION_EDIT_ACTION);
const current = this.reservations.getReservation(String(reservationId), String(tripId));
const current = await this.reservations.getReservation(String(reservationId), String(tripId));
if (!current) throw new ForbiddenResource(`no reservation ${reservationId} on trip ${tripId}`);
await this.requireOwnReferences(tripId, input);
const { reservation, accommodationChanged } = await this.reservations.update(String(reservationId), String(tripId), input as never, current as never);
@@ -67,7 +67,7 @@ export class ReservationsRpc {
const i = input as { title?: string; type?: string; create_budget_entry?: unknown };
await this.reservations.syncBudgetOnUpdate(String(tripId), String(reservationId), i.title ?? '', i.type, cur.title, cur.type, i.create_budget_entry as never, undefined);
this.realtime.broadcast(tripId, 'reservation:updated', { reservation }, undefined);
this.notifyBooking(actor, tripId, i.title || cur.title, i.type || cur.type || '');
await this.notifyBooking(actor, tripId, i.title || cur.title, i.type || cur.type || '');
return reservation;
}
@@ -82,7 +82,7 @@ export class ReservationsRpc {
if (accommodationDeleted) this.realtime.broadcast(tripId, 'accommodation:deleted', { accommodationId: deleted.accommodation_id }, undefined);
if (deletedBudgetItemId) this.realtime.broadcast(tripId, 'budget:deleted', { itemId: deletedBudgetItemId }, undefined);
this.realtime.broadcast(tripId, 'reservation:deleted', { reservationId }, undefined);
this.notifyBooking(actor, tripId, deleted.title, deleted.type || '');
await this.notifyBooking(actor, tripId, deleted.title, deleted.type || '');
return { deleted: true };
}
@@ -110,14 +110,14 @@ export class ReservationsRpc {
* so it is named here as well, after the ownership check.
*/
private async requireOwnReferences(tripId: number, input: Record<string, unknown>): Promise<void> {
const offenders = this.reservations.referencesOutsideTrip(String(tripId), input as never);
const offenders = await this.reservations.referencesOutsideTrip(String(tripId), input as never);
if (offenders.length > 0) throw new ForbiddenResource(`not part of trip ${tripId}: ${offenders.join(', ')}`);
const unknown = await this.reservations.unresolvedReferences(String(tripId), input as never);
if (unknown.length > 0) throw new BadParams(`unknown reference: ${unknown.join(', ')}`);
}
/** Fire-and-forget, exactly as the REST controller sends it, so it never blocks the write. */
private notifyBooking(actingUserId: number, tripId: number, booking: string, type: string): void {
this.reservations.notifyBookingChange(tripId, actingUserId, booking, type);
private async notifyBooking(actingUserId: number, tripId: number, booking: string, type: string): Promise<void> {
await this.reservations.notifyBookingChange(tripId, actingUserId, booking, type);
}
}
@@ -155,7 +155,7 @@ export class ReservationsService {
private readonly uow: UnitOfWork,
) {}
verifyTripAccess(tripId: string | number, userId: number) {
async verifyTripAccess(tripId: string | number, userId: number) {
return this.db.canAccessTrip(tripId, userId);
}
@@ -185,7 +185,7 @@ export class ReservationsService {
}
/** Fire-and-forget booking-change notification, mirroring the legacy dynamic import. */
notifyBookingChange(tripId: string | number, actorId: number, booking: string, type: string): void {
async notifyBookingChange(tripId: string | number, actorId: number, booking: string, type: string): Promise<void> {
// Injected, not a lazy import of the old notifications bridge. The laziness bought
// nothing the module graph does not already give — NotificationsModule
// reaches nothing in this direction — and it hid the edge while handing the
@@ -212,7 +212,7 @@ export class ReservationsService {
}
}
loadEndpointsByTrip(tripId: string | number): Map<number, ReservationEndpoint[]> {
async loadEndpointsByTrip(tripId: string | number): Promise<Map<number, ReservationEndpoint[]>> {
const rows = this.db.all<ReservationEndpoint>(`
SELECT e.* FROM reservation_endpoints e
JOIN reservations r ON e.reservation_id = r.id
@@ -229,7 +229,7 @@ export class ReservationsService {
}
/** Users assignable on a trip: its members (guests included) plus the owner. */
private assignableUserIds(tripId: string | number): Set<number> {
private async assignableUserIds(tripId: string | number): Promise<Set<number>> {
const members = this.db.all<{ user_id: number }>('SELECT user_id FROM trip_members WHERE trip_id = ?', tripId);
const ids = new Set(members.map(m => m.user_id));
const owner = this.db.get<{ user_id: number }>('SELECT user_id FROM trips WHERE id = ?', tripId);
@@ -237,7 +237,7 @@ export class ReservationsService {
return ids;
}
loadTravelersByTrip(tripId: string | number): Map<number, ReservationTraveler[]> {
async loadTravelersByTrip(tripId: string | number): Promise<Map<number, ReservationTraveler[]>> {
const rows = this.db.all<ReservationTraveler & { reservation_id: number }>(`
SELECT rt.reservation_id, rt.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar, u.is_guest
FROM reservation_travelers rt
@@ -255,7 +255,7 @@ export class ReservationsService {
return map;
}
loadTravelers(reservationId: number | string): ReservationTraveler[] {
async loadTravelers(reservationId: number | string): Promise<ReservationTraveler[]> {
return this.reads.loadTravelers(reservationId);
}
@@ -264,10 +264,10 @@ export class ReservationsService {
* accepted — ids that aren't on the trip are silently dropped so a stale client
* can't leak a cross-trip user. #1517.
*/
setReservationTravelers(reservationId: number | string, tripId: string | number, userIds: number[]): void {
const allowed = this.assignableUserIds(tripId);
async setReservationTravelers(reservationId: number | string, tripId: string | number, userIds: number[]): Promise<void> {
const allowed = await this.assignableUserIds(tripId);
const ids = [...new Set(userIds)].filter(uid => allowed.has(uid));
this.db.transaction(() => {
await this.uow.transactional(async () => {
this.db.run('DELETE FROM reservation_travelers WHERE reservation_id = ?', reservationId);
if (ids.length > 0) {
const insert = this.db.prepare('INSERT OR IGNORE INTO reservation_travelers (reservation_id, user_id) VALUES (?, ?)');
@@ -277,10 +277,10 @@ export class ReservationsService {
}
/** Assign trip members / named guests to a reservation (#1517). Null when off-trip. */
setTravelers(id: string, tripId: string, userIds: number[]) {
if (!this.getReservation(id, tripId)) return null;
this.setReservationTravelers(id, tripId, userIds);
return { travelers: this.loadTravelers(id), reservation: this.getReservationWithJoins(Number(id)) };
async setTravelers(id: string, tripId: string, userIds: number[]) {
if (!(await this.getReservation(id, tripId))) return null;
await this.setReservationTravelers(id, tripId, userIds);
return { travelers: await this.loadTravelers(id), reservation: await this.getReservationWithJoins(Number(id)) };
}
// Resolve the day row whose date matches the date portion of an ISO-ish
@@ -288,11 +288,11 @@ export class ReservationsService {
// `reservation_time` / `reservation_end_time` so non-transport bookings
// (tours, restaurants, events, ...) end up on the right day in the UI,
// which now filters by day_id instead of reservation_time.
private resolveDayIdFromTime(
private async resolveDayIdFromTime(
tripId: string | number,
time: string | null | undefined,
clampToNearest = true,
): number | null {
): Promise<number | null> {
if (!time) return null;
const datePart = time.slice(0, 10);
if (!/^\d{4}-\d{2}-\d{2}$/.test(datePart)) return null;
@@ -318,7 +318,7 @@ export class ReservationsService {
// the new range is left untouched. Hotels linked to a day_accommodation are excluded here —
// resyncAccommodationDays re-anchors the accommodation span and its linked reservation;
// unlinked dated hotels (e.g. imported ones) re-anchor like any other booking.
resyncReservationDays(tripId: string | number): void {
async resyncReservationDays(tripId: string | number): Promise<void> {
const rows = this.db.all<{
id: number; reservation_time: string | null; reservation_end_time: string | null;
day_id: number | null; end_day_id: number | null;
@@ -329,12 +329,12 @@ export class ReservationsService {
tripId
);
const update = this.db.prepare('UPDATE reservations SET day_id = ?, end_day_id = ? WHERE id = ?');
this.db.transaction(() => {
await this.uow.transactional(async () => {
for (const r of rows) {
const newDayId = this.resolveDayIdFromTime(tripId, r.reservation_time, false);
const newDayId = await this.resolveDayIdFromTime(tripId, r.reservation_time, false);
if (newDayId == null) continue;
const newEndDayId = r.reservation_end_time
? (this.resolveDayIdFromTime(tripId, r.reservation_end_time, false) ?? r.end_day_id)
? ((await this.resolveDayIdFromTime(tripId, r.reservation_end_time, false)) ?? r.end_day_id)
: r.end_day_id;
if (newDayId !== r.day_id || newEndDayId !== r.end_day_id) {
update.run(newDayId, newEndDayId, r.id);
@@ -343,7 +343,7 @@ export class ReservationsService {
});
}
private saveEndpoints(reservationId: number, endpoints: EndpointInput[]): void {
private async saveEndpoints(reservationId: number, endpoints: EndpointInput[]): Promise<void> {
// Run the transaction through DatabaseService (which re-derives the
// statement from the injected connection on each call). The bridge
// instance is built over the reinitialize-proof `db` Proxy, so a
@@ -351,7 +351,7 @@ export class ReservationsService {
// connection can't leave this holding a dead handle — the legacy module
// bound its transaction lazily per call for the same reason ("The
// database connection is not open").
this.db.transaction(() => {
await this.uow.transactional(async () => {
this.db.run('DELETE FROM reservation_endpoints WHERE reservation_id = ?', reservationId);
const insert = this.db.prepare(`
INSERT INTO reservation_endpoints (reservation_id, role, sequence, name, code, lat, lng, timezone, local_time, local_date)
@@ -369,7 +369,7 @@ export class ReservationsService {
});
}
list(tripId: string | number) {
async list(tripId: string | number) {
const reservations = this.db.all<ReservationRow>(`
SELECT r.*, d.day_number, p.name as place_name, r.assignment_id,
ap.place_id as accommodation_place_id, acc_p.name as accommodation_name,
@@ -396,8 +396,8 @@ export class ReservationsService {
posMap.get(dp.reservation_id)![dp.day_id] = dp.position;
}
const endpointsMap = this.loadEndpointsByTrip(tripId);
const travelersMap = this.loadTravelersByTrip(tripId);
const endpointsMap = await this.loadEndpointsByTrip(tripId);
const travelersMap = await this.loadTravelersByTrip(tripId);
for (const r of reservations) {
r.day_positions = posMap.get(r.id) || null;
@@ -432,7 +432,7 @@ export class ReservationsService {
* old date. Both halves of the report come from reading a hotel's date off
* fields hotels do not use.
*/
listUpcoming(userId: number, limit = 6) {
async listUpcoming(userId: number, limit = 6) {
const today = new Date().toISOString().slice(0, 10);
const now = new Date().toISOString();
@@ -512,7 +512,7 @@ export class ReservationsService {
return reservations;
}
getReservationWithJoins(id: string | number) {
async getReservationWithJoins(id: string | number) {
return this.reads.getReservationWithJoins(id);
}
@@ -527,7 +527,7 @@ export class ReservationsService {
*
* Returns the offending field names, empty when the body is clean.
*/
referencesOutsideTrip(tripId: string | number, data: CreateReservationData | UpdateReservationData): string[] {
async referencesOutsideTrip(tripId: string | number, data: CreateReservationData | UpdateReservationData): Promise<string[]> {
const offenders: string[] = [];
// An id that resolves to nothing is not an offender. accommodation_id in
// particular carries no foreign key, so shortening a trip's date range
@@ -621,7 +621,7 @@ export class ReservationsService {
/** Is there still a row behind this id? Existence only — which trip it sits
* on is the guards' question, and they answer it before the write. */
private referenceExists(table: 'days' | 'places' | 'day_assignments', id: unknown): boolean {
private async referenceExists(table: 'days' | 'places' | 'day_assignments', id: unknown): Promise<boolean> {
return !!this.db.get(`SELECT id FROM ${table} WHERE id = ?`, id);
}
@@ -635,8 +635,8 @@ export class ReservationsService {
* (#2355), and an update rebinds whatever the row already held, so a guard
* on the body alone never reaches it.
*/
private resolvedOrNull(table: 'days' | 'places' | 'day_assignments', id: number | null): number | null {
return id != null && this.referenceExists(table, id) ? id : null;
private async resolvedOrNull(table: 'days' | 'places' | 'day_assignments', id: number | null): Promise<number | null> {
return id != null && (await this.referenceExists(table, id)) ? id : null;
}
/**
@@ -655,11 +655,11 @@ export class ReservationsService {
* unplaceable class would collapse to (#2355). Its message survives, so the
* importer that logs and moves on still names the field.
*/
private requireResolvableStay(acc: CreateAccommodation): void {
private async requireResolvableStay(acc: CreateAccommodation): Promise<void> {
const missing: string[] = [];
if (acc.place_id && !this.referenceExists('places', acc.place_id)) missing.push('place_id');
if (!this.referenceExists('days', acc.start_day_id)) missing.push('start_day_id');
if (!this.referenceExists('days', acc.end_day_id)) missing.push('end_day_id');
if (acc.place_id && !(await this.referenceExists('places', acc.place_id))) missing.push('place_id');
if (!(await this.referenceExists('days', acc.start_day_id))) missing.push('start_day_id');
if (!(await this.referenceExists('days', acc.end_day_id))) missing.push('end_day_id');
if (missing.length > 0) {
throw new BadRequestException(`Unknown reference: ${missing.map((field) => `create_accommodation.${field}`).join(', ')}`);
}
@@ -694,7 +694,7 @@ export class ReservationsService {
if (type === 'hotel' && !resolvedAccommodationId && create_accommodation) {
const { place_id: accPlaceId, start_day_id, end_day_id, check_in, check_out, confirmation: accConf } = create_accommodation;
if (start_day_id && end_day_id) {
this.requireResolvableStay(create_accommodation);
await this.requireResolvableStay(create_accommodation);
const accResult = this.db.run(
'INSERT INTO day_accommodations (trip_id, place_id, start_day_id, end_day_id, check_in, check_out, confirmation) VALUES (?, ?, ?, ?, ?, ?, ?)',
tripId, accPlaceId || null, start_day_id, end_day_id, check_in || null, check_out || null, accConf || confirmation_number || null
@@ -715,17 +715,17 @@ export class ReservationsService {
const resolvedType = type || 'other';
let resolvedDayId: number | null = day_id ?? null;
if (resolvedDayId == null && resolvedType !== 'hotel' && reservation_time) {
resolvedDayId = this.resolveDayIdFromTime(tripId, reservation_time);
resolvedDayId = await this.resolveDayIdFromTime(tripId, reservation_time);
}
let resolvedEndDayId: number | null = end_day_id ?? null;
if (resolvedEndDayId == null && resolvedType !== 'hotel' && reservation_end_time) {
resolvedEndDayId = this.resolveDayIdFromTime(tripId, reservation_end_time);
resolvedEndDayId = await this.resolveDayIdFromTime(tripId, reservation_end_time);
}
resolvedDayId = this.resolvedOrNull('days', resolvedDayId);
resolvedEndDayId = this.resolvedOrNull('days', resolvedEndDayId);
const resolvedPlaceId = this.resolvedOrNull('places', place_id || null);
const resolvedAssignmentId = this.resolvedOrNull('day_assignments', assignment_id || null);
resolvedDayId = await this.resolvedOrNull('days', resolvedDayId);
resolvedEndDayId = await this.resolvedOrNull('days', resolvedEndDayId);
const resolvedPlaceId = await this.resolvedOrNull('places', place_id || null);
const resolvedAssignmentId = await this.resolvedOrNull('day_assignments', assignment_id || null);
const result = this.db.run(`
INSERT INTO reservations (trip_id, day_id, end_day_id, place_id, assignment_id, title, reservation_time, reservation_end_time, location, confirmation_number, notes, url, status, type, accommodation_id, metadata, needs_review)
@@ -751,7 +751,7 @@ export class ReservationsService {
);
if (endpoints && endpoints.length > 0) {
this.saveEndpoints(Number(result.lastInsertRowid), endpoints);
await this.saveEndpoints(Number(result.lastInsertRowid), endpoints);
}
// Sync check-in/out to accommodation if linked. Keyed off the RESOLVED id
@@ -775,11 +775,11 @@ export class ReservationsService {
}
// The row was just inserted, so the re-select can't miss (legacy typed this any).
const reservation = this.getReservationWithJoins(Number(result.lastInsertRowid))!;
const reservation = (await this.getReservationWithJoins(Number(result.lastInsertRowid)))!;
return { reservation, accommodationCreated, stayMirror };
}
updatePositions(tripId: string | number, positions: { id: number; day_plan_position?: number }[], dayId?: number | string | null) {
async updatePositions(tripId: string | number, positions: { id: number; day_plan_position?: number }[], dayId?: number | string | null): Promise<void> {
if (dayId) {
// Per-day positions for multi-day reservations, scoped the way the legacy
// branch below already scopes its update. The table carries no trip_id and
@@ -795,7 +795,7 @@ export class ReservationsService {
JOIN days d ON d.trip_id = r.trip_id
WHERE r.id = ? AND d.id = ? AND r.trip_id = ?
`);
this.db.transaction(() => {
await this.uow.transactional(async () => {
for (const item of positions) {
// position is NOT NULL while the wire contract leaves the value optional.
stmt.run(item.day_plan_position ?? 0, item.id, dayId, tripId);
@@ -804,7 +804,7 @@ export class ReservationsService {
} else {
// Legacy: update global position
const stmt = this.db.prepare('UPDATE reservations SET day_plan_position = ? WHERE id = ? AND trip_id = ?');
this.db.transaction(() => {
await this.uow.transactional(async () => {
for (const item of positions) {
stmt.run(item.day_plan_position, item.id, tripId);
}
@@ -812,7 +812,7 @@ export class ReservationsService {
}
}
getReservation(id: string | number, tripId: string | number) {
async getReservation(id: string | number, tripId: string | number) {
return this.db.get<Reservation>('SELECT * FROM reservations WHERE id = ? AND trip_id = ?', id, tripId);
}
@@ -846,7 +846,7 @@ export class ReservationsService {
if (type === 'hotel' && create_accommodation) {
const { place_id: accPlaceId, start_day_id, end_day_id, check_in, check_out, confirmation: accConf } = create_accommodation;
if (start_day_id && end_day_id) {
this.requireResolvableStay(create_accommodation);
await this.requireResolvableStay(create_accommodation);
if (resolvedAccId) {
const prior = this.db.get<{ check_in: string | null }>('SELECT check_in FROM day_accommodations WHERE id = ?', resolvedAccId);
this.db.run(
@@ -897,7 +897,7 @@ export class ReservationsService {
// No day set but we have a date — pin it to the matching day so the booking
// still shows in the Plan (covers bookings saved without a selected day, and
// the case where an earlier edit cleared day_id).
nextDayId = this.resolveDayIdFromTime(tripId, nextReservationTime);
nextDayId = await this.resolveDayIdFromTime(tripId, nextReservationTime);
} else if (day_id === undefined) {
// Field absent and nothing to derive from — keep whatever it had.
nextDayId = current.day_id ?? null;
@@ -909,15 +909,15 @@ export class ReservationsService {
if (end_day_id !== undefined) {
nextEndDayId = end_day_id ?? null;
} else if (reservation_end_time !== undefined && resolvedType !== 'hotel') {
nextEndDayId = this.resolveDayIdFromTime(tripId, nextReservationEndTime);
nextEndDayId = await this.resolveDayIdFromTime(tripId, nextReservationEndTime);
} else {
nextEndDayId = current.end_day_id ?? null;
}
nextDayId = this.resolvedOrNull('days', nextDayId);
nextEndDayId = this.resolvedOrNull('days', nextEndDayId);
const nextPlaceId = this.resolvedOrNull('places', place_id !== undefined ? (place_id || null) : (current.place_id ?? null));
const nextAssignmentId = this.resolvedOrNull('day_assignments', assignment_id !== undefined ? (assignment_id || null) : (current.assignment_id ?? null));
nextDayId = await this.resolvedOrNull('days', nextDayId);
nextEndDayId = await this.resolvedOrNull('days', nextEndDayId);
const nextPlaceId = await this.resolvedOrNull('places', place_id !== undefined ? (place_id || null) : (current.place_id ?? null));
const nextAssignmentId = await this.resolvedOrNull('day_assignments', assignment_id !== undefined ? (assignment_id || null) : (current.assignment_id ?? null));
this.db.run(`
UPDATE reservations SET
@@ -959,7 +959,7 @@ export class ReservationsService {
);
if (endpoints !== undefined) {
this.saveEndpoints(Number(id), endpoints);
await this.saveEndpoints(Number(id), endpoints);
}
// Sync check-in/out to accommodation if linked
@@ -983,7 +983,7 @@ export class ReservationsService {
// The caller passed the pre-checked `current` row, so the re-select can't
// miss (legacy typed this any).
const reservation = this.getReservationWithJoins(id)!;
const reservation = (await this.getReservationWithJoins(id))!;
return { reservation, accommodationChanged, stayMirror };
}
@@ -18,7 +18,7 @@ export class UpcomingReservationsController {
constructor(private readonly reservations: ReservationsService) {}
@Get('upcoming')
upcoming(@CurrentUser() user: User) {
return { reservations: this.reservations.listUpcoming(user.id) };
async upcoming(@CurrentUser() user: User) {
return { reservations: await this.reservations.listUpcoming(user.id) };
}
}
@@ -18,22 +18,22 @@ export class DayBoundariesController {
constructor(private readonly boundaries: DayBoundariesService, private readonly realtime: RealtimeService) {}
@Get()
list(@Param('tripId') tripId: string) {
return { boundaries: this.boundaries.list(tripId) };
async list(@Param('tripId') tripId: string) {
return { boundaries: await this.boundaries.list(tripId) };
}
@Put()
@RequirePermission('day_edit')
save(@Param('tripId') tripId: string, @Body() body: DayBoundaryDto, @Headers('x-socket-id') socketId?: string) {
const boundaries = this.boundaries.save(tripId, body);
async save(@Param('tripId') tripId: string, @Body() body: DayBoundaryDto, @Headers('x-socket-id') socketId?: string) {
const boundaries = await this.boundaries.save(tripId, body);
this.realtime.broadcast(tripId, 'roadtripBoundary:changed', { boundaries }, socketId);
return { boundaries };
}
@Delete(':dayNumber')
@RequirePermission('day_edit')
remove(@Param('tripId') tripId: string, @Param('dayNumber', ParseIntPipe) dayNumber: number, @Headers('x-socket-id') socketId?: string) {
const boundaries = this.boundaries.remove(tripId, dayNumber);
async remove(@Param('tripId') tripId: string, @Param('dayNumber', ParseIntPipe) dayNumber: number, @Headers('x-socket-id') socketId?: string) {
const boundaries = await this.boundaries.remove(tripId, dayNumber);
this.realtime.broadcast(tripId, 'roadtripBoundary:changed', { boundaries }, socketId);
return { boundaries };
}
@@ -32,7 +32,7 @@ export class DayBoundariesMcp {
})
async list({ tripId }: { tripId: number }, ctx: McpContext) {
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
return ok({ boundaries: this.boundaries.list(tripId) });
return ok({ boundaries: await this.boundaries.list(tripId) });
}
@Tool({
@@ -46,10 +46,10 @@ export class DayBoundariesMcp {
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
// A stop from another trip is refused by the service, with the reason.
return answeringRefusals(() => {
return answeringRefusals(async () => {
const boundaries = boundary
? this.boundaries.save(tripId, { ...boundary, day_number: dayNumber })
: this.boundaries.remove(tripId, dayNumber);
? await this.boundaries.save(tripId, { ...boundary, day_number: dayNumber })
: await this.boundaries.remove(tripId, dayNumber);
this.realtime.broadcast(String(tripId), 'roadtripBoundary:changed', { boundaries });
return ok({ boundaries });
});
@@ -6,13 +6,13 @@ import { DatabaseService } from '../database/database.service';
export class DayBoundariesService {
constructor(private readonly db: DatabaseService) {}
list(tripId: string | number): RoadtripDayBoundary[] {
async list(tripId: string | number): Promise<RoadtripDayBoundary[]> {
return this.db.all<RoadtripDayBoundary>(
'SELECT day_number, from_assignment_id, to_assignment_id, fraction FROM roadtrip_day_boundaries WHERE trip_id = ? ORDER BY day_number', tripId,
);
}
save(tripId: string | number, boundary: RoadtripDayBoundary): RoadtripDayBoundary[] {
async save(tripId: string | number, boundary: RoadtripDayBoundary): Promise<RoadtripDayBoundary[]> {
const belongs = (id: number) => this.db.get(
'SELECT a.id FROM day_assignments a JOIN days d ON d.id = a.day_id WHERE a.id = ? AND d.trip_id = ?', id, tripId,
);
@@ -26,7 +26,7 @@ export class DayBoundariesService {
return this.list(tripId);
}
remove(tripId: string | number, dayNumber: number): RoadtripDayBoundary[] {
async remove(tripId: string | number, dayNumber: number): Promise<RoadtripDayBoundary[]> {
this.db.run('DELETE FROM roadtrip_day_boundaries WHERE trip_id = ? AND day_number = ?', tripId, dayNumber);
return this.list(tripId);
}
@@ -88,11 +88,11 @@ export class RoadtripPlanService {
return {
days,
visits,
settings: this.preferences.read(tripId),
settings: await this.preferences.read(tripId),
profiles: await this.router.profiles(),
vias: this.roadtrip.listForTrip(tripId),
tracks: this.roadtrip.tracksForTrip(tripId),
boundaries: this.boundaries.list(tripId),
vias: await this.roadtrip.listForTrip(tripId),
tracks: await this.roadtrip.tracksForTrip(tripId),
boundaries: await this.boundaries.list(tripId),
};
}
@@ -18,13 +18,13 @@ export class RoadtripPreferencesController {
constructor(private readonly preferences: RoadtripPreferencesService) {}
@Get()
read(@Param('tripId') tripId: string) {
return { tripId: Number(tripId), preferences: this.preferences.read(Number(tripId)) };
async read(@Param('tripId') tripId: string) {
return { tripId: Number(tripId), preferences: await this.preferences.read(Number(tripId)) };
}
@Put()
@RequirePermission('day_edit')
update(@Param('tripId') tripId: string, @Body() patch: PreferencesDto, @Headers('x-socket-id') socketId?: string) {
return { tripId: Number(tripId), preferences: this.preferences.update(Number(tripId), patch, socketId) };
async update(@Param('tripId') tripId: string, @Body() patch: PreferencesDto, @Headers('x-socket-id') socketId?: string) {
return { tripId: Number(tripId), preferences: await this.preferences.update(Number(tripId), patch, socketId) };
}
}
@@ -43,7 +43,7 @@ export class RoadtripPreferencesMcp {
})
async read({ tripId }: { tripId: number }, ctx: McpContext) {
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
return ok({ tripId, settings: this.preferences.read(tripId), scope: 'trip' });
return ok({ tripId, settings: await this.preferences.read(tripId), scope: 'trip' });
}
@Tool({
@@ -60,6 +60,6 @@ export class RoadtripPreferencesMcp {
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
// A day window that ends before it starts is refused by the service, with the reason.
return answeringRefusals(() => ok({ tripId, settings: this.preferences.update(tripId, settings), scope: 'trip' }));
return answeringRefusals(async () => ok({ tripId, settings: await this.preferences.update(tripId, settings), scope: 'trip' }));
}
}
@@ -1,5 +1,6 @@
import { DatabaseService } from '../database/database.service';
import { RealtimeService } from '../realtime/realtime.service';
import { UnitOfWork } from '../database/unit-of-work';
import { HttpException, Injectable } from '@nestjs/common';
import {
ROADTRIP_PREFERENCE_KEYS,
@@ -13,9 +14,10 @@ export class RoadtripPreferencesService {
constructor(
private readonly db: DatabaseService,
private readonly realtime: RealtimeService,
private readonly uow: UnitOfWork,
) {}
read(tripId: number): RoadtripPreferences {
async read(tripId: number): Promise<RoadtripPreferences> {
const settings: Record<string, unknown> = {};
for (const row of this.db.all<{ key: string; value: string }>(
'SELECT key, value FROM roadtrip_preferences WHERE trip_id = ?',
@@ -35,10 +37,10 @@ export class RoadtripPreferencesService {
return roadtripPreferencesSchema.parse(preferences);
}
update(tripId: number, patch: RoadtripPreferences, socketId?: string): RoadtripPreferences {
async update(tripId: number, patch: RoadtripPreferences, socketId?: string): Promise<RoadtripPreferences> {
const validated = roadtripPreferencesUpdateSchema.parse(patch);
const saved = this.db.transaction(() => {
const next = { ...this.read(tripId), ...validated };
const saved = await this.uow.transactional(async () => {
const next = { ...(await this.read(tripId)), ...validated };
if (next.roadtrip_day_start && next.roadtrip_day_end && next.roadtrip_day_end <= next.roadtrip_day_start) {
throw new HttpException({ error: 'Day end must be later than day start.' }, 400);
}
+37 -36
View File
@@ -33,27 +33,27 @@ export class RoadtripController {
/** Every via of the trip, so the client can route all days without a request per day. */
@Get('vias')
listAll(@Param('tripId') tripId: string): { vias: RoadtripVia[]; tracks: RoadtripDayTrack[] } {
return { vias: this.roadtrip.listForTrip(tripId), tracks: this.roadtrip.tracksForTrip(tripId) };
async listAll(@Param('tripId') tripId: string): Promise<{ vias: RoadtripVia[]; tracks: RoadtripDayTrack[] }> {
return { vias: await this.roadtrip.listForTrip(tripId), tracks: await this.roadtrip.tracksForTrip(tripId) };
}
@Get('days/:dayId/vias')
list(@Param('tripId') tripId: string, @Param('dayId') dayId: string): { vias: RoadtripVia[] } {
this.requireDay(dayId, tripId);
return { vias: this.roadtrip.listForDay(dayId) };
async list(@Param('tripId') tripId: string, @Param('dayId') dayId: string): Promise<{ vias: RoadtripVia[] }> {
await this.requireDay(dayId, tripId);
return { vias: await this.roadtrip.listForDay(dayId) };
}
@RequirePermission('day_edit')
@Post('days/:dayId/vias')
create(
async create(
@Param('tripId') tripId: string,
@Param('dayId') dayId: string,
@Body() body: RoadtripViaCreateDto,
@Headers('x-socket-id') socketId?: string,
): { via: RoadtripVia } {
this.requireDay(dayId, tripId);
const via = this.roadtrip.create(dayId, body);
this.announce(tripId, dayId, socketId);
): Promise<{ via: RoadtripVia }> {
await this.requireDay(dayId, tripId);
const via = await this.roadtrip.create(dayId, body);
await this.announce(tripId, dayId, socketId);
return { via };
}
@@ -68,26 +68,27 @@ export class RoadtripController {
@RequirePermission('day_edit')
@Post('days/:dayId/vias/batch')
@HttpCode(200)
createMany(
async createMany(
@Param('tripId') tripId: string,
@Param('dayId') dayId: string,
@Body() body: RoadtripViaBatchDto,
@Headers('x-socket-id') socketId?: string,
): { vias: RoadtripVia[] } {
this.requireDay(dayId, tripId);
): Promise<{ vias: RoadtripVia[] }> {
await this.requireDay(dayId, tripId);
// Permission is not enough on its own: a place id from somebody else's trip would
// otherwise become this day's label, and a place that is not a track would become a
// label that can never be drawn.
if (body.track && !this.roadtrip.trackExists(body.track.place_id, tripId)) {
if (body.track && !(await this.roadtrip.trackExists(body.track.place_id, tripId))) {
throw new HttpException({ error: 'Track not found' }, 404);
}
const vias = this.roadtrip.createMany(dayId, body);
this.announce(tripId, dayId, socketId);
const vias = await this.roadtrip.createMany(dayId, body);
await this.announce(tripId, dayId, socketId);
// A batch is how a day starts following a recorded track, so the track it now follows
// is news in its own right: the rail draws a badge for it and the map a line.
const tracks = await this.roadtrip.tracksForTrip(tripId);
this.roadtrip.broadcast(tripId, 'roadtripTrack:changed', {
dayId,
track: this.roadtrip.tracksForTrip(tripId).find(t => String(t.day_id) === String(dayId)) ?? null,
track: tracks.find(t => String(t.day_id) === String(dayId)) ?? null,
}, socketId);
return { vias };
}
@@ -102,48 +103,48 @@ export class RoadtripController {
@RequirePermission('day_edit')
@Put('days/:dayId/vias')
@HttpCode(200)
reanchor(
async reanchor(
@Param('tripId') tripId: string,
@Param('dayId') dayId: string,
@Body() body: RoadtripViaReanchorDto,
@Headers('x-socket-id') socketId?: string,
): { vias: RoadtripVia[] } {
this.requireDay(dayId, tripId);
const vias = this.roadtrip.reanchor(dayId, body);
this.announce(tripId, dayId, socketId);
): Promise<{ vias: RoadtripVia[] }> {
await this.requireDay(dayId, tripId);
const vias = await this.roadtrip.reanchor(dayId, body);
await this.announce(tripId, dayId, socketId);
return { vias };
}
@RequirePermission('day_edit')
@Put('days/:dayId/vias/:id')
@HttpCode(200)
update(
async update(
@Param('tripId') tripId: string,
@Param('dayId') dayId: string,
@Param('id') id: string,
@Body() body: RoadtripViaUpdateDto,
@Headers('x-socket-id') socketId?: string,
): { via: RoadtripVia } {
this.requireDay(dayId, tripId);
const via = this.roadtrip.move(id, dayId, body.lat, body.lng, body.after_order_index);
): Promise<{ via: RoadtripVia }> {
await this.requireDay(dayId, tripId);
const via = await this.roadtrip.move(id, dayId, body.lat, body.lng, body.after_order_index);
if (!via) throw new HttpException({ error: 'Via not found' }, 404);
this.announce(tripId, dayId, socketId);
await this.announce(tripId, dayId, socketId);
return { via };
}
@RequirePermission('day_edit')
@Delete('days/:dayId/vias/:id')
remove(
async remove(
@Param('tripId') tripId: string,
@Param('dayId') dayId: string,
@Param('id') id: string,
@Headers('x-socket-id') socketId?: string,
): { success: true } {
this.requireDay(dayId, tripId);
if (!this.roadtrip.remove(id, dayId)) {
): Promise<{ success: true }> {
await this.requireDay(dayId, tripId);
if (!(await this.roadtrip.remove(id, dayId))) {
throw new HttpException({ error: 'Via not found' }, 404);
}
this.announce(tripId, dayId, socketId);
await this.announce(tripId, dayId, socketId);
return { success: true };
}
@@ -155,10 +156,10 @@ export class RoadtripController {
* routes means a client applies them all the same way. The originating socket is
* excluded, so the person dragging does not get their own point handed back mid-drag.
*/
private announce(tripId: string, dayId: string, socketId: string | undefined): void {
private async announce(tripId: string, dayId: string, socketId: string | undefined): Promise<void> {
this.roadtrip.broadcast(tripId, 'roadtripVia:changed', {
dayId,
vias: this.roadtrip.listForDay(dayId),
vias: await this.roadtrip.listForDay(dayId),
}, socketId);
}
@@ -167,8 +168,8 @@ export class RoadtripController {
* Without it a valid day id from someone else's trip would be editable through a trip
* the caller does have access to.
*/
private requireDay(dayId: string, tripId: string): void {
if (!this.roadtrip.dayExists(dayId, tripId)) {
private async requireDay(dayId: string, tripId: string): Promise<void> {
if (!(await this.roadtrip.dayExists(dayId, tripId))) {
throw new HttpException({ error: 'Day not found' }, 404);
}
}
+23 -22
View File
@@ -50,10 +50,10 @@ export class RoadtripMcp {
async listVias({ tripId, dayId }: { tripId: number; dayId?: number }, ctx: McpContext) {
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
if (dayId != null) {
if (!this.roadtrip.dayExists(dayId, tripId)) return noAccess();
return ok({ vias: this.roadtrip.listForDay(dayId) });
if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
return ok({ vias: await this.roadtrip.listForDay(dayId) });
}
return ok({ vias: this.roadtrip.listForTrip(tripId), tracks: this.roadtrip.tracksForTrip(tripId) });
return ok({ vias: await this.roadtrip.listForTrip(tripId), tracks: await this.roadtrip.tracksForTrip(tripId) });
}
@Tool({
@@ -77,9 +77,9 @@ export class RoadtripMcp {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
if (!this.roadtrip.dayExists(dayId, tripId)) return noAccess();
const via = this.roadtrip.create(dayId, { after_order_index, lat, lng });
this.announce(tripId, dayId);
if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
const via = await this.roadtrip.create(dayId, { after_order_index, lat, lng });
await this.announce(tripId, dayId);
return ok({ via });
}
@@ -119,16 +119,17 @@ export class RoadtripMcp {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
if (!this.roadtrip.dayExists(dayId, tripId)) return noAccess();
if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
// The same check the REST route makes, in the same change: permission alone would let
// a place id from another trip, or a place that is not a track at all, become this
// day's label.
if (track && !this.roadtrip.trackExists(track.place_id, tripId)) return noAccess();
const made = this.roadtrip.createMany(dayId, { vias, replace_legs, track });
this.announce(tripId, dayId);
if (track && !(await this.roadtrip.trackExists(track.place_id, tripId))) return noAccess();
const made = await this.roadtrip.createMany(dayId, { vias, replace_legs, track });
await this.announce(tripId, dayId);
const tracks = await this.roadtrip.tracksForTrip(String(tripId));
this.roadtrip.broadcast(String(tripId), 'roadtripTrack:changed', {
dayId,
track: this.roadtrip.tracksForTrip(String(tripId)).find(t => String(t.day_id) === String(dayId)) ?? null,
track: tracks.find(t => String(t.day_id) === String(dayId)) ?? null,
}, undefined);
return ok({ vias: made });
}
@@ -157,9 +158,9 @@ export class RoadtripMcp {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
if (!this.roadtrip.dayExists(dayId, tripId)) return noAccess();
const next = this.roadtrip.reanchor(dayId, { vias, remove });
this.announce(tripId, dayId);
if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
const next = await this.roadtrip.reanchor(dayId, { vias, remove });
await this.announce(tripId, dayId);
return ok({ vias: next });
}
@@ -179,9 +180,9 @@ export class RoadtripMcp {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
if (!this.roadtrip.dayExists(dayId, tripId)) return noAccess();
if (!this.roadtrip.remove(viaId, dayId)) return noAccess();
this.announce(tripId, dayId);
if (!(await this.roadtrip.dayExists(dayId, tripId))) return noAccess();
if (!(await this.roadtrip.remove(viaId, dayId))) return noAccess();
await this.announce(tripId, dayId);
return ok({ success: true });
}
@@ -195,10 +196,10 @@ export class RoadtripMcp {
if (await this.auth.isDemoUser(ctx.userId)) return demoDenied();
if (!this.db.canAccessTrip(input.tripId, ctx.userId)) return noAccess();
if (!(await this.guards.hasTripPermission('day_edit', input.tripId, ctx.userId))) return permissionDenied();
if (!this.roadtrip.dayExists(input.dayId, input.tripId)) return noAccess();
const via = this.roadtrip.move(input.viaId, input.dayId, input.lat, input.lng, input.after_order_index);
if (!(await this.roadtrip.dayExists(input.dayId, input.tripId))) return noAccess();
const via = await this.roadtrip.move(input.viaId, input.dayId, input.lat, input.lng, input.after_order_index);
if (!via) return noAccess();
this.announce(input.tripId, input.dayId);
await this.announce(input.tripId, input.dayId);
return ok({ via });
}
@@ -210,10 +211,10 @@ export class RoadtripMcp {
* No originating socket to exclude here — a tool call has no socket of its own, so the
* client that asked for it hears about it like everyone else.
*/
private announce(tripId: number, dayId: number): void {
private async announce(tripId: number, dayId: number): Promise<void> {
this.roadtrip.broadcast(String(tripId), 'roadtripVia:changed', {
dayId,
vias: this.roadtrip.listForDay(String(dayId)),
vias: await this.roadtrip.listForDay(String(dayId)),
}, undefined);
}
}
+19 -17
View File
@@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common';
import type { RoadtripDayTrack, RoadtripVia, TrekWsPayload, TrekWsTripEventName } from '@trek/shared';
import { DatabaseService } from '../database/database.service';
import { RealtimeService } from '../realtime/realtime.service';
import { UnitOfWork } from '../database/unit-of-work';
/**
* Via points: the places a day's drive is made to pass through without stopping.
@@ -16,6 +17,7 @@ export class RoadtripService {
constructor(
private readonly db: DatabaseService,
private readonly realtime: RealtimeService,
private readonly uow: UnitOfWork,
) {}
/**
@@ -34,7 +36,7 @@ export class RoadtripService {
}
/** The day exists and belongs to this trip. 404 material, checked before every write. */
dayExists(dayId: string | number, tripId: string | number): boolean {
async dayExists(dayId: string | number, tripId: string | number): Promise<boolean> {
return !!this.db.get<{ id: number }>(
'SELECT id FROM days WHERE id = ? AND trip_id = ?',
dayId,
@@ -42,7 +44,7 @@ export class RoadtripService {
);
}
listForDay(dayId: string | number): RoadtripVia[] {
async listForDay(dayId: string | number): Promise<RoadtripVia[]> {
return this.db.all<RoadtripVia>(
`SELECT id, day_id, after_order_index, sequence, lat, lng, created_at
FROM roadtrip_vias
@@ -53,7 +55,7 @@ export class RoadtripService {
}
/** Every via of a trip, so the client can route all days without one request per day. */
listForTrip(tripId: string | number): RoadtripVia[] {
async listForTrip(tripId: string | number): Promise<RoadtripVia[]> {
return this.db.all<RoadtripVia>(
`SELECT v.id, v.day_id, v.after_order_index, v.sequence, v.lat, v.lng, v.created_at
FROM roadtrip_vias v
@@ -64,7 +66,7 @@ export class RoadtripService {
);
}
create(dayId: string | number, input: { after_order_index: number; lat: number; lng: number; sequence?: number }): RoadtripVia {
async create(dayId: string | number, input: { after_order_index: number; lat: number; lng: number; sequence?: number }): Promise<RoadtripVia> {
// Appended after whatever already follows that stop, unless the caller says where.
const sequence = input.sequence ?? (
this.db.get<{ next: number }>(
@@ -81,7 +83,7 @@ export class RoadtripService {
input.lat,
input.lng,
);
return this.byId(Number(result.lastInsertRowid))!;
return (await this.byId(Number(result.lastInsertRowid)))!;
}
/**
@@ -94,15 +96,15 @@ export class RoadtripService {
* `replace_legs` clears by leg rather than by day, so vias the traveller placed by hand
* on other legs survive a track being laid on this one.
*/
createMany(
async createMany(
dayId: string | number,
input: {
vias: { after_order_index: number; lat: number; lng: number }[];
replace_legs?: number[];
track?: { place_id: number; stray_km?: number | null } | null;
},
): RoadtripVia[] {
return this.db.transaction(() => {
): Promise<RoadtripVia[]> {
return this.uow.transactional(async () => {
// Inside the same transaction as the chain it describes. A day that says it follows
// a road whose vias never landed is worse than a day that says nothing.
if (input.track === null) {
@@ -152,7 +154,7 @@ export class RoadtripService {
* Read with the vias in one go: both are wanted on every load of road-trip mode, and a
* second route for a handful of rows would be a second round trip for nothing.
*/
tracksForTrip(tripId: string | number): RoadtripDayTrack[] {
async tracksForTrip(tripId: string | number): Promise<RoadtripDayTrack[]> {
return this.db.all<RoadtripDayTrack>(
`SELECT t.day_id, t.place_id, t.stray_km
FROM roadtrip_day_tracks t
@@ -164,7 +166,7 @@ export class RoadtripService {
}
/** Whether a place is on this trip, and is a track rather than an ordinary place. */
trackExists(placeId: number, tripId: string | number): boolean {
async trackExists(placeId: number, tripId: string | number): Promise<boolean> {
return !!this.db.get<{ id: number }>(
"SELECT id FROM places WHERE id = ? AND trip_id = ? AND route_geometry IS NOT NULL AND route_geometry != ''",
placeId,
@@ -173,13 +175,13 @@ export class RoadtripService {
}
/** Moving a via is the whole edit; where it sits in the chain does not change. */
move(
async move(
id: string | number,
dayId: string | number,
lat: number,
lng: number,
afterOrderIndex?: number,
): RoadtripVia | null {
): Promise<RoadtripVia | null> {
const existing = this.db.get<{ id: number }>(
'SELECT id FROM roadtrip_vias WHERE id = ? AND day_id = ?',
id,
@@ -216,11 +218,11 @@ export class RoadtripService {
* the day, and a via somebody else deleted in the meantime is not a failure of the
* re-anchoring; failing the batch over it would leave the rest of the day mis-pinned.
*/
reanchor(
async reanchor(
dayId: string | number,
input: { vias: { id: number; after_order_index: number }[]; remove?: number[] },
): RoadtripVia[] {
return this.db.transaction(() => {
): Promise<RoadtripVia[]> {
return this.uow.transactional(async () => {
// Read before writing: the OLD anchor is what says which of two merged
// legs came first, and after the updates that information is gone.
const before = new Map(
@@ -286,12 +288,12 @@ export class RoadtripService {
});
}
remove(id: string | number, dayId: string | number): boolean {
async remove(id: string | number, dayId: string | number): Promise<boolean> {
const result = this.db.run('DELETE FROM roadtrip_vias WHERE id = ? AND day_id = ?', id, dayId);
return result.changes > 0;
}
private byId(id: number): RoadtripVia | null {
private async byId(id: number): Promise<RoadtripVia | null> {
return this.db.get<RoadtripVia>(
'SELECT id, day_id, after_order_index, sequence, lat, lng, created_at FROM roadtrip_vias WHERE id = ?',
id,
+1 -1
View File
@@ -249,7 +249,7 @@ export class TransitMcp {
needs_review: false,
});
this.guards.safeBroadcast(tripId, 'reservation:created', { reservation });
this.reservations.notifyBookingChange(tripId, ctx.userId, reservation.title, reservation.type || '');
await this.reservations.notifyBookingChange(tripId, ctx.userId, reservation.title, reservation.type || '');
return ok({ reservation });
}
}
@@ -79,7 +79,7 @@ export class TripReadModelService {
checked: (packingItems as { checked: number }[]).filter(i => i.checked).length,
};
const reservations = this.reservations.list(tripId);
const reservations = await this.reservations.list(tripId);
const collab_notes = await this.collab.listNotes(tripId);
return {
@@ -109,7 +109,7 @@ export class TripReadModelService {
packingItems: await this.packing.listItems(tripId, viewerId),
todoItems: await this.todo.listItems(tripId),
budgetItems: await this.budget.listBudgetItems(tripId),
reservations: this.reservations.list(tripId),
reservations: await this.reservations.list(tripId),
files: await this.files.listFiles(tripId, false),
accommodations: await this.accommodations.list(tripId),
members: [owner, ...(members || [])].filter(Boolean),
+2 -2
View File
@@ -272,12 +272,12 @@ export class TripsController {
}
@Get(':id/export.ics')
exportIcs(@CurrentUser() user: User, @Param('id') id: string, @Res() res: Response) {
async exportIcs(@CurrentUser() user: User, @Param('id') id: string, @Res() res: Response) {
if (!this.trips.canAccessTrip(id, user.id)) {
throw new HttpException({ error: 'Trip not found' }, 404);
}
try {
const { ics, filename } = this.calendar.exportICS(id);
const { ics, filename } = await this.calendar.exportICS(id);
res.setHeader('Content-Type', 'text/calendar; charset=utf-8');
res.setHeader('Content-Disposition', contentDisposition(filename, 'attachment'));
res.send(ics);
+1 -1
View File
@@ -533,7 +533,7 @@ export class TripsMcp {
async exportTripIcs({ tripId }: { tripId: number }, ctx: McpContext) {
if (!this.trips.canAccessTrip(tripId, ctx.userId)) return noAccess();
try {
const { ics, filename } = this.calendar.exportICS(tripId);
const { ics, filename } = await this.calendar.exportICS(tripId);
return ok({ ics, filename });
} catch {
return { content: [{ type: 'text' as const, text: 'Trip not found.' }], isError: true };
+4 -3
View File
@@ -67,7 +67,7 @@ export class TripsRpc {
@PluginMethod('trips.getReservations', { permission: 'db:read:trips' })
getReservations(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
return this.guards.tripRead(params, ctx, () => this.reservations.list(String(num(params.tripId, 'tripId'))));
return this.guards.tripRead(params, ctx, async () => this.reservations.list(String(num(params.tripId, 'tripId'))));
}
@PluginMethod('trips.getDays', { permission: 'db:read:trips' })
@@ -95,12 +95,13 @@ export class TripsRpc {
}
@PluginMethod('reservations.listMine', { permission: 'db:read:trips' })
listMyReservations(_params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
async listMyReservations(_params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
if (ctx.actingUserId === undefined) {
throw new ForbiddenResource('reservation reads require an authenticated user context');
}
const trips = this.trips.list(ctx.actingUserId, null) as Array<{ id: number }>;
return trips.flatMap((t) => this.reservations.list(String(t.id)));
const perTrip = await Promise.all(trips.map((t) => this.reservations.list(String(t.id))));
return perTrip.flat();
}
@PluginMethod('trips.members', { permission: 'db:read:trips' })
+1 -1
View File
@@ -440,7 +440,7 @@ export class TripsService {
// Default: generateDays re-dates day rows positionally; re-anchor dated bookings to
// the day matching their absolute reservation_time, and accommodations (+ their
// linked hotel reservations) to the days now holding their pre-change dates (#1288).
this.reservations.resyncReservationDays(tripId);
await this.reservations.resyncReservationDays(tripId);
await this.days.resyncAccommodationDays(tripId, prevDateByDayId);
}
});