import { randomUUID } from "node:crypto"; import { eq } from "drizzle-orm"; import { afterAll, expect, test, vi } from "vitest"; import { downloadEvents } from "@/db/schema"; import { createAlbumGrantRepository, createAlbumGrantService } from "@/modules/albums/grants"; import { createUsageService, createUsageServiceRepository } from "@/modules/usages/service"; import { requestFingerprint } from "@/modules/usages/types"; import { startPostgres } from "./postgres"; const testDb = await startPostgres({ through: "0001_editorial_approval_notice.sql" }); afterAll(() => testDb.stop()); const validAssetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; const validAlbumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; const cleanKey = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; const collidingKey = "dddddddd-dddd-4ddd-8ddd-dddddddddddd"; const authorizedAt = new Date("2026-08-09T08:00:00.000Z"); const repeatAt = new Date("2026-08-09T08:01:00.000Z"); const laterNullAt = new Date("2026-08-09T08:02:00.000Z"); async function insertLegacyUsage({ editorialId, assetId = validAssetId, albumId = validAlbumId, purpose = "Titelgeschichte", reference = "Ausgabe 8/26", }: { editorialId: string; assetId?: string; albumId?: string; purpose?: string; reference?: string | null; }) { const usageId = randomUUID(); await testDb.pool.query( `insert into usages ( id, editorial_account_id, immich_asset_id, filename_snapshot, immich_album_id_snapshot, album_name_snapshot, purpose, internal_reference, price_cents, billing_status, created_at ) values ($1, $2, $3, 'legacy.jpg', $4, 'Legacy Album', $5, $6, 2300, 'open', $7)`, [usageId, editorialId, assetId, albumId, purpose, reference, authorizedAt], ); return usageId; } async function insertLegacyEvent({ editorialId, usageId, assetId = validAssetId, idempotencyKey = randomUUID(), note = null, at = authorizedAt, }: { editorialId: string; usageId: string; assetId?: string; idempotencyKey?: string; note?: string | null; at?: Date; }) { const eventId = randomUUID(); await testDb.pool.query( `insert into download_events ( id, editorial_account_id, usage_id, immich_asset_id, authorized_at, status, repeat_download_note, request_id, idempotency_key ) values ($1, $2, $3, $4, $5, 'authorized', $6, $7, $8)`, [eventId, editorialId, usageId, assetId, at, note, randomUUID(), idempotencyKey], ); return eventId; } test("0002 preserves dirty rows and reconstructs only provable legacy intents", async () => { const userId = randomUUID(); const editorialId = randomUUID(); await testDb.pool.query( `insert into users (id, name, email, email_verified) values ($1, 'Legacy Redaktion', $2, true)`, [userId, `${userId}@example.com`], ); await testDb.pool.query( `insert into editorial_accounts ( id, user_id, name, contact_name, login_email, status, current_price_cents ) values ($1, $2, 'Legacy Redaktion', 'Legacy Kontakt', $3, 'active', 2300)`, [editorialId, userId, `${userId}@example.com`], ); await testDb.pool.query( `insert into album_grants (editorial_account_id, immich_album_id) values ($1, $2), ($1, $3), ($1, $4)`, [editorialId, validAlbumId.toUpperCase(), "legacy album / 2019", validAlbumId], ); const cleanUsageId = await insertLegacyUsage({ editorialId, assetId: validAssetId.toUpperCase(), albumId: validAlbumId.toUpperCase(), }); const cleanEventId = await insertLegacyEvent({ editorialId, usageId: cleanUsageId, assetId: validAssetId.toUpperCase(), idempotencyKey: cleanKey.toUpperCase(), }); const repeatUsageId = await insertLegacyUsage({ editorialId }); const repeatInitialEventId = await insertLegacyEvent({ editorialId, usageId: repeatUsageId }); const provableRepeatEventId = await insertLegacyEvent({ editorialId, usageId: repeatUsageId, note: "Web-Ausgabe", at: repeatAt, }); const laterNullEventId = await insertLegacyEvent({ editorialId, usageId: repeatUsageId, at: laterNullAt, }); const tabPurposeUsageId = await insertLegacyUsage({ editorialId, purpose: "\tTitelgeschichte", }); const tabPurposeEventId = await insertLegacyEvent({ editorialId, usageId: tabPurposeUsageId, }); const newlineReferenceUsageId = await insertLegacyUsage({ editorialId, reference: "Ausgabe 8/26\n", }); const newlineReferenceEventId = await insertLegacyEvent({ editorialId, usageId: newlineReferenceUsageId, }); const nbspNoteUsageId = await insertLegacyUsage({ editorialId }); const nbspNoteInitialEventId = await insertLegacyEvent({ editorialId, usageId: nbspNoteUsageId, }); const nbspNoteEventId = await insertLegacyEvent({ editorialId, usageId: nbspNoteUsageId, note: "\u00a0Web-Ausgabe", at: repeatAt, }); const dirtyAssetId = "legacy-asset/not-a-uuid"; const dirtyAlbumId = "legacy album / 2019"; const dirtyUsageId = await insertLegacyUsage({ editorialId, assetId: dirtyAssetId, albumId: dirtyAlbumId, }); const dirtyEventId = await insertLegacyEvent({ editorialId, usageId: dirtyUsageId, assetId: dirtyAssetId, idempotencyKey: "legacy-request", }); const equalTimeUsageId = await insertLegacyUsage({ editorialId }); const equalTimeEventIds = await Promise.all([ insertLegacyEvent({ editorialId, usageId: equalTimeUsageId }), insertLegacyEvent({ editorialId, usageId: equalTimeUsageId, note: "Wiederholung", }), ]); const contradictoryUsageId = await insertLegacyUsage({ editorialId }); const contradictoryEventId = await insertLegacyEvent({ editorialId, usageId: contradictoryUsageId, note: "Als Wiederholung markiert", }); const collisionUsageIds = await Promise.all([ insertLegacyUsage({ editorialId }), insertLegacyUsage({ editorialId }), ]); const collisionEventIds = await Promise.all([ insertLegacyEvent({ editorialId, usageId: collisionUsageIds[0], idempotencyKey: collidingKey.toUpperCase(), }), insertLegacyEvent({ editorialId, usageId: collisionUsageIds[1], idempotencyKey: collidingKey, }), ]); await testDb.applyRemainingMigrations(); const immich = { getAlbum: vi.fn(), getAsset: vi.fn(), }; const usageService = createUsageService({ repository: createUsageServiceRepository(testDb.database), immich, }); await expect( usageService.createNewUsage({ editorialId: editorialId.toUpperCase(), assetId: validAssetId.toUpperCase(), albumId: validAlbumId.toUpperCase(), purpose: "Titelgeschichte", reference: "Ausgabe 8/26", idempotencyKey: cleanKey.toUpperCase(), }), ).resolves.toEqual({ id: cleanEventId, usageId: cleanUsageId, assetId: validAssetId.toUpperCase(), priceCents: 2300, billable: true, status: "authorized", authorizedAt, }); expect(immich.getAlbum).not.toHaveBeenCalled(); expect(immich.getAsset).not.toHaveBeenCalled(); const migratedEvents = await testDb.pool.query<{ id: string; idempotency_key: string; immich_asset_id: string; intent_kind: string; request_fingerprint: string; }>( `select id, idempotency_key, immich_asset_id, intent_kind, request_fingerprint from download_events`, ); expect(migratedEvents.rows).toHaveLength(14); const byId = new Map(migratedEvents.rows.map((row) => [row.id, row])); expect(byId.get(cleanEventId)).toMatchObject({ idempotency_key: cleanKey, immich_asset_id: validAssetId.toUpperCase(), intent_kind: "new_usage", request_fingerprint: requestFingerprint({ kind: "new_usage", editorialId, assetId: validAssetId, albumId: validAlbumId, purpose: "Titelgeschichte", reference: "Ausgabe 8/26", }), }); expect(byId.get(dirtyEventId)).toMatchObject({ idempotency_key: "legacy-request", immich_asset_id: dirtyAssetId, intent_kind: "legacy", }); expect(byId.get(repeatInitialEventId)?.intent_kind).toBe("new_usage"); expect(byId.get(provableRepeatEventId)).toMatchObject({ intent_kind: "repeat_download", request_fingerprint: requestFingerprint({ kind: "repeat_download", editorialId, usageId: repeatUsageId, note: "Web-Ausgabe", }), }); for (const id of [ laterNullEventId, tabPurposeEventId, newlineReferenceEventId, nbspNoteEventId, ...equalTimeEventIds, contradictoryEventId, ...collisionEventIds, ]) { expect(byId.get(id)?.intent_kind).toBe("legacy"); expect(byId.get(id)?.request_fingerprint).toMatch(/^[0-9a-f]{64}$/); } expect(byId.get(nbspNoteInitialEventId)?.intent_kind).toBe("new_usage"); expect(collisionEventIds.map((id) => byId.get(id)?.idempotency_key).sort()).toEqual( [collidingKey.toUpperCase(), collidingKey].sort(), ); const dirtySnapshots = await testDb.pool.query<{ immich_asset_id: string; immich_album_id_snapshot: string; }>("select immich_asset_id, immich_album_id_snapshot from usages where id = $1", [dirtyUsageId]); expect(dirtySnapshots.rows[0]).toEqual({ immich_asset_id: dirtyAssetId, immich_album_id_snapshot: dirtyAlbumId, }); const dirtyGrant = await testDb.pool.query<{ immich_album_id: string }>( "select immich_album_id from album_grants where immich_album_id = $1", [dirtyAlbumId], ); expect(dirtyGrant.rows).toEqual([{ immich_album_id: dirtyAlbumId }]); await expect( testDb.pool.query( "insert into album_grants (editorial_account_id, immich_album_id) values ($1, $2)", [editorialId, "new-invalid-album"], ), ).rejects.toThrow(/album_grants_immich_album_id_uuid_check/); await expect( testDb.pool.query( "update album_grants set revoked_at = now() where immich_album_id = $1", [dirtyAlbumId], ), ).rejects.toThrow(/album_grants_immich_album_id_uuid_check/); const grantService = createAlbumGrantService({ repository: createAlbumGrantRepository(testDb.database), immich: { getAlbum: vi.fn().mockResolvedValue({ id: validAlbumId, albumName: "Legacy Album", description: null, albumThumbnailAssetId: null, assetCount: 0, assets: [], }), listAlbums: vi.fn(), }, }); await grantService.revokeAlbum({ editorialId, immichAlbumId: validAlbumId, adminUserId: userId, }); let canonicalGrantRows = await testDb.pool.query<{ immich_album_id: string; revoked_at: Date | null; }>( "select immich_album_id, revoked_at from album_grants where lower(immich_album_id) = $1", [validAlbumId], ); expect(canonicalGrantRows.rows).toHaveLength(2); expect(canonicalGrantRows.rows.map((row) => row.immich_album_id).sort()).toEqual( [validAlbumId.toUpperCase(), validAlbumId].sort(), ); expect(canonicalGrantRows.rows.every((row) => row.revoked_at !== null)).toBe(true); await grantService.grantAlbum({ editorialId, immichAlbumId: validAlbumId, adminUserId: userId, }); canonicalGrantRows = await testDb.pool.query( "select immich_album_id, revoked_at from album_grants where lower(immich_album_id) = $1", [validAlbumId], ); expect(canonicalGrantRows.rows.filter((row) => row.revoked_at === null)).toHaveLength(1); await expect( usageService.createNewUsage({ editorialId, assetId: validAssetId, albumId: validAlbumId, purpose: "Titelgeschichte", reference: "Ausgabe 8/26", idempotencyKey: collidingKey, }), ).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); const [cleanEvent] = await testDb.database .select() .from(downloadEvents) .where(eq(downloadEvents.id, cleanEventId)); expect(cleanEvent).toMatchObject({ legacyIntent: true, intentKind: "new_usage" }); });