import { randomUUID } from "node:crypto"; import { and, count, eq } from "drizzle-orm"; import type { PoolClient } from "pg"; import { afterAll, expect, test, vi } from "vitest"; import { albumGrants, auditEvents, downloadEvents, editorialAccounts, usages, users, } from "@/db/schema"; import { createUsageService, createUsageServiceRepository, } from "@/modules/usages/service"; import { createDownloadService, createRepeatDownloadRepository, } from "@/modules/downloads/service"; import { assertOriginalAccess } from "@/modules/albums/photo-access"; import { requestFingerprint } from "@/modules/usages/types"; import { startPostgres } from "./postgres"; const testDb = await startPostgres(); const database = testDb.database; afterAll(() => testDb.stop()); const assetId = "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa"; const albumId = "bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb"; const otherAlbumId = "cccccccc-cccc-4ccc-8ccc-cccccccccccc"; const asset = { id: assetId, type: "IMAGE" as const, originalFileName: "jubel.jpg", originalMimeType: "image/jpeg", localDateTime: null, fileCreatedAt: null, albums: [{ id: albumId }], }; function createServices() { const immich = { getAlbum: vi.fn().mockResolvedValue({ id: albumId, albumName: "Presse 2026" }), getAsset: vi.fn().mockResolvedValue(asset), searchPhotos: vi.fn().mockResolvedValue({ items: [{ id: asset.id }], total: 1, nextPage: null, previousPage: null, }), }; return { usageService: createUsageService({ repository: createUsageServiceRepository(database), immich, }), downloadService: createDownloadService({ repository: createRepeatDownloadRepository(database, (editorialId, assetId, albumId, tx) => assertOriginalAccess(editorialId, assetId, albumId, tx, immich)), }), immich, }; } async function seedEditorial({ status = "active", priceCents = 1_500, albumId: grantedAlbumId = albumId, revoked = false, collabEnabled = false, flatrateActive = false, flatratePriceCents = null, flatrateAssetLimit = null, }: { status?: "active" | "suspended" | "pending_approval"; priceCents?: number | null; albumId?: string; revoked?: boolean; collabEnabled?: boolean; flatrateActive?: boolean; flatratePriceCents?: number | null; flatrateAssetLimit?: number | null; } = {}) { const userId = randomUUID(); const editorialId = randomUUID(); await database.insert(users).values({ id: userId, name: "Test Redaktion", email: `${userId}@example.com`, emailVerified: true, }); await database.insert(editorialAccounts).values({ id: editorialId, userId, name: "Test Redaktion", contactName: "Testkontakt", loginEmail: `${userId}@example.com`, status, currentPriceCents: priceCents, collabEnabled, flatrateActive, flatratePriceCents, flatrateAssetLimit, }); await database.insert(albumGrants).values({ editorialAccountId: editorialId, immichAlbumId: grantedAlbumId, revokedAt: revoked ? new Date("2026-08-08T00:00:00.000Z") : null, }); return editorialId; } function newInput(editorialId: string, idempotencyKey = randomUUID()) { return { editorialId, assetId, albumId, purpose: "Titelgeschichte", reference: "Ausgabe 8/26", idempotencyKey, }; } async function insertWinner( client: PoolClient, input: ReturnType, fingerprint: string, kind: "new_usage" | "repeat_download" = "new_usage", ) { const usageId = randomUUID(); const eventId = randomUUID(); const authorizedAt = new Date("2026-08-09T10:00:00.000Z"); await client.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, 'winner.jpg', $4, 'Presse 2026', $5, $6, 1500, 'open', $7)`, [ usageId, input.editorialId, input.assetId, input.albumId, input.purpose, input.reference, authorizedAt, ], ); await client.query( `insert into download_events ( id, editorial_account_id, usage_id, immich_asset_id, authorized_at, status, request_id, idempotency_key, intent_kind, request_fingerprint ) values ($1, $2, $3, $4, $5, 'authorized', $6, $7, $8, $9)`, [ eventId, input.editorialId, usageId, input.assetId, authorizedAt, randomUUID(), input.idempotencyKey, kind, fingerprint, ], ); return { eventId, usageId, authorizedAt }; } test("atomically snapshots price and metadata, authorizes one event, and audits no secrets", async () => { const editorialId = await seedEditorial(); const { usageService } = createServices(); const input = newInput(editorialId); const intent = await usageService.createNewUsage(input); const [usage] = await database.select().from(usages).where(eq(usages.id, intent.usageId)); const [event] = await database.select().from(downloadEvents).where(eq(downloadEvents.id, intent.id)); const [audit] = await database .select() .from(auditEvents) .where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, intent.usageId))); expect(usage).toMatchObject({ editorialAccountId: editorialId, immichAssetId: assetId, filenameSnapshot: "jubel.jpg", immichAlbumIdSnapshot: albumId, albumNameSnapshot: "Presse 2026", purpose: "Titelgeschichte", internalReference: "Ausgabe 8/26", priceCents: 1_500, billingStatus: "open", }); expect(event).toMatchObject({ editorialAccountId: editorialId, usageId: intent.usageId, status: "authorized", intentKind: "new_usage", }); expect(audit).toMatchObject({ actorType: "editorial", entityType: "usage" }); expect(JSON.stringify(audit)).not.toContain(input.idempotencyKey); expect(JSON.stringify(audit)).not.toContain("test-immich-key"); }); test.each([ ["zero price", "active", 0, false, "INVALID_PRICE"], ["missing price", "active", null, false, "INVALID_PRICE"], ["suspended account", "suspended", 1_500, false, "EDITORIAL_NOT_ACTIVE"], ["revoked grant", "active", 1_500, true, "ALBUM_NOT_GRANTED"], ] as const)("rejects %s transactionally without accounting rows", async (_label, status, priceCents, revoked, code) => { const editorialId = await seedEditorial({ status, priceCents, revoked }); const { usageService } = createServices(); await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({ code }); const [usageCount] = await database .select({ value: count() }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)); const [eventCount] = await database .select({ value: count() }) .from(downloadEvents) .where(eq(downloadEvents.editorialAccountId, editorialId)); expect({ usages: usageCount.value, events: eventCount.value }).toEqual({ usages: 0, events: 0 }); }); test("requires an active grant for the exact requested album", async () => { const editorialId = await seedEditorial({ albumId: otherAlbumId }); const { usageService } = createServices(); await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED", }); }); test("rechecks exact album membership after database locks before inserting", async () => { const editorialId = await seedEditorial(); const { usageService, immich } = createServices(); immich.searchPhotos .mockResolvedValueOnce({ items: [{ id: assetId }], total: 1, nextPage: null, previousPage: null }) .mockResolvedValueOnce({ items: [], total: 0, nextPage: null, previousPage: null }); await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({ code: "ASSET_NOT_IN_ALBUM", }); const [usageCount] = await database .select({ value: count() }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)); expect(immich.getAlbum).toHaveBeenCalledTimes(1); expect(usageCount.value).toBe(0); }); test("rejects an otherwise equivalent winner when the editorial is suspended while waiting", async () => { const editorialId = await seedEditorial(); const input = newInput(editorialId); const immich = createServices().immich; const realRepository = createUsageServiceRepository(database); let releaseFastMiss!: () => void; const fastMiss = new Promise((resolve) => { releaseFastMiss = resolve; }); const usageService = createUsageService({ repository: { ...realRepository, async findIntent(requestEditorialId, key) { const intent = await realRepository.findIntent(requestEditorialId, key); releaseFastMiss(); return intent; }, }, immich, }); const locker = await testDb.pool.connect(); await locker.query("begin"); await locker.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [editorialId]); try { const pending = usageService.createNewUsage(input); await fastMiss; await insertWinner( locker, input, requestFingerprint({ kind: "new_usage", editorialId, assetId, albumId, purpose: input.purpose, reference: input.reference, }), ); await locker.query("update editorial_accounts set status = 'suspended' where id = $1", [ editorialId, ]); await locker.query("commit"); await expect(pending).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" }); expect(immich.getAlbum).toHaveBeenCalledTimes(1); expect(immich.getAsset).toHaveBeenCalledTimes(1); } finally { await locker.query("rollback"); locker.release(); } }); test("reports a conflicting winner committed while waiting before later state errors", async () => { const editorialId = await seedEditorial(); const input = newInput(editorialId); const { immich } = createServices(); const realRepository = createUsageServiceRepository(database); let releaseFastMiss!: () => void; const fastMiss = new Promise((resolve) => { releaseFastMiss = resolve; }); const usageService = createUsageService({ repository: { ...realRepository, async findIntent(requestEditorialId, key) { const intent = await realRepository.findIntent(requestEditorialId, key); releaseFastMiss(); return intent; }, }, immich, }); const locker = await testDb.pool.connect(); await locker.query("begin"); await locker.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [editorialId]); try { const pending = usageService.createNewUsage(input); await fastMiss; await insertWinner(locker, input, "0".repeat(64)); await locker.query("update editorial_accounts set status = 'suspended' where id = $1", [ editorialId, ]); await locker.query("commit"); await expect(pending).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); expect(immich.getAlbum).toHaveBeenCalledTimes(1); expect(immich.getAsset).toHaveBeenCalledTimes(1); } finally { await locker.query("rollback"); locker.release(); } }); test("same-key concurrency across database clients creates exactly one usage, event, and audit", async () => { const editorialId = await seedEditorial(); const { usageService } = createServices(); const input = newInput(editorialId); const [first, second] = await Promise.all([ usageService.createNewUsage(input), usageService.createNewUsage(input), ]); expect(second).toEqual(first); const [usageCount] = await database .select({ value: count() }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)); const [eventCount] = await database .select({ value: count() }) .from(downloadEvents) .where(eq(downloadEvents.editorialAccountId, editorialId)); const [auditCount] = await database .select({ value: count() }) .from(auditEvents) .where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, first.usageId))); expect({ usages: usageCount.value, events: eventCount.value, audits: auditCount.value }).toEqual({ usages: 1, events: 1, audits: 1, }); }); test("the same key may be reused by a different editorial but not for a different payload", async () => { const firstEditorialId = await seedEditorial(); const secondEditorialId = await seedEditorial(); const { usageService } = createServices(); const key = randomUUID(); await usageService.createNewUsage(newInput(firstEditorialId, key)); await expect( usageService.createNewUsage({ ...newInput(firstEditorialId, key), purpose: "Online-Aufmacher" }), ).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); await expect(usageService.createNewUsage(newInput(secondEditorialId, key))).resolves.toMatchObject({ billable: true, }); }); function errorChainIncludes(expected: string) { return (error: unknown): boolean => { let current = error; while (current instanceof Error) { if (current.message.includes(expected)) return true; const cause: unknown = current.cause; if (!cause) break; current = cause; } return false; }; } test("an audit failure rolls back both the usage and authorized event", async () => { const editorialId = await seedEditorial(); const { usageService } = createServices(); await testDb.pool.query(` create function reject_billable_usage_audit() returns trigger language plpgsql as $$ begin if new.event_type = 'billable_usage_created' then raise exception 'audit rejected'; end if; return new; end $$ `); await testDb.pool.query(` create trigger reject_billable_usage_audit before insert on audit_events for each row execute function reject_billable_usage_audit() `); try { await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toSatisfy( errorChainIncludes("audit rejected"), ); } finally { await testDb.pool.query("drop trigger reject_billable_usage_audit on audit_events"); await testDb.pool.query("drop function reject_billable_usage_audit()"); } const [usageCount] = await database .select({ value: count() }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)); const [eventCount] = await database .select({ value: count() }) .from(downloadEvents) .where(eq(downloadEvents.editorialAccountId, editorialId)); expect({ usages: usageCount.value, events: eventCount.value }).toEqual({ usages: 0, events: 0 }); }); test("a repeat remains free after a price change and creates no additional usage", async () => { const editorialId = await seedEditorial(); const { usageService, downloadService } = createServices(); const first = await usageService.createNewUsage(newInput(editorialId)); await markDelivered(first.id); await database .update(editorialAccounts) .set({ currentPriceCents: 2_100 }) .where(eq(editorialAccounts.id, editorialId)); const repeat = await downloadService.createRepeatDownload({ editorialId, usageId: first.usageId, note: "Web-Ausgabe", idempotencyKey: randomUUID(), }); expect(repeat).toMatchObject({ usageId: first.usageId, priceCents: 0, billable: false }); const [usageCount] = await database .select({ value: count() }) .from(usages) .where(eq(usages.editorialAccountId, editorialId)); expect(usageCount.value).toBe(1); }); test("same-key repeat concurrency creates one free event", async () => { const editorialId = await seedEditorial(); const { usageService, downloadService } = createServices(); const first = await usageService.createNewUsage(newInput(editorialId)); await markDelivered(first.id); const repeatInput = { editorialId, usageId: first.usageId, note: "Web-Ausgabe", idempotencyKey: randomUUID(), }; const [repeatOne, repeatTwo] = await Promise.all([ downloadService.createRepeatDownload(repeatInput), downloadService.createRepeatDownload(repeatInput), ]); expect(repeatTwo).toEqual(repeatOne); const [eventCount] = await database .select({ value: count() }) .from(downloadEvents) .where(and(eq(downloadEvents.usageId, first.usageId), eq(downloadEvents.intentKind, "repeat_download"))); expect(eventCount.value).toBe(1); }); test("rechecks suspension after an idempotent repeat winner commits", async () => { const editorialId = await seedEditorial(); const { usageService } = createServices(); const first = await usageService.createNewUsage(newInput(editorialId)); const input = { editorialId, usageId: first.usageId, note: "Web-Ausgabe", idempotencyKey: randomUUID(), }; const downloadService = createDownloadService({ repository: createRepeatDownloadRepository(database, async () => undefined), }); const eventId = randomUUID(); const authorizedAt = new Date("2026-08-09T11:00:00.000Z"); const locker = await testDb.pool.connect(); await locker.query("begin"); await locker.query("select pg_advisory_xact_lock(hashtextextended($1, 0))", [editorialId]); try { const pending = downloadService.createRepeatDownload(input); await locker.query( `insert into download_events ( id, editorial_account_id, usage_id, immich_asset_id, authorized_at, status, repeat_download_note, request_id, idempotency_key, intent_kind, request_fingerprint ) values ($1, $2, $3, $4, $5, 'authorized', $6, $7, $8, 'repeat_download', $9)`, [ eventId, editorialId, first.usageId, assetId, authorizedAt, input.note, randomUUID(), input.idempotencyKey, requestFingerprint({ kind: "repeat_download", editorialId, usageId: first.usageId, note: input.note, }), ], ); await locker.query("update editorial_accounts set status = 'suspended' where id = $1", [ editorialId, ]); await locker.query("commit"); await expect(pending).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" }); } finally { await locker.query("rollback"); locker.release(); } }); test("a suspended owner cannot create a repeat event", async () => { const editorialId = await seedEditorial(); const { usageService, downloadService } = createServices(); const first = await usageService.createNewUsage(newInput(editorialId)); await database .update(editorialAccounts) .set({ status: "suspended" }) .where(eq(editorialAccounts.id, editorialId)); await expect( downloadService.createRepeatDownload({ editorialId, usageId: first.usageId, idempotencyKey: randomUUID(), }), ).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" }); }); test("repeat ownership is scoped to the active editorial", async () => { const ownerId = await seedEditorial(); const otherEditorialId = await seedEditorial(); const { usageService, downloadService } = createServices(); const first = await usageService.createNewUsage(newInput(ownerId)); await expect( downloadService.createRepeatDownload({ editorialId: otherEditorialId, usageId: first.usageId, idempotencyKey: randomUUID(), }), ).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" }); }); test("collab usages are free and flagged when the editorial is enabled", async () => { const editorialId = await seedEditorial({ collabEnabled: true }); const { usageService } = createServices(); const intent = await usageService.createNewUsage({ ...newInput(editorialId), collab: true }); expect(intent.priceCents).toBe(0); const [usage] = await database .select({ collab: usages.collab, priceCents: usages.priceCents }) .from(usages) .where(eq(usages.id, intent.usageId)); expect(usage).toEqual({ collab: true, priceCents: 0 }); const [audit] = await database .select({ newValues: auditEvents.newValues }) .from(auditEvents) .where(and(eq(auditEvents.entityId, intent.usageId), eq(auditEvents.eventType, "billable_usage_created"))); expect(audit.newValues).toMatchObject({ collab: true, priceCents: 0 }); }); test("collab usages are rejected when the editorial is not enabled", async () => { const editorialId = await seedEditorial({ collabEnabled: false }); const { usageService } = createServices(); await expect( usageService.createNewUsage({ ...newInput(editorialId), collab: true }), ).rejects.toMatchObject({ code: "COLLAB_NOT_ENABLED" }); }); test("collab usages do not consume the flatrate asset limit", async () => { const editorialId = await seedEditorial({ collabEnabled: true, flatrateActive: true, flatratePriceCents: 500, flatrateAssetLimit: 1, }); const { usageService } = createServices(); const collabIntent = await usageService.createNewUsage({ ...newInput(editorialId), collab: true }); expect(collabIntent.priceCents).toBe(0); // The single flatrate slot is still free after the collab usage. const flatrateIntent = await usageService.createNewUsage(newInput(editorialId)); expect(flatrateIntent.priceCents).toBe(0); // Limit exhausted: the next regular usage costs the individual price. const paidIntent = await usageService.createNewUsage(newInput(editorialId)); expect(paidIntent.priceCents).toBe(1_500); }); async function markDelivered(downloadId: string): Promise { const deliveredAt = new Date(); await database .update(downloadEvents) .set({ status: "completed", startedAt: deliveredAt, completedAt: deliveredAt, transferredBytes: 1, }) .where(eq(downloadEvents.id, downloadId)); } test("revocation blocks an idempotent new intent and an eligible repeat while retaining the usage", async () => { const editorialId = await seedEditorial(); const { usageService, downloadService } = createServices(); const input = newInput(editorialId); const intent = await usageService.createNewUsage(input); await database.update(downloadEvents).set({ status: "completed", transferredBytes: 8 }) .where(eq(downloadEvents.id, intent.id)); const repeatInput = { editorialId, usageId: intent.usageId, idempotencyKey: randomUUID() }; await expect(downloadService.createRepeatDownload(repeatInput)).resolves.toMatchObject({ priceCents: 0 }); await database.update(albumGrants).set({ revokedAt: new Date() }) .where(eq(albumGrants.editorialAccountId, editorialId)); await expect(usageService.createNewUsage(input)).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" }); await expect(downloadService.createRepeatDownload(repeatInput)).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED" }); await expect(usageService.listPriorUsages(editorialId, assetId)).resolves.toEqual([ expect.objectContaining({ id: intent.usageId, purpose: input.purpose }), ]); }); test("calculates ZIP pricing server-side and refuses a price above the confirmed cap", async () => { const editorialId = await seedEditorial({ priceCents: 1500 }); const { usageService } = createServices(); const input = newInput(editorialId); await expect(usageService.createNewUsage({ ...input, maxPriceCents: 1499 })) .rejects.toMatchObject({ code: "INVALID_PRICE" }); await database.update(editorialAccounts).set({ flatrateActive: true, flatratePriceCents: 10000, flatrateAssetLimit: 1, }).where(eq(editorialAccounts.id, editorialId)); await expect(usageService.createNewUsage({ ...input, maxPriceCents: 1499 })) .resolves.toMatchObject({ priceCents: 0 }); await expect(usageService.createNewUsage({ ...newInput(editorialId), maxPriceCents: 1500 })) .resolves.toMatchObject({ priceCents: 1500 }); });