feat: stream originals with download accounting
This commit is contained in:
1 parent
c400167b8f
commit
8871e4794a
28 files changed
+4081
-8
No files matched your search
@@ -0,0 +1,137 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, expect, test, vi } from "vitest";
|
||||
|
||||
import { UsageDialog } from "./usage-dialog";
|
||||
|
||||
const idempotencyKey = "55555555-5555-4555-8555-555555555555";
|
||||
|
||||
beforeEach(() => {
|
||||
Object.defineProperty(HTMLDialogElement.prototype, "showModal", {
|
||||
configurable: true,
|
||||
value() {
|
||||
this.setAttribute("open", "");
|
||||
},
|
||||
});
|
||||
Object.defineProperty(HTMLDialogElement.prototype, "close", {
|
||||
configurable: true,
|
||||
value() {
|
||||
this.removeAttribute("open");
|
||||
this.dispatchEvent(new Event("close"));
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
cleanup();
|
||||
vi.restoreAllMocks();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
function renderDialog() {
|
||||
return render(
|
||||
<UsageDialog
|
||||
albumId="33333333-3333-4333-8333-333333333333"
|
||||
assetId="22222222-2222-4222-8222-222222222222"
|
||||
filename="tor-des-monats.jpg"
|
||||
newUsagePriceCents={1_500}
|
||||
priorUsages={[
|
||||
{
|
||||
id: "44444444-4444-4444-8444-444444444444",
|
||||
purpose: "Online-Nachbericht",
|
||||
createdAt: "2026-08-09T10:00:00.000Z",
|
||||
},
|
||||
]}
|
||||
/>,
|
||||
);
|
||||
}
|
||||
|
||||
test("offers an existing free use and a new server-priced use with required purpose", () => {
|
||||
renderDialog();
|
||||
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
|
||||
|
||||
expect(screen.getByRole("dialog", { name: /nutzung auswählen/i })).not.toBeNull();
|
||||
expect(
|
||||
(screen.getByRole("radio", {
|
||||
name: /online-nachbericht.*0,00\s*€/i,
|
||||
}) as HTMLInputElement).checked,
|
||||
).toBe(true);
|
||||
expect(
|
||||
(screen.getByRole("radio", { name: /neue nutzung.*15,00\s*€/i }) as HTMLInputElement)
|
||||
.checked,
|
||||
).toBe(false);
|
||||
expect(
|
||||
(screen.getByRole("textbox", { name: /^verwendungszweck$/i }) as HTMLTextAreaElement)
|
||||
.disabled,
|
||||
).toBe(true);
|
||||
|
||||
fireEvent.click(screen.getByRole("radio", { name: /neue nutzung/i }));
|
||||
expect(
|
||||
(screen.getByRole("textbox", { name: /^verwendungszweck$/i }) as HTMLTextAreaElement)
|
||||
.required,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test("reuses one idempotency key when the same failed submission is retried", async () => {
|
||||
const randomUUID = vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
|
||||
const fetch = vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||
.mockResolvedValueOnce(
|
||||
Response.json({
|
||||
downloadId: "66666666-6666-4666-8666-666666666666",
|
||||
fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file",
|
||||
priceCents: 1_500,
|
||||
billable: true,
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
|
||||
renderDialog();
|
||||
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
|
||||
fireEvent.click(screen.getByRole("radio", { name: /neue nutzung/i }));
|
||||
fireEvent.change(screen.getByRole("textbox", { name: /^verwendungszweck$/i }), {
|
||||
target: { value: "Titelgeschichte" },
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByRole("button", { name: /download anfordern/i }));
|
||||
await screen.findByRole("alert");
|
||||
fireEvent.click(screen.getByRole("button", { name: /download erneut anfordern/i }));
|
||||
|
||||
await waitFor(() => expect(anchorClick).toHaveBeenCalledOnce());
|
||||
expect(randomUUID).toHaveBeenCalledOnce();
|
||||
expect(fetch).toHaveBeenCalledTimes(2);
|
||||
for (const [, init] of fetch.mock.calls) {
|
||||
expect(JSON.parse(String(init?.body))).toMatchObject({ idempotencyKey });
|
||||
}
|
||||
});
|
||||
|
||||
test("suppresses double-click submission while one request is pending", async () => {
|
||||
vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
|
||||
let resolveRequest: ((response: Response) => void) | undefined;
|
||||
const fetch = vi.fn().mockReturnValue(
|
||||
new Promise<Response>((resolve) => {
|
||||
resolveRequest = resolve;
|
||||
}),
|
||||
);
|
||||
vi.stubGlobal("fetch", fetch);
|
||||
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
|
||||
renderDialog();
|
||||
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
|
||||
const submit = screen.getByRole("button", { name: /download anfordern/i });
|
||||
|
||||
fireEvent.click(submit);
|
||||
fireEvent.click(submit);
|
||||
|
||||
expect(fetch).toHaveBeenCalledOnce();
|
||||
resolveRequest?.(
|
||||
Response.json({
|
||||
downloadId: "66666666-6666-4666-8666-666666666666",
|
||||
fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file",
|
||||
priceCents: 0,
|
||||
billable: false,
|
||||
}),
|
||||
);
|
||||
await waitFor(() => expect((submit as HTMLButtonElement).disabled).toBe(false));
|
||||
});
|
||||
@@ -0,0 +1,224 @@
|
||||
"use client";
|
||||
|
||||
import { useRef, useState, type FormEvent } from "react";
|
||||
|
||||
import type { DownloadDialogUsage } from "@/modules/downloads/stream";
|
||||
|
||||
type UsageDialogProps = Readonly<{
|
||||
albumId: string;
|
||||
assetId: string;
|
||||
filename: string;
|
||||
newUsagePriceCents: number;
|
||||
priorUsages: DownloadDialogUsage[];
|
||||
}>;
|
||||
|
||||
type IntentResponse = {
|
||||
downloadId: string;
|
||||
fileUrl: string;
|
||||
priceCents: number;
|
||||
billable: boolean;
|
||||
};
|
||||
|
||||
const priceFormatter = new Intl.NumberFormat("de-DE", {
|
||||
style: "currency",
|
||||
currency: "EUR",
|
||||
});
|
||||
const dateFormatter = new Intl.DateTimeFormat("de-DE", {
|
||||
dateStyle: "medium",
|
||||
});
|
||||
|
||||
export function UsageDialog({
|
||||
albumId,
|
||||
assetId,
|
||||
filename,
|
||||
newUsagePriceCents,
|
||||
priorUsages,
|
||||
}: UsageDialogProps) {
|
||||
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||
const firstChoiceRef = useRef<HTMLInputElement>(null);
|
||||
const idempotencyKeyRef = useRef<string | null>(null);
|
||||
const initialChoice = priorUsages[0] ? `repeat:${priorUsages[0].id}` : "new_usage";
|
||||
const [choice, setChoice] = useState(initialChoice);
|
||||
const [purpose, setPurpose] = useState("");
|
||||
const [pending, setPending] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
function openDialog() {
|
||||
setChoice(initialChoice);
|
||||
setPurpose("");
|
||||
setPending(false);
|
||||
setError(null);
|
||||
idempotencyKeyRef.current = null;
|
||||
dialogRef.current?.showModal();
|
||||
requestAnimationFrame(() => firstChoiceRef.current?.focus());
|
||||
}
|
||||
|
||||
function closeDialog() {
|
||||
if (!pending) dialogRef.current?.close();
|
||||
}
|
||||
|
||||
function resetSubmission() {
|
||||
idempotencyKeyRef.current = null;
|
||||
setError(null);
|
||||
}
|
||||
|
||||
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
if (pending) return;
|
||||
setPending(true);
|
||||
setError(null);
|
||||
idempotencyKeyRef.current ??= crypto.randomUUID();
|
||||
|
||||
const payload = choice.startsWith("repeat:")
|
||||
? {
|
||||
kind: "repeat_download" as const,
|
||||
usageId: choice.slice("repeat:".length),
|
||||
idempotencyKey: idempotencyKeyRef.current,
|
||||
}
|
||||
: {
|
||||
kind: "new_usage" as const,
|
||||
assetId,
|
||||
albumId,
|
||||
purpose,
|
||||
idempotencyKey: idempotencyKeyRef.current,
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch("/api/download-intents", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
if (!response.ok) throw new Error("intent failed");
|
||||
const intent = (await response.json()) as IntentResponse;
|
||||
if (!isLocalDownloadUrl(intent.fileUrl, intent.downloadId)) {
|
||||
throw new Error("invalid download url");
|
||||
}
|
||||
const link = document.createElement("a");
|
||||
link.href = intent.fileUrl;
|
||||
link.download = filename;
|
||||
link.click();
|
||||
dialogRef.current?.close();
|
||||
idempotencyKeyRef.current = null;
|
||||
} catch {
|
||||
setError(
|
||||
"Der Download konnte nicht vorbereitet werden. Versuchen Sie dieselbe Anfrage erneut.",
|
||||
);
|
||||
} finally {
|
||||
setPending(false);
|
||||
}
|
||||
}
|
||||
|
||||
const isNewUsage = choice === "new_usage";
|
||||
|
||||
return (
|
||||
<>
|
||||
<button className="download-trigger" onClick={openDialog} type="button">
|
||||
Original laden
|
||||
</button>
|
||||
<dialog
|
||||
aria-labelledby={`usage-dialog-title-${assetId}`}
|
||||
className="usage-dialog"
|
||||
onCancel={(event) => {
|
||||
if (pending) event.preventDefault();
|
||||
}}
|
||||
onClose={() => {
|
||||
setError(null);
|
||||
idempotencyKeyRef.current = null;
|
||||
}}
|
||||
ref={dialogRef}
|
||||
>
|
||||
<form onSubmit={submit}>
|
||||
<div className="usage-dialog-heading">
|
||||
<p className="editorial-kicker">Download · {filename}</p>
|
||||
<h2 id={`usage-dialog-title-${assetId}`}>Nutzung auswählen</h2>
|
||||
<p>Ordnen Sie das Original einer bestehenden oder einer neuen Nutzung zu.</p>
|
||||
</div>
|
||||
|
||||
<fieldset className="usage-options" disabled={pending}>
|
||||
<legend>Abrechnung</legend>
|
||||
{priorUsages.map((usage, index) => (
|
||||
<label className="usage-option" key={usage.id}>
|
||||
<input
|
||||
checked={choice === `repeat:${usage.id}`}
|
||||
name={`usage-${assetId}`}
|
||||
onChange={() => {
|
||||
setChoice(`repeat:${usage.id}`);
|
||||
resetSubmission();
|
||||
}}
|
||||
ref={index === 0 ? firstChoiceRef : undefined}
|
||||
type="radio"
|
||||
value={`repeat:${usage.id}`}
|
||||
/>
|
||||
<span>
|
||||
<strong>{usage.purpose}</strong>
|
||||
<small>Bestehende Nutzung · {formatDate(usage.createdAt)}</small>
|
||||
</span>
|
||||
<b>{priceFormatter.format(0)}</b>
|
||||
</label>
|
||||
))}
|
||||
<label className="usage-option">
|
||||
<input
|
||||
checked={isNewUsage}
|
||||
name={`usage-${assetId}`}
|
||||
onChange={() => {
|
||||
setChoice("new_usage");
|
||||
resetSubmission();
|
||||
}}
|
||||
ref={priorUsages.length === 0 ? firstChoiceRef : undefined}
|
||||
type="radio"
|
||||
value="new_usage"
|
||||
/>
|
||||
<span>
|
||||
<strong>Neue Nutzung</strong>
|
||||
<small>Neue Veröffentlichung oder neuer Verwendungszweck</small>
|
||||
</span>
|
||||
<b>{priceFormatter.format(newUsagePriceCents / 100)}</b>
|
||||
</label>
|
||||
</fieldset>
|
||||
|
||||
<label className="usage-purpose" htmlFor={`usage-purpose-${assetId}`}>
|
||||
Verwendungszweck
|
||||
<textarea
|
||||
disabled={!isNewUsage || pending}
|
||||
id={`usage-purpose-${assetId}`}
|
||||
maxLength={200}
|
||||
minLength={3}
|
||||
onChange={(event) => {
|
||||
setPurpose(event.target.value);
|
||||
resetSubmission();
|
||||
}}
|
||||
required={isNewUsage}
|
||||
rows={3}
|
||||
value={purpose}
|
||||
/>
|
||||
</label>
|
||||
|
||||
{error ? <p role="alert">{error}</p> : null}
|
||||
|
||||
<div className="usage-dialog-actions">
|
||||
<button disabled={pending} onClick={closeDialog} type="button">
|
||||
Abbrechen
|
||||
</button>
|
||||
<button className="download-confirm" disabled={pending} type="submit">
|
||||
{pending
|
||||
? "Download wird vorbereitet …"
|
||||
: error
|
||||
? "Download erneut anfordern"
|
||||
: "Download anfordern"}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</dialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
function formatDate(value: string): string {
|
||||
const date = new Date(value);
|
||||
return Number.isNaN(date.valueOf()) ? "Datum unbekannt" : dateFormatter.format(date);
|
||||
}
|
||||
|
||||
function isLocalDownloadUrl(fileUrl: string, downloadId: string): boolean {
|
||||
return fileUrl === `/api/downloads/${encodeURIComponent(downloadId)}/file`;
|
||||
}
|
||||
@@ -15,6 +15,7 @@ export function PortalShell({ children }: Readonly<{ children: ReactNode }>) {
|
||||
<span>Redaktionsarchiv</span>
|
||||
<nav aria-label="Redaktion">
|
||||
<Link href="/redaktion/alben">Alben</Link>
|
||||
<Link href="/redaktion/nutzungen">Nutzungen</Link>
|
||||
<Link href="/redaktion/profil">Profil</Link>
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
Reference in new issue
Block a user