import { randomUUID } from "node:crypto"; import { and, count, eq } from "drizzle-orm"; 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 { startPostgres } from "./postgres"; const testDb = await startPostgres(); const database = testDb.database; afterAll(() => testDb.stop()); const asset = { id: "asset-1", type: "IMAGE" as const, originalFileName: "jubel.jpg", originalMimeType: "image/jpeg", localDateTime: null, fileCreatedAt: null, albums: [{ id: "album-1" }], }; function createServices() { const immich = { listAlbumsForAsset: vi.fn().mockResolvedValue([ { id: "album-1", albumName: "Presse 2026", description: null, albumThumbnailAssetId: "asset-1", assetCount: 1, }, ]), getAsset: vi.fn().mockResolvedValue(asset), }; return { usageService: createUsageService({ repository: createUsageServiceRepository(database), immich, }), downloadService: createDownloadService({ repository: createRepeatDownloadRepository(database), }), immich, }; } async function seedEditorial({ status = "active", priceCents = 1_500, albumId = "album-1", revoked = false, }: { status?: "active" | "suspended" | "pending_approval"; priceCents?: number | null; albumId?: string; revoked?: boolean; } = {}) { 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, }); await database.insert(albumGrants).values({ editorialAccountId: editorialId, immichAlbumId: albumId, revokedAt: revoked ? new Date("2026-08-08T00:00:00.000Z") : null, }); return editorialId; } function newInput(editorialId: string, idempotencyKey = randomUUID()) { return { editorialId, assetId: "asset-1", albumId: "album-1", purpose: "Titelgeschichte", reference: "Ausgabe 8/26", idempotencyKey, }; } 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: "asset-1", filenameSnapshot: "jubel.jpg", immichAlbumIdSnapshot: "album-1", 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: "album-2" }); const { usageService } = createServices(); await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({ code: "ALBUM_NOT_GRANTED", }); }); 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, }); }); 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.toThrow("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 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)); 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("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" }); });