fix: harden delivery accounting and history

This commit is contained in:
Leon Tonhäuser committed 2026-08-10 13:44:04 +02:00
1 parent 8871e4794a
commit 510fde7afa
13 files changed
+728 -88

No files matched your search

+80 -3
View File
@@ -20,6 +20,7 @@ test("renders every terminal attempt with its immutable usage snapshot", () => {
reference: "Ausgabe 8/26",
createdAt: new Date("2026-08-09T10:00:00.000Z"),
billingStatus: "open",
priceCents: 1_500,
billableCents: 1_500,
attempts: [
{
@@ -55,6 +56,9 @@ test("renders every terminal attempt with its immutable usage snapshot", () => {
page: 1,
pageSize: 20,
hasNext: true,
attemptPageSize: 25,
attemptCursor: "1786314600000.current",
nextAttemptCursor: "1786311000000.next",
}}
/>,
);
@@ -65,20 +69,93 @@ test("renders every terminal attempt with its immutable usage snapshot", () => {
expect(screen.getByText("Abgeschlossen")).not.toBeNull();
expect(screen.getByText("Unterbrochen")).not.toBeNull();
expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).not.toBeNull();
expect(screen.getByText(/15,00\s*€/)).not.toBeNull();
expect(screen.getAllByText(/15,00\s*€/)).toHaveLength(2);
expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(2);
expect(screen.getByRole("link", { name: /nächste seite/i }).getAttribute("href")).toBe(
expect(screen.getByRole("link", { name: /nächste nutzungsseite/i }).getAttribute("href")).toBe(
"/redaktion/nutzungen?page=2",
);
expect(
screen.getByRole("link", { name: /neueste auslieferungen/i }).getAttribute("href"),
).toBe("/redaktion/nutzungen?page=1");
expect(
screen.getByRole("link", { name: /ältere auslieferungen/i }).getAttribute("href"),
).toBe(
"/redaktion/nutzungen?page=1&attemptCursor=1786311000000.next",
);
});
test("renders a directional empty state", () => {
render(
<UsageHistoryContent
history={{ items: [], page: 1, pageSize: 20, hasNext: false }}
history={{
items: [],
page: 1,
pageSize: 20,
hasNext: false,
attemptPageSize: 25,
}}
/>,
);
expect(screen.getByText(/noch keine nutzungen/i)).not.toBeNull();
expect(screen.getByRole("link", { name: /zu den alben/i })).not.toBeNull();
});
test("shows the usage-level price and billing status before any attempt is terminal", () => {
render(
<UsageHistoryContent
history={{
items: [
{
usageId: "usage-open",
filename: "noch-im-abruf.jpg",
albumName: "Pressebilder",
purpose: "Online-Meldung",
createdAt: new Date("2026-08-10T10:00:00.000Z"),
billingStatus: "open",
priceCents: 1_500,
billableCents: 1_500,
attempts: [],
},
],
page: 1,
pageSize: 20,
hasNext: false,
attemptPageSize: 25,
}}
/>,
);
expect(screen.getByText("Abrechnungsstatus")).not.toBeNull();
expect(screen.getByText("Offen")).not.toBeNull();
expect(screen.getByText(/15,00\s*€/)).not.toBeNull();
});
test("keeps the immutable usage price visible when billing was voided", () => {
render(
<UsageHistoryContent
history={{
items: [
{
usageId: "usage-voided",
filename: "fehlgeschlagen.jpg",
albumName: "Pressebilder",
purpose: "Online-Meldung",
createdAt: new Date("2026-08-10T10:00:00.000Z"),
billingStatus: "voided",
priceCents: 1_500,
billableCents: 0,
attempts: [],
},
],
page: 1,
pageSize: 20,
hasNext: false,
attemptPageSize: 25,
}}
/>,
);
expect(screen.getByText("Storniert")).not.toBeNull();
expect(screen.getByText(/15,00\s*€/)).not.toBeNull();
});
+12 -4
View File
@@ -4,20 +4,28 @@ import { requireEditorial } from "../access";
import { UsageHistoryContent } from "./usage-history-content";
type UsageHistoryPageProps = Readonly<{
searchParams: Promise<{ page?: string | string[] }>;
searchParams: Promise<{ page?: string | string[]; attemptCursor?: string | string[] }>;
}>;
export default async function UsagesPage({ searchParams }: UsageHistoryPageProps) {
const [principal, parameters] = await Promise.all([requireEditorial(), searchParams]);
const result = await loadHistory(principal.editorialId, singleValue(parameters.page));
const result = await loadHistory(
principal.editorialId,
singleValue(parameters.page),
singleValue(parameters.attemptCursor),
);
if (result.unavailable) return <HistoryUnavailable />;
return <UsageHistoryContent history={result.history} />;
}
async function loadHistory(editorialId: string, page: string | undefined) {
async function loadHistory(
editorialId: string,
page: string | undefined,
attemptCursor: string | undefined,
) {
try {
return {
history: await listEditorialUsageHistory(editorialId, page),
history: await listEditorialUsageHistory(editorialId, page, attemptCursor),
unavailable: false as const,
};
} catch {
@@ -1,11 +1,8 @@
import Link from "next/link";
import { formatBerlinDateTime } from "@/modules/downloads/format";
import type { UsageHistoryAttempt, UsageHistoryPage } from "@/modules/downloads/stream";
const dateTimeFormatter = new Intl.DateTimeFormat("de-DE", {
dateStyle: "medium",
timeStyle: "short",
});
const priceFormatter = new Intl.NumberFormat("de-DE", {
style: "currency",
currency: "EUR",
@@ -39,7 +36,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
<li key={usage.usageId}>
<article className="usage-ledger-entry">
<header>
<p>{formatDateTime(usage.createdAt)}</p>
<p>{formatBerlinDateTime(usage.createdAt)}</p>
<h2>{usage.filename}</h2>
</header>
<dl className="usage-snapshot">
@@ -51,6 +48,14 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
<dt>Verwendungszweck</dt>
<dd>{usage.purpose}</dd>
</div>
<div>
<dt>Nutzungspreis</dt>
<dd>{priceFormatter.format(usage.priceCents / 100)}</dd>
</div>
<div>
<dt>Abrechnungsstatus</dt>
<dd>{billingStatusLabel(usage.billingStatus)}</dd>
</div>
{usage.reference ? (
<div>
<dt>Interne Referenz</dt>
@@ -59,7 +64,9 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
) : null}
</dl>
{usage.attempts.length === 0 ? (
<p className="usage-attempt-empty">Noch kein abgeschlossener Auslieferungsversuch.</p>
<p className="usage-attempt-empty">
Keine Auslieferungsversuche auf dieser Auslieferungsseite.
</p>
) : (
<ol className="usage-attempts" aria-label={`Auslieferungen für ${usage.filename}`}>
{usage.attempts.map((attempt) => (
@@ -74,6 +81,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
)}
<HistoryPagination history={history} />
<AttemptPagination history={history} />
</section>
);
}
@@ -81,7 +89,9 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
return (
<li>
<time dateTime={attempt.finishedAt.toISOString()}>{formatDateTime(attempt.finishedAt)}</time>
<time dateTime={attempt.finishedAt.toISOString()}>
{formatBerlinDateTime(attempt.finishedAt)}
</time>
<strong>{statusLabel(attempt.status)}</strong>
<span>{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"}</span>
<span>{byteFormatter.format(attempt.transferredBytes)}</span>
@@ -95,12 +105,36 @@ function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>)
return (
<nav aria-label="Seiten der Nutzungshistorie" className="photo-pagination">
{history.page > 1 ? (
<Link href={`/redaktion/nutzungen?page=${history.page - 1}`}>Vorherige Seite</Link>
<Link href={`/redaktion/nutzungen?page=${history.page - 1}`}>
Vorherige Nutzungsseite
</Link>
) : (
<span />
)}
{history.hasNext ? (
<Link href={`/redaktion/nutzungen?page=${history.page + 1}`}>Nächste Seite</Link>
<Link href={`/redaktion/nutzungen?page=${history.page + 1}`}>
Nächste Nutzungsseite
</Link>
) : null}
</nav>
);
}
function AttemptPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
if (!history.attemptCursor && !history.nextAttemptCursor) return null;
return (
<nav aria-label="Seiten der Auslieferungsversuche" className="photo-pagination">
{history.attemptCursor ? (
<Link href={`/redaktion/nutzungen?page=${history.page}`}>Neueste Auslieferungen</Link>
) : (
<span />
)}
{history.nextAttemptCursor ? (
<Link
href={`/redaktion/nutzungen?page=${history.page}&attemptCursor=${encodeURIComponent(history.nextAttemptCursor)}`}
>
Ältere Auslieferungen
</Link>
) : null}
</nav>
);
@@ -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<UsageHistoryPage["items"][number]["billingStatus"], string> = {
open: "Offen",
billed: "Abgerechnet",
reopened: "Wieder geöffnet",
voided: "Storniert",
};
return labels[status];
}
+2 -4
View File
@@ -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 {
+17
View File
@@ -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);
},
);
+37
View File
@@ -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<typeof schema>,
editorialId: string,
usageId: string,
): Promise<boolean> {
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);
}
+18
View File
@@ -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");
});
+18
View File
@@ -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);
}
+24 -4
View File
@@ -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
+6
View File
@@ -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",
},
);
});
+209 -59
View File
@@ -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<typeof schema>,
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<typeof schema>,
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<UsageHistoryPage>;
listEditorialUsageHistory(
editorialId: string,
page: number,
attemptCursor: HistoryAttemptCursor | undefined,
): Promise<UsageHistoryPage>;
};
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<typeof schema>,
): 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<string>`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<string, typeof eventRows>();
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 = {