refactor(server): journey-table survivors in trips, photos, memories, auth-cleanup and plugin-contributions through repositories

This commit is contained in:
jubnl
2026-09-23 23:37:01 +02:00
parent 992f9ae4a7
commit 3a4646a7bb
41 changed files with 537 additions and 137 deletions
@@ -131,4 +131,19 @@ export class JourneyContributorsRepository extends TrekRepository<JourneyContrib
async deleteNonOwner(journeyId: number, userId: number): Promise<number> {
return await this.nativeDelete({ journey: journeyId, user: userId, role: { $ne: 'owner' } });
}
/**
* UC10 (Plan 3g Task 4 survivor, `UserCleanupService.cleanupUserReferences`)
* — `DELETE FROM journey_contributors WHERE user_id = ?`: contributor rows
* on OTHER users' journeys (not covered by UC8's cascade). Unscoped by
* journey and carries no `role != 'owner'` guard, unlike {@link
* deleteNonOwner}/JG119 — by the call order UC8 already ran first and
* deleted every journey this user owns (cascading away their own
* `role='owner'` row on each), so no remaining row for this user can be
* `role='owner'`; the absent guard is preserved exactly, not added
* defensively.
*/
async deleteAllForUser(userId: number): Promise<void> {
await this.nativeDelete({ user: userId });
}
}
@@ -147,6 +147,44 @@ export class JourneyEntriesRepository extends TrekRepository<JourneyEntries> {
);
}
/**
* TP32 (Plan 3g Task 4 survivor, `TripsService.remove`) — `DELETE FROM
* journey_entries WHERE source_trip_id = ? AND type = 'skeleton'`. NO
* `journey_id` scope, unlike {@link deleteSkeletonsForTrip}/JG31 — a trip
* delete drops every skeleton synced from it across every journey it was
* ever linked to, not just one. A genuinely different statement text, not
* a call to {@link deleteSkeletonsForTrip}.
*/
async deleteAllSkeletonsForTrip(tripId: number): Promise<void> {
await this.nativeDelete({ sourceTrip: tripId, type: 'skeleton' });
}
/**
* TP33 (Plan 3g Task 4 survivor, `TripsService.remove`) — `UPDATE
* journey_entries SET source_trip_id=NULL, source_place_id=NULL,
* source_assignment_id=NULL WHERE source_trip_id = ?`. NO `journey_id`
* scope AND no `type != 'skeleton'` filter, unlike {@link
* detachFilledForTrip}/JG32 — by the time this runs, {@link
* deleteAllSkeletonsForTrip}/TP32 has already removed every skeleton row
* with this `source_trip_id` (same transaction, called first in
* `TripsService.remove`), so every row this statement can still match is
* already non-skeleton; the missing filter is preserved exactly, not
* "fixed" into a redundant one.
*/
async detachAllFilledForTrip(tripId: number): Promise<void> {
await this.nativeUpdate({ sourceTrip: tripId }, { sourcePlace: null, sourceTrip: null, source_assignment_id: null });
}
/**
* UC9 (Plan 3g Task 4 survivor, `UserCleanupService.cleanupUserReferences`)
* — `DELETE FROM journey_entries WHERE author_id = ?`: entries this user
* authored on OTHER users' journeys (not covered by UC8's cascade, since
* those journeys aren't owned by the departing user).
*/
async deleteByAuthorId(userId: number): Promise<void> {
await this.nativeDelete({ author: userId });
}
/** JG35 — `syncTripPlaces`'s existing-skeleton dedup-key read: `SELECT source_place_id, source_assignment_id FROM journey_entries WHERE journey_id = ? AND source_trip_id = ?`. */
async listSourceKeysForTrip(journeyId: number, tripId: number): Promise<{ source_place_id: number; source_assignment_id: number | null }[]> {
return await this.qb('je')
@@ -117,6 +117,58 @@ export class JourneyPhotosRepository extends TrekRepository<JourneyPhotos> {
return await this.count({ journey: journeyId });
}
/**
* PH10 (Plan 3g Task 4 survivor, `TrekPhotoRegistrationService.deleteIfOrphan`)
* — `SELECT 1 FROM journey_photos WHERE photo_id = ?`: the `journey_photos`
* half of PH10's split orphan-check (the `trip_photos` half is 3e's own,
* already converted onto `TripPhotosRepository.existsForPhoto`).
*/
async existsForPhoto(photoId: number): Promise<boolean> {
const row = await this.qb('gp').select(['gp.id']).where({ photo: photoId }).execute<{ id: number } | undefined>('get', false);
return !!row;
}
/**
* MA1 (Plan 3g Task 4 survivor, `MemoriesAccessService.canAccessUserPhoto`'s
* journey-photo half) — `SELECT gp.journey_id FROM journey_photos gp JOIN
* trek_photos tkp ON tkp.id=gp.photo_id WHERE tkp.asset_id=? AND
* tkp.provider=? AND tkp.owner_id=? LIMIT 1`. Security-critical: returns
* only the FIRST matching row's `journey_id` (the legacy statement's own
* `LIMIT 1`), not every journey the asset might appear in — preserved
* exactly, not "fixed" into a list.
*/
async findJourneyIdForAsset(assetId: string, provider: string, ownerId: number): Promise<number | undefined> {
const row = await this.kysely<GalleryKyselyDB>()
.selectFrom('journey_photos as gp')
.innerJoin('trek_photos as tkp', 'tkp.id', 'gp.photo_id')
.select('gp.journey_id')
.where('tkp.asset_id', '=', assetId)
.where('tkp.provider', '=', provider)
.where('tkp.owner_id', '=', ownerId)
.executeTakeFirst();
return row?.journey_id;
}
/**
* MA6 (Plan 3g Task 4 survivor, `MemoriesAccessService.canAccessTrekPhoto`'s
* unified-photo-access read) — the outer `SELECT 1 FROM journey_photos gp
* WHERE gp.photo_id=?` half of the original correlated `EXISTS` statement;
* returns every DISTINCT `journey_id` a `journey_photos` row links this
* `trek_photos.id` to (a photo can be added to more than one journey's
* gallery), so the caller can probe owner-or-contributor access against
* each one in turn — same loop shape `MemoriesAccessService`'s own MA5
* (`sharedTripIds`/`findAccessible`) already uses for the trip-photo half.
*/
async listJourneyIdsForPhoto(photoId: number): Promise<number[]> {
const rows = await this.kysely<GalleryKyselyDB>()
.selectFrom('journey_photos')
.select('journey_id')
.distinct()
.where('photo_id', '=', photoId)
.execute();
return rows.map((r) => r.journey_id);
}
/** JG88/JG99 — `ensureInGallery`'s and `uploadGalleryPhotos`'s next-sort-order probe: `SELECT MAX(sort_order) as m FROM journey_photos WHERE journey_id = ?`, one statement text. */
async maxSortOrder(journeyId: number): Promise<number | null> {
const row = await this.kysely<GalleryKyselyDB>()
@@ -260,6 +260,15 @@ export class JourneyShareTokensRepository extends TrekRepository<JourneyShareTok
await this.nativeDelete({ journey: journeyId });
}
/**
* UC7 (Plan 3g Task 4 survivor, `UserCleanupService.cleanupUserReferences`)
* — `DELETE FROM journey_share_tokens WHERE created_by = ?`: erasure of
* public share links this user created (on any journey, owned or not).
*/
async deleteByCreatedBy(userId: number): Promise<void> {
await this.nativeDelete({ createdByRef: userId });
}
/**
* JS6/JS9 — the public photo/asset validators' token lookup: `SELECT
* journey_id, share_gallery FROM journey_share_tokens WHERE token = ?`.
@@ -236,4 +236,14 @@ export class JourneysRepository extends TrekRepository<Journeys> {
async deleteById(id: number): Promise<void> {
await this.nativeDelete({ id });
}
/**
* UC8 (Plan 3g Task 4 survivor, `UserCleanupService.cleanupUserReferences`)
* — `DELETE FROM journeys WHERE user_id = ?`: every journey this user
* owns, cascading to its entries/contributors/share_tokens/photos via the
* already-declared `deleteRule('cascade')` FKs.
*/
async deleteOwnedByUser(userId: number): Promise<void> {
await this.nativeDelete({ user: userId });
}
}
+10 -1
View File
@@ -10,6 +10,10 @@ import { InviteTokens } from '../../db/entities/InviteTokens.entity';
import { McpTokens } from '../../db/entities/McpTokens.entity';
import { OauthTokens } from '../../db/entities/OauthTokens.entity';
import { PasswordResetTokens } from '../../db/entities/PasswordResetTokens.entity';
import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity';
import { Journeys } from '../../db/entities/Journeys.entity';
import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
import { JourneyContributors } from '../../db/entities/JourneyContributors.entity';
import { TokensModule } from '../tokens/tokens.module';
import { AuthPublicController } from './auth-public.controller';
import { AuthController } from './auth.controller';
@@ -84,7 +88,12 @@ import { AllowedFileTypesModule } from '../files/allowed-file-types.module';
// resolves from THIS module's own `forFeature` graph regardless of who
// else also registers it (`tokens.module.ts`'s own docstring explains
// why). PasswordResetTokens: AuthService's own table (Plan 3b Task 5).
MikroOrmModule.forFeature([AppSettings, Users, WebauthnCredentials, WebauthnChallenges, InviteTokens, McpTokens, OauthTokens, PasswordResetTokens, BudgetItems])],
// JourneyShareTokens/Journeys/JourneyEntries/JourneyContributors: Plan
// 3g Task 4's own addition — `UserCleanupService.cleanupUserReferences`'s
// UC7-10 GDPR-erasure deletes, reached the same cross-domain way as
// McpTokens/OauthTokens above (owned by `nest/journey`, registered here
// for THIS module's own `@InjectRepository` params).
MikroOrmModule.forFeature([AppSettings, Users, WebauthnCredentials, WebauthnChallenges, InviteTokens, McpTokens, OauthTokens, PasswordResetTokens, BudgetItems, JourneyShareTokens, Journeys, JourneyEntries, JourneyContributors])],
controllers: [AuthPublicController, AuthController, PasskeyController],
providers: [AuthService, UserProfileService, RegistrationInvitesService, PasskeyService, UserCleanupService, WebauthnConfigService, AuthMcp],
exports: [AuthService, RegistrationInvitesService, PasskeyService, UserCleanupService],
+37 -14
View File
@@ -12,6 +12,14 @@ import { Users } from '../../db/entities/Users.entity';
import type { UsersRepository } from '../../db/repositories/Users.repository';
import { BudgetItems } from '../../db/entities/BudgetItems.entity';
import type { BudgetItemsRepository } from '../../db/repositories/BudgetItems.repository';
import { JourneyShareTokens } from '../../db/entities/JourneyShareTokens.entity';
import type { JourneyShareTokensRepository } from '../../db/repositories/JourneyShareTokens.repository';
import { Journeys } from '../../db/entities/Journeys.entity';
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
import type { JourneyEntriesRepository } from '../../db/repositories/JourneyEntries.repository';
import { JourneyContributors } from '../../db/entities/JourneyContributors.entity';
import type { JourneyContributorsRepository } from '../../db/repositories/JourneyContributors.repository';
/**
* Account erasure — everything that has to happen around `DELETE FROM users`
@@ -34,6 +42,13 @@ export class UserCleanupService {
@InjectRepository(Users) private readonly usersRepo: UsersRepository,
// Plan 3e Task 2 (budget) — additive, UC5 only.
@InjectRepository(BudgetItems) private readonly budgetItemsRepo: BudgetItemsRepository,
// Plan 3g Task 4 (UC7-10) — the genuinely-journey GDPR-erasure deletes.
// UC6 (`share_tokens`, `nest/share`, Plan 3h) is NOT one of these — see
// `cleanupUserReferences`'s own doc comment.
@InjectRepository(JourneyShareTokens) private readonly journeyShareTokensRepo: JourneyShareTokensRepository,
@InjectRepository(Journeys) private readonly journeysRepo: JourneysRepository,
@InjectRepository(JourneyEntries) private readonly journeyEntriesRepo: JourneyEntriesRepository,
@InjectRepository(JourneyContributors) private readonly journeyContributorsRepo: JourneyContributorsRepository,
) {}
/**
@@ -82,27 +97,35 @@ export class UserCleanupService {
}
/**
* UC4–UC10: every table here is owned by a domain outside this plan —
* `trip_members` (`nest/trip-membership`, Plan 3c), `budget_items`
* (`nest/budget`, Plan 3e), `share_tokens`/`journey_share_tokens`/
* `journeys`/`journey_entries`/`journey_contributors` (`nest/share`/
* `nest/journey-share`/`nest/journey-domain`, Plan 3g) — so they stay raw
* `DatabaseService` calls (Plan 3b Task 5 ruling; inventory §6). Verbatim
* otherwise: same statement order, same bounded 3-table
* journey/journey_entries/journey_contributors sequence,
* `this.budget.removeUserFromBudgetItems` unchanged.
* UC4–UC10: `trip_members` (`nest/trip-membership`, Plan 3c) and
* `budget_items` (`nest/budget`, Plan 3e) are owned by domains outside
* this plan, so UC4 stays a raw `DatabaseService` call (Plan 3b Task 5
* ruling; inventory §6) — UC5 is already converted (`budgetItemsRepo
* .clearPaidByUser`). `share_tokens` (UC6) belongs to `nest/share`
* (trip-level share links, Plan 3h) — a genuinely different table from
* the four below despite sharing this method and this erasure
* transaction, so it ALSO stays a raw `DatabaseService` call, but for a
* different reason than UC4 (not this plan's table at all, not merely
* "another plan hasn't converted it yet"). `journey_share_tokens`/
* `journeys`/`journey_entries`/`journey_contributors` (UC7-10,
* `nest/journey-share`/`nest/journey-domain`, Plan 3g) ARE this plan's
* own and are converted (Plan 3g Task 4) onto their owning repositories.
* Verbatim otherwise: same statement order, same bounded 4-table
* share_tokens/journey_share_tokens/journeys/journey_entries/
* journey_contributors sequence, `this.budget.removeUserFromBudgetItems`
* unchanged.
*/
private async cleanupUserReferences(userId: number): Promise<void> {
this.db.run('UPDATE trip_members SET invited_by = NULL WHERE invited_by = ?', userId); // UC4 — Plan 3c
await this.budgetItemsRepo.clearPaidByUser(userId); // UC5 — Plan 3e Task 2, converted.
await this.budget.removeUserFromBudgetItems(userId);
this.db.run('DELETE FROM share_tokens WHERE created_by = ?', userId); // UC6 — Plan 3g
this.db.run('DELETE FROM journey_share_tokens WHERE created_by = ?', userId); // UC7 — Plan 3g
this.db.run('DELETE FROM share_tokens WHERE created_by = ?', userId); // UC6 — Plan 3h
await this.journeyShareTokensRepo.deleteByCreatedBy(userId); // UC7 — converted (Plan 3g Task 4)
// Owned journeys cascade-delete their entries/contributors/share_tokens/photos via journey_id FKs
this.db.run('DELETE FROM journeys WHERE user_id = ?', userId); // UC8 — Plan 3g
await this.journeysRepo.deleteOwnedByUser(userId); // UC8 — converted (Plan 3g Task 4)
// Entries authored on other users' journeys (not covered by the cascade above)
this.db.run('DELETE FROM journey_entries WHERE author_id = ?', userId); // UC9 — Plan 3g
this.db.run('DELETE FROM journey_contributors WHERE user_id = ?', userId); // UC10 — Plan 3g
await this.journeyEntriesRepo.deleteByAuthorId(userId); // UC9 — converted (Plan 3g Task 4)
await this.journeyContributorsRepo.deleteAllForUser(userId); // UC10 — converted (Plan 3g Task 4)
}
/**
@@ -12,6 +12,12 @@ import { TripAlbumLinks } from '../../db/entities/TripAlbumLinks.entity';
import type { TripAlbumLinksRepository } from '../../db/repositories/TripAlbumLinks.repository';
import { Trips } from '../../db/entities/Trips.entity';
import type { TripsRepository } from '../../db/repositories/Trips.repository';
import { Journeys } from '../../db/entities/Journeys.entity';
import type { JourneysRepository } from '../../db/repositories/Journeys.repository';
import { JourneyContributors } from '../../db/entities/JourneyContributors.entity';
import type { JourneyContributorsRepository } from '../../db/repositories/JourneyContributors.repository';
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
import type { JourneyPhotosRepository } from '../../db/repositories/JourneyPhotos.repository';
/**
* Who may see which photo, and the album-link lookups the provider syncs need.
@@ -24,9 +30,14 @@ import type { TripsRepository } from '../../db/repositories/Trips.repository';
* Stays a service, not a single-table repository (Plan 3e): it composes
* access logic across `trip_photos`/`trek_photos`/`trip_album_links`
* (this plan's own tables) and `journeys`/`journey_contributors`/
* `journey_photos` (Plan 3g's, not yet converted — every read against them
* below stays raw, marked `// <SITE> — Plan 3g`). `DatabaseService` stays
* injected for exactly those raw reads and for the `canAccessTrip` primitive
* `journey_photos` (Plan 3g's — MA1/MA2/MA6, converted by Plan 3g Task 4
* onto `JourneysRepository`/`JourneyContributorsRepository`/
* `JourneyPhotosRepository`, NOT routed through `JourneyDomainService
* .canAccessJourney` — this service re-implements the same owner-or
* -contributor logic inline for its own reasons, composing it with the
* trip-photo check in one method; a service-to-service dependency here
* would be a bigger structural change than a survivor cleanup is scoped
* for). `DatabaseService` stays injected for the `canAccessTrip` primitive
* (a cross-cutting primitive, not a per-domain SQL statement this plan
* converts).
*/
@@ -38,8 +49,19 @@ export class MemoriesAccessService {
@InjectRepository(TrekPhotos) private readonly trekPhotos: TrekPhotosRepository,
@InjectRepository(TripAlbumLinks) private readonly tripAlbumLinks: TripAlbumLinksRepository,
@InjectRepository(Trips) private readonly trips: TripsRepository,
// Plan 3g Task 4 (MA1/MA2/MA6) — the journey half of the cross-domain
// photo-access checks below.
@InjectRepository(Journeys) private readonly journeys: JourneysRepository,
@InjectRepository(JourneyContributors) private readonly journeyContributors: JourneyContributorsRepository,
@InjectRepository(JourneyPhotos) private readonly journeyPhotos: JourneyPhotosRepository,
) {}
/** MA2's owner-OR-contributor check, shared by MA2 and MA6's per-journey loop — the same two-branch `journeys`/`journey_contributors` logic `canAccessJourney` uses, re-implemented here (see the class docstring on why it isn't a call to `JourneyDomainService`). */
private async ownerOrContributor(journeyId: number, userId: number): Promise<boolean> {
if (await this.journeys.isOwnedByUser(journeyId, userId)) return true;
return await this.journeyContributors.existsForUser(journeyId, userId);
}
async canAccessUserPhoto(requestingUserId: number, ownerUserId: number, tripId: string, assetId: string, provider: string): Promise<boolean> {
if (requestingUserId === ownerUserId) {
return true;
@@ -47,26 +69,12 @@ export class MemoriesAccessService {
// Journey photos use tripId=0 — check journey_photos + journey_contributors
if (tripId === '0') {
// MA1 — Plan 3g (journey_photos is not yet an owned repository table).
const journeyPhoto = this.db.get<{ journey_id: number }>(`
SELECT gp.journey_id
FROM journey_photos gp
JOIN trek_photos tkp ON tkp.id = gp.photo_id
WHERE tkp.asset_id = ?
AND tkp.provider = ?
AND tkp.owner_id = ?
LIMIT 1
`, assetId, provider, ownerUserId);
if (!journeyPhoto) return false;
// MA1 — converted (Plan 3g Task 4).
const journeyId = await this.journeyPhotos.findJourneyIdForAsset(assetId, provider, ownerUserId);
if (journeyId === undefined) return false;
// MA2 — Plan 3g (journeys/journey_contributors are not yet owned repository tables).
const access = this.db.get(`
SELECT 1 FROM journeys WHERE id = ? AND user_id = ?
UNION ALL
SELECT 1 FROM journey_contributors WHERE journey_id = ? AND user_id = ?
LIMIT 1
`, journeyPhoto.journey_id, requestingUserId, journeyPhoto.journey_id, requestingUserId);
return !!access;
// MA2 — converted (Plan 3g Task 4).
return await this.ownerOrContributor(journeyId, requestingUserId);
}
// Regular trip photos — join through trek_photos (MA3).
@@ -100,22 +108,21 @@ export class MemoriesAccessService {
}
// Check journey_photos — is this photo in a journey the user can access?
// MA6 — Plan 3g (journey_photos/journeys/journey_contributors are not yet owned repository tables).
const journeyAccess = this.db.get(`
SELECT 1 FROM journey_photos gp
WHERE gp.photo_id = ?
AND EXISTS (
SELECT 1 FROM journeys j WHERE j.id = gp.journey_id AND j.user_id = ?
UNION ALL
SELECT 1 FROM journey_contributors jc WHERE jc.journey_id = gp.journey_id AND jc.user_id = ?
)
LIMIT 1
`, trekPhotoId, requestingUserId, requestingUserId);
// MA6 — converted (Plan 3g Task 4). Every journey this photo is linked
// into (a photo can be in more than one journey's gallery), probed the
// same loop-and-check shape as the trip-photo half above (MA5).
let journeyAccess = false;
for (const journeyId of await this.journeyPhotos.listJourneyIdsForPhoto(trekPhotoId)) {
if (await this.ownerOrContributor(journeyId, requestingUserId)) {
journeyAccess = true;
break;
}
}
if (journeyAccess) return true;
// Local photos without owner (uploaded files) — check if user has journey access
if (photo.provider === 'local' && !photo.owner_id) {
return !!journeyAccess;
return journeyAccess;
}
return false;
+9 -2
View File
@@ -33,6 +33,9 @@ import { Trips } from '../../db/entities/Trips.entity';
import { TrekPhotoCacheMeta } from '../../db/entities/TrekPhotoCacheMeta.entity';
import { PhotoProviders } from '../../db/entities/PhotoProviders.entity';
import { Users } from '../../db/entities/Users.entity';
import { Journeys } from '../../db/entities/Journeys.entity';
import { JourneyContributors } from '../../db/entities/JourneyContributors.entity';
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
/**
* Memories (photo-providers) domain — mounted at /api/integrations/memories.
@@ -63,12 +66,16 @@ import { Users } from '../../db/entities/Users.entity';
* this module) and `Users` (owned elsewhere, reached the same way `Trips`
* is above) are added for `UnifiedMemoriesService`/`ImmichService`/
* `SynologyService`/`MemoriesMcp`'s `@InjectRepository` constructor params
* (Plan 3e Task 7).
* (Plan 3e Task 7). `Journeys`/`JourneyContributors`/`JourneyPhotos` are
* Plan 3g Task 4's own addition: `MemoriesAccessService`'s MA1/MA2/MA6
* (`canAccessUserPhoto`/`canAccessTrekPhoto`'s journey half) now inject
* `JourneysRepository`/`JourneyContributorsRepository`/
* `JourneyPhotosRepository` directly instead of raw `DatabaseService` reads.
*/
@Module({
imports: [
NotificationsModule, AddonsModule, AuditModule, TrekPhotosModule, RealtimeModule, SchedulingModule, StorageModule,
MikroOrmModule.forFeature([TripPhotos, TrekPhotos, TripAlbumLinks, Trips, TrekPhotoCacheMeta, PhotoProviders, Users]),
MikroOrmModule.forFeature([TripPhotos, TrekPhotos, TripAlbumLinks, Trips, TrekPhotoCacheMeta, PhotoProviders, Users, Journeys, JourneyContributors, JourneyPhotos]),
],
controllers: [UnifiedMemoriesController, ImmichMemoriesController, SynologyMemoriesController],
providers: [
+5 -2
View File
@@ -3,6 +3,7 @@ import { MikroOrmModule } from '@mikro-orm/nestjs';
import { TrekPhotoRegistrationService } from './trek-photos.repository';
import { TrekPhotos } from '../../db/entities/TrekPhotos.entity';
import { TripPhotos } from '../../db/entities/TripPhotos.entity';
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
/**
* The trek_photos store on its own, so both halves can have it without
@@ -16,10 +17,12 @@ import { TripPhotos } from '../../db/entities/TripPhotos.entity';
*
* `MikroOrmModule.forFeature` registers `TrekPhotosRepository`/
* `TripPhotosRepository` (the ORM ones) for `TrekPhotoRegistrationService`'s
* `@InjectRepository` constructor params (Plan 3e Task 6).
* `@InjectRepository` constructor params (Plan 3e Task 6). `JourneyPhotos` is
* Plan 3g Task 4's own addition — PH10's `journey_photos` orphan-check half
* (`deleteIfOrphan`) now injects `JourneyPhotosRepository` too.
*/
@Module({
imports: [MikroOrmModule.forFeature([TrekPhotos, TripPhotos])],
imports: [MikroOrmModule.forFeature([TrekPhotos, TripPhotos, JourneyPhotos])],
providers: [TrekPhotoRegistrationService],
exports: [TrekPhotoRegistrationService],
})
@@ -7,6 +7,8 @@ import { TrekPhotos } from '../../db/entities/TrekPhotos.entity';
import type { TrekPhotosRepository } from '../../db/repositories/TrekPhotos.repository';
import { TripPhotos } from '../../db/entities/TripPhotos.entity';
import type { TripPhotosRepository } from '../../db/repositories/TripPhotos.repository';
import { JourneyPhotos } from '../../db/entities/JourneyPhotos.entity';
import type { JourneyPhotosRepository } from '../../db/repositories/JourneyPhotos.repository';
/**
* The `trek_photos` table: register a photo, look one up, retarget it, drop it
@@ -35,6 +37,9 @@ export class TrekPhotoRegistrationService {
constructor(
@InjectRepository(TrekPhotos) private readonly trekPhotos: TrekPhotosRepository,
@InjectRepository(TripPhotos) private readonly tripPhotos: TripPhotosRepository,
// Plan 3g Task 4 (PH10) — the `journey_photos` half of `deleteIfOrphan`'s
// split orphan-check.
@InjectRepository(JourneyPhotos) private readonly journeyPhotos: JourneyPhotosRepository,
private readonly db: DatabaseService,
) {}
@@ -137,16 +142,15 @@ export class TrekPhotoRegistrationService {
*
* PH10's original statement was one `UNION ALL` existence check across
* `trip_photos` and `journey_photos`; split into its two halves here
* (`TripPhotosRepository.existsForPhoto` for the 3e-owned table, a still
* -raw `journey_photos` read for the not-yet-converted Plan 3g table) —
* logically identical (neither half needs to run if the other already
* found a row), never a transaction (both are reads).
* (`TripPhotosRepository.existsForPhoto` for the 3e-owned table,
* `JourneyPhotosRepository.existsForPhoto` for the Plan 3g-owned table,
* converted by Plan 3g Task 4) — logically identical (neither half needs
* to run if the other already found a row), never a transaction (both are
* reads).
*/
async deleteIfOrphan(photoId: number): Promise<void> {
if (await this.tripPhotos.existsForPhoto(photoId)) return;
// PH10 — Plan 3g (journey_photos is not yet an owned repository table).
const stillUsedByJourney = this.db.get('SELECT 1 FROM journey_photos WHERE photo_id = ?', photoId);
if (stillUsedByJourney) return;
if (await this.journeyPhotos.existsForPhoto(photoId)) return; // PH10 — converted (Plan 3g Task 4)
await this.trekPhotos.deleteNonLocal(photoId);
}
}
@@ -1,7 +1,9 @@
import { Controller, Get, Param, Req, UseGuards } from '@nestjs/common';
import type { Request } from 'express';
import { DatabaseService } from '../../database/database.service';
import { InjectRepository } from '@mikro-orm/nestjs';
import { JourneyDomainService } from '../../journey/journey-domain.service';
import { JourneyEntries } from '../../../db/entities/JourneyEntries.entity';
import type { JourneyEntriesRepository } from '../../../db/repositories/JourneyEntries.repository';
import { AddonsService } from '../../addons/addons.service';
import { ADDON_IDS } from '../../../addons';
import { JwtAuthGuard } from '../../auth/jwt-auth.guard';
@@ -13,7 +15,10 @@ import { stripEmoji } from '../text-sanitize';
* GET /api/journal-entry-rows/:entryId — extra rows for a journal entry,
* contributed by plugins implementing the `journalEntryProvider` hook. Additive +
* fail-safe like place-details: the entry's journey must be one the caller can
* access (owner/contributor — the same gate as the journal detail routes), the
* access (owner/contributor via `JourneyDomainService.canAccessJourney` — the
* same gate as the journal detail routes; the `journey_id` lookup that feeds
* it is JEC1, converted onto `JourneyEntriesRepository.findById`, Plan 3g
* Task 4), the
* Journey addon must be on (an off addon just yields nothing, this endpoint is
* purely additive), each provider runs host->plugin on a short timeout, and one
* that errors/times out contributes nothing.
@@ -68,7 +73,11 @@ function normalize(raw: unknown): EntryRow[] {
export class JournalEntryRowsController {
constructor(
private readonly hooks: PluginHooks,
private readonly dbs: DatabaseService,
// JEC1 (Plan 3g Task 4) — the entry's `journey_id` lookup below; was a
// raw `DatabaseService` read, now `JourneyEntriesRepository.findById`
// (already the widest `SELECT * FROM journey_entries WHERE id = ?` dup
// group's own resolution, so no narrower single-column method needed).
@InjectRepository(JourneyEntries) private readonly journeyEntries: JourneyEntriesRepository,
private readonly addons: AddonsService,
private readonly journey: JourneyDomainService,
) {}
@@ -84,7 +93,7 @@ export class JournalEntryRowsController {
if (!Number.isFinite(entryId) || userId == null) return { providers: [] };
// The entry's journey must be one the caller can access — same gate as a read.
const row = this.dbs.connection.prepare('SELECT journey_id FROM journey_entries WHERE id = ?').get(entryId) as { journey_id: number } | undefined;
const row = await this.journeyEntries.findById(entryId); // JEC1 — converted (Plan 3g Task 4)
if (!row || !(await this.journey.canAccessJourney(row.journey_id, userId))) return { providers: [] };
const ids = this.hooks.providersOf('journalEntryProvider');
@@ -1,7 +1,9 @@
import { Module } from '@nestjs/common';
import { MikroOrmModule } from '@mikro-orm/nestjs';
import { PluginsRuntimeModule } from '../plugins-runtime.module';
import { AddonsModule } from '../../addons/addons.module';
import { JourneyDomainModule } from '../../journey/journey-domain.module';
import { JourneyEntries } from '../../../db/entities/JourneyEntries.entity';
import { PlaceDetailsController } from './place-details.controller';
import { PluginSearchController } from './plugin-search.controller';
import { TripWarningsController } from './trip-warnings.controller';
@@ -32,9 +34,16 @@ import { JournalEntryRowsController } from './journal-entry-rows.controller';
* throws — so they belong together and nowhere else. None of them can install,
* activate or configure anything, which is why they are separated from the CRUD
* surface in PluginsModule.
*
* `MikroOrmModule.forFeature([JourneyEntries])` registers
* `JourneyEntriesRepository` for `JournalEntryRowsController`'s own
* `@InjectRepository` constructor param (JEC1, Plan 3g Task 4) — importing
* `JourneyDomainModule` above brings in `JourneyDomainService` for the
* `canAccessJourney` call but does NOT export `MikroOrmModule`, so the
* entity needs its own registration here too.
*/
@Module({
imports: [PluginsRuntimeModule, AddonsModule, JourneyDomainModule],
imports: [PluginsRuntimeModule, AddonsModule, JourneyDomainModule, MikroOrmModule.forFeature([JourneyEntries])],
controllers: [
PlaceDetailsController,
PluginSearchController,
+24 -19
View File
@@ -4,6 +4,7 @@ import { EntityManager } from '@mikro-orm/core';
import { DatabaseService } from '../database/database.service';
import { Trips } from '../../db/entities/Trips.entity';
import { Days } from '../../db/entities/Days.entity';
import { JourneyEntries } from '../../db/entities/JourneyEntries.entity';
import { Users } from '../../db/entities/Users.entity';
import { Places } from '../../db/entities/Places.entity';
import { DayAssignments } from '../../db/entities/DayAssignments.entity';
@@ -178,14 +179,17 @@ export class TripsService {
private readonly em: EntityManager,
) {}
// Plan 3c Task 7: the raw better-sqlite3 handle now backs only the three
// documented survivors — `remove`'s TP32/TP33 (journey_entries, Plan 3g)
// and `copy`/`getCopiedTrip` (Task 8's own file). Every other method below
// reads/writes through `tripsRepo`/`daysRepo` (or a sibling repository
// reached the same way `TripsService.canAccessTrip`/`.isOwner` already
// did since Task 0b: `this.em.getRepository(...)`, not a new constructor
// parameter — the shared per-request `EntityManager` caches repositories,
// so this is the same instance a hand-constructed test spies on).
// Plan 3c Task 7: the raw better-sqlite3 handle used to back `remove`'s
// TP32/TP33 (journey_entries) — converted by Plan 3g Task 4 onto
// `JourneyEntriesRepository` below, leaving `db`/`dbs` unused in this file
// (kept rather than removed, to avoid a `TripsService` constructor-shape
// change outside this survivor task's scope). Every method in this file
// reads/writes through `tripsRepo`/`daysRepo`/`journeyEntriesRepo` (or a
// sibling repository reached the same way `TripsService.canAccessTrip`/
// `.isOwner` already did since Task 0b: `this.em.getRepository(...)`, not
// a new constructor parameter — the shared per-request `EntityManager`
// caches repositories, so this is the same instance a hand-constructed
// test spies on).
private get db() {
return this.dbs.connection;
}
@@ -198,6 +202,13 @@ export class TripsService {
return this.em.getRepository(Days);
}
// Plan 3g Task 4 (TP32/TP33) — `journey_entries`' trip-wide skeleton
// cleanup/detach, reached the same `this.em.getRepository(...)` way as
// `tripsRepo`/`daysRepo` above.
private get journeyEntriesRepo() {
return this.em.getRepository(JourneyEntries);
}
// Plan 3c Task 8 (`copy`'s own 6 owned tables): resolved the same way
// `tripsRepo`/`daysRepo` above are — `this.em.getRepository(...)`, not a
// new constructor parameter.
@@ -632,9 +643,9 @@ export class TripsService {
// ── Delete ─────────────────────────────────────────────────────────────────
/**
* TP30–TP34 (inventory §11c) — TP32/TP33 (`journey_entries`) stay raw
* inside the transaction (`// Plan 3g`, that table's owning plan); every
* other statement moved through `TripsRepository`.
* TP30–TP34 (inventory §11c) — every statement, including TP32/TP33
* (`journey_entries`), moves through a repository (TP32/TP33 converted by
* Plan 3g Task 4 onto `JourneyEntriesRepository`).
*/
async remove(tripId: string | number, userId: number, userRole: string): Promise<DeleteTripInfo> {
const trip = await this.tripsRepo.findIdTitleOwner(tripId); // TP30 (the `id` field this method also selects is unused here)
@@ -652,15 +663,9 @@ export class TripsService {
await this.uow.transactional(async () => {
// Clean up journey entries synced from this trip before deleting
// Delete skeleton entries (unfilled synced places)
this.db.prepare(`
DELETE FROM journey_entries
WHERE source_trip_id = ? AND type = 'skeleton'
`).run(tripId); // TP32 — Plan 3g
await this.journeyEntriesRepo.deleteAllSkeletonsForTrip(Number(tripId)); // TP32 — converted (Plan 3g Task 4)
// Detach filled entries (keep user's written content, just remove trip link)
this.db.prepare(`
UPDATE journey_entries SET source_trip_id = NULL, source_place_id = NULL, source_assignment_id = NULL
WHERE source_trip_id = ?
`).run(tripId); // TP33 — Plan 3g
await this.journeyEntriesRepo.detachAllFilledForTrip(Number(tripId)); // TP33 — converted (Plan 3g Task 4)
await this.tripsRepo.deleteById(Number(tripId)); // TP34 — safe: `trip` above only resolved through the raw-bind seam on a real row
});