mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-03 17:41:51 +00:00
refactor(budget, common, day-notes, days): async DB-touching methods; transactions through UnitOfWork
This commit is contained in:
@@ -95,7 +95,7 @@ export class AdminController {
|
||||
|
||||
@Delete('users/:id')
|
||||
async deleteUser(@CurrentUser() user: User, @Param('id') id: string, @Req() req: Request) {
|
||||
const result = ok(this.admin.deleteUser(id, user.id));
|
||||
const result = ok(await this.admin.deleteUser(id, user.id));
|
||||
await this.audit.writeAudit({ userId: user.id, action: 'admin.user_delete', resource: String(id), ip: getClientIp(req), details: { targetUser: result.email } });
|
||||
logInfo(`Admin ${user.email} deleted user ${result.email}`);
|
||||
return { success: true };
|
||||
|
||||
@@ -248,7 +248,7 @@ export class AdminService {
|
||||
};
|
||||
}
|
||||
|
||||
deleteUser(id: string, currentUserId: number) {
|
||||
async deleteUser(id: string, currentUserId: number) {
|
||||
if (Number.parseInt(id) === currentUserId) {
|
||||
return { error: 'Cannot delete own account', status: 400 };
|
||||
}
|
||||
@@ -256,7 +256,7 @@ export class AdminService {
|
||||
const userToDel = this.db.get<{ id: number; email: string }>('SELECT id, email FROM users WHERE id = ?', id);
|
||||
if (!userToDel) return { error: 'User not found', status: 404 };
|
||||
|
||||
this.userCleanup.deleteUserCompletely(userToDel.id);
|
||||
await this.userCleanup.deleteUserCompletely(userToDel.id);
|
||||
emitUserDeleted(userToDel.id); // let plugins erase their own per-user data
|
||||
return { email: userToDel.email };
|
||||
}
|
||||
|
||||
@@ -222,7 +222,7 @@ export class AssignmentsMcp {
|
||||
if (!this.assignments.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (!this.assignments.getAssignmentForTrip(assignmentId, tripId)) return errorResult('Assignment not found.');
|
||||
if (!this.days.getDay(newDayId, tripId)) return errorResult('Day not found.');
|
||||
if (!(await this.days.getDay(newDayId, tripId))) return errorResult('Day not found.');
|
||||
const result = await this.assignments.moveAssignment(assignmentId, newDayId, orderIndex ?? 0);
|
||||
// REST parity shape ({ assignment, oldDayId, newDayId }) — the client keys its
|
||||
// per-day assignment map on newDayId, so omitting it filed the moved assignment
|
||||
@@ -294,7 +294,7 @@ export class AssignmentsMcp {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.assignments.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (!this.days.getDay(dayId, tripId)) return errorResult('Day not found.');
|
||||
if (!(await this.days.getDay(dayId, tripId))) return errorResult('Day not found.');
|
||||
this.assignments.reorderAssignments(dayId, assignmentIds);
|
||||
// REST parity shape ({ dayId, orderedIds }) — the client only reads orderedIds,
|
||||
// so broadcasting the tool-input key name emptied the day for collaborators.
|
||||
|
||||
@@ -126,7 +126,7 @@ export class AuthController {
|
||||
|
||||
@Delete('me')
|
||||
async deleteAccount(@CurrentUser() user: User, @Req() req: Request) {
|
||||
const result = this.auth.deleteAccount(user.id, user.email, user.role);
|
||||
const result = await this.auth.deleteAccount(user.id, user.email, user.role);
|
||||
if (result.error) {
|
||||
throw new HttpException({ error: result.error }, result.status!);
|
||||
}
|
||||
|
||||
@@ -610,7 +610,7 @@ export class AuthService {
|
||||
return { success: true, token };
|
||||
}
|
||||
|
||||
deleteAccount(userId: number, userEmail: string, userRole: string): { error?: string; status?: number; success?: boolean } {
|
||||
async deleteAccount(userId: number, userEmail: string, userRole: string): Promise<{ error?: string; status?: number; success?: boolean }> {
|
||||
if (readEnv().demo.enabled && isDemoEmail(userEmail)) {
|
||||
return { error: 'Account deletion is disabled in demo mode.', status: 403 };
|
||||
}
|
||||
@@ -620,7 +620,7 @@ export class AuthService {
|
||||
return { error: 'Cannot delete the last admin account', status: 400 };
|
||||
}
|
||||
}
|
||||
this.userCleanup.deleteUserCompletely(userId);
|
||||
await this.userCleanup.deleteUserCompletely(userId);
|
||||
emitUserDeleted(userId); // let plugins erase their own per-user data
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { DatabaseService } from '../database/database.service';
|
||||
// AuthModule -> BudgetModule cycle that used to force budget.bridge here.
|
||||
import { BudgetService } from '../budget/budget.service';
|
||||
import { pluginsDataRoot } from '../plugins/paths';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
|
||||
/**
|
||||
* Account erasure — everything that has to happen around `DELETE FROM users`
|
||||
@@ -24,6 +25,7 @@ export class UserCleanupService {
|
||||
constructor(
|
||||
private readonly db: DatabaseService,
|
||||
private readonly budget: BudgetService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
/**
|
||||
@@ -63,10 +65,10 @@ export class UserCleanupService {
|
||||
} catch { /* plugins / queue table absent (slim schema) */ }
|
||||
}
|
||||
|
||||
private cleanupUserReferences(userId: number): void {
|
||||
private async cleanupUserReferences(userId: number): Promise<void> {
|
||||
this.db.run('UPDATE trip_members SET invited_by = NULL WHERE invited_by = ?', userId);
|
||||
this.db.run('UPDATE budget_items SET paid_by_user_id = NULL WHERE paid_by_user_id = ?', userId);
|
||||
this.budget.removeUserFromBudgetItems(userId);
|
||||
await this.budget.removeUserFromBudgetItems(userId);
|
||||
this.db.run('DELETE FROM share_tokens WHERE created_by = ?', userId);
|
||||
this.db.run('DELETE FROM journey_share_tokens WHERE created_by = ?', userId);
|
||||
// Owned journeys cascade-delete their entries/contributors/share_tokens/photos via journey_id FKs
|
||||
@@ -76,9 +78,9 @@ export class UserCleanupService {
|
||||
this.db.run('DELETE FROM journey_contributors WHERE user_id = ?', userId);
|
||||
}
|
||||
|
||||
deleteUserCompletely(userId: number): void {
|
||||
this.db.transaction(() => {
|
||||
this.cleanupUserReferences(userId);
|
||||
async deleteUserCompletely(userId: number): Promise<void> {
|
||||
await this.uow.transactional(async () => {
|
||||
await this.cleanupUserReferences(userId);
|
||||
this.erasePluginUserData(userId);
|
||||
this.db.run('DELETE FROM users WHERE id = ?', userId);
|
||||
});
|
||||
|
||||
@@ -327,7 +327,7 @@ export class BookingImportService {
|
||||
// Freeze the live FX rate for a foreign-currency booking price so a
|
||||
// settled position isn't re-opened when live rates drift (#1445).
|
||||
await this.budget.freezeForeignRate(tripId, budgetData);
|
||||
const budgetItem = this.budget.createBudgetItem(tripId, budgetData);
|
||||
const budgetItem = await this.budget.createBudgetItem(tripId, budgetData);
|
||||
this.realtime.broadcast(tripId, 'budget:created', { item: budgetItem }, socketId);
|
||||
} catch (err) {
|
||||
console.error(
|
||||
|
||||
@@ -57,17 +57,17 @@ export class BudgetController {
|
||||
|
||||
|
||||
@Get()
|
||||
list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
|
||||
return { items: this.budget.list(tripId) };
|
||||
async list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
|
||||
return { items: await this.budget.list(tripId) };
|
||||
}
|
||||
|
||||
@Get('summary/per-person')
|
||||
perPerson(@CurrentUser() user: User, @Param('tripId') tripId: string) {
|
||||
return { summary: this.budget.perPersonSummary(tripId) };
|
||||
async perPerson(@CurrentUser() user: User, @Param('tripId') tripId: string) {
|
||||
return { summary: await this.budget.perPersonSummary(tripId) };
|
||||
}
|
||||
|
||||
@Get('settlement')
|
||||
settlement(
|
||||
async settlement(
|
||||
@CurrentUser() user: User,
|
||||
@Trip() trip: TripAccess,
|
||||
@Param('tripId') tripId: string,
|
||||
@@ -77,8 +77,8 @@ export class BudgetController {
|
||||
}
|
||||
|
||||
@Get('settlements')
|
||||
listSettlements(@CurrentUser() user: User, @Param('tripId') tripId: string) {
|
||||
return { settlements: this.budget.listSettlements(tripId) };
|
||||
async listSettlements(@CurrentUser() user: User, @Param('tripId') tripId: string) {
|
||||
return { settlements: await this.budget.listSettlements(tripId) };
|
||||
}
|
||||
|
||||
@RequirePermission('budget_edit')
|
||||
@@ -128,13 +128,13 @@ export class BudgetController {
|
||||
|
||||
@RequirePermission('budget_edit')
|
||||
@Delete('settlements/:settlementId')
|
||||
deleteSettlement(
|
||||
async deleteSettlement(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('settlementId') settlementId: string,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
if (!this.budget.deleteSettlement(settlementId, tripId)) {
|
||||
if (!(await this.budget.deleteSettlement(settlementId, tripId))) {
|
||||
throw new HttpException({ error: 'Settlement not found' }, 404);
|
||||
}
|
||||
this.budget.broadcast(tripId, 'budget:settlement-deleted', { settlementId: Number(settlementId) }, socketId);
|
||||
@@ -156,26 +156,26 @@ export class BudgetController {
|
||||
|
||||
@RequirePermission('budget_edit')
|
||||
@Put('reorder/items')
|
||||
reorderItems(
|
||||
async reorderItems(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Body() body: BudgetReorderItemsDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
this.budget.reorderItems(tripId, body.orderedIds);
|
||||
await this.budget.reorderItems(tripId, body.orderedIds);
|
||||
this.budget.broadcast(tripId, 'budget:reordered', { orderedIds: body.orderedIds }, socketId);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@RequirePermission('budget_edit')
|
||||
@Put('reorder/categories')
|
||||
reorderCategories(
|
||||
async reorderCategories(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Body() body: BudgetReorderCategoriesDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
this.budget.reorderCategories(tripId, body.orderedCategories);
|
||||
await this.budget.reorderCategories(tripId, body.orderedCategories);
|
||||
this.budget.broadcast(tripId, 'budget:reordered', { orderedCategories: body.orderedCategories }, socketId);
|
||||
return { success: true };
|
||||
}
|
||||
@@ -194,7 +194,7 @@ export class BudgetController {
|
||||
throw new HttpException({ error: 'Budget item not found' }, 404);
|
||||
}
|
||||
if (updated.reservation_id && body.total_price !== undefined) {
|
||||
this.budget.syncReservationPrice(tripId, updated.reservation_id, updated.total_price, socketId);
|
||||
await this.budget.syncReservationPrice(tripId, updated.reservation_id, updated.total_price, socketId);
|
||||
}
|
||||
this.budget.broadcast(tripId, 'budget:updated', { item: updated }, socketId);
|
||||
return { item: updated };
|
||||
@@ -202,14 +202,14 @@ export class BudgetController {
|
||||
|
||||
@RequirePermission('budget_edit')
|
||||
@Put(':id/members')
|
||||
updateMembers(
|
||||
async updateMembers(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: BudgetUpdateMembersDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const result = this.budget.updateMembers(id, tripId, body.user_ids);
|
||||
const result = await this.budget.updateMembers(id, tripId, body.user_ids);
|
||||
if (!result) {
|
||||
throw new HttpException({ error: 'Budget item not found' }, 404);
|
||||
}
|
||||
@@ -219,14 +219,14 @@ export class BudgetController {
|
||||
|
||||
@RequirePermission('budget_edit')
|
||||
@Put(':id/payers')
|
||||
setPayers(
|
||||
async setPayers(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('id') id: string,
|
||||
@Body() body: BudgetUpdatePayersDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const item = this.budget.setPayers(id, tripId, body.payers);
|
||||
const item = await this.budget.setPayers(id, tripId, body.payers);
|
||||
if (!item) {
|
||||
throw new HttpException({ error: 'Budget item not found' }, 404);
|
||||
}
|
||||
@@ -236,7 +236,7 @@ export class BudgetController {
|
||||
|
||||
@RequirePermission('budget_edit')
|
||||
@Put(':id/members/:userId/paid')
|
||||
toggleMemberPaid(
|
||||
async toggleMemberPaid(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('id') id: string,
|
||||
@@ -244,20 +244,20 @@ export class BudgetController {
|
||||
@Body() body: BudgetToggleMemberPaidDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const member = this.budget.toggleMemberPaid(id, tripId, userId, body.paid);
|
||||
const member = await this.budget.toggleMemberPaid(id, tripId, userId, body.paid);
|
||||
this.budget.broadcast(tripId, 'budget:member-paid-updated', { itemId: Number(id), userId: Number(userId), paid: body.paid ? 1 : 0 }, socketId);
|
||||
return { member };
|
||||
}
|
||||
|
||||
@RequirePermission('budget_edit')
|
||||
@Delete(':id')
|
||||
remove(
|
||||
async remove(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('id') id: string,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
if (!this.budget.remove(id, tripId)) {
|
||||
if (!(await this.budget.remove(id, tripId))) {
|
||||
throw new HttpException({ error: 'Budget item not found' }, 404);
|
||||
}
|
||||
this.budget.broadcast(tripId, 'budget:deleted', { itemId: Number(id) }, socketId);
|
||||
|
||||
@@ -16,6 +16,7 @@ import { BudgetService } from './budget.service';
|
||||
import { ExchangeRatesService } from './exchange-rates.service';
|
||||
import { addonGate } from '../addons/addon-gate';
|
||||
import { AddonsService } from '../addons/addons.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
|
||||
/** Legacy registrar gate: the whole budget surface rides the budget addon. */
|
||||
const budgetAddonOn = addonGate(ADDON_IDS.BUDGET);
|
||||
@@ -84,11 +85,12 @@ export class BudgetMcp {
|
||||
private readonly membership: TripMembershipService,
|
||||
readonly addons: AddonsService,
|
||||
private readonly guards: McpToolGuardsService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
/** The AuthService.isDemoUser check without the auth graph (demo-write.ts). */
|
||||
private isDemoUser(userId: number): boolean {
|
||||
return isDemoUserId(this.env, this.db, userId);
|
||||
private async isDemoUser(userId: number): Promise<boolean> {
|
||||
return await isDemoUserId(this.env, this.db, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -111,12 +113,12 @@ export class BudgetMcp {
|
||||
* (the write path overwrites total_price with their sum), so the stated total
|
||||
* is not necessarily the figure that ends up in the row.
|
||||
*/
|
||||
private settledTotalCents(
|
||||
private async settledTotalCents(
|
||||
tripId: number,
|
||||
payers: { user_id: number; amount: number }[] | undefined,
|
||||
total_price: number | undefined,
|
||||
fallbackCents: number,
|
||||
): number {
|
||||
): Promise<number> {
|
||||
// Once payers are sent at all, the write path derives the total from them and
|
||||
// an empty list therefore means zero, not "no opinion". Reading total_price
|
||||
// here instead would certify a split against a figure the row never receives.
|
||||
@@ -138,12 +140,12 @@ export class BudgetMcp {
|
||||
* user_id is refused for the same reason: the write path drops both silently,
|
||||
* which would unbalance a split that had just been checked.
|
||||
*/
|
||||
private splitRefusal(
|
||||
private async splitRefusal(
|
||||
tripId: number,
|
||||
members: { user_id: number; amount: number }[],
|
||||
totalCents: number,
|
||||
payers?: { user_id: number; amount: number }[],
|
||||
): string | null {
|
||||
): Promise<string | null> {
|
||||
const roster = this.db.rosterUserIds(tripId);
|
||||
const strangers = members.filter(m => !roster.has(m.user_id)).map(m => m.user_id);
|
||||
if (strangers.length > 0) {
|
||||
@@ -169,7 +171,7 @@ export class BudgetMcp {
|
||||
}
|
||||
|
||||
/** The sibling tools' foreign-id rule: a linked id must live on the same trip. */
|
||||
private placeOnTrip(tripId: number, placeId: number): boolean {
|
||||
private async placeOnTrip(tripId: number, placeId: number): Promise<boolean> {
|
||||
return !!this.db.get('SELECT id FROM places WHERE id = ? AND trip_id = ?', placeId, tripId);
|
||||
}
|
||||
|
||||
@@ -203,13 +205,13 @@ export class BudgetMcp {
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('budget_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (members !== undefined && member_ids !== undefined) return errorResult('Pass either members (uneven split) or member_ids (equal split), not both.');
|
||||
if (place_id != null && !this.placeOnTrip(tripId, place_id)) return errorResult('place_id does not belong to this trip.');
|
||||
if (place_id != null && !(await this.placeOnTrip(tripId, place_id))) return errorResult('place_id does not belong to this trip.');
|
||||
if (members !== undefined) {
|
||||
const refusal = this.splitRefusal(tripId, members, this.settledTotalCents(tripId, payers, total_price, toCents(total_price)), payers);
|
||||
const refusal = await this.splitRefusal(tripId, members, await this.settledTotalCents(tripId, payers, total_price, toCents(total_price)), payers);
|
||||
if (refusal) return errorResult(refusal);
|
||||
}
|
||||
// The split participants are the members of an uneven split; the equal-split
|
||||
@@ -219,7 +221,7 @@ export class BudgetMcp {
|
||||
// Freeze the live FX rate at entry time so a settled position isn't re-opened
|
||||
// when live rates drift (#1445) — same as the REST create path.
|
||||
await this.budget.freezeForeignRate(tripId, itemData);
|
||||
const item = this.budget.createBudgetItem(tripId, itemData);
|
||||
const item = await this.budget.createBudgetItem(tripId, itemData);
|
||||
this.guards.safeBroadcast(tripId, 'budget:created', { item });
|
||||
return ok({ item });
|
||||
}
|
||||
@@ -236,10 +238,10 @@ export class BudgetMcp {
|
||||
access: { group: 'budget', mode: 'write' },
|
||||
})
|
||||
async deleteBudgetItem({ tripId, itemId }: { tripId: number; itemId: number }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('budget_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const deleted = this.budget.deleteBudgetItem(itemId, tripId);
|
||||
const deleted = await this.budget.deleteBudgetItem(itemId, tripId);
|
||||
if (!deleted) return errorResult('Budget item not found.');
|
||||
this.guards.safeBroadcast(tripId, 'budget:deleted', { itemId });
|
||||
return ok({ success: true });
|
||||
@@ -278,16 +280,16 @@ export class BudgetMcp {
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('budget_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (members !== undefined && member_ids !== undefined) return errorResult('Pass either members (uneven split) or member_ids (equal split), not both.');
|
||||
if (members !== undefined) {
|
||||
// An edit that leaves the total alone still has to reconcile against it, so
|
||||
// the stored figure stands in when the call does not restate one.
|
||||
const existing = this.budget.getBudgetItem(itemId, tripId);
|
||||
const existing = await this.budget.getBudgetItem(itemId, tripId);
|
||||
if (!existing) return errorResult('Budget item not found.');
|
||||
const refusal = this.splitRefusal(tripId, members, this.settledTotalCents(tripId, payers, total_price, toCents(existing.total_price)), payers);
|
||||
const refusal = await this.splitRefusal(tripId, members, await this.settledTotalCents(tripId, payers, total_price, toCents(existing.total_price)), payers);
|
||||
if (refusal) return errorResult(refusal);
|
||||
}
|
||||
// Freeze-then-write composite: a currency change re-freezes the rate at entry
|
||||
@@ -322,16 +324,16 @@ export class BudgetMcp {
|
||||
},
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('budget_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (place_id != null && !this.placeOnTrip(tripId, place_id)) return errorResult('place_id does not belong to this trip.');
|
||||
if (place_id != null && !(await this.placeOnTrip(tripId, place_id))) return errorResult('place_id does not belong to this trip.');
|
||||
// Omitted userIds → default to the whole trip, matching create_budget_item.
|
||||
const members = (userIds && userIds.length > 0) ? userIds : await this.resolveMemberIds(tripId, undefined);
|
||||
try {
|
||||
const item = this.db.transaction(() => {
|
||||
const created = this.budget.createBudgetItem(tripId, { category, name, total_price, note, member_ids: members, place_id });
|
||||
return this.budget.getBudgetItem(created.id, tripId)!;
|
||||
const item = await this.uow.transactional(async () => {
|
||||
const created = await this.budget.createBudgetItem(tripId, { category, name, total_price, note, member_ids: members, place_id });
|
||||
return (await this.budget.getBudgetItem(created.id, tripId))!;
|
||||
});
|
||||
this.guards.safeBroadcast(tripId, 'budget:created', { item });
|
||||
if (members && members.length > 0) this.guards.safeBroadcast(tripId, 'budget:members-updated', { itemId: item.id, members: item.members, persons: item.persons });
|
||||
@@ -354,12 +356,12 @@ export class BudgetMcp {
|
||||
access: { group: 'budget', mode: 'write' },
|
||||
})
|
||||
async setBudgetItemMembers({ tripId, itemId, userIds }: { tripId: number; itemId: number; userIds: number[] }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('budget_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const result = this.budget.updateMembers(itemId, tripId, userIds);
|
||||
const result = await this.budget.updateMembers(itemId, tripId, userIds);
|
||||
if (!result) return errorResult('Budget item not found.');
|
||||
const item = this.budget.getBudgetItem(itemId, tripId);
|
||||
const item = await this.budget.getBudgetItem(itemId, tripId);
|
||||
this.guards.safeBroadcast(tripId, 'budget:members-updated', { itemId, members: result.members, persons: result.item.persons });
|
||||
return ok({ item });
|
||||
}
|
||||
@@ -378,10 +380,10 @@ export class BudgetMcp {
|
||||
access: { group: 'budget', mode: 'write' },
|
||||
})
|
||||
async toggleBudgetMemberPaid({ tripId, itemId, memberId, paid }: { tripId: number; itemId: number; memberId: number; paid: boolean }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('budget_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const member = this.budget.toggleMemberPaid(itemId, tripId, memberId, paid);
|
||||
const member = await this.budget.toggleMemberPaid(itemId, tripId, memberId, paid);
|
||||
this.guards.safeBroadcast(tripId, 'budget:member-paid-updated', { itemId, userId: memberId, paid: paid ? 1 : 0 });
|
||||
return ok({ member });
|
||||
}
|
||||
@@ -400,12 +402,12 @@ export class BudgetMcp {
|
||||
access: { group: 'budget', mode: 'read' },
|
||||
})
|
||||
async getSettlementSummary({ tripId, base }: { tripId: number; base?: string }, ctx: McpContext) {
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
const trip = this.db.get<{ currency?: string }>('SELECT currency FROM trips WHERE id = ?', tripId);
|
||||
const tripCurrency = trip?.currency || 'EUR';
|
||||
const effectiveBase = (base || tripCurrency).toUpperCase();
|
||||
const rates = await this.exchangeRates.getRates(effectiveBase);
|
||||
const summary = this.budget.calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency });
|
||||
const summary = await this.budget.calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency });
|
||||
return ok({ summary });
|
||||
}
|
||||
|
||||
@@ -420,8 +422,8 @@ export class BudgetMcp {
|
||||
access: { group: 'budget', mode: 'read' },
|
||||
})
|
||||
async listSettlements({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
return ok({ settlements: this.budget.listSettlements(tripId) });
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
return ok({ settlements: await this.budget.listSettlements(tripId) });
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -443,8 +445,8 @@ export class BudgetMcp {
|
||||
{ tripId, from_user_id, to_user_id, amount, currency, settled_at }: { tripId: number; from_user_id: number; to_user_id: number; amount: number; currency?: string | null; settled_at?: string | null },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('budget_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
// Freeze-then-write composite, same as the REST path: the rate for the display
|
||||
// currency is frozen at entry time (#1445).
|
||||
@@ -474,8 +476,8 @@ export class BudgetMcp {
|
||||
{ tripId, settlementId, from_user_id, to_user_id, amount, currency, settled_at }: { tripId: number; settlementId: number; from_user_id: number; to_user_id: number; amount: number; currency?: string | null; settled_at?: string | null },
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('budget_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
// Freeze-then-write composite, same as the REST path: an edit that leaves the
|
||||
// currency alone keeps the rate frozen at settle time.
|
||||
@@ -497,10 +499,10 @@ export class BudgetMcp {
|
||||
access: { group: 'budget', mode: 'write' },
|
||||
})
|
||||
async deleteSettlement({ tripId, settlementId }: { tripId: number; settlementId: number }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.budget.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!(await this.budget.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('budget_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const deleted = this.budget.deleteSettlement(settlementId, tripId);
|
||||
const deleted = await this.budget.deleteSettlement(settlementId, tripId);
|
||||
if (!deleted) return errorResult('Settlement not found.');
|
||||
this.guards.safeBroadcast(tripId, 'budget:settlement-deleted', { settlementId });
|
||||
return ok({ success: true });
|
||||
@@ -518,7 +520,7 @@ export class BudgetMcp {
|
||||
})
|
||||
async tripBudgetResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
|
||||
const id = parseId(tripId);
|
||||
if (id === null || !this.budget.verifyTripAccess(id, ctx.userId)) {
|
||||
if (id === null || !(await this.budget.verifyTripAccess(id, ctx.userId))) {
|
||||
return {
|
||||
contents: [{
|
||||
uri: uri.href,
|
||||
@@ -527,7 +529,7 @@ export class BudgetMcp {
|
||||
}],
|
||||
};
|
||||
}
|
||||
const items = this.budget.listBudgetItems(id);
|
||||
const items = await this.budget.listBudgetItems(id);
|
||||
return {
|
||||
contents: [{
|
||||
uri: uri.href,
|
||||
@@ -547,7 +549,7 @@ export class BudgetMcp {
|
||||
})
|
||||
async tripBudgetPerPersonResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
|
||||
const id = parseId(tripId);
|
||||
if (id === null || !this.budget.verifyTripAccess(id, ctx.userId)) {
|
||||
if (id === null || !(await this.budget.verifyTripAccess(id, ctx.userId))) {
|
||||
return {
|
||||
contents: [{
|
||||
uri: uri.href,
|
||||
@@ -556,7 +558,7 @@ export class BudgetMcp {
|
||||
}],
|
||||
};
|
||||
}
|
||||
const summary = this.budget.getPerPersonSummary(id);
|
||||
const summary = await this.budget.getPerPersonSummary(id);
|
||||
return {
|
||||
contents: [{
|
||||
uri: uri.href,
|
||||
@@ -576,7 +578,7 @@ export class BudgetMcp {
|
||||
})
|
||||
async tripBudgetSettlementResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
|
||||
const id = parseId(tripId);
|
||||
if (id === null || !this.budget.verifyTripAccess(id, ctx.userId)) {
|
||||
if (id === null || !(await this.budget.verifyTripAccess(id, ctx.userId))) {
|
||||
return {
|
||||
contents: [{
|
||||
uri: uri.href,
|
||||
@@ -592,7 +594,7 @@ export class BudgetMcp {
|
||||
const tripCurrency = trip?.currency || 'EUR';
|
||||
const effectiveBase = tripCurrency.toUpperCase();
|
||||
const rates = await this.exchangeRates.getRates(effectiveBase);
|
||||
const settlement = this.budget.calculateSettlement(id, { base: effectiveBase, rates, tripCurrency });
|
||||
const settlement = await this.budget.calculateSettlement(id, { base: effectiveBase, rates, tripCurrency });
|
||||
return {
|
||||
contents: [{
|
||||
uri: uri.href,
|
||||
|
||||
@@ -6,6 +6,7 @@ import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
import type { User, BudgetItem, BudgetItemMember, BudgetItemPayer, BudgetItemReceipt } from '../../types';
|
||||
import { ExchangeRatesService } from './exchange-rates.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
|
||||
type Trip = TripAccess;
|
||||
|
||||
@@ -98,7 +99,7 @@ function allocateDisplayCents(cents: number[], factor: number, total = Math.roun
|
||||
* UserCleanupService, injects this class now.)
|
||||
*
|
||||
* Quirk fixes on top of the relocated legacy behavior: every multi-statement
|
||||
* write now runs in db.transaction() ("transactions are not optional"),
|
||||
* write now runs in uow.transactional() ("transactions are not optional"),
|
||||
* linkBudgetItemToReservation passes reservation_id through the insert instead
|
||||
* of a redundant second UPDATE, settlement re-selects are targeted single-row
|
||||
* queries instead of a full listSettlements() scan, settlement usernames use
|
||||
@@ -112,9 +113,10 @@ export class BudgetService {
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly exchangeRates: ExchangeRatesService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
verifyTripAccess(tripId: string | number, userId: number) {
|
||||
async verifyTripAccess(tripId: string | number, userId: number) {
|
||||
return this.db.canAccessTrip(tripId, userId);
|
||||
}
|
||||
|
||||
@@ -130,7 +132,7 @@ export class BudgetService {
|
||||
// Helpers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
private loadItemMembers(itemId: number | string) {
|
||||
private async loadItemMembers(itemId: number | string) {
|
||||
const rows = this.db.all<BudgetItemMember>(`
|
||||
SELECT bm.user_id, bm.paid, bm.amount, COALESCE(u.display_name, u.username) AS username, u.avatar
|
||||
FROM budget_item_members bm
|
||||
@@ -140,7 +142,7 @@ export class BudgetService {
|
||||
return rows.map(m => ({ ...m, avatar_url: avatarUrl(m) }));
|
||||
}
|
||||
|
||||
private loadItemPayers(itemId: number | string) {
|
||||
private async loadItemPayers(itemId: number | string) {
|
||||
const rows = this.db.all<BudgetItemPayer>(`
|
||||
SELECT bp.user_id, bp.amount, COALESCE(u.display_name, u.username) AS username, u.avatar
|
||||
FROM budget_item_payers bp
|
||||
@@ -150,7 +152,7 @@ export class BudgetService {
|
||||
return rows.map(p => ({ ...p, avatar_url: avatarUrl(p) }));
|
||||
}
|
||||
|
||||
private loadItemReceipts(itemId: number | string): BudgetItemReceipt[] {
|
||||
private async loadItemReceipts(itemId: number | string): Promise<BudgetItemReceipt[]> {
|
||||
const rows = this.db.all<{
|
||||
id: number;
|
||||
filename: string;
|
||||
@@ -183,7 +185,7 @@ export class BudgetService {
|
||||
* name and an avatar attached. Off-roster ids drop silently, the way the
|
||||
* packing and reservations assignee paths handle them.
|
||||
*/
|
||||
private rosterMemberIds(tripId: string | number, userIds: number[]): Set<number> {
|
||||
private async rosterMemberIds(tripId: string | number, userIds: number[]): Promise<Set<number>> {
|
||||
const unique = new Set(userIds);
|
||||
if (unique.size === 0) return new Set();
|
||||
const roster = this.db.rosterUserIds(tripId);
|
||||
@@ -195,10 +197,10 @@ export class BudgetService {
|
||||
* A negative amount is a real payer — the recipient of a refund (#2176) — and
|
||||
* is stored as such; only a zero (or NaN) amount says nothing and is dropped.
|
||||
*/
|
||||
private writeItemPayers(itemId: number | string, tripId: string | number, payers: { user_id: number; amount: number }[]) {
|
||||
private async writeItemPayers(itemId: number | string, tripId: string | number, payers: { user_id: number; amount: number }[]) {
|
||||
this.db.run('DELETE FROM budget_item_payers WHERE budget_item_id = ?', itemId);
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_payers (budget_item_id, user_id, amount) VALUES (?, ?, ?)');
|
||||
const known = this.rosterMemberIds(tripId, payers.map(p => p.user_id));
|
||||
const known = await this.rosterMemberIds(tripId, payers.map(p => p.user_id));
|
||||
const accepted: number[] = [];
|
||||
for (const p of payers) {
|
||||
if (!p.amount || !known.has(p.user_id)) continue;
|
||||
@@ -225,7 +227,7 @@ export class BudgetService {
|
||||
* nothing to do with the expense. A link whose file already sits in the trash
|
||||
* is left in place, so restoring that file brings it back attached.
|
||||
*/
|
||||
private unlinkReceipts(budgetItemId: number | string, keep: ReadonlySet<number> = new Set()) {
|
||||
private async unlinkReceipts(budgetItemId: number | string, keep: ReadonlySet<number> = new Set()) {
|
||||
const rows = this.db.all<{ id: number; file_id: number; reservation_id: number | null; assignment_id: number | null; place_id: number | null }>(
|
||||
`SELECT fl.id, fl.file_id, fl.reservation_id, fl.assignment_id, fl.place_id
|
||||
FROM file_links fl
|
||||
@@ -247,7 +249,7 @@ export class BudgetService {
|
||||
// CRUD
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
listBudgetItems(tripId: string | number) {
|
||||
async listBudgetItems(tripId: string | number) {
|
||||
const items = this.db.all<BudgetItem>(`
|
||||
SELECT bi.* FROM budget_items bi
|
||||
LEFT JOIN budget_category_order bco ON bco.trip_id = bi.trip_id AND bco.category = bi.category
|
||||
@@ -437,10 +439,10 @@ export class BudgetService {
|
||||
`, prev, tripId);
|
||||
};
|
||||
|
||||
this.db.transaction(() => { rebase('budget_items'); rebase('budget_settlements'); pinPlaces(); });
|
||||
await this.uow.transactional(async () => { rebase('budget_items'); rebase('budget_settlements'); pinPlaces(); });
|
||||
}
|
||||
|
||||
createBudgetItem(
|
||||
async createBudgetItem(
|
||||
tripId: string | number,
|
||||
data: {
|
||||
category?: string; name: string; total_price?: number;
|
||||
@@ -454,7 +456,7 @@ export class BudgetService {
|
||||
receipt_file_ids?: number[];
|
||||
},
|
||||
) {
|
||||
return this.db.transaction(() => {
|
||||
return await this.uow.transactional(async () => {
|
||||
const maxOrder = this.db.get<{ max: number | null }>('SELECT MAX(sort_order) as max FROM budget_items WHERE trip_id = ?', tripId)!;
|
||||
const sortOrder = (maxOrder.max !== null ? maxOrder.max : -1) + 1;
|
||||
|
||||
@@ -474,9 +476,9 @@ export class BudgetService {
|
||||
const payerTotal = sumMoney((data.payers || []).filter(p => p.amount !== 0).map(p => p.amount));
|
||||
const total = data.payers && data.payers.length > 0 ? payerTotal : (data.total_price || 0);
|
||||
|
||||
const knownMembers = data.members ? this.rosterMemberIds(tripId, data.members.map(m => m.user_id)) : null;
|
||||
const knownMembers = data.members ? await this.rosterMemberIds(tripId, data.members.map(m => m.user_id)) : null;
|
||||
const members = data.members && knownMembers ? data.members.filter(m => knownMembers.has(m.user_id)) : undefined;
|
||||
const knownIds = data.member_ids ? this.rosterMemberIds(tripId, data.member_ids) : null;
|
||||
const knownIds = data.member_ids ? await this.rosterMemberIds(tripId, data.member_ids) : null;
|
||||
const memberIds = data.member_ids && knownIds ? data.member_ids.filter(uid => knownIds.has(uid)) : undefined;
|
||||
|
||||
const { note, ticket } = splitLegacyTicketNote(data.note, data.ticket_json);
|
||||
@@ -500,7 +502,7 @@ export class BudgetService {
|
||||
);
|
||||
|
||||
const itemId = result.lastInsertRowid as number;
|
||||
if (data.payers && data.payers.length > 0) this.writeItemPayers(itemId, tripId, data.payers);
|
||||
if (data.payers && data.payers.length > 0) await this.writeItemPayers(itemId, tripId, data.payers);
|
||||
if (members && members.length > 0) {
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, ?)');
|
||||
for (const m of members) insert.run(itemId, m.user_id, m.amount !== undefined && m.amount !== null ? m.amount : null);
|
||||
@@ -521,34 +523,34 @@ export class BudgetService {
|
||||
}
|
||||
|
||||
const item = this.db.get<BudgetItem>('SELECT * FROM budget_items WHERE id = ?', itemId)!;
|
||||
item.members = this.loadItemMembers(itemId);
|
||||
item.payers = this.loadItemPayers(itemId);
|
||||
item.receipts = this.loadItemReceipts(itemId);
|
||||
item.members = await this.loadItemMembers(itemId);
|
||||
item.payers = await this.loadItemPayers(itemId);
|
||||
item.receipts = await this.loadItemReceipts(itemId);
|
||||
return item;
|
||||
});
|
||||
}
|
||||
|
||||
/** Fetch a single budget item hydrated with its members, payers, and receipts, scoped to the trip. */
|
||||
getBudgetItem(id: string | number, tripId: string | number): BudgetItem | null {
|
||||
async getBudgetItem(id: string | number, tripId: string | number): Promise<BudgetItem | null> {
|
||||
const item = this.db.get<BudgetItem>('SELECT * FROM budget_items WHERE id = ? AND trip_id = ?', id, tripId);
|
||||
if (!item) return null;
|
||||
item.members = this.loadItemMembers(id);
|
||||
item.payers = this.loadItemPayers(id);
|
||||
item.receipts = this.loadItemReceipts(id);
|
||||
item.members = await this.loadItemMembers(id);
|
||||
item.payers = await this.loadItemPayers(id);
|
||||
item.receipts = await this.loadItemReceipts(id);
|
||||
return item;
|
||||
}
|
||||
|
||||
linkBudgetItemToReservation(
|
||||
async linkBudgetItemToReservation(
|
||||
tripId: string | number,
|
||||
reservationId: number,
|
||||
data: { name: string; category?: string; total_price: number },
|
||||
) {
|
||||
// createBudgetItem accepts reservation_id directly — the legacy separate
|
||||
// UPDATE after the insert was redundant (and non-atomic).
|
||||
return this.createBudgetItem(tripId, { ...data, reservation_id: reservationId });
|
||||
return await this.createBudgetItem(tripId, { ...data, reservation_id: reservationId });
|
||||
}
|
||||
|
||||
updateBudgetItem(
|
||||
async updateBudgetItem(
|
||||
id: string | number,
|
||||
tripId: string | number,
|
||||
data: {
|
||||
@@ -561,7 +563,7 @@ export class BudgetService {
|
||||
receipt_file_ids?: number[];
|
||||
},
|
||||
) {
|
||||
return this.db.transaction(() => {
|
||||
return await this.uow.transactional(async () => {
|
||||
const item = this.db.get('SELECT * FROM budget_items WHERE id = ? AND trip_id = ?', id, tripId);
|
||||
if (!item) return null;
|
||||
|
||||
@@ -602,7 +604,7 @@ export class BudgetService {
|
||||
|
||||
// Optional inline payer/member replacement (the edit modal saves all at once).
|
||||
if (data.payers !== undefined) {
|
||||
this.writeItemPayers(id, tripId, data.payers);
|
||||
await this.writeItemPayers(id, tripId, data.payers);
|
||||
// writeItemPayers derives total_price from the payer sum (0 for no payers).
|
||||
// A "recorded total, nobody assigned" expense clears payers but still carries
|
||||
// an explicit total_price — re-apply it so it isn't clobbered to 0.
|
||||
@@ -611,14 +613,14 @@ export class BudgetService {
|
||||
}
|
||||
}
|
||||
if (data.members !== undefined) {
|
||||
const known = this.rosterMemberIds(tripId, data.members.map(m => m.user_id));
|
||||
const known = await this.rosterMemberIds(tripId, data.members.map(m => m.user_id));
|
||||
const members = data.members.filter(m => known.has(m.user_id));
|
||||
this.db.run('DELETE FROM budget_item_members WHERE budget_item_id = ?', id);
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, ?)');
|
||||
for (const m of members) insert.run(id, m.user_id, m.amount !== undefined && m.amount !== null ? m.amount : null);
|
||||
this.db.run('UPDATE budget_items SET persons = ? WHERE id = ?', members.length || null, id);
|
||||
} else if (data.member_ids !== undefined) {
|
||||
const known = this.rosterMemberIds(tripId, data.member_ids);
|
||||
const known = await this.rosterMemberIds(tripId, data.member_ids);
|
||||
const memberIds = data.member_ids.filter(uid => known.has(uid));
|
||||
this.db.run('DELETE FROM budget_item_members WHERE budget_item_id = ?', id);
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid, amount) VALUES (?, ?, 0, NULL)');
|
||||
@@ -643,7 +645,7 @@ export class BudgetService {
|
||||
// second spare row into the pair the first one just wrote.
|
||||
const wanted = [...new Set(data.receipt_file_ids.map(Number))];
|
||||
const keep = new Set(wanted);
|
||||
this.unlinkReceipts(id, keep);
|
||||
await this.unlinkReceipts(id, keep);
|
||||
if (wanted.length > 0) {
|
||||
const insertLink = this.db.prepare('INSERT OR IGNORE INTO file_links (file_id, budget_item_id) VALUES (?, ?)');
|
||||
const adopt = this.db.prepare('UPDATE file_links SET budget_item_id = ? WHERE id = ?');
|
||||
@@ -671,9 +673,9 @@ export class BudgetService {
|
||||
}
|
||||
|
||||
const updated = this.db.get<BudgetItem>('SELECT * FROM budget_items WHERE id = ?', id)!;
|
||||
updated.members = this.loadItemMembers(id);
|
||||
updated.payers = this.loadItemPayers(id);
|
||||
updated.receipts = this.loadItemReceipts(id);
|
||||
updated.members = await this.loadItemMembers(id);
|
||||
updated.payers = await this.loadItemPayers(id);
|
||||
updated.receipts = await this.loadItemReceipts(id);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
@@ -682,38 +684,38 @@ export class BudgetService {
|
||||
// Payers
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
setItemPayers(id: string | number, tripId: string | number, payers: { user_id: number; amount: number }[]) {
|
||||
return this.db.transaction(() => {
|
||||
async setItemPayers(id: string | number, tripId: string | number, payers: { user_id: number; amount: number }[]) {
|
||||
return await this.uow.transactional(async () => {
|
||||
const item = this.db.get('SELECT id FROM budget_items WHERE id = ? AND trip_id = ?', id, tripId);
|
||||
if (!item) return null;
|
||||
this.writeItemPayers(id, tripId, payers);
|
||||
await this.writeItemPayers(id, tripId, payers);
|
||||
const updated = this.db.get<BudgetItem>('SELECT * FROM budget_items WHERE id = ?', id)!;
|
||||
updated.members = this.loadItemMembers(id);
|
||||
updated.payers = this.loadItemPayers(id);
|
||||
updated.members = await this.loadItemMembers(id);
|
||||
updated.payers = await this.loadItemPayers(id);
|
||||
return updated;
|
||||
});
|
||||
}
|
||||
|
||||
deleteBudgetItem(id: string | number, tripId: string | number): boolean {
|
||||
async deleteBudgetItem(id: string | number, tripId: string | number): Promise<boolean> {
|
||||
const item = this.db.get<{ id: number; reservation_id: number | null }>(
|
||||
'SELECT id, reservation_id FROM budget_items WHERE id = ? AND trip_id = ?', id, tripId,
|
||||
);
|
||||
if (!item) return false;
|
||||
return this.db.transaction(() => {
|
||||
return await this.uow.transactional(async () => {
|
||||
// Find all receipts attached to this item before deleting it
|
||||
// The receipts stay; only their tie to this expense goes. Rows that
|
||||
// carry nothing else are removed, rows that also point at a place or a
|
||||
// booking keep those. A link on a file already in the trash is left for
|
||||
// the SET NULL on the foreign key, so restoring the file does not bring
|
||||
// back a pointer to an expense that no longer exists.
|
||||
this.unlinkReceipts(id);
|
||||
await this.unlinkReceipts(id);
|
||||
this.db.run('DELETE FROM budget_items WHERE id = ?', id);
|
||||
|
||||
// The booking keeps a copy of this expense's total in its metadata, and
|
||||
// the reservation update path preserves that copy across edits. With the
|
||||
// expense gone there is nothing left to mirror, so drop it here rather
|
||||
// than leave a price on the card that no longer has anything behind it.
|
||||
if (item.reservation_id) this.clearReservationPrice(tripId, item.reservation_id);
|
||||
if (item.reservation_id) await this.clearReservationPrice(tripId, item.reservation_id);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
@@ -722,7 +724,7 @@ export class BudgetService {
|
||||
* The counterpart to syncReservationPrice: take the mirrored total back off
|
||||
* the booking. Non-fatal, exactly like the writer.
|
||||
*/
|
||||
private clearReservationPrice(tripId: string | number, reservationId: number): void {
|
||||
private async clearReservationPrice(tripId: string | number, reservationId: number): Promise<void> {
|
||||
try {
|
||||
const reservation = this.db.get<{ id: number; metadata: string | null }>(
|
||||
'SELECT id, metadata FROM reservations WHERE id = ? AND trip_id = ?',
|
||||
@@ -745,8 +747,8 @@ export class BudgetService {
|
||||
// Members
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
updateMembers(id: string | number, tripId: string | number, userIds: number[]) {
|
||||
return this.db.transaction(() => {
|
||||
async updateMembers(id: string | number, tripId: string | number, userIds: number[]) {
|
||||
return await this.uow.transactional(async () => {
|
||||
const item = this.db.get('SELECT * FROM budget_items WHERE id = ? AND trip_id = ?', id, tripId);
|
||||
if (!item) return null;
|
||||
|
||||
@@ -756,7 +758,7 @@ export class BudgetService {
|
||||
|
||||
this.db.run('DELETE FROM budget_item_members WHERE budget_item_id = ?', id);
|
||||
|
||||
const known = this.rosterMemberIds(tripId, userIds);
|
||||
const known = await this.rosterMemberIds(tripId, userIds);
|
||||
const memberIds = userIds.filter(uid => known.has(uid));
|
||||
if (memberIds.length > 0) {
|
||||
const insert = this.db.prepare('INSERT OR IGNORE INTO budget_item_members (budget_item_id, user_id, paid) VALUES (?, ?, ?)');
|
||||
@@ -767,14 +769,14 @@ export class BudgetService {
|
||||
}
|
||||
|
||||
// loadItemMembers already applies avatar_url — the legacy second .map was redundant.
|
||||
const members = this.loadItemMembers(id);
|
||||
const members = await this.loadItemMembers(id);
|
||||
const updated = this.db.get<BudgetItem>('SELECT * FROM budget_items WHERE id = ?', id)!;
|
||||
return { members, item: updated };
|
||||
});
|
||||
}
|
||||
|
||||
removeUserFromBudgetItems(userId: number): void {
|
||||
this.db.transaction(() => {
|
||||
async removeUserFromBudgetItems(userId: number): Promise<void> {
|
||||
await this.uow.transactional(async () => {
|
||||
const itemIds = this.db.all<{ budget_item_id: number }>(
|
||||
'SELECT DISTINCT budget_item_id FROM budget_item_members WHERE user_id = ?',
|
||||
userId,
|
||||
@@ -794,7 +796,7 @@ export class BudgetService {
|
||||
});
|
||||
}
|
||||
|
||||
toggleMemberPaid(id: string | number, tripId: string | number, userId: string | number, paid: boolean) {
|
||||
async toggleMemberPaid(id: string | number, tripId: string | number, userId: string | number, paid: boolean) {
|
||||
// Resolve the item within the caller's trip before updating.
|
||||
const item = this.db.get('SELECT id FROM budget_items WHERE id = ? AND trip_id = ?', id, tripId);
|
||||
if (!item) return null;
|
||||
@@ -814,7 +816,7 @@ export class BudgetService {
|
||||
// Per-person summary
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
getPerPersonSummary(tripId: string | number) {
|
||||
async getPerPersonSummary(tripId: string | number) {
|
||||
const summary = this.db.all<{ user_id: number; username: string; avatar: string | null; total_assigned: number; total_paid: number; items_count: number }>(`
|
||||
SELECT bm.user_id, COALESCE(u.display_name, u.username) AS username, u.avatar,
|
||||
SUM(COALESCE(bm.amount, bi.total_price * 1.0 / (SELECT COUNT(*) FROM budget_item_members WHERE budget_item_id = bi.id))) as total_assigned,
|
||||
@@ -880,7 +882,7 @@ export class BudgetService {
|
||||
* expense list converted again on the client with today's rate would not add up
|
||||
* to a figure that was booked at the rate frozen on entry.
|
||||
*/
|
||||
calculateSettlement(
|
||||
async calculateSettlement(
|
||||
tripId: string | number,
|
||||
opts: { base?: string; rates?: Record<string, number> | null; tripCurrency?: string } = {},
|
||||
) {
|
||||
@@ -1035,7 +1037,7 @@ export class BudgetService {
|
||||
// counts even when neither user has an expense-derived balance yet — a manual
|
||||
// payment, or one left behind after its expense was deleted, then correctly
|
||||
// surfaces as an amount still to square up instead of silently vanishing.
|
||||
const settlements = this.listSettlements(tripId);
|
||||
const settlements = await this.listSettlements(tripId);
|
||||
const ensureSettled = (id: number, username: string | undefined, avatar_url: string | null | undefined) => {
|
||||
if (!balances[id]) balances[id] = { user_id: id, username: username || '', avatar_url: avatar_url ?? null, cents: 0 };
|
||||
return balances[id];
|
||||
@@ -1162,7 +1164,7 @@ export class BudgetService {
|
||||
};
|
||||
}
|
||||
|
||||
listSettlements(tripId: string | number) {
|
||||
async listSettlements(tripId: string | number) {
|
||||
const rows = this.db.all<SettlementRow>(
|
||||
`${BudgetService.SETTLEMENT_SELECT}
|
||||
WHERE s.trip_id = ?
|
||||
@@ -1172,7 +1174,7 @@ export class BudgetService {
|
||||
}
|
||||
|
||||
/** Targeted single-row read (the legacy re-select was a full listSettlements scan). */
|
||||
getSettlement(id: string | number, tripId: string | number) {
|
||||
async getSettlement(id: string | number, tripId: string | number) {
|
||||
const row = this.db.get<SettlementRow>(
|
||||
`${BudgetService.SETTLEMENT_SELECT}
|
||||
WHERE s.trip_id = ? AND s.id = ?
|
||||
@@ -1181,7 +1183,7 @@ export class BudgetService {
|
||||
}
|
||||
|
||||
/** Raw settlement insert (no FX freeze) — the REST path wraps it in createSettlement. */
|
||||
insertSettlement(
|
||||
async insertSettlement(
|
||||
tripId: string | number,
|
||||
data: { from_user_id: number; to_user_id: number; amount: number; currency?: string | null; exchange_rate?: number; settled_at?: string | null },
|
||||
createdByUserId?: number,
|
||||
@@ -1194,11 +1196,11 @@ export class BudgetService {
|
||||
data.settled_at || null,
|
||||
createdByUserId ?? null,
|
||||
);
|
||||
return this.getSettlement(Number(result.lastInsertRowid), tripId);
|
||||
return await this.getSettlement(Number(result.lastInsertRowid), tripId);
|
||||
}
|
||||
|
||||
/** Raw settlement update (no FX freeze) — the REST path wraps it in updateSettlement. */
|
||||
applySettlementUpdate(
|
||||
async applySettlementUpdate(
|
||||
id: string | number,
|
||||
tripId: string | number,
|
||||
data: { from_user_id: number; to_user_id: number; amount: number; currency?: string | null; exchange_rate?: number; settled_at?: string | null },
|
||||
@@ -1219,10 +1221,10 @@ export class BudgetService {
|
||||
data.settled_at !== undefined ? 1 : 0, data.settled_at || null,
|
||||
id,
|
||||
);
|
||||
return this.getSettlement(id, tripId);
|
||||
return await this.getSettlement(id, tripId);
|
||||
}
|
||||
|
||||
deleteSettlement(id: string | number, tripId: string | number): boolean {
|
||||
async deleteSettlement(id: string | number, tripId: string | number): Promise<boolean> {
|
||||
const row = this.db.get('SELECT id FROM budget_settlements WHERE id = ? AND trip_id = ?', id, tripId);
|
||||
if (!row) return false;
|
||||
this.db.run('DELETE FROM budget_settlements WHERE id = ?', id);
|
||||
@@ -1233,36 +1235,36 @@ export class BudgetService {
|
||||
// Controller-facing surface (unchanged from the pre-fold wrapper)
|
||||
// -------------------------------------------------------------------------
|
||||
|
||||
list(tripId: string) {
|
||||
return this.listBudgetItems(tripId);
|
||||
async list(tripId: string) {
|
||||
return await this.listBudgetItems(tripId);
|
||||
}
|
||||
|
||||
perPersonSummary(tripId: string) {
|
||||
return this.getPerPersonSummary(tripId);
|
||||
async perPersonSummary(tripId: string) {
|
||||
return await this.getPerPersonSummary(tripId);
|
||||
}
|
||||
|
||||
async settlement(tripId: string, base: string | undefined, tripCurrency: string) {
|
||||
const effectiveBase = (base || tripCurrency || 'EUR').toUpperCase();
|
||||
const rates = await this.exchangeRates.getRates(effectiveBase);
|
||||
return this.calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency });
|
||||
return await this.calculateSettlement(tripId, { base: effectiveBase, rates, tripCurrency });
|
||||
}
|
||||
|
||||
async create(tripId: string, data: Parameters<BudgetService['createBudgetItem']>[1]) {
|
||||
await this.freezeForeignRate(tripId, data);
|
||||
return this.createBudgetItem(tripId, data);
|
||||
return await this.createBudgetItem(tripId, data);
|
||||
}
|
||||
|
||||
async update(id: string | number, tripId: string | number, data: Parameters<BudgetService['updateBudgetItem']>[2]) {
|
||||
await this.freezeForeignRate(tripId, data, id);
|
||||
return this.updateBudgetItem(id, tripId, data);
|
||||
return await this.updateBudgetItem(id, tripId, data);
|
||||
}
|
||||
|
||||
remove(id: string, tripId: string): boolean {
|
||||
return this.deleteBudgetItem(id, tripId);
|
||||
async remove(id: string, tripId: string): Promise<boolean> {
|
||||
return await this.deleteBudgetItem(id, tripId);
|
||||
}
|
||||
|
||||
setPayers(id: string, tripId: string, payers: { user_id: number; amount: number }[]) {
|
||||
return this.setItemPayers(id, tripId, payers);
|
||||
async setPayers(id: string, tripId: string, payers: { user_id: number; amount: number }[]) {
|
||||
return await this.setItemPayers(id, tripId, payers);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1273,41 +1275,41 @@ export class BudgetService {
|
||||
* found" 404, which is also what keeps the endpoint from confirming whether
|
||||
* an id it rejected exists at all.
|
||||
*/
|
||||
private settlementPartiesOnTrip(tripId: string | number, data: { from_user_id: number; to_user_id: number }): boolean {
|
||||
private async settlementPartiesOnTrip(tripId: string | number, data: { from_user_id: number; to_user_id: number }): Promise<boolean> {
|
||||
const roster = this.db.rosterUserIds(tripId);
|
||||
return roster.has(data.from_user_id) && roster.has(data.to_user_id);
|
||||
}
|
||||
|
||||
async createSettlement(tripId: string | number, data: { from_user_id: number; to_user_id: number; amount: number; currency?: string | null; settled_at?: string | null }, userId: number) {
|
||||
if (!this.settlementPartiesOnTrip(tripId, data)) return null;
|
||||
if (!(await this.settlementPartiesOnTrip(tripId, data))) return null;
|
||||
// Freeze the FX rate for the display currency the amount was entered in so the
|
||||
// transfer keeps cancelling its expense when live rates drift (#1445).
|
||||
await this.freezeForeignRate(tripId, data);
|
||||
return this.insertSettlement(tripId, data, userId);
|
||||
return await this.insertSettlement(tripId, data, userId);
|
||||
}
|
||||
|
||||
async updateSettlement(id: string | number, tripId: string | number, data: { from_user_id: number; to_user_id: number; amount: number; currency?: string | null; settled_at?: string | null }) {
|
||||
// Pass the settlement's stored currency so an edit that doesn't change it keeps
|
||||
// the already-frozen rate (#1445) — otherwise a live-rate drift would re-open a
|
||||
// settled position on an unrelated edit.
|
||||
if (!this.settlementPartiesOnTrip(tripId, data)) return null;
|
||||
const existing = this.getSettlement(id, tripId);
|
||||
if (!(await this.settlementPartiesOnTrip(tripId, data))) return null;
|
||||
const existing = await this.getSettlement(id, tripId);
|
||||
await this.freezeForeignRate(tripId, data, undefined, existing?.currency ?? null);
|
||||
return this.applySettlementUpdate(id, tripId, data);
|
||||
return await this.applySettlementUpdate(id, tripId, data);
|
||||
}
|
||||
|
||||
reorderItems(tripId: string, orderedIds: number[]): void {
|
||||
async reorderItems(tripId: string, orderedIds: number[]): Promise<void> {
|
||||
const update = this.db.prepare('UPDATE budget_items SET sort_order = ? WHERE id = ? AND trip_id = ?');
|
||||
this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
orderedIds.forEach((id, index) => update.run(index, id, tripId));
|
||||
});
|
||||
}
|
||||
|
||||
reorderCategories(tripId: string, orderedCategories: string[]): void {
|
||||
async reorderCategories(tripId: string, orderedCategories: string[]): Promise<void> {
|
||||
const upsert = this.db.prepare(
|
||||
'INSERT INTO budget_category_order (trip_id, category, sort_order) VALUES (?, ?, ?) ON CONFLICT(trip_id, category) DO UPDATE SET sort_order = excluded.sort_order'
|
||||
);
|
||||
this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
orderedCategories.forEach((cat, index) => upsert.run(tripId, cat, index));
|
||||
});
|
||||
}
|
||||
@@ -1317,7 +1319,7 @@ export class BudgetService {
|
||||
* total_price changes, write it into the reservation's metadata and broadcast
|
||||
* reservation:updated. Non-fatal — a failure here never breaks the budget update.
|
||||
*/
|
||||
syncReservationPrice(tripId: string, reservationId: number, totalPrice: number, socketId: string | undefined): void {
|
||||
async syncReservationPrice(tripId: string, reservationId: number, totalPrice: number, socketId: string | undefined): Promise<void> {
|
||||
try {
|
||||
const reservation = this.db.get<{ id: number; metadata: string | null }>(
|
||||
'SELECT id, metadata FROM reservations WHERE id = ? AND trip_id = ?',
|
||||
|
||||
@@ -37,10 +37,10 @@ export class CostsRpc {
|
||||
) {}
|
||||
|
||||
@PluginMethod('costs.getByTrip', { permission: 'db:read:costs' })
|
||||
getByTrip(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
return this.guards.tripRead(params, ctx, async () => {
|
||||
async getByTrip(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
return await this.guards.tripRead(params, ctx, async () => {
|
||||
await this.requireBudgetAddon();
|
||||
return this.budget.listBudgetItems(num(params.tripId, 'tripId'));
|
||||
return await this.budget.listBudgetItems(num(params.tripId, 'tripId'));
|
||||
});
|
||||
}
|
||||
|
||||
@@ -54,7 +54,11 @@ export class CostsRpc {
|
||||
// one, so injecting TripsService here would close a cycle. Same id set,
|
||||
// same newest-first order.
|
||||
const tripIds = await this.membership.listAccessibleTripIds(ctx.actingUserId);
|
||||
return tripIds.flatMap((id) => this.budget.listBudgetItems(id));
|
||||
// Sequential, not Promise.all: the legacy flatMap read each trip's items one
|
||||
// after the other, in id order, and the output order is the contract here.
|
||||
const items: unknown[] = [];
|
||||
for (const id of tripIds) items.push(...(await this.budget.listBudgetItems(id)));
|
||||
return items;
|
||||
}
|
||||
|
||||
@PluginMethod('costs.create', { permission: 'db:write:costs' })
|
||||
@@ -95,7 +99,7 @@ export class CostsRpc {
|
||||
const actor = this.requireCostActor(ctx);
|
||||
await this.requireBudgetAddon();
|
||||
await this.requireCostEdit(tripId, actor);
|
||||
if (!this.budget.remove(String(itemId), String(tripId))) {
|
||||
if (!(await this.budget.remove(String(itemId), String(tripId)))) {
|
||||
throw new ForbiddenResource(`no cost ${itemId} on trip ${tripId}`);
|
||||
}
|
||||
this.realtime.broadcast(tripId, 'budget:deleted', { itemId });
|
||||
|
||||
@@ -39,8 +39,8 @@ export class CategoriesMcp {
|
||||
) {}
|
||||
|
||||
/** The AuthService.isDemoUser check without the auth graph (demo-write.ts). */
|
||||
private isDemoUser(userId: number): boolean {
|
||||
return isDemoUserId(this.env, this.db, userId);
|
||||
private async isDemoUser(userId: number): Promise<boolean> {
|
||||
return await isDemoUserId(this.env, this.db, userId);
|
||||
}
|
||||
|
||||
@Tool({
|
||||
@@ -67,7 +67,7 @@ export class CategoriesMcp {
|
||||
access: { group: 'places', mode: 'write' },
|
||||
})
|
||||
async createCategory({ name, color, icon }: { name: string; color?: string; icon?: string }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
// The palette is instance-wide; the REST route restricts management to admins. Match it.
|
||||
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
|
||||
const category = await this.categories.create(ctx.userId, name, color, icon);
|
||||
@@ -87,7 +87,7 @@ export class CategoriesMcp {
|
||||
access: { group: 'places', mode: 'write' },
|
||||
})
|
||||
async updateCategory({ categoryId, name, color, icon }: { categoryId: number; name?: string; color?: string; icon?: string }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
|
||||
if (!(await this.categories.getById(categoryId))) return errorResult('Category not found');
|
||||
const category = await this.categories.update(categoryId, name, color, icon);
|
||||
@@ -104,7 +104,7 @@ export class CategoriesMcp {
|
||||
access: { group: 'places', mode: 'write' },
|
||||
})
|
||||
async deleteCategory({ categoryId }: { categoryId: number }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.guards.isAdminUser(ctx.userId)) return adminRequired();
|
||||
if (!(await this.categories.getById(categoryId))) return errorResult('Category not found');
|
||||
await this.categories.remove(categoryId);
|
||||
|
||||
@@ -29,7 +29,7 @@ export function isDemoWriteBlocked(env: RuntimeEnvService, email: string | null
|
||||
* relocated so surfaces that hold only a user id (the *.mcp.ts demo guards)
|
||||
* don't need the whole auth graph for one check.
|
||||
*/
|
||||
export function isDemoUserId(env: RuntimeEnvService, db: DatabaseService, userId: number): boolean {
|
||||
export async function isDemoUserId(env: RuntimeEnvService, db: DatabaseService, userId: number): Promise<boolean> {
|
||||
if (!env.isDemoMode()) return false;
|
||||
const user = db.get<{ email: string }>('SELECT email FROM users WHERE id = ?', userId);
|
||||
return isDemoEmail(user?.email);
|
||||
|
||||
@@ -21,9 +21,9 @@ export class IdempotencyCleanupJob implements OnApplicationBootstrap {
|
||||
this.registrar.register('idempotency-cleanup', '0 3 * * *', () => this.tick());
|
||||
}
|
||||
|
||||
tick(): void {
|
||||
async tick(): Promise<void> {
|
||||
try {
|
||||
const removed = purgeExpiredIdempotencyKeys(undefined, undefined, this.db);
|
||||
const removed = await purgeExpiredIdempotencyKeys(undefined, undefined, this.db);
|
||||
if (removed > 0) {
|
||||
logInfo(`Idempotency cleanup: removed ${removed} expired key(s)`);
|
||||
}
|
||||
|
||||
@@ -18,11 +18,11 @@ export interface PurgeDb {
|
||||
/** Delete idempotency keys older than the configured TTL. Returns rows removed.
|
||||
* The db is a required parameter now (DatabaseService satisfies PurgeDb
|
||||
* structurally) — the old lazy-require default died with the scheduler. */
|
||||
export function purgeExpiredIdempotencyKeys(
|
||||
export async function purgeExpiredIdempotencyKeys(
|
||||
now: number = Date.now(),
|
||||
ttlSeconds: number = readEnv().session.idempotencyTtlSeconds,
|
||||
database: PurgeDb,
|
||||
): number {
|
||||
): Promise<number> {
|
||||
const cutoff = Math.floor(now / 1000) - ttlSeconds;
|
||||
const result = database.prepare('DELETE FROM idempotency_keys WHERE created_at < ?').run(cutoff);
|
||||
return result.changes;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { CallHandler, ExecutionContext, HttpException, Injectable, NestInterceptor } from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import { Observable, from, of } from 'rxjs';
|
||||
import { finalize, switchMap } from 'rxjs/operators';
|
||||
import { finalize, mergeAll, switchMap } from 'rxjs/operators';
|
||||
import { DatabaseService } from '../database/database.service';
|
||||
|
||||
/**
|
||||
@@ -53,7 +53,7 @@ interface IdempotencyRow {
|
||||
export class IdempotencyInterceptor implements NestInterceptor {
|
||||
constructor(private readonly database: DatabaseService) {}
|
||||
|
||||
intercept(context: ExecutionContext, next: CallHandler): Observable<unknown> {
|
||||
async intercept(context: ExecutionContext, next: CallHandler): Promise<Observable<unknown>> {
|
||||
const req = context.switchToHttp().getRequest<Request & { user?: { id: number } }>();
|
||||
const res = context.switchToHttp().getResponse<Response>();
|
||||
|
||||
@@ -71,32 +71,48 @@ export class IdempotencyInterceptor implements NestInterceptor {
|
||||
throw new HttpException({ error: 'X-Idempotency-Key exceeds maximum length of 128 characters' }, 400);
|
||||
}
|
||||
|
||||
const existing = this.lookup(key, userId, req);
|
||||
const existing = await this.lookup(key, userId, req);
|
||||
if (existing) return this.replay(existing, res);
|
||||
|
||||
const signature = `${userId}|${req.method}|${req.path}|${key}`;
|
||||
const pending = inFlight.get(signature);
|
||||
if (pending !== undefined) {
|
||||
// The wait stays inside the stream, where it was: `intercept` answers at
|
||||
// once with an Observable that only produces when the first request has.
|
||||
// `afterPending` is async now (the store read is), so what switchMap emits
|
||||
// is itself an Observable and needs the extra mergeAll to be flattened.
|
||||
return from(pending).pipe(
|
||||
switchMap(() => {
|
||||
const stored = this.lookup(key, userId, req);
|
||||
if (stored) return this.replay(stored, res);
|
||||
// The first request answered without caching anything (it failed, or
|
||||
// it never went through res.json). Run this one normally rather than
|
||||
// inventing a response for it.
|
||||
return this.run(signature, key, userId, req, res, next);
|
||||
}),
|
||||
switchMap(() => this.afterPending(signature, key, userId, req, res, next)),
|
||||
mergeAll(),
|
||||
);
|
||||
}
|
||||
|
||||
return this.run(signature, key, userId, req, res, next);
|
||||
return await this.run(signature, key, userId, req, res, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* What a waiter does once the request holding its key has answered: replay the
|
||||
* response that request stored, or — when it stored nothing (it failed, or it
|
||||
* never went through res.json) — run normally rather than inventing one.
|
||||
*/
|
||||
private async afterPending(
|
||||
signature: string,
|
||||
key: string,
|
||||
userId: number,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: CallHandler,
|
||||
): Promise<Observable<unknown>> {
|
||||
const stored = await this.lookup(key, userId, req);
|
||||
if (stored) return this.replay(stored, res);
|
||||
return await this.run(signature, key, userId, req, res, next);
|
||||
}
|
||||
|
||||
/**
|
||||
* Scope the lookup by method + path as well as user, so the same key replayed
|
||||
* against a different endpoint can't return an unrelated cached body.
|
||||
*/
|
||||
private lookup(key: string, userId: number, req: Request): IdempotencyRow | undefined {
|
||||
private async lookup(key: string, userId: number, req: Request): Promise<IdempotencyRow | undefined> {
|
||||
return this.database.get<IdempotencyRow>(
|
||||
'SELECT status_code, response_body FROM idempotency_keys WHERE key = ? AND user_id = ? AND method = ? AND path = ?',
|
||||
key, userId, req.method, req.path,
|
||||
@@ -108,14 +124,14 @@ export class IdempotencyInterceptor implements NestInterceptor {
|
||||
return of(JSON.parse(row.response_body));
|
||||
}
|
||||
|
||||
private run(
|
||||
private async run(
|
||||
signature: string,
|
||||
key: string,
|
||||
userId: number,
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: CallHandler,
|
||||
): Observable<unknown> {
|
||||
): Promise<Observable<unknown>> {
|
||||
const originalJson = res.json.bind(res);
|
||||
const database = this.database;
|
||||
|
||||
|
||||
@@ -38,33 +38,33 @@ export class DayNotesController {
|
||||
|
||||
|
||||
@Get()
|
||||
list(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('dayId') dayId: string) {
|
||||
return { notes: this.notes.list(dayId, tripId) };
|
||||
async list(@CurrentUser() user: User, @Param('tripId') tripId: string, @Param('dayId') dayId: string) {
|
||||
return { notes: await this.notes.list(dayId, tripId) };
|
||||
}
|
||||
|
||||
@RequirePermission('day_edit')
|
||||
@Post()
|
||||
create(
|
||||
async create(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('dayId') dayId: string,
|
||||
@Body() body: DayNoteCreateDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
if (!this.notes.dayExists(dayId, tripId)) {
|
||||
if (!(await this.notes.dayExists(dayId, tripId))) {
|
||||
throw new HttpException({ error: 'Day not found' }, 404);
|
||||
}
|
||||
if (!body.text?.trim()) {
|
||||
throw new HttpException({ error: 'Text required' }, 400);
|
||||
}
|
||||
const note = this.notes.create(dayId, tripId, body.text, body.time, body.icon, body.sort_order, body.color);
|
||||
const note = await this.notes.create(dayId, tripId, body.text, body.time, body.icon, body.sort_order, body.color);
|
||||
this.notes.broadcast(tripId, 'dayNote:created', { dayId: Number(dayId), note }, socketId);
|
||||
return { note };
|
||||
}
|
||||
|
||||
@RequirePermission('day_edit')
|
||||
@Put(':id')
|
||||
update(
|
||||
async update(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('dayId') dayId: string,
|
||||
@@ -72,28 +72,28 @@ export class DayNotesController {
|
||||
@Body() body: DayNoteUpdateDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const current = this.notes.getNote(id, dayId, tripId);
|
||||
const current = await this.notes.getNote(id, dayId, tripId);
|
||||
if (!current) {
|
||||
throw new HttpException({ error: 'Note not found' }, 404);
|
||||
}
|
||||
const note = this.notes.update(id, current as never, { text: body.text, time: body.time, icon: body.icon, sort_order: body.sort_order, color: body.color });
|
||||
const note = await this.notes.update(id, current as never, { text: body.text, time: body.time, icon: body.icon, sort_order: body.sort_order, color: body.color });
|
||||
this.notes.broadcast(tripId, 'dayNote:updated', { dayId: Number(dayId), note }, socketId);
|
||||
return { note };
|
||||
}
|
||||
|
||||
@RequirePermission('day_edit')
|
||||
@Delete(':id')
|
||||
remove(
|
||||
async remove(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('dayId') dayId: string,
|
||||
@Param('id') id: string,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
if (!this.notes.getNote(id, dayId, tripId)) {
|
||||
if (!(await this.notes.getNote(id, dayId, tripId))) {
|
||||
throw new HttpException({ error: 'Note not found' }, 404);
|
||||
}
|
||||
this.notes.remove(id);
|
||||
await this.notes.remove(id);
|
||||
this.notes.broadcast(tripId, 'dayNote:deleted', { noteId: Number(id), dayId: Number(dayId) }, socketId);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -68,10 +68,10 @@ export class DayNotesMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.notes.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.notes.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (!this.notes.dayExists(dayId, tripId)) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
|
||||
const note = this.notes.create(dayId, tripId, text, time, icon, sort_order, color);
|
||||
if (!(await this.notes.dayExists(dayId, tripId))) return { content: [{ type: 'text' as const, text: 'Day not found.' }], isError: true };
|
||||
const note = await this.notes.create(dayId, tripId, text, time, icon, sort_order, color);
|
||||
this.guards.safeBroadcast(tripId, 'dayNote:created', { dayId, note });
|
||||
return ok({ note });
|
||||
}
|
||||
@@ -99,11 +99,11 @@ export class DayNotesMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.notes.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.notes.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const existing = this.notes.getNote(noteId, dayId, tripId);
|
||||
const existing = await this.notes.getNote(noteId, dayId, tripId);
|
||||
if (!existing) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
|
||||
const note = this.notes.update(noteId, existing, { text, time: time !== undefined ? time : undefined, icon, color, sort_order });
|
||||
const note = await this.notes.update(noteId, existing, { text, time: time !== undefined ? time : undefined, icon, color, sort_order });
|
||||
this.guards.safeBroadcast(tripId, 'dayNote:updated', { dayId, note });
|
||||
return ok({ note });
|
||||
}
|
||||
@@ -121,11 +121,11 @@ export class DayNotesMcp {
|
||||
})
|
||||
async deleteDayNote({ tripId, dayId, noteId }: { tripId: number; dayId: number; noteId: number }, ctx: McpContext) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.notes.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.notes.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const note = this.notes.getNote(noteId, dayId, tripId);
|
||||
const note = await this.notes.getNote(noteId, dayId, tripId);
|
||||
if (!note) return { content: [{ type: 'text' as const, text: 'Note not found.' }], isError: true };
|
||||
this.notes.remove(noteId);
|
||||
await this.notes.remove(noteId);
|
||||
this.guards.safeBroadcast(tripId, 'dayNote:deleted', { noteId, dayId });
|
||||
return ok({ success: true });
|
||||
}
|
||||
@@ -140,7 +140,7 @@ export class DayNotesMcp {
|
||||
async dayNotesResource(uri: URL, { tripId, dayId }: { tripId: string | string[]; dayId: string | string[] }, ctx: McpContext) {
|
||||
const tId = parseId(tripId);
|
||||
const dId = parseId(dayId);
|
||||
if (tId === null || dId === null || !this.notes.verifyTripAccess(tId, ctx.userId)) {
|
||||
if (tId === null || dId === null || !(await this.notes.verifyTripAccess(tId, ctx.userId))) {
|
||||
return {
|
||||
contents: [{
|
||||
uri: uri.href,
|
||||
@@ -149,7 +149,7 @@ export class DayNotesMcp {
|
||||
}],
|
||||
};
|
||||
}
|
||||
const notes = this.notes.list(dId, tId);
|
||||
const notes = await this.notes.list(dId, tId);
|
||||
return {
|
||||
contents: [{
|
||||
uri: uri.href,
|
||||
|
||||
@@ -28,9 +28,9 @@ export class DayNotesRpc {
|
||||
) {}
|
||||
|
||||
@PluginMethod('daynotes.list', { permission: 'db:read:daynotes' })
|
||||
list(params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
return this.guards.tripRead(params, ctx, () =>
|
||||
this.dayNotes.list(num(params.dayId, 'dayId'), num(params.tripId, 'tripId')),
|
||||
async list(params: Record<string, unknown>, ctx: PluginRpcContext): Promise<unknown> {
|
||||
return await this.guards.tripRead(params, ctx, async () =>
|
||||
await this.dayNotes.list(num(params.dayId, 'dayId'), num(params.tripId, 'tripId')),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -42,9 +42,9 @@ export class DayNotesRpc {
|
||||
const input = asPayload(params.input);
|
||||
if (typeof input.text !== 'string' || input.text.trim() === '') throw new BadParams('note text is required');
|
||||
await this.guards.requireTripEdit(tripId, actor, DAY_NOTE_EDIT_ACTION);
|
||||
if (!this.dayNotes.dayExists(dayId, tripId)) throw new ForbiddenResource(`no day ${dayId} on trip ${tripId}`);
|
||||
if (!(await this.dayNotes.dayExists(dayId, tripId))) throw new ForbiddenResource(`no day ${dayId} on trip ${tripId}`);
|
||||
const i = input as DayNoteInput;
|
||||
const note = this.dayNotes.create(dayId, tripId, i.text ?? '', i.time, i.icon, i.sort_order);
|
||||
const note = await this.dayNotes.create(dayId, tripId, i.text ?? '', i.time, i.icon, i.sort_order);
|
||||
this.realtime.broadcast(tripId, 'dayNote:created', { dayId, note }, undefined);
|
||||
return note;
|
||||
}
|
||||
@@ -56,9 +56,9 @@ export class DayNotesRpc {
|
||||
const noteId = num(params.noteId, 'noteId');
|
||||
const actor = this.guards.requireActor(ctx, 'day note');
|
||||
await this.guards.requireTripEdit(tripId, actor, DAY_NOTE_EDIT_ACTION);
|
||||
const current = this.dayNotes.getNote(noteId, dayId, tripId);
|
||||
const current = await this.dayNotes.getNote(noteId, dayId, tripId);
|
||||
if (!current) throw new ForbiddenResource(`no note ${noteId} on day ${dayId}`);
|
||||
const note = this.dayNotes.update(noteId, current as never, asPayload(params.input) as DayNoteInput);
|
||||
const note = await this.dayNotes.update(noteId, current as never, asPayload(params.input) as DayNoteInput);
|
||||
this.realtime.broadcast(tripId, 'dayNote:updated', { dayId, note }, undefined);
|
||||
return note;
|
||||
}
|
||||
@@ -70,9 +70,9 @@ export class DayNotesRpc {
|
||||
const noteId = num(params.noteId, 'noteId');
|
||||
const actor = this.guards.requireActor(ctx, 'day note');
|
||||
await this.guards.requireTripEdit(tripId, actor, DAY_NOTE_EDIT_ACTION);
|
||||
const current = this.dayNotes.getNote(noteId, dayId, tripId);
|
||||
const current = await this.dayNotes.getNote(noteId, dayId, tripId);
|
||||
if (!current) throw new ForbiddenResource(`no note ${noteId} on day ${dayId}`);
|
||||
this.dayNotes.remove(noteId);
|
||||
await this.dayNotes.remove(noteId);
|
||||
this.realtime.broadcast(tripId, 'dayNote:deleted', { noteId, dayId }, undefined);
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ export class DayNotesService {
|
||||
private readonly realtime: RealtimeService,
|
||||
) {}
|
||||
|
||||
verifyTripAccess(tripId: string | number, userId: number): TripAccess | undefined {
|
||||
async verifyTripAccess(tripId: string | number, userId: number): Promise<TripAccess | undefined> {
|
||||
return this.dbs.canAccessTrip(tripId, userId);
|
||||
}
|
||||
|
||||
@@ -45,22 +45,22 @@ export class DayNotesService {
|
||||
this.realtime.broadcast(tripId, event, payload, socketId);
|
||||
}
|
||||
|
||||
list(dayId: string | number, tripId: string | number) {
|
||||
async list(dayId: string | number, tripId: string | number) {
|
||||
return this.dbs.all(
|
||||
'SELECT * FROM day_notes WHERE day_id = ? AND trip_id = ? ORDER BY sort_order ASC, created_at ASC',
|
||||
dayId, tripId,
|
||||
);
|
||||
}
|
||||
|
||||
dayExists(dayId: string | number, tripId: string | number) {
|
||||
async dayExists(dayId: string | number, tripId: string | number) {
|
||||
return this.dbs.get('SELECT id FROM days WHERE id = ? AND trip_id = ?', dayId, tripId);
|
||||
}
|
||||
|
||||
getNote(id: string | number, dayId: string | number, tripId: string | number) {
|
||||
async getNote(id: string | number, dayId: string | number, tripId: string | number) {
|
||||
return this.dbs.get<DayNote>('SELECT * FROM day_notes WHERE id = ? AND day_id = ? AND trip_id = ?', id, dayId, tripId);
|
||||
}
|
||||
|
||||
create(dayId: string | number, tripId: string | number, text: string, time?: string | null, icon?: string | null, sortOrder?: number, color?: string | null) {
|
||||
async create(dayId: string | number, tripId: string | number, text: string, time?: string | null, icon?: string | null, sortOrder?: number, color?: string | null) {
|
||||
const result = this.dbs.run(
|
||||
'INSERT INTO day_notes (day_id, trip_id, text, time, icon, sort_order, color) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
||||
dayId, tripId, text.trim(), time || null, icon || '📝', sortOrder ?? 9999, normalizeNoteColor(color),
|
||||
@@ -68,7 +68,7 @@ export class DayNotesService {
|
||||
return this.dbs.get('SELECT * FROM day_notes WHERE id = ?', result.lastInsertRowid);
|
||||
}
|
||||
|
||||
update(id: string | number, current: DayNote, fields: { text?: string; time?: string | null; icon?: string | null; sort_order?: number; color?: string | null }) {
|
||||
async update(id: string | number, current: DayNote, fields: { text?: string; time?: string | null; icon?: string | null; sort_order?: number; color?: string | null }) {
|
||||
this.dbs.run(
|
||||
'UPDATE day_notes SET text = ?, time = ?, icon = ?, sort_order = ?, color = ? WHERE id = ?',
|
||||
fields.text !== undefined ? fields.text.trim() : current.text,
|
||||
@@ -81,7 +81,7 @@ export class DayNotesService {
|
||||
return this.dbs.get('SELECT * FROM day_notes WHERE id = ?', id);
|
||||
}
|
||||
|
||||
remove(id: string | number): void {
|
||||
async remove(id: string | number): Promise<void> {
|
||||
this.dbs.run('DELETE FROM day_notes WHERE id = ?', id);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,13 +35,13 @@ export class DaysController {
|
||||
constructor(private readonly days: DaysService) {}
|
||||
|
||||
@Get()
|
||||
list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
|
||||
return this.days.list(tripId);
|
||||
async list(@CurrentUser() user: User, @Param('tripId') tripId: string) {
|
||||
return await this.days.list(tripId);
|
||||
}
|
||||
|
||||
@RequirePermission('day_edit')
|
||||
@Post()
|
||||
create(
|
||||
async create(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Body() body: DayCreateDto,
|
||||
@@ -50,8 +50,8 @@ export class DaysController {
|
||||
// A `position` means "insert a new empty day here" (which on a dated trip
|
||||
// extends the trip and re-pins dates); without it, the legacy append.
|
||||
const day = body.position !== undefined
|
||||
? this.days.insert(tripId, body.position)
|
||||
: this.days.create(tripId, body.date, body.notes);
|
||||
? await this.days.insert(tripId, body.position)
|
||||
: await this.days.create(tripId, body.date, body.notes);
|
||||
// An insert can shuffle dates/positions of other days, so collaborators
|
||||
// refetch the whole list; a plain append only needs the new day.
|
||||
const event = body.position !== undefined ? 'day:reordered' : 'day:created';
|
||||
@@ -91,7 +91,7 @@ export class DaysController {
|
||||
@Body() body: DayUpdateDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
const current = this.days.getDay(id, tripId);
|
||||
const current = await this.days.getDay(id, tripId);
|
||||
if (!current) {
|
||||
throw new HttpException({ error: 'Day not found' }, 404);
|
||||
}
|
||||
@@ -112,7 +112,7 @@ export class DaysController {
|
||||
@Body() body: DayTransportDto,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
if (!this.days.getDay(id, tripId)) {
|
||||
if (!(await this.days.getDay(id, tripId))) {
|
||||
throw new HttpException({ error: 'Day not found' }, 404);
|
||||
}
|
||||
const day = await this.days.setDefaultTransportMode(id, body.transport_mode ?? null);
|
||||
@@ -122,16 +122,16 @@ export class DaysController {
|
||||
|
||||
@RequirePermission('day_edit')
|
||||
@Delete(':id')
|
||||
remove(
|
||||
async remove(
|
||||
@CurrentUser() user: User,
|
||||
@Param('tripId') tripId: string,
|
||||
@Param('id') id: string,
|
||||
@Headers('x-socket-id') socketId?: string,
|
||||
) {
|
||||
if (!this.days.getDay(id, tripId)) {
|
||||
if (!(await this.days.getDay(id, tripId))) {
|
||||
throw new HttpException({ error: 'Day not found' }, 404);
|
||||
}
|
||||
this.days.remove(id);
|
||||
await this.days.remove(id);
|
||||
this.days.broadcast(tripId, 'day:deleted', { dayId: Number(id) }, socketId);
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
@@ -63,9 +63,9 @@ export class DaysMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.days.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.days.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const current = this.days.getDay(dayId, tripId);
|
||||
const current = await this.days.getDay(dayId, tripId);
|
||||
if (!current) return errorResult('Day not found.');
|
||||
// The rest spread carries only the keys the caller actually sent, which is
|
||||
// what update()'s presence sentinels need: naming the two fields here would
|
||||
@@ -92,15 +92,15 @@ export class DaysMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.days.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.days.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (position === undefined) {
|
||||
const day = this.days.create(tripId, date, notes);
|
||||
const day = await this.days.create(tripId, date, notes);
|
||||
this.guards.safeBroadcast(tripId, 'day:created', { day });
|
||||
return ok({ day });
|
||||
}
|
||||
try {
|
||||
const day = this.days.insert(tripId, position);
|
||||
const day = await this.days.insert(tripId, position);
|
||||
// An insert renumbers and re-dates every later day, so collaborators get
|
||||
// the list-wide event and refetch, the same one the REST create route sends.
|
||||
this.guards.safeBroadcast(tripId, 'day:reordered', { day });
|
||||
@@ -127,7 +127,7 @@ export class DaysMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.days.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.days.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
try {
|
||||
await this.days.reorder(tripId, orderedIds);
|
||||
@@ -154,10 +154,10 @@ export class DaysMcp {
|
||||
})
|
||||
async deleteDay({ tripId, dayId }: { tripId: number; dayId: number }, ctx: McpContext) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.days.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.days.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (!this.days.getDay(dayId, tripId)) return errorResult('Day not found.');
|
||||
this.days.remove(dayId);
|
||||
if (!(await this.days.getDay(dayId, tripId))) return errorResult('Day not found.');
|
||||
await this.days.remove(dayId);
|
||||
// REST parity shape ({ dayId }) — the client reads payload.dayId, so the { id }
|
||||
// variant never removed the day from collaborator screens.
|
||||
this.guards.safeBroadcast(tripId, 'day:deleted', { dayId });
|
||||
@@ -180,9 +180,9 @@ export class DaysMcp {
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.days.verifyTripAccess(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.days.verifyTripAccess(tripId, ctx.userId))) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('day_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
if (!this.days.getDay(dayId, tripId)) return errorResult('Day not found.');
|
||||
if (!(await this.days.getDay(dayId, tripId))) return errorResult('Day not found.');
|
||||
const day = await this.days.setDefaultTransportMode(dayId, transport_mode ?? null);
|
||||
this.guards.safeBroadcast(tripId, 'day:updated', { day });
|
||||
return ok({ day });
|
||||
@@ -197,7 +197,7 @@ export class DaysMcp {
|
||||
})
|
||||
async tripDaysResource(uri: URL, { tripId }: { tripId: string | string[] }, ctx: McpContext) {
|
||||
const id = parseId(tripId);
|
||||
if (id === null || !this.days.verifyTripAccess(id, ctx.userId)) {
|
||||
if (id === null || !(await this.days.verifyTripAccess(id, ctx.userId))) {
|
||||
return {
|
||||
contents: [{
|
||||
uri: uri.href,
|
||||
|
||||
@@ -31,7 +31,7 @@ export class DaysRpc {
|
||||
if (!parsed.success) throw new BadParams(`invalid day: ${schemaMessage(parsed.error)}`);
|
||||
await this.guards.requireTripEdit(tripId, actor, DAY_EDIT_ACTION);
|
||||
const input = parsed.data as { date?: string; notes?: string };
|
||||
const day = this.days.create(tripId, input.date, input.notes);
|
||||
const day = await this.days.create(tripId, input.date, input.notes);
|
||||
this.realtime.broadcast(tripId, 'day:created', { day });
|
||||
return day;
|
||||
}
|
||||
@@ -45,7 +45,7 @@ export class DaysRpc {
|
||||
if (!parsed.success) throw new BadParams(`invalid day: ${schemaMessage(parsed.error)}`);
|
||||
await this.guards.requireTripEdit(tripId, actor, DAY_EDIT_ACTION);
|
||||
// getDay scopes the row to the trip before the write touches it.
|
||||
const current = this.days.getDay(dayId, tripId);
|
||||
const current = await this.days.getDay(dayId, tripId);
|
||||
if (!current) throw new ForbiddenResource(`no day ${dayId} on trip ${tripId}`);
|
||||
const day = await this.days.update(dayId, current, parsed.data as { notes?: string; title?: string | null });
|
||||
this.realtime.broadcast(tripId, 'day:updated', { day });
|
||||
@@ -58,8 +58,8 @@ export class DaysRpc {
|
||||
const dayId = num(params.dayId, 'dayId');
|
||||
const actor = this.guards.requireActor(ctx, 'day');
|
||||
await this.guards.requireTripEdit(tripId, actor, DAY_EDIT_ACTION);
|
||||
if (!this.days.getDay(dayId, tripId)) throw new ForbiddenResource(`no day ${dayId} on trip ${tripId}`);
|
||||
this.days.remove(dayId);
|
||||
if (!(await this.days.getDay(dayId, tripId))) throw new ForbiddenResource(`no day ${dayId} on trip ${tripId}`);
|
||||
await this.days.remove(dayId);
|
||||
this.realtime.broadcast(tripId, 'day:deleted', { dayId });
|
||||
return { deleted: true };
|
||||
}
|
||||
|
||||
@@ -6,6 +6,7 @@ import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { QueryHelpersService } from '../query-helpers/query-helpers.service';
|
||||
import { formatAssignmentWithPlace } from '../common/rowShape';
|
||||
import type { AssignmentRow, Day, DayNote, User } from '../../types';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
|
||||
type Trip = TripAccess;
|
||||
|
||||
@@ -47,7 +48,7 @@ export class DayReorderError extends Error {}
|
||||
* legacy services/dayService.ts: identical statements, the `||` falsy-coercion
|
||||
* defaults, the post-write re-selects, the two-phase negative-day_number
|
||||
* renumber and the reservation re-stamping). The legacy hand-rolled
|
||||
* BEGIN/COMMIT blocks in reorder/insert became db.transaction() (same
|
||||
* BEGIN/COMMIT blocks in reorder/insert became uow.transactional() (same
|
||||
* rollback-on-throw semantics, savepoint-safe when nested). Verified defects
|
||||
* were fixed after the port (2026-07): update() now presence-sentinels BOTH
|
||||
* columns (the legacy always-write wiped notes when only a title was sent),
|
||||
@@ -66,9 +67,10 @@ export class DaysService {
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly queryHelpers: QueryHelpersService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
verifyTripAccess(tripId: string | number, userId: number) {
|
||||
async verifyTripAccess(tripId: string | number, userId: number) {
|
||||
return this.db.canAccessTrip(Number(tripId), userId);
|
||||
}
|
||||
|
||||
@@ -216,7 +218,7 @@ export class DaysService {
|
||||
return { days: daysWithAssignments };
|
||||
}
|
||||
|
||||
create(tripId: string | number, date?: string, notes?: string) {
|
||||
async create(tripId: string | number, date?: string, notes?: string) {
|
||||
const maxDay = this.db.get<{ max: number | null }>('SELECT MAX(day_number) as max FROM days WHERE trip_id = ?', tripId)!;
|
||||
const dayNumber = (maxDay.max || 0) + 1;
|
||||
|
||||
@@ -229,7 +231,7 @@ export class DaysService {
|
||||
return { ...day, assignments: [] };
|
||||
}
|
||||
|
||||
getDay(id: string | number, tripId: string | number) {
|
||||
async getDay(id: string | number, tripId: string | number) {
|
||||
return this.db.get<Day>('SELECT * FROM days WHERE id = ? AND trip_id = ?', id, tripId);
|
||||
}
|
||||
|
||||
@@ -258,7 +260,7 @@ export class DaysService {
|
||||
return { ...updatedDay, assignments: await this.getAssignmentsForDay(id) };
|
||||
}
|
||||
|
||||
remove(id: string | number): void {
|
||||
async remove(id: string | number): Promise<void> {
|
||||
this.db.run('DELETE FROM days WHERE id = ?', id);
|
||||
}
|
||||
|
||||
@@ -281,11 +283,11 @@ export class DaysService {
|
||||
* date (time-of-day preserved). Transport endpoints (flight legs) shift by the
|
||||
* same per-booking day delta so multi-leg timing stays internally consistent.
|
||||
*/
|
||||
restampReservationDates(
|
||||
async restampReservationDates(
|
||||
tripId: string | number,
|
||||
oldDateById: Map<number, string | null>,
|
||||
newDateById: Map<number, string | null>,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const reservations = this.db.all<{
|
||||
id: number; day_id: number | null; end_day_id: number | null;
|
||||
reservation_time: string | null; reservation_end_time: string | null;
|
||||
@@ -325,7 +327,7 @@ export class DaysService {
|
||||
}
|
||||
|
||||
/** A stay must not end before it begins after a reorder/insert. */
|
||||
private assertNoInvertedAccommodation(tripId: string | number): void {
|
||||
private async assertNoInvertedAccommodation(tripId: string | number): Promise<void> {
|
||||
const spans = this.db.all<{ id: number; start_no: number; end_no: number }>(`
|
||||
SELECT a.id, s.day_number AS start_no, e.day_number AS end_no
|
||||
FROM day_accommodations a
|
||||
@@ -350,10 +352,10 @@ export class DaysService {
|
||||
* whole trip still shifts everything together. The linked hotel reservation follows
|
||||
* its accommodation's start day in both branches.
|
||||
*/
|
||||
resyncAccommodationDays(
|
||||
async resyncAccommodationDays(
|
||||
tripId: string | number,
|
||||
prevDateByDayId: Map<number, string | null>,
|
||||
): void {
|
||||
): Promise<void> {
|
||||
const stays = this.db.all<{ id: number; start_day_id: number; end_day_id: number }>(
|
||||
'SELECT id, start_day_id, end_day_id FROM day_accommodations WHERE trip_id = ?',
|
||||
tripId
|
||||
@@ -405,7 +407,7 @@ export class DaysService {
|
||||
* Reorder whole days. `orderedIds` is the desired full sequence of this trip's
|
||||
* day ids (a permutation of the current ids).
|
||||
*/
|
||||
reorder(tripId: string | number, orderedIds: number[]) {
|
||||
async reorder(tripId: string | number, orderedIds: number[]) {
|
||||
const rows = this.db.all<{ id: number; day_number: number; date: string | null }>(
|
||||
'SELECT id, day_number, date FROM days WHERE trip_id = ? ORDER BY day_number',
|
||||
tripId
|
||||
@@ -424,7 +426,7 @@ export class DaysService {
|
||||
const setDayNumber = this.db.prepare('UPDATE days SET day_number = ? WHERE id = ?');
|
||||
const setDayNumberAndDate = this.db.prepare('UPDATE days SET day_number = ?, date = ? WHERE id = ?');
|
||||
|
||||
this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
// Two-phase renumber to dodge UNIQUE(trip_id, day_number) collisions.
|
||||
orderedIds.forEach((id, i) => setDayNumber.run(-(i + 1), id));
|
||||
const newDateById = new Map<number, string | null>();
|
||||
@@ -434,11 +436,11 @@ export class DaysService {
|
||||
newDateById.set(id, date);
|
||||
});
|
||||
|
||||
if (isDated) this.restampReservationDates(tripId, oldDateById, newDateById);
|
||||
this.assertNoInvertedAccommodation(tripId);
|
||||
if (isDated) await this.restampReservationDates(tripId, oldDateById, newDateById);
|
||||
await this.assertNoInvertedAccommodation(tripId);
|
||||
});
|
||||
|
||||
return this.list(tripId);
|
||||
return await this.list(tripId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -447,7 +449,7 @@ export class DaysService {
|
||||
* stay contiguous, the trip's end_date extends by one day, and bookings on
|
||||
* shifted days have their dates re-stamped (same rules as reorder).
|
||||
*/
|
||||
insert(tripId: string | number, position?: number) {
|
||||
async insert(tripId: string | number, position?: number) {
|
||||
const rows = this.db.all<{ id: number; day_number: number; date: string | null }>(
|
||||
'SELECT id, day_number, date FROM days WHERE trip_id = ? ORDER BY day_number',
|
||||
tripId
|
||||
@@ -460,7 +462,7 @@ export class DaysService {
|
||||
const setDayNumber = this.db.prepare('UPDATE days SET day_number = ? WHERE id = ?');
|
||||
|
||||
if (!isDated) {
|
||||
const newRowid = this.db.transaction(() => {
|
||||
const newRowid = await this.uow.transactional(async () => {
|
||||
const toShift = rows.filter(r => r.day_number >= pos);
|
||||
toShift.forEach(r => setDayNumber.run(-r.day_number, r.id));
|
||||
const result = this.db.run('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, NULL)', tripId, pos);
|
||||
@@ -477,7 +479,7 @@ export class DaysService {
|
||||
const oldDateById = new Map(rows.map(r => [r.id, r.date]));
|
||||
const setDayNumberAndDate = this.db.prepare('UPDATE days SET day_number = ?, date = ? WHERE id = ?');
|
||||
|
||||
const newId = this.db.transaction(() => {
|
||||
const newId = await this.uow.transactional(async () => {
|
||||
rows.forEach((r, i) => setDayNumber.run(-(i + 1), r.id));
|
||||
const result = this.db.run('INSERT INTO days (trip_id, day_number, date) VALUES (?, ?, ?)', tripId, pos, dates[pos - 1]);
|
||||
const insertedId = Number(result.lastInsertRowid);
|
||||
@@ -490,8 +492,8 @@ export class DaysService {
|
||||
newDateById.set(id, dates[i]);
|
||||
});
|
||||
|
||||
this.restampReservationDates(tripId, oldDateById, newDateById);
|
||||
this.assertNoInvertedAccommodation(tripId);
|
||||
await this.restampReservationDates(tripId, oldDateById, newDateById);
|
||||
await this.assertNoInvertedAccommodation(tripId);
|
||||
this.db.run('UPDATE trips SET end_date = ? WHERE id = ?', dates[dates.length - 1], tripId);
|
||||
|
||||
return insertedId;
|
||||
|
||||
@@ -41,8 +41,8 @@ export class FeedsMcp {
|
||||
) {}
|
||||
|
||||
/** The AuthService.isDemoUser check without the auth graph (demo-write.ts). */
|
||||
private isDemoUser(userId: number): boolean {
|
||||
return isDemoUserId(this.env, this.db, userId);
|
||||
private async isDemoUser(userId: number): Promise<boolean> {
|
||||
return await isDemoUserId(this.env, this.db, userId);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -90,7 +90,7 @@ export class FeedsMcp {
|
||||
access: { group: 'trips', mode: 'share' },
|
||||
})
|
||||
async enableTripCalendarFeed({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const denied = await this.denyTripFeed(tripId, ctx.userId);
|
||||
if ((await denied)) return denied;
|
||||
return ok(this.feeds.generateTripToken(String(tripId), ctx.userId, this.base()));
|
||||
@@ -106,7 +106,7 @@ export class FeedsMcp {
|
||||
access: { group: 'trips', mode: 'share' },
|
||||
})
|
||||
async rotateTripCalendarFeed({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const denied = await this.denyTripFeed(tripId, ctx.userId);
|
||||
if ((await denied)) return denied;
|
||||
return ok(this.feeds.rotateTripToken(String(tripId), ctx.userId, this.base()));
|
||||
@@ -122,7 +122,7 @@ export class FeedsMcp {
|
||||
access: { group: 'trips', mode: 'share' },
|
||||
})
|
||||
async disableTripCalendarFeed({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const denied = await this.denyTripFeed(tripId, ctx.userId);
|
||||
if ((await denied)) return denied;
|
||||
this.feeds.disableTripToken(String(tripId), ctx.userId);
|
||||
@@ -153,7 +153,7 @@ export class FeedsMcp {
|
||||
access: { group: 'trips', mode: 'share' },
|
||||
})
|
||||
async enableAllTripsCalendarFeed(_input: Record<string, never>, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
return ok(this.feeds.generateUserToken(ctx.userId, this.base()));
|
||||
}
|
||||
|
||||
@@ -165,7 +165,7 @@ export class FeedsMcp {
|
||||
access: { group: 'trips', mode: 'share' },
|
||||
})
|
||||
async rotateAllTripsCalendarFeed(_input: Record<string, never>, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
return ok(this.feeds.rotateUserToken(ctx.userId, this.base()));
|
||||
}
|
||||
|
||||
@@ -177,7 +177,7 @@ export class FeedsMcp {
|
||||
access: { group: 'trips', mode: 'share' },
|
||||
})
|
||||
async disableAllTripsCalendarFeed(_input: Record<string, never>, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
this.feeds.disableUserToken(ctx.userId);
|
||||
return ok({ feed_url: null });
|
||||
}
|
||||
|
||||
@@ -157,7 +157,7 @@ export class PluginMcpToolsService implements OnApplicationBootstrap, OnModuleDe
|
||||
if (!pluginsEnabled()) return errorResult('Plugins are disabled on this server.');
|
||||
// The plugins domain's first demo gate. The child has none of its own, and
|
||||
// the ~40 isDemoUser checks elsewhere are per-handler, so it belongs here.
|
||||
if (isDemoUserId(this.env, this.dbs, ctx.userId)) return demoDenied();
|
||||
if (await isDemoUserId(this.env, this.dbs, ctx.userId)) return demoDenied();
|
||||
|
||||
try {
|
||||
const raw = await this.hooks.callMcpTool(pluginId, { name, args: args ?? {} }, ctx.userId);
|
||||
|
||||
@@ -73,7 +73,7 @@ export class ReservationsController {
|
||||
if (accommodationCreated) {
|
||||
this.reservations.broadcast(tripId, 'accommodation:created', {}, socketId);
|
||||
}
|
||||
this.reservations.syncBudgetOnCreate(tripId, reservation.id, body.title, body.type, body.create_budget_entry, socketId);
|
||||
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 ?? '');
|
||||
return { reservation };
|
||||
@@ -114,7 +114,7 @@ export class ReservationsController {
|
||||
this.reservations.broadcast(tripId, 'accommodation:updated', {}, socketId);
|
||||
}
|
||||
const cur = current as { title: string; type?: string };
|
||||
this.reservations.syncBudgetOnUpdate(tripId, id, body.title ?? '', body.type, cur.title, cur.type, body.create_budget_entry, socketId);
|
||||
await this.reservations.syncBudgetOnUpdate(tripId, id, body.title ?? '', body.type, cur.title, cur.type, body.create_budget_entry, socketId);
|
||||
this.reservations.broadcast(tripId, 'reservation:updated', { reservation }, socketId);
|
||||
// Push a locally-edited AirTrail flight back to AirTrail (fire-and-forget,
|
||||
// under the importer's credentials — see airtrailSync). #214
|
||||
|
||||
@@ -156,7 +156,7 @@ interface LegPlan {
|
||||
reservationEndTime?: string;
|
||||
// A day row carries an optional date, so the caller cannot promise one. Every
|
||||
// read below treats a dateless day as "no date known" rather than stamping undefined.
|
||||
lookupDay: (id: number) => { date?: string | null } | undefined;
|
||||
lookupDay: (id: number) => Promise<{ date?: string | null } | undefined>;
|
||||
}
|
||||
|
||||
interface LegOutcome {
|
||||
@@ -174,7 +174,7 @@ interface LegOutcome {
|
||||
* Validate the legs against the endpoints and fold them into the metadata.
|
||||
* Returns the values the write should use, or the first error as text.
|
||||
*/
|
||||
function applyLegs(plan: LegPlan): LegOutcome | { error: string } {
|
||||
async function applyLegs(plan: LegPlan): Promise<LegOutcome | { error: string }> {
|
||||
const { legs, lookupDay } = plan;
|
||||
const last = legs.length - 1;
|
||||
|
||||
@@ -190,7 +190,7 @@ function applyLegs(plan: LegPlan): LegOutcome | { error: string } {
|
||||
for (let i = 0; i < legs.length; i++) {
|
||||
for (const field of ['dep_day_id', 'arr_day_id'] as const) {
|
||||
const dayId = legs[i][field];
|
||||
if (dayId != null && !lookupDay(dayId))
|
||||
if (dayId != null && !(await lookupDay(dayId)))
|
||||
return { error: `legs[${i}].${field} does not belong to this trip.` };
|
||||
}
|
||||
}
|
||||
@@ -204,10 +204,10 @@ function applyLegs(plan: LegPlan): LegOutcome | { error: string } {
|
||||
|
||||
const endpoints = plan.endpoints.map(e => ({ ...e }));
|
||||
let endpointsChanged = false;
|
||||
const syncEndpoint = (index: number, time: string | null | undefined, dayId: number | null | undefined, label: string): string | null => {
|
||||
const syncEndpoint = async (index: number, time: string | null | undefined, dayId: number | null | undefined, label: string): Promise<string | null> => {
|
||||
const ep = endpoints[index];
|
||||
if (dayId != null && !ep.local_date) {
|
||||
const day = lookupDay(dayId);
|
||||
const day = await lookupDay(dayId);
|
||||
if (day?.date) { ep.local_date = day.date; endpointsChanged = true; }
|
||||
}
|
||||
if (!time) return null;
|
||||
@@ -229,7 +229,7 @@ function applyLegs(plan: LegPlan): LegOutcome | { error: string } {
|
||||
if (leg.to && arrEp.code && leg.to.toUpperCase() !== arrEp.code.toUpperCase())
|
||||
return { error: `legs[${i}].to (${leg.to}) does not match endpoints[${i + 1}] (${arrEp.code}).` };
|
||||
|
||||
const depConflict = syncEndpoint(i, leg.dep_time, leg.dep_day_id, `legs[${i}].dep_time`);
|
||||
const depConflict = await syncEndpoint(i, leg.dep_time, leg.dep_day_id, `legs[${i}].dep_time`);
|
||||
if (depConflict) return { error: depConflict };
|
||||
|
||||
const entry: MetaRecord = {
|
||||
@@ -251,7 +251,7 @@ function applyLegs(plan: LegPlan): LegOutcome | { error: string } {
|
||||
merged.push(entry);
|
||||
}
|
||||
|
||||
const arrConflict = syncEndpoint(legs.length, legs[last].arr_time, lastArrDay, `legs[${last}].arr_time`);
|
||||
const arrConflict = await syncEndpoint(legs.length, legs[last].arr_time, lastArrDay, `legs[${last}].arr_time`);
|
||||
if (arrConflict) return { error: arrConflict };
|
||||
|
||||
const metadata: MetaRecord = { ...plan.baseMetadata, legs: merged };
|
||||
@@ -278,9 +278,9 @@ function applyLegs(plan: LegPlan): LegOutcome | { error: string } {
|
||||
const endDayId = plan.endDayId ?? lastArrDay ?? undefined;
|
||||
// Same fallback as the form's buildTime: date the time when the day is known,
|
||||
// otherwise keep the bare 'HH:mm' rather than dropping it.
|
||||
const stamp = (day: number | undefined, time: string | null | undefined) => {
|
||||
const stamp = async (day: number | undefined, time: string | null | undefined) => {
|
||||
if (!time) return undefined;
|
||||
const row = day === undefined ? undefined : lookupDay(day);
|
||||
const row = day === undefined ? undefined : await lookupDay(day);
|
||||
return row?.date ? `${row.date}T${time}` : time;
|
||||
};
|
||||
|
||||
@@ -290,8 +290,8 @@ function applyLegs(plan: LegPlan): LegOutcome | { error: string } {
|
||||
endpointsChanged,
|
||||
day_id: dayId,
|
||||
end_day_id: endDayId,
|
||||
reservation_time: plan.reservationTime ?? stamp(dayId, legs[0].dep_time),
|
||||
reservation_end_time: plan.reservationEndTime ?? stamp(endDayId, legs[last].arr_time),
|
||||
reservation_time: plan.reservationTime ?? await stamp(dayId, legs[0].dep_time),
|
||||
reservation_end_time: plan.reservationEndTime ?? await stamp(endDayId, legs[last].arr_time),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -366,13 +366,13 @@ export class ReservationsMcp {
|
||||
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
|
||||
// Validate that all referenced IDs belong to this trip
|
||||
if (day_id && !this.days.getDay(day_id, tripId))
|
||||
if (day_id && !(await this.days.getDay(day_id, tripId)))
|
||||
return errorResult('day_id does not belong to this trip.');
|
||||
if (place_id && !this.assignments.placeExists(place_id, tripId))
|
||||
return errorResult('place_id does not belong to this trip.');
|
||||
if (start_day_id && !this.days.getDay(start_day_id, tripId))
|
||||
if (start_day_id && !(await this.days.getDay(start_day_id, tripId)))
|
||||
return errorResult('start_day_id does not belong to this trip.');
|
||||
if (end_day_id && !this.days.getDay(end_day_id, tripId))
|
||||
if (end_day_id && !(await this.days.getDay(end_day_id, tripId)))
|
||||
return errorResult('end_day_id does not belong to this trip.');
|
||||
if (assignment_id && !this.assignments.getAssignmentForTrip(assignment_id, tripId))
|
||||
return errorResult('assignment_id does not belong to this trip.');
|
||||
@@ -395,7 +395,7 @@ export class ReservationsMcp {
|
||||
}
|
||||
|
||||
if (price != null && price > 0) {
|
||||
const item = this.budget.linkBudgetItemToReservation(tripId, reservation.id, {
|
||||
const item = await this.budget.linkBudgetItemToReservation(tripId, reservation.id, {
|
||||
name: title,
|
||||
category: budget_category || type,
|
||||
total_price: price,
|
||||
@@ -540,7 +540,7 @@ export class ReservationsMcp {
|
||||
// The service scopes the write to the trip on its own, so a foreign id is
|
||||
// already harmless — say so rather than reporting a success that moved
|
||||
// nothing, the way the sibling tools above do.
|
||||
if (dayId && !this.days.getDay(dayId, tripId))
|
||||
if (dayId && !(await this.days.getDay(dayId, tripId)))
|
||||
return errorResult('dayId does not belong to this trip.');
|
||||
|
||||
this.reservations.updatePositions(tripId, positions, dayId);
|
||||
@@ -579,9 +579,9 @@ export class ReservationsMcp {
|
||||
|
||||
if (!this.assignments.placeExists(place_id, tripId))
|
||||
return errorResult('place_id does not belong to this trip.');
|
||||
if (!this.days.getDay(start_day_id, tripId))
|
||||
if (!(await this.days.getDay(start_day_id, tripId)))
|
||||
return errorResult('start_day_id does not belong to this trip.');
|
||||
if (!this.days.getDay(end_day_id, tripId))
|
||||
if (!(await this.days.getDay(end_day_id, tripId)))
|
||||
return errorResult('end_day_id does not belong to this trip.');
|
||||
|
||||
const isNewAccommodation = !current.accommodation_id;
|
||||
@@ -700,9 +700,9 @@ export class ReservationsMcp {
|
||||
|
||||
if (metadata && 'legs' in metadata) return errorResult(LEGS_IN_METADATA_ERROR);
|
||||
|
||||
if (start_day_id && !this.days.getDay(start_day_id, tripId))
|
||||
if (start_day_id && !(await this.days.getDay(start_day_id, tripId)))
|
||||
return errorResult('start_day_id does not belong to this trip.');
|
||||
if (end_day_id && !this.days.getDay(end_day_id, tripId))
|
||||
if (end_day_id && !(await this.days.getDay(end_day_id, tripId)))
|
||||
return errorResult('end_day_id does not belong to this trip.');
|
||||
|
||||
const resolved = resolveEndpointCoords(endpoints);
|
||||
@@ -716,7 +716,7 @@ export class ReservationsMcp {
|
||||
let arrivalTime = reservation_end_time;
|
||||
|
||||
if (legs !== undefined) {
|
||||
const applied = applyLegs({
|
||||
const applied = await applyLegs({
|
||||
legs,
|
||||
type,
|
||||
endpoints: resolved.endpoints,
|
||||
@@ -757,7 +757,7 @@ export class ReservationsMcp {
|
||||
});
|
||||
|
||||
if (price != null && price > 0) {
|
||||
const item = this.budget.linkBudgetItemToReservation(tripId, reservation.id, {
|
||||
const item = await this.budget.linkBudgetItemToReservation(tripId, reservation.id, {
|
||||
name: title,
|
||||
category: budget_category || type,
|
||||
total_price: price,
|
||||
@@ -815,9 +815,9 @@ export class ReservationsMcp {
|
||||
if (!(TRANSPORT_TYPES as readonly string[]).includes(resolvedType))
|
||||
return errorResult('Reservation is not a transport type. Use update_reservation instead.');
|
||||
|
||||
if (start_day_id && !this.days.getDay(start_day_id, tripId))
|
||||
if (start_day_id && !(await this.days.getDay(start_day_id, tripId)))
|
||||
return errorResult('start_day_id does not belong to this trip.');
|
||||
if (end_day_id && !this.days.getDay(end_day_id, tripId))
|
||||
if (end_day_id && !(await this.days.getDay(end_day_id, tripId)))
|
||||
return errorResult('end_day_id does not belong to this trip.');
|
||||
|
||||
// Only resolve when endpoints are explicitly provided; undefined leaves them untouched.
|
||||
@@ -836,7 +836,7 @@ export class ReservationsMcp {
|
||||
|
||||
if (legs !== undefined) {
|
||||
const stored = parseStoredMetadata(existing.metadata);
|
||||
const applied = applyLegs({
|
||||
const applied = await applyLegs({
|
||||
legs,
|
||||
type: resolvedType,
|
||||
// Endpoints the caller did not replace stay the geometry the legs run
|
||||
|
||||
@@ -42,7 +42,7 @@ export class ReservationsRpc {
|
||||
const { reservation, accommodationCreated } = await this.reservations.create(String(tripId), input as never);
|
||||
if (accommodationCreated) this.realtime.broadcast(tripId, 'accommodation:created', {}, undefined);
|
||||
const i = input as { title?: string; type?: string; create_budget_entry?: unknown };
|
||||
this.reservations.syncBudgetOnCreate(String(tripId), reservation.id, i.title ?? '', i.type, i.create_budget_entry as never, undefined);
|
||||
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 ?? '');
|
||||
return reservation;
|
||||
@@ -65,7 +65,7 @@ export class ReservationsRpc {
|
||||
if (accommodationChanged) this.realtime.broadcast(tripId, 'accommodation:updated', {}, undefined);
|
||||
const cur = current as { title: string; type?: string };
|
||||
const i = input as { title?: string; type?: string; create_budget_entry?: unknown };
|
||||
this.reservations.syncBudgetOnUpdate(String(tripId), String(reservationId), i.title ?? '', i.type, cur.title, cur.type, i.create_budget_entry as never, undefined);
|
||||
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 || '');
|
||||
return reservation;
|
||||
|
||||
@@ -1031,10 +1031,10 @@ export class ReservationsService {
|
||||
}
|
||||
|
||||
/** POST side effect: auto-create a linked budget item when a price is provided. */
|
||||
syncBudgetOnCreate(tripId: string, reservationId: number, title: string, type: string | undefined, entry: BudgetEntry, socketId: string | undefined): void {
|
||||
async syncBudgetOnCreate(tripId: string, reservationId: number, title: string, type: string | undefined, entry: BudgetEntry, socketId: string | undefined): Promise<void> {
|
||||
if (!entry || !(Number(entry.total_price) > 0)) return;
|
||||
try {
|
||||
const item = this.budget.linkBudgetItemToReservation(tripId, reservationId, {
|
||||
const item = await this.budget.linkBudgetItemToReservation(tripId, reservationId, {
|
||||
name: title,
|
||||
category: entry.category || type || 'Other',
|
||||
total_price: entry.total_price!,
|
||||
@@ -1046,7 +1046,7 @@ export class ReservationsService {
|
||||
}
|
||||
|
||||
/** PUT side effect: drop the linked budget item when the price is cleared, else create/update it. */
|
||||
syncBudgetOnUpdate(tripId: string, id: string, title: string, type: string | undefined, currentTitle: string, currentType: string | undefined, entry: BudgetEntry, socketId: string | undefined): void {
|
||||
async syncBudgetOnUpdate(tripId: string, id: string, title: string, type: string | undefined, currentTitle: string, currentType: string | undefined, entry: BudgetEntry, socketId: string | undefined): Promise<void> {
|
||||
// When the booking type changes, keep a linked expense's category in sync —
|
||||
// but only if it still carries the auto-derived category (so a manual pick in
|
||||
// the Costs editor is preserved). Runs regardless of create_budget_entry.
|
||||
@@ -1056,7 +1056,7 @@ export class ReservationsService {
|
||||
const oldCat = typeToCostCategory(currentType);
|
||||
const newCat = typeToCostCategory(type);
|
||||
if (oldCat !== newCat && linked.category === oldCat) {
|
||||
const updated = this.budget.updateBudgetItem(linked.id, tripId, { category: newCat });
|
||||
const updated = await this.budget.updateBudgetItem(linked.id, tripId, { category: newCat });
|
||||
this.realtime.broadcast(tripId, 'budget:updated', { item: updated }, socketId);
|
||||
}
|
||||
}
|
||||
@@ -1071,7 +1071,7 @@ export class ReservationsService {
|
||||
// Explicit clear (total_price 0/empty) — drop the linked item.
|
||||
const linked = this.db.get<{ id: number }>('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?', tripId, id);
|
||||
if (linked) {
|
||||
this.budget.deleteBudgetItem(linked.id, tripId);
|
||||
await this.budget.deleteBudgetItem(linked.id, tripId);
|
||||
this.realtime.broadcast(tripId, 'budget:deleted', { itemId: linked.id }, socketId);
|
||||
}
|
||||
return;
|
||||
@@ -1082,10 +1082,10 @@ export class ReservationsService {
|
||||
const category = entry.category || type || currentType || 'Other';
|
||||
const existing = this.db.get<{ id: number }>('SELECT id FROM budget_items WHERE trip_id = ? AND reservation_id = ?', tripId, id);
|
||||
if (existing) {
|
||||
const updated = this.budget.updateBudgetItem(existing.id, tripId, { name: itemName, category, total_price: entry.total_price });
|
||||
const updated = await this.budget.updateBudgetItem(existing.id, tripId, { name: itemName, category, total_price: entry.total_price });
|
||||
this.realtime.broadcast(tripId, 'budget:updated', { item: updated }, socketId);
|
||||
} else {
|
||||
const item = this.budget.createBudgetItem(tripId, { name: itemName, category, total_price: entry.total_price });
|
||||
const item = await this.budget.createBudgetItem(tripId, { name: itemName, category, total_price: entry.total_price });
|
||||
this.db.run('UPDATE budget_items SET reservation_id = ? WHERE id = ?', id, item.id);
|
||||
item.reservation_id = Number(id);
|
||||
this.realtime.broadcast(tripId, 'budget:created', { item }, socketId);
|
||||
|
||||
@@ -186,7 +186,7 @@ export class TransitMcp {
|
||||
if (this.auth.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (!this.db.canAccessTrip(tripId, ctx.userId)) return noAccess();
|
||||
if (!(await this.guards.hasTripPermission('reservation_edit', tripId, ctx.userId))) return permissionDenied();
|
||||
const day = this.days.getDay(dayId, tripId);
|
||||
const day = await this.days.getDay(dayId, tripId);
|
||||
if (!day) {
|
||||
return { content: [{ type: 'text' as const, text: 'dayId does not belong to this trip.' }], isError: true };
|
||||
}
|
||||
|
||||
@@ -41,8 +41,8 @@ export class TripInviteMcp {
|
||||
) {}
|
||||
|
||||
/** The AuthService.isDemoUser check without the auth graph (demo-write.ts). */
|
||||
private isDemoUser(userId: number): boolean {
|
||||
return isDemoUserId(this.env, this.db, userId);
|
||||
private async isDemoUser(userId: number): Promise<boolean> {
|
||||
return await isDemoUserId(this.env, this.db, userId);
|
||||
}
|
||||
|
||||
/** Trip access first (404-equivalent), then share_manage, which is requireManage() in the controller. */
|
||||
@@ -88,7 +88,7 @@ export class TripInviteMcp {
|
||||
{ tripId, expires_in_days }: { tripId: number } & TripInviteLinkCreateRequest,
|
||||
ctx: McpContext,
|
||||
) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const denied = await this.denyManage(tripId, ctx.userId);
|
||||
if ((await denied)) return denied;
|
||||
// The route's own coercion, kept verbatim: the shared contract admits a
|
||||
@@ -122,7 +122,7 @@ export class TripInviteMcp {
|
||||
access: (ctx) => canShareTrips(ctx.scopes) && canWrite(ctx.scopes, 'trips'),
|
||||
})
|
||||
async deleteTripInviteLink({ tripId }: { tripId: number }, ctx: McpContext) {
|
||||
if (this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
if (await this.isDemoUser(ctx.userId)) return demoDenied();
|
||||
const denied = await this.denyManage(tripId, ctx.userId);
|
||||
if ((await denied)) return denied;
|
||||
this.invites.remove(tripId);
|
||||
|
||||
@@ -153,8 +153,8 @@ export class TripMembersController {
|
||||
@Delete(':id/guests/:userId')
|
||||
@UseGuards(TripOwnerGuard)
|
||||
@RequireTripOwner('Only the owner can manage guests', { param: 'id' })
|
||||
deleteGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
if (!this.roster.deleteGuest(id, Number.parseInt(userId))) {
|
||||
async deleteGuest(@CurrentUser() user: User, @Param('id') id: string, @Param('userId') userId: string) {
|
||||
if (!(await this.roster.deleteGuest(id, Number.parseInt(userId)))) {
|
||||
throw new HttpException({ error: 'Guest not found' }, 404);
|
||||
}
|
||||
return { success: true };
|
||||
|
||||
@@ -4,6 +4,7 @@ import { DatabaseService } from '../database/database.service';
|
||||
import type { User } from '../../types';
|
||||
import { avatarUrl } from '../common/avatarUrl';
|
||||
import { UserCleanupService } from '../auth/user-cleanup.service';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
import { BudgetService } from '../budget/budget.service';
|
||||
import { PermissionsService } from '../permissions/permissions.service';
|
||||
import { RealtimeService } from '../realtime/realtime.service';
|
||||
@@ -66,6 +67,7 @@ export class TripMembersService {
|
||||
private readonly permissions: PermissionsService,
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly notifications: NotificationsService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
private get db() {
|
||||
@@ -249,7 +251,7 @@ export class TripMembersService {
|
||||
return true;
|
||||
}
|
||||
|
||||
deleteGuest(tripId: string | number, guestUserId: number): boolean {
|
||||
async deleteGuest(tripId: string | number, guestUserId: number): Promise<boolean> {
|
||||
if (!this.guestOfTrip(tripId, guestUserId)) return false;
|
||||
// A guest is still a user id a plugin may hold data for, so erase that too — the
|
||||
// host-side per-user tables + a durable own-db erasure per granted plugin — exactly
|
||||
@@ -259,14 +261,14 @@ export class TripMembersService {
|
||||
// run in one transaction, so a failure mid-flow can't leave the expense
|
||||
// divisors re-derived for a guest that still exists (or vice versa). The
|
||||
// plugin-side erasure/notification keep their order around it.
|
||||
this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
// Re-split the expenses they were part of before the cascade takes their member
|
||||
// rows away — the divisor is denormalized and cannot follow a foreign key (#1553).
|
||||
this.budget.removeUserFromBudgetItems(guestUserId);
|
||||
await this.budget.removeUserFromBudgetItems(guestUserId);
|
||||
// Deleting the guest's users row cascades its membership and every assignment join
|
||||
// (trip_members, budget/packing/assignment links) via the ON DELETE foreign keys.
|
||||
this.db.prepare('DELETE FROM users WHERE id = ? AND is_guest = 1').run(guestUserId);
|
||||
})();
|
||||
});
|
||||
emitUserDeleted(guestUserId); // deliver the erasure to any active plugin now
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -62,7 +62,7 @@ export class TripReadModelService {
|
||||
|
||||
const accommodations = this.accommodations.list(tripId);
|
||||
|
||||
const budgetItems = this.budget.listBudgetItems(tripId);
|
||||
const budgetItems = await this.budget.listBudgetItems(tripId);
|
||||
const budget = {
|
||||
items: budgetItems,
|
||||
item_count: budgetItems.length,
|
||||
@@ -108,7 +108,7 @@ export class TripReadModelService {
|
||||
// (#858) never land in this viewer's offline cache.
|
||||
packingItems: this.packing.listItems(tripId, viewerId),
|
||||
todoItems: this.todo.listItems(tripId),
|
||||
budgetItems: this.budget.listBudgetItems(tripId),
|
||||
budgetItems: await this.budget.listBudgetItems(tripId),
|
||||
reservations: this.reservations.list(tripId),
|
||||
files: this.files.listFiles(tripId, false),
|
||||
accommodations: this.accommodations.list(tripId),
|
||||
|
||||
@@ -493,7 +493,7 @@ export class TripsMcp {
|
||||
const ownerRow = this.trips.getOwner(tripId);
|
||||
if (!ownerRow || ownerRow.user_id !== ctx.userId)
|
||||
return { content: [{ type: 'text' as const, text: 'Only the trip owner can manage guests.' }], isError: true };
|
||||
if (!this.members.deleteGuest(tripId, guestId))
|
||||
if (!(await this.members.deleteGuest(tripId, guestId)))
|
||||
return { content: [{ type: 'text' as const, text: 'Guest not found.' }], isError: true };
|
||||
this.guards.safeBroadcast(tripId, 'member:removed', { userId: guestId });
|
||||
return ok({ success: true });
|
||||
|
||||
@@ -133,7 +133,7 @@ export class TripsRpc {
|
||||
try {
|
||||
// The no-rebase core, parity with the legacy host path, which never
|
||||
// re-anchored the budget currency.
|
||||
const result = this.trips.updateTrip(tripId, actor, input as Parameters<TripsService['updateTrip']>[2], user?.role ?? 'user');
|
||||
const result = await this.trips.updateTrip(tripId, actor, input as Parameters<TripsService['updateTrip']>[2], user?.role ?? 'user');
|
||||
this.realtime.broadcast(tripId, 'trip:updated', { trip: result.updatedTrip });
|
||||
return result.updatedTrip;
|
||||
} catch (e) {
|
||||
|
||||
@@ -12,6 +12,7 @@ import { VacayService } from '../vacay/vacay.service';
|
||||
import { UnsplashService } from '../unsplash/unsplash.service';
|
||||
import { StorageService } from '../storage/storage.service';
|
||||
import { NotFoundError, ValidationError } from '../common/domain-errors';
|
||||
import { UnitOfWork } from '../database/unit-of-work';
|
||||
|
||||
export const MS_PER_DAY = 86400000;
|
||||
|
||||
@@ -159,6 +160,7 @@ export class TripsService {
|
||||
private readonly realtime: RealtimeService,
|
||||
private readonly unsplash: UnsplashService,
|
||||
private readonly storage: StorageService,
|
||||
private readonly uow: UnitOfWork,
|
||||
) {}
|
||||
|
||||
private get db() {
|
||||
@@ -391,7 +393,7 @@ export class TripsService {
|
||||
* through update() below; the plugin RPC host calls this directly (parity:
|
||||
* the legacy host path never rebased).
|
||||
*/
|
||||
updateTrip(tripId: string | number, userId: number, data: UpdateTripData, userRole: string): UpdateTripResult {
|
||||
async updateTrip(tripId: string | number, userId: number, data: UpdateTripData, userRole: string): Promise<UpdateTripResult> {
|
||||
const trip = this.db.prepare('SELECT * FROM trips WHERE id = ?').get(tripId) as Trip & { reminder_days?: number } | undefined;
|
||||
if (!trip) throw new NotFoundError('Trip not found');
|
||||
|
||||
@@ -418,7 +420,7 @@ export class TripsService {
|
||||
this.vacay.shiftOwnerEntriesForTripWindow(trip.user_id, trip.start_date, trip.end_date, newStart);
|
||||
|
||||
if (regenerate) {
|
||||
this.db.transaction(() => {
|
||||
await this.uow.transactional(async () => {
|
||||
// Accommodations have no absolute date columns, so their pre-change dates must be
|
||||
// snapshotted before generateDays re-dates the day rows in place.
|
||||
const prevDateByDayId = new Map(
|
||||
@@ -433,15 +435,15 @@ export class TripsService {
|
||||
(this.db.prepare('SELECT id, date FROM days WHERE trip_id = ?').all(tripId) as { id: number; date: string | null }[])
|
||||
.map(d => [d.id, d.date]),
|
||||
);
|
||||
this.days.restampReservationDates(tripId, prevDateByDayId, newDateByDayId);
|
||||
await this.days.restampReservationDates(tripId, prevDateByDayId, newDateByDayId);
|
||||
} else {
|
||||
// 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);
|
||||
this.days.resyncAccommodationDays(tripId, prevDateByDayId);
|
||||
await this.days.resyncAccommodationDays(tripId, prevDateByDayId);
|
||||
}
|
||||
})();
|
||||
});
|
||||
}
|
||||
|
||||
const changes: Record<string, unknown> = {};
|
||||
@@ -491,7 +493,7 @@ export class TripsService {
|
||||
// otherwise the frozen FX rates and the currency-less expenses that inherit the
|
||||
// trip's base are left pointing at a currency that no longer exists (#1543).
|
||||
await this.budget.rebaseTripCurrency(tripId, body.currency);
|
||||
return this.updateTrip(tripId, userId, body, role);
|
||||
return await this.updateTrip(tripId, userId, body, role);
|
||||
}
|
||||
|
||||
// ── Delete ─────────────────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user