{formatDateTime(usage.createdAt)}
+{formatBerlinDateTime(usage.createdAt)}
{usage.filename}
-
@@ -51,6 +48,14 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
- Verwendungszweck
- {usage.purpose} +
- Nutzungspreis +
- {priceFormatter.format(usage.priceCents / 100)} +
- Abrechnungsstatus +
- {billingStatusLabel(usage.billingStatus)} +
- Interne Referenz @@ -59,7 +64,9 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor ) : null} {usage.attempts.length === 0 ? ( -
-
-
+
{statusLabel(attempt.status)}
{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"}
{byteFormatter.format(attempt.transferredBytes)}
@@ -95,12 +105,36 @@ function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>)
return (
+ );
+}
+
+function AttemptPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
+ if (!history.attemptCursor && !history.nextAttemptCursor) return null;
+ return (
+
);
@@ -115,6 +149,12 @@ function statusLabel(status: UsageHistoryAttempt["status"]): string {
return labels[status];
}
-function formatDateTime(value: Date): string {
- return dateTimeFormatter.format(value);
+function billingStatusLabel(status: UsageHistoryPage["items"][number]["billingStatus"]): string {
+ const labels: Record
= { + open: "Offen", + billed: "Abgerechnet", + reopened: "Wieder geöffnet", + voided: "Storniert", + }; + return labels[status]; } diff --git a/src/components/download/usage-dialog.tsx b/src/components/download/usage-dialog.tsx index 8346b5d..971be2a 100644 --- a/src/components/download/usage-dialog.tsx +++ b/src/components/download/usage-dialog.tsx @@ -2,6 +2,7 @@ import { useRef, useState, type FormEvent } from "react"; +import { formatBerlinDate } from "@/modules/downloads/format"; import type { DownloadDialogUsage } from "@/modules/downloads/stream"; type UsageDialogProps = Readonly<{ @@ -23,9 +24,6 @@ const priceFormatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR", }); -const dateFormatter = new Intl.DateTimeFormat("de-DE", { - dateStyle: "medium", -}); export function UsageDialog({ albumId, @@ -216,7 +214,7 @@ export function UsageDialog({ function formatDate(value: string): string { const date = new Date(value); - return Number.isNaN(date.valueOf()) ? "Datum unbekannt" : dateFormatter.format(date); + return Number.isNaN(date.valueOf()) ? "Datum unbekannt" : formatBerlinDate(date); } function isLocalDownloadUrl(fileUrl: string, downloadId: string): boolean { diff --git a/src/modules/downloads/eligibility.test.ts b/src/modules/downloads/eligibility.test.ts new file mode 100644 index 0000000..4ba9d5c --- /dev/null +++ b/src/modules/downloads/eligibility.test.ts @@ -0,0 +1,17 @@ +import { expect, test } from "vitest"; + +import { isFreeRepeatEligible } from "./eligibility"; + +test.each([ + ["open", true, true], + ["billed", true, true], + ["reopened", true, true], + ["voided", true, false], + ["open", false, false], + ["billed", false, false], +] as const)( + "repeat eligibility for billing status %s and deliveredOriginal=%s is %s", + (billingStatus, deliveredOriginal, expected) => { + expect(isFreeRepeatEligible(billingStatus, deliveredOriginal)).toBe(expected); + }, +); diff --git a/src/modules/downloads/eligibility.ts b/src/modules/downloads/eligibility.ts new file mode 100644 index 0000000..00a2321 --- /dev/null +++ b/src/modules/downloads/eligibility.ts @@ -0,0 +1,37 @@ +import "server-only"; + +import { and, eq, gt, inArray } from "drizzle-orm"; +import type { NodePgDatabase } from "drizzle-orm/node-postgres"; + +import { downloadEvents } from "@/db/schema"; +import type * as schema from "@/db/schema"; + +type UsageBillingStatus = "open" | "billed" | "reopened" | "voided"; + +export function isFreeRepeatEligible( + billingStatus: UsageBillingStatus, + deliveredOriginal: boolean, +): boolean { + return billingStatus !== "voided" && deliveredOriginal; +} + +export async function hasDeliveredOriginal( + database: NodePgDatabase , + editorialId: string, + usageId: string, +): Promise { + const [delivery] = await database + .select({ id: downloadEvents.id }) + .from(downloadEvents) + .where( + and( + eq(downloadEvents.editorialAccountId, editorialId), + eq(downloadEvents.usageId, usageId), + eq(downloadEvents.intentKind, "new_usage"), + inArray(downloadEvents.status, ["completed", "interrupted"]), + gt(downloadEvents.transferredBytes, 0), + ), + ) + .limit(1); + return Boolean(delivery); +} diff --git a/src/modules/downloads/format.test.ts b/src/modules/downloads/format.test.ts new file mode 100644 index 0000000..c55a7cb --- /dev/null +++ b/src/modules/downloads/format.test.ts @@ -0,0 +1,18 @@ +import { afterEach, expect, test, vi } from "vitest"; + +const originalTimeZone = process.env.TZ; + +afterEach(() => { + process.env.TZ = originalTimeZone; + vi.resetModules(); +}); + +test("formats dialog and history dates explicitly in Europe/Berlin", async () => { + process.env.TZ = "America/Los_Angeles"; + vi.resetModules(); + const { formatBerlinDate, formatBerlinDateTime } = await import("./format"); + const afterBerlinMidnight = new Date("2026-08-09T22:30:00.000Z"); + + expect(formatBerlinDate(afterBerlinMidnight)).toBe("10.08.2026"); + expect(formatBerlinDateTime(afterBerlinMidnight)).toBe("10.08.2026, 00:30"); +}); diff --git a/src/modules/downloads/format.ts b/src/modules/downloads/format.ts new file mode 100644 index 0000000..8d8092a --- /dev/null +++ b/src/modules/downloads/format.ts @@ -0,0 +1,18 @@ +const berlinDateFormatter = new Intl.DateTimeFormat("de-DE", { + dateStyle: "medium", + timeZone: "Europe/Berlin", +}); + +const berlinDateTimeFormatter = new Intl.DateTimeFormat("de-DE", { + dateStyle: "medium", + timeStyle: "short", + timeZone: "Europe/Berlin", +}); + +export function formatBerlinDate(value: Date): string { + return berlinDateFormatter.format(value); +} + +export function formatBerlinDateTime(value: Date): string { + return berlinDateTimeFormatter.format(value); +} diff --git a/src/modules/downloads/service.ts b/src/modules/downloads/service.ts index a6f356d..883f506 100644 --- a/src/modules/downloads/service.ts +++ b/src/modules/downloads/service.ts @@ -2,7 +2,7 @@ import "server-only"; import { randomUUID } from "node:crypto"; -import { and, eq, inArray } from "drizzle-orm"; +import { and, eq } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { db } from "@/db/client"; @@ -23,6 +23,8 @@ import { type PersistedDownloadIntent, } from "@/modules/usages/service"; +import { hasDeliveredOriginal, isFreeRepeatEligible } from "./eligibility"; + export type PersistedRepeatIntent = PersistedDownloadIntent & { kind: "repeat_download" }; export type RepeatIntentInput = { @@ -76,7 +78,13 @@ export function createRepeatDownloadRepository( input.editorialId, input.idempotencyKey, ); - if (existing) return asRepeatIntent(existing); + if ( + existing && + (existing.kind !== "repeat_download" || + existing.requestFingerprint !== input.requestFingerprint) + ) { + throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); + } const [editorial] = await transaction .select({ id: editorialAccounts.id, status: editorialAccounts.status }) @@ -89,18 +97,30 @@ export function createRepeatDownloadRepository( } const [usage] = await transaction - .select({ id: usages.id, assetId: usages.immichAssetId }) + .select({ + id: usages.id, + assetId: usages.immichAssetId, + billingStatus: usages.billingStatus, + }) .from(usages) .where( and( eq(usages.id, input.usageId), eq(usages.editorialAccountId, input.editorialId), - inArray(usages.billingStatus, ["open", "billed", "reopened"]), ), ) .for("update") .limit(1); if (!usage) throw new UsageAccountingError("USAGE_NOT_FOUND"); + const deliveredOriginal = await hasDeliveredOriginal( + transaction, + input.editorialId, + usage.id, + ); + if (!isFreeRepeatEligible(usage.billingStatus, deliveredOriginal)) { + throw new UsageAccountingError("USAGE_NOT_FOUND"); + } + if (existing) return asRepeatIntent(existing); const authorizedAt = new Date(); const [event] = await transaction diff --git a/src/modules/downloads/stream.test.ts b/src/modules/downloads/stream.test.ts index 31958e4..1f6df72 100644 --- a/src/modules/downloads/stream.test.ts +++ b/src/modules/downloads/stream.test.ts @@ -197,6 +197,7 @@ test("normalizes and bounds history pagination before the scoped repository quer page: HISTORY_MAX_PAGE, pageSize: 20, hasNext: false, + attemptPageSize: 25, }), }; const history = createDownloadHistoryService({ repository }); @@ -204,11 +205,16 @@ test("normalizes and bounds history pagination before the scoped repository quer await history.listEditorialUsageHistory( "11111111-1111-4111-8111-111111111111", "999999999999999999999999", + "1786314600000000.22222222-2222-4222-8222-222222222222", ); expect(repository.listEditorialUsageHistory).toHaveBeenCalledWith( "11111111-1111-4111-8111-111111111111", HISTORY_MAX_PAGE, + { + authorizedAtMicros: "1786314600000000", + downloadId: "22222222-2222-4222-8222-222222222222", + }, ); }); diff --git a/src/modules/downloads/stream.ts b/src/modules/downloads/stream.ts index 11e92ea..960065a 100644 --- a/src/modules/downloads/stream.ts +++ b/src/modules/downloads/stream.ts @@ -1,6 +1,6 @@ import "server-only"; -import { and, desc, eq, inArray } from "drizzle-orm"; +import { and, desc, eq, inArray, sql } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { db } from "@/db/client"; @@ -8,8 +8,11 @@ import { auditEvents, downloadEvents, editorialAccounts, usages } from "@/db/sch import type * as schema from "@/db/schema"; import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types"; +import { hasDeliveredOriginal, isFreeRepeatEligible } from "./eligibility"; + export const HISTORY_PAGE_SIZE = 20; export const HISTORY_MAX_PAGE = 1_000; +export const HISTORY_ATTEMPT_PAGE_SIZE = 25; export type ClaimedDownload = { id: string; @@ -127,57 +130,80 @@ export function createDownloadDeliveryRepository( return { async claimAuthorized(editorialId, downloadId) { return database.transaction(async (transaction) => { + const [candidate] = await transaction + .select({ + id: downloadEvents.id, + usageId: downloadEvents.usageId, + assetId: downloadEvents.immichAssetId, + intentKind: downloadEvents.intentKind, + status: downloadEvents.status, + }) + .from(downloadEvents) + .where( + and( + eq(downloadEvents.id, downloadId), + eq(downloadEvents.editorialAccountId, editorialId), + ), + ) + .limit(1); + if (!candidate) return { outcome: "not_found" } as const; + if (candidate.status !== "authorized") { + return { outcome: "not_authorized" } as const; + } + + const [usage] = await transaction + .select({ + filename: usages.filenameSnapshot, + billingStatus: usages.billingStatus, + }) + .from(usages) + .where( + and( + eq(usages.id, candidate.usageId), + eq(usages.editorialAccountId, editorialId), + ), + ) + .for("update") + .limit(1); + if (!usage) return { outcome: "not_found" } as const; + + const intentKind = claimedIntentKind(candidate.intentKind); + const deliveredOriginal = + intentKind === "repeat_download" + ? await hasDeliveredOriginal(transaction, editorialId, candidate.usageId) + : false; + const eligible = + intentKind === "repeat_download" + ? isFreeRepeatEligible(usage.billingStatus, deliveredOriginal) + : usage.billingStatus !== "voided"; + if (!eligible) { + if (intentKind === "repeat_download") { + await invalidateAuthorizedRepeat(transaction, candidate.id, new Date()); + } + return { outcome: "not_authorized" } as const; + } + const [claimed] = await transaction .update(downloadEvents) .set({ status: "streaming", startedAt: new Date() }) .where( and( - eq(downloadEvents.id, downloadId), + eq(downloadEvents.id, candidate.id), eq(downloadEvents.editorialAccountId, editorialId), eq(downloadEvents.status, "authorized"), ), ) - .returning({ - id: downloadEvents.id, - usageId: downloadEvents.usageId, - assetId: downloadEvents.immichAssetId, - intentKind: downloadEvents.intentKind, - }); - - if (!claimed) { - const [owned] = await transaction - .select({ id: downloadEvents.id }) - .from(downloadEvents) - .where( - and( - eq(downloadEvents.id, downloadId), - eq(downloadEvents.editorialAccountId, editorialId), - ), - ) - .limit(1); - return owned - ? ({ outcome: "not_authorized" } as const) - : ({ outcome: "not_found" } as const); - } - - const [usage] = await transaction - .select({ filename: usages.filenameSnapshot }) - .from(usages) - .where( - and( - eq(usages.id, claimed.usageId), - eq(usages.editorialAccountId, editorialId), - ), - ) - .limit(1); - if (!usage) return { outcome: "not_found" } as const; + .returning({ id: downloadEvents.id }); + if (!claimed) return { outcome: "not_authorized" } as const; return { outcome: "claimed", download: { - ...claimed, + id: candidate.id, + usageId: candidate.usageId, + assetId: candidate.assetId, filename: usage.filename, - intentKind: claimedIntentKind(claimed.intentKind), + intentKind, }, } as const; }); @@ -186,6 +212,33 @@ export function createDownloadDeliveryRepository( async failBeforeDelivery(downloadId, options) { return database.transaction(async (transaction) => { const terminalAt = new Date(); + const [candidate] = await transaction + .select({ + usageId: downloadEvents.usageId, + editorialId: downloadEvents.editorialAccountId, + intentKind: downloadEvents.intentKind, + requestId: downloadEvents.requestId, + }) + .from(downloadEvents) + .where( + and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming")), + ) + .limit(1); + if (!candidate) return false; + + const [usage] = await transaction + .select({ billingStatus: usages.billingStatus }) + .from(usages) + .where( + and( + eq(usages.id, candidate.usageId), + eq(usages.editorialAccountId, candidate.editorialId), + ), + ) + .for("update") + .limit(1); + if (!usage) return false; + const [failed] = await transaction .update(downloadEvents) .set({ @@ -196,22 +249,17 @@ export function createDownloadDeliveryRepository( .where( and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming")), ) - .returning({ - usageId: downloadEvents.usageId, - editorialId: downloadEvents.editorialAccountId, - intentKind: downloadEvents.intentKind, - requestId: downloadEvents.requestId, - }); + .returning({ id: downloadEvents.id }); if (!failed) return false; - if (options.voidNewUsage && failed.intentKind === "new_usage") { + if (options.voidNewUsage && candidate.intentKind === "new_usage") { const [voided] = await transaction .update(usages) .set({ billingStatus: "voided" }) .where( and( - eq(usages.id, failed.usageId), - eq(usages.editorialAccountId, failed.editorialId), + eq(usages.id, candidate.usageId), + eq(usages.editorialAccountId, candidate.editorialId), inArray(usages.billingStatus, ["open", "reopened"]), ), ) @@ -219,19 +267,34 @@ export function createDownloadDeliveryRepository( if (!voided) { throw new Error("Billable usage could not be voided before delivery"); } + await transaction + .update(downloadEvents) + .set({ + status: "failed_before_delivery", + transferredBytes: 0, + completedAt: terminalAt, + }) + .where( + and( + eq(downloadEvents.editorialAccountId, candidate.editorialId), + eq(downloadEvents.usageId, candidate.usageId), + eq(downloadEvents.intentKind, "repeat_download"), + eq(downloadEvents.status, "authorized"), + ), + ); await transaction.insert(auditEvents).values({ eventType: "billable_usage_voided_before_delivery", actorType: "system", entityType: "usage", - entityId: failed.usageId, - previousValues: { billingStatus: "open" }, + entityId: candidate.usageId, + previousValues: { billingStatus: usage.billingStatus }, newValues: { billingStatus: "voided", downloadId, reason: "failed_before_delivery", }, occurredAt: terminalAt, - requestId: failed.requestId, + requestId: candidate.requestId, }); } return true; @@ -248,6 +311,23 @@ export function createDownloadDeliveryRepository( }; } +async function invalidateAuthorizedRepeat( + transaction: NodePgDatabase , + downloadId: string, + terminalAt: Date, +) { + await transaction + .update(downloadEvents) + .set({ + status: "failed_before_delivery", + transferredBytes: 0, + completedAt: terminalAt, + }) + .where( + and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "authorized")), + ); +} + async function markTerminal( database: NodePgDatabase , downloadId: string, @@ -287,6 +367,7 @@ export type UsageHistoryItem = { reference?: string; createdAt: Date; billingStatus: "open" | "billed" | "reopened" | "voided"; + priceCents: number; billableCents: number; attempts: UsageHistoryAttempt[]; }; @@ -296,10 +377,22 @@ export type UsageHistoryPage = { page: number; pageSize: number; hasNext: boolean; + attemptPageSize: number; + attemptCursor?: string; + nextAttemptCursor?: string; +}; + +export type HistoryAttemptCursor = { + authorizedAtMicros: string; + downloadId: string; }; export type DownloadHistoryRepository = { - listEditorialUsageHistory(editorialId: string, page: number): Promise ; + listEditorialUsageHistory( + editorialId: string, + page: number, + attemptCursor: HistoryAttemptCursor | undefined, + ): Promise ; }; export function createDownloadHistoryService({ @@ -308,11 +401,20 @@ export function createDownloadHistoryService({ repository: DownloadHistoryRepository; }) { return { - async listEditorialUsageHistory(editorialId: string, rawPage: unknown) { - return repository.listEditorialUsageHistory( + async listEditorialUsageHistory( + editorialId: string, + rawPage: unknown, + rawAttemptCursor?: unknown, + ) { + const attemptCursor = normalizeAttemptCursor(rawAttemptCursor); + const result = await repository.listEditorialUsageHistory( normalizeUuid(editorialId), normalizeHistoryPage(rawPage), + attemptCursor, ); + return attemptCursor + ? { ...result, attemptCursor: encodeAttemptCursor(attemptCursor) } + : result; }, }; } @@ -321,7 +423,7 @@ export function createPostgresDownloadHistoryRepository( database: NodePgDatabase , ): DownloadHistoryRepository { return { - async listEditorialUsageHistory(editorialId, page) { + async listEditorialUsageHistory(editorialId, page, attemptCursor) { const offset = (page - 1) * HISTORY_PAGE_SIZE; const usageRows = await database .select({ @@ -342,11 +444,21 @@ export function createPostgresDownloadHistoryRepository( const hasNext = usageRows.length > HISTORY_PAGE_SIZE; const pageRows = usageRows.slice(0, HISTORY_PAGE_SIZE); if (pageRows.length === 0) { - return { items: [], page, pageSize: HISTORY_PAGE_SIZE, hasNext }; + return { + items: [], + page, + pageSize: HISTORY_PAGE_SIZE, + hasNext, + attemptPageSize: HISTORY_ATTEMPT_PAGE_SIZE, + }; } const usageIds = pageRows.map((usage) => usage.usageId); - const eventRows = await database + const authorizedAtMicros = sql `floor(extract(epoch from ${downloadEvents.authorizedAt}) * 1000000)::bigint`; + const beforeCursor = attemptCursor + ? sql`(${authorizedAtMicros}, ${downloadEvents.id}) < (${attemptCursor.authorizedAtMicros}::bigint, ${attemptCursor.downloadId}::uuid)` + : undefined; + const eventRowsWithNext = await database .select({ downloadId: downloadEvents.id, usageId: downloadEvents.usageId, @@ -355,6 +467,7 @@ export function createPostgresDownloadHistoryRepository( finishedAt: downloadEvents.completedAt, transferredBytes: downloadEvents.transferredBytes, intentKind: downloadEvents.intentKind, + authorizedAtMicros, }) .from(downloadEvents) .where( @@ -366,9 +479,21 @@ export function createPostgresDownloadHistoryRepository( "interrupted", "failed_before_delivery", ]), + beforeCursor, ), ) - .orderBy(desc(downloadEvents.authorizedAt), desc(downloadEvents.id)); + .orderBy(desc(downloadEvents.authorizedAt), desc(downloadEvents.id)) + .limit(HISTORY_ATTEMPT_PAGE_SIZE + 1); + const hasNextAttempts = eventRowsWithNext.length > HISTORY_ATTEMPT_PAGE_SIZE; + const eventRows = eventRowsWithNext.slice(0, HISTORY_ATTEMPT_PAGE_SIZE); + const lastEvent = eventRows.at(-1); + const nextAttemptCursor = + hasNextAttempts && lastEvent + ? encodeAttemptCursor({ + authorizedAtMicros: lastEvent.authorizedAtMicros, + downloadId: lastEvent.downloadId, + }) + : undefined; const eventsByUsage = new Map (); for (const event of eventRows) { @@ -388,6 +513,7 @@ export function createPostgresDownloadHistoryRepository( ...(usage.reference === null ? {} : { reference: usage.reference }), createdAt: usage.createdAt, billingStatus: usage.billingStatus, + priceCents: usage.priceCents, billableCents, attempts: (eventsByUsage.get(usage.usageId) ?? []).map((event) => ({ downloadId: event.downloadId, @@ -406,6 +532,8 @@ export function createPostgresDownloadHistoryRepository( page, pageSize: HISTORY_PAGE_SIZE, hasNext, + attemptPageSize: HISTORY_ATTEMPT_PAGE_SIZE, + ...(nextAttemptCursor ? { nextAttemptCursor } : {}), }; }, }; @@ -430,14 +558,36 @@ function claimedIntentKind(value: string): ClaimedDownload["intentKind"] { } function normalizeHistoryPage(value: unknown): number { + return normalizeBoundedPage(value, HISTORY_MAX_PAGE); +} + +function normalizeBoundedPage(value: unknown, maximum: number): number { let page = 1; if (typeof value === "number" && Number.isSafeInteger(value)) { page = value; } else if (typeof value === "string" && /^\d+$/.test(value)) { const parsed = Number(value); - page = Number.isSafeInteger(parsed) ? parsed : HISTORY_MAX_PAGE; + page = Number.isSafeInteger(parsed) ? parsed : maximum; } - return Math.min(HISTORY_MAX_PAGE, Math.max(1, page)); + return Math.min(maximum, Math.max(1, page)); +} + +function normalizeAttemptCursor(value: unknown): HistoryAttemptCursor | undefined { + if (typeof value !== "string") return undefined; + const match = /^(\d{1,18})\.([0-9a-f-]{36})$/.exec(value); + if (!match) return undefined; + try { + return { + authorizedAtMicros: match[1], + downloadId: normalizeUuid(match[2]), + }; + } catch { + return undefined; + } +} + +function encodeAttemptCursor(cursor: HistoryAttemptCursor): string { + return `${cursor.authorizedAtMicros}.${cursor.downloadId}`; } export type DownloadDialogUsage = { diff --git a/tests/db/download-delivery.test.ts b/tests/db/download-delivery.test.ts index 374de3a..503629c 100644 --- a/tests/db/download-delivery.test.ts +++ b/tests/db/download-delivery.test.ts @@ -6,6 +6,7 @@ import { createDownloadDeliveryRepository, createDownloadHistoryService, createPostgresDownloadHistoryRepository, + HISTORY_ATTEMPT_PAGE_SIZE, } from "@/modules/downloads/stream"; import { createDownloadService, createRepeatDownloadRepository } from "@/modules/downloads/service"; import { startPostgres } from "./postgres"; @@ -33,6 +34,9 @@ test("a no-byte new failure retains the attempt and voids its billable usage", a const seed = await testDb.seedEditorialWithUsage(); const id = randomUUID(); await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id }); + await testDb.pool.query("update usages set billing_status = 'reopened' where id = $1", [ + seed.usageId, + ]); const repository = createDownloadDeliveryRepository(testDb.database); await repository.claimAuthorized(seed.editorialId, id); @@ -49,13 +53,16 @@ test("a no-byte new failure retains the attempt and voids its billable usage", a [seed.usageId], ); const audit = await testDb.pool.query( - "select event_type from audit_events where entity_id = $1 order by occurred_at desc", + "select event_type, previous_values from audit_events where entity_id = $1 order by occurred_at desc", [seed.usageId], ); expect(event.rows[0]).toMatchObject({ status: "failed_before_delivery" }); expect(Number(event.rows[0].transferred_bytes)).toBe(0); expect(usage.rows[0]).toEqual({ billing_status: "voided" }); - expect(audit.rows[0]).toEqual({ event_type: "billable_usage_voided_before_delivery" }); + expect(audit.rows[0]).toEqual({ + event_type: "billable_usage_voided_before_delivery", + previous_values: { billingStatus: "reopened" }, + }); const repeats = createDownloadService({ repository: createRepeatDownloadRepository(testDb.database), @@ -69,8 +76,92 @@ test("a no-byte new failure retains the attempt and voids its billable usage", a ).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" }); }); +test("rejects a free repeat until a new-usage original delivered bytes", async () => { + const seed = await testDb.seedEditorialWithUsage(); + const repeats = createDownloadService({ + repository: createRepeatDownloadRepository(testDb.database), + }); + + await expect( + repeats.createRepeatDownload({ + editorialId: seed.editorialId, + usageId: seed.usageId, + idempotencyKey: randomUUID(), + }), + ).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" }); +}); + +test.each(["completed", "interrupted"] as const)( + "allows a free repeat after an original %s delivery", + async (terminalStatus) => { + const seed = await testDb.seedEditorialWithUsage(); + const originalId = randomUUID(); + await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id: originalId }); + const delivery = createDownloadDeliveryRepository(testDb.database); + await delivery.claimAuthorized(seed.editorialId, originalId); + if (terminalStatus === "completed") { + await delivery.markCompleted(originalId, 120); + } else { + await delivery.markInterrupted(originalId, 80); + } + const repeats = createDownloadService({ + repository: createRepeatDownloadRepository(testDb.database), + }); + + const repeat = await repeats.createRepeatDownload({ + editorialId: seed.editorialId, + usageId: seed.usageId, + idempotencyKey: randomUUID(), + }); + + await expect(delivery.claimAuthorized(seed.editorialId, repeat.id)).resolves.toMatchObject({ + outcome: "claimed", + }); + }, +); + +test("a later new-use void invalidates a pre-authorized eligible repeat", async () => { + const seed = await testDb.seedEditorialWithUsage(); + const originalId = randomUUID(); + const failingNewId = randomUUID(); + await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id: originalId }); + await testDb.insertDownload({ + ...seed, + idempotencyKey: randomUUID(), + id: failingNewId, + }); + const delivery = createDownloadDeliveryRepository(testDb.database); + await delivery.claimAuthorized(seed.editorialId, originalId); + await delivery.markCompleted(originalId, 120); + await delivery.claimAuthorized(seed.editorialId, failingNewId); + const repeats = createDownloadService({ + repository: createRepeatDownloadRepository(testDb.database), + }); + const repeatIntent = await repeats.createRepeatDownload({ + editorialId: seed.editorialId, + usageId: seed.usageId, + idempotencyKey: randomUUID(), + }); + + const failed = await delivery.failBeforeDelivery(failingNewId, { voidNewUsage: true }); + const repeatClaim = await delivery.claimAuthorized(seed.editorialId, repeatIntent.id); + + expect(failed).toBe(true); + expect(repeatClaim.outcome).toBe("not_authorized"); + const repeatRow = await testDb.pool.query( + "select status from download_events where id = $1", + [repeatIntent.id], + ); + expect(repeatRow.rows[0]).toEqual({ status: "failed_before_delivery" }); +}); + test("a failed repeat attempt never mutates the original usage", async () => { const seed = await testDb.seedEditorialWithUsage(); + const originalId = randomUUID(); + await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id: originalId }); + const repository = createDownloadDeliveryRepository(testDb.database); + await repository.claimAuthorized(seed.editorialId, originalId); + await repository.markCompleted(originalId, 10); const id = randomUUID(); await testDb.insertDownload({ ...seed, @@ -78,7 +169,6 @@ test("a failed repeat attempt never mutates the original usage", async () => { id, intentKind: "repeat_download", }); - const repository = createDownloadDeliveryRepository(testDb.database); await repository.claimAuthorized(seed.editorialId, id); await repository.failBeforeDelivery(id, { voidNewUsage: false }); @@ -150,3 +240,40 @@ test("history is editorial-scoped, terminal-only, and paginated by usage", async expect(page.items[0].attempts.some((attempt) => attempt.downloadId === ownAuthorized)).toBe(false); expect(page.items[0].attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false); }); + +test("history bounds terminal attempts and exposes every attempt through pagination", async () => { + const own = await testDb.seedEditorialWithUsage(); + const attemptIds: string[] = []; + for (let index = 0; index < HISTORY_ATTEMPT_PAGE_SIZE + 1; index += 1) { + const id = randomUUID(); + attemptIds.push(id); + await testDb.insertDownload({ + ...own, + id, + idempotencyKey: randomUUID(), + intentKind: index === 0 ? "new_usage" : "repeat_download", + }); + } + await testDb.pool.query( + "update download_events set status = 'completed', started_at = now(), completed_at = now(), transferred_bytes = 5 where usage_id = $1", + [own.usageId], + ); + const history = createDownloadHistoryService({ + repository: createPostgresDownloadHistoryRepository(testDb.database), + }); + + const first = await history.listEditorialUsageHistory(own.editorialId, 1, 1); + expect(first.nextAttemptCursor).toBeDefined(); + const second = await history.listEditorialUsageHistory( + own.editorialId, + 1, + first.nextAttemptCursor, + ); + const firstIds = first.items.flatMap((usage) => usage.attempts.map((attempt) => attempt.downloadId)); + const secondIds = second.items.flatMap((usage) => usage.attempts.map((attempt) => attempt.downloadId)); + + expect(firstIds).toHaveLength(HISTORY_ATTEMPT_PAGE_SIZE); + expect(secondIds).toHaveLength(1); + expect(second.nextAttemptCursor).toBeUndefined(); + expect(new Set([...firstIds, ...secondIds])).toEqual(new Set(attemptIds)); +});
Noch kein abgeschlossener Auslieferungsversuch.
++ Keine Auslieferungsversuche auf dieser Auslieferungsseite. +
) : (-
{usage.attempts.map((attempt) => (
@@ -74,6 +81,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
)}