import { expect, test, vi } from "vitest"; import { createUsageService, type BillableIntentInput, type PersistedDownloadIntent, type UsageRepository, } from "./service"; import { UsageAccountingError, type PriorUsage } from "./types"; const editorialId = "11111111-1111-4111-8111-111111111111"; const idempotencyKey = "22222222-2222-4222-8222-222222222222"; const newUsageInput = { editorialId, assetId: "asset-1", albumId: "album-1", purpose: "Titelgeschichte", reference: "Ausgabe 8/26", idempotencyKey, }; function createRepository() { const intents = new Map(); const usages: BillableIntentInput[] = []; const priorUsages: PriorUsage[] = []; let priceCents: number | null = 1_500; let status = "active"; const repository: UsageRepository = { async findIntent(requestEditorialId, key) { return intents.get(`${requestEditorialId}:${key}`) ?? null; }, async createBillableIntent(input) { if (status !== "active") { throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); } if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) { throw new UsageAccountingError("INVALID_PRICE"); } const key = `${input.editorialId}:${input.idempotencyKey}`; const existing = intents.get(key); if (existing) return existing; usages.push(input); const intent: PersistedDownloadIntent = { id: `download-${intents.size + 1}`, usageId: `usage-${usages.length}`, assetId: input.assetId, priceCents: priceCents!, billable: true, status: "authorized", authorizedAt: new Date("2026-08-09T08:00:00.000Z"), requestFingerprint: input.requestFingerprint, kind: "new_usage", }; intents.set(key, intent); return intent; }, async listPriorUsages() { return priorUsages; }, }; return { repository, intents, usages, priorUsages, setPrice(value: number | null) { priceCents = value; }, setStatus(value: string) { status = value; }, }; } function createService() { const state = createRepository(); const immich = { listAlbumsForAsset: vi.fn().mockResolvedValue([ { id: "album-1", albumName: "Presse 2026", description: null, albumThumbnailAssetId: "asset-1", assetCount: 1, }, ]), getAsset: vi.fn().mockResolvedValue({ id: "asset-1", type: "IMAGE" as const, originalFileName: "jubel.jpg", originalMimeType: "image/jpeg", localDateTime: null, fileCreatedAt: null, albums: [{ id: "album-1" }], }), }; return { ...state, immich, service: createUsageService({ repository: state.repository, immich }) }; } test("snapshots the current editorial price and normalized Immich metadata", async () => { const { service, usages } = createService(); const intent = await service.createNewUsage({ ...newUsageInput, purpose: " Titelgeschichte ", reference: " Ausgabe 8/26 ", }); expect(intent).toMatchObject({ priceCents: 1_500, billable: true, status: "authorized" }); expect(usages).toEqual([ expect.objectContaining({ assetId: "asset-1", albumId: "album-1", albumName: "Presse 2026", filename: "jubel.jpg", purpose: "Titelgeschichte", reference: "Ausgabe 8/26", }), ]); }); test("returns the exact persisted intent for an equivalent idempotent retry", async () => { const { service, usages, immich } = createService(); const first = await service.createNewUsage(newUsageInput); const second = await service.createNewUsage(newUsageInput); expect(second).toEqual(first); expect(usages).toHaveLength(1); expect(immich.getAsset).toHaveBeenCalledTimes(1); }); test("keeps the original snapshot after a price change while a new key uses the new price", async () => { const { service, setPrice } = createService(); const original = await service.createNewUsage(newUsageInput); setPrice(2_100); await expect(service.createNewUsage(newUsageInput)).resolves.toEqual(original); await expect( service.createNewUsage({ ...newUsageInput, idempotencyKey: "33333333-3333-4333-8333-333333333333", }), ).resolves.toMatchObject({ priceCents: 2_100 }); }); test.each([ ["zero", 0], ["missing", null], ] as const)("rejects a %s current price", async (_label, price) => { const { service, setPrice } = createService(); setPrice(price); await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ code: "INVALID_PRICE", }); }); test.each(["suspended", "pending_approval"])("rejects a %s editorial account", async (status) => { const { service, setStatus } = createService(); setStatus(status); await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE", }); }); test.each([ ["ab", "INVALID_INPUT"], ["x".repeat(201), "INVALID_INPUT"], ["Titelgeschichte", "INVALID_INPUT", "x".repeat(201)], ["Titelgeschichte", "INVALID_INPUT", undefined, "not-a-uuid"], ] as const)( "rejects malformed purpose, reference, or idempotency input before side effects", async (purpose: string, code: string, reference?: string, key?: string) => { const { service, repository, immich } = createService(); const findIntent = vi.spyOn(repository, "findIntent"); await expect( service.createNewUsage({ ...newUsageInput, purpose, reference: reference ?? "Ausgabe 8/26", idempotencyKey: key ?? idempotencyKey, }), ).rejects.toMatchObject({ code }); expect(findIntent).not.toHaveBeenCalled(); expect(immich.listAlbumsForAsset).not.toHaveBeenCalled(); expect(immich.getAsset).not.toHaveBeenCalled(); }, ); test("rejects an asset outside the exact requested album", async () => { const { service, immich, usages } = createService(); immich.listAlbumsForAsset.mockResolvedValue([ { id: "album-2", albumName: "Andere Bilder", description: null, albumThumbnailAssetId: null, assetCount: 1, }, ]); await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ code: "ASSET_NOT_IN_ALBUM", }); expect(immich.getAsset).not.toHaveBeenCalled(); expect(usages).toHaveLength(0); }); test("rejects a missing asset immediately before accounting", async () => { const { service, immich, usages } = createService(); immich.getAsset.mockRejectedValue({ code: "IMMICH_NOT_FOUND" }); await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ code: "ASSET_NOT_FOUND", }); expect(usages).toHaveLength(0); }); test("rejects a non-image asset immediately before accounting", async () => { const { service, immich, usages } = createService(); immich.getAsset.mockResolvedValue({ id: "asset-1", type: "VIDEO", originalFileName: "clip.mp4", originalMimeType: "video/mp4", localDateTime: null, fileCreatedAt: null, albums: [{ id: "album-1" }], }); await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ code: "ASSET_NOT_IMAGE", }); expect(usages).toHaveLength(0); }); test("rejects reuse of an idempotency key for a materially different new usage", async () => { const { service, usages, immich } = createService(); await service.createNewUsage(newUsageInput); await expect( service.createNewUsage({ ...newUsageInput, purpose: "Online-Aufmacher" }), ).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); expect(usages).toHaveLength(1); expect(immich.getAsset).toHaveBeenCalledTimes(1); }); test("lists only the repository's prior usages for the requested editorial asset", async () => { const { service, priorUsages } = createService(); priorUsages.push({ id: "usage-1", assetId: "asset-1", filename: "jubel.jpg", albumId: "album-1", albumName: "Presse 2026", purpose: "Titelgeschichte", reference: undefined, priceCents: 1_500, billingStatus: "open", createdAt: new Date("2026-08-09T08:00:00.000Z"), }); await expect(service.listPriorUsages(editorialId, "asset-1")).resolves.toEqual(priorUsages); });