fix: harden delivery accounting and history
This commit is contained in:
1 parent
8871e4794a
commit
510fde7afa
13 files changed
+728
-88
No files matched your search
@@ -0,0 +1,124 @@
|
|||||||
|
# Task 9 — Authorized Original Streaming and Delivery Outcomes
|
||||||
|
|
||||||
|
## Delivered
|
||||||
|
|
||||||
|
- Added authenticated `POST /api/download-intents` and `GET /api/downloads/:downloadId/file` routes. Both derive the editorial scope exclusively from `requireActiveEditorial`; request payloads cannot supply editorial IDs or prices.
|
||||||
|
- Added a strict discriminated intent payload for `new_usage` versus `repeat_download`. Unknown/mixed fields, including client-controlled `editorialId` and `priceCents`, are rejected before accounting side effects. Responses expose only the download ID, same-origin file URL, server price, and billable flag.
|
||||||
|
- Added an atomic PostgreSQL claim for one owned `authorized` event. The conditional `authorized -> streaming` update commits before Immich is called, so concurrent GETs allow at most one upstream request. A same-editorial reused event returns a stable conflict; invalid, missing, and foreign-editorial IDs retain generic not-found behavior.
|
||||||
|
- Added unbuffered original streaming with exact byte accounting, upstream cancellation, contained cancellation rejections, safe upstream-reader cleanup, and exactly-once terminal settlement under local and database races.
|
||||||
|
- Added safe download response headers: `private, no-store`, syntactically validated media type and length, `nosniff`, and an attachment disposition with a control/path-separator-free ASCII fallback plus RFC 5987 UTF-8 `filename*`. No Immich URL, API key, or upstream-internal header is forwarded.
|
||||||
|
- Added the accessible German usage dialog to each catalog photo. Existing owned usages show `0,00 EUR`; a new usage shows the current server-read editorial price and requires a purpose. Only the dialog is a Client Component. Native dialog/radio/keyboard behavior, explicit focus, pending-state Escape handling, and visible focus styles are retained.
|
||||||
|
- The dialog creates one UUID only when a submission starts. It keeps that key through a failed retry, suppresses double-click requests, and resets the key only when the material selection/purpose changes or the action completes/closes.
|
||||||
|
- Added the editorial usage-history page and navigation. Its bounded, principal-scoped read model paginates immutable usage snapshots and includes every completed, interrupted, and failed-before-delivery attempt with filename, album, purpose, reference, date/time, bytes, attempt kind, outcome, and billable cents. It has German empty, pagination, and unavailable states.
|
||||||
|
- Voided usages are excluded from free-repeat authorization and prior-usage choices. Interrupted/completed original usages remain eligible for a new zero-cost repeat intent.
|
||||||
|
|
||||||
|
## Delivery state machine
|
||||||
|
|
||||||
|
1. Intent services create one immutable `authorized` event.
|
||||||
|
2. The file route conditionally claims `authorized -> streaming`, scoped by both `downloadId` and the authenticated `editorialId`.
|
||||||
|
3. A clean upstream close performs `streaming -> completed` with the exact enqueued byte count.
|
||||||
|
4. An upstream error or client cancellation after at least one byte performs `streaming -> interrupted`; the usage remains unchanged and can receive a new repeat intent.
|
||||||
|
5. An upstream error or cancellation before the first byte performs `streaming -> failed_before_delivery` with zero bytes.
|
||||||
|
6. For a `new_usage` failure before delivery, the same transaction changes the usage from `open|reopened -> voided` and appends `billable_usage_voided_before_delivery` to the audit log. The failed event and usage remain immutable/explainable; nothing is deleted.
|
||||||
|
7. For a repeat failure, the original usage is never mutated. The event alone records the failed attempt.
|
||||||
|
8. Every terminal repository update is conditional on `status = streaming`; competing completion/interruption/failure attempts therefore have at most one winner.
|
||||||
|
|
||||||
|
## Migration
|
||||||
|
|
||||||
|
- Added `drizzle/0003_stream_delivery.sql` with the durable `usage_billing_status = 'voided'` value.
|
||||||
|
- Generated `drizzle/meta/0003_snapshot.json` and updated `drizzle/meta/_journal.json`.
|
||||||
|
- `pnpm exec drizzle-kit check` reports `Everything's fine`.
|
||||||
|
- `pnpm exec drizzle-kit generate --name stream_delivery_final_noop` reports `No schema changes, nothing to migrate`.
|
||||||
|
- The deterministic migration contract verifies that 0003 adds the supported state and never deletes usage history.
|
||||||
|
|
||||||
|
## TDD evidence
|
||||||
|
|
||||||
|
### Initial streaming, routes, dialog, and migration RED
|
||||||
|
|
||||||
|
- Command: `pnpm test src/modules/downloads/stream.test.ts src/app/api/downloads/'[downloadId]'/file/route.test.ts src/app/api/download-intents/route.test.ts src/components/download/usage-dialog.test.tsx tests/db/download-delivery-migration-sql.test.ts`
|
||||||
|
- Result: 5 failed suites. The stream, both routes, dialog, and 0003 migration were absent; failures were module-resolution/ENOENT failures, as expected.
|
||||||
|
|
||||||
|
### Catalog and history RED
|
||||||
|
|
||||||
|
- Command: `pnpm test src/modules/albums/catalog-content.test.tsx src/app/redaktion/nutzungen/page.test.tsx`
|
||||||
|
- Result: 2 failed files. The catalog had no original-download action and the history page did not exist.
|
||||||
|
|
||||||
|
### Claimed-body cleanup RED/GREEN
|
||||||
|
|
||||||
|
- RED command: `pnpm test src/app/api/downloads/'[downloadId]'/file/route.test.ts -t 'upstream body cannot'`
|
||||||
|
- RED result: the route returned 503 for a locked upstream body but failed to terminally account for its already-claimed event.
|
||||||
|
- GREEN result after the scoped fix: 1 passed / 10 skipped. The route now cancels the upstream body best-effort and records the no-byte terminal outcome.
|
||||||
|
|
||||||
|
### Header-boundary hardening RED/GREEN
|
||||||
|
|
||||||
|
- RED command: `pnpm test src/app/api/downloads/'[downloadId]'/file/route.test.ts -t 'untrustworthy media|malformed Unicode'`
|
||||||
|
- RED result: 2 failed / 11 skipped. CR/LF in an upstream media type reached `Headers` and produced 503; a lone Unicode surrogate caused `encodeURIComponent` to throw.
|
||||||
|
- GREEN result: 2 passed / 11 skipped. Media-type optional whitespace is now restricted to HTTP space/tab, malformed values fall back to `application/octet-stream`, and malformed surrogate code units are replaced before RFC 5987 encoding.
|
||||||
|
|
||||||
|
### Focused GREEN
|
||||||
|
|
||||||
|
- Command: `pnpm typecheck && pnpm test src/modules/downloads/stream.test.ts src/app/api/downloads/'[downloadId]'/file/route.test.ts src/app/api/download-intents/route.test.ts src/components/download/usage-dialog.test.tsx src/modules/albums/catalog-content.test.tsx src/app/redaktion/nutzungen/page.test.tsx tests/db/download-delivery-migration-sql.test.ts`
|
||||||
|
- Result: typecheck passed; 7 files / 33 tests passed before the final route-handler build refactor.
|
||||||
|
- After isolating handler/test exports from Next route/page modules, the focused route/history set passed 3 files / 19 tests and lint passed.
|
||||||
|
|
||||||
|
### Real PostgreSQL tests
|
||||||
|
|
||||||
|
- Added `tests/db/download-delivery.test.ts`, unskipped, against PostgreSQL 17 via Testcontainers.
|
||||||
|
- It covers the concurrent authorized claim, new-use pre-byte void plus audit and repeat denial, repeat failure preservation, exactly-one competing terminal transition, and editorial-scoped terminal history.
|
||||||
|
- Command: `pnpm test tests/db/download-delivery.test.ts`
|
||||||
|
- Result: the suite failed before collecting/executing tests with `Could not find a working container runtime strategy`; 0 tests ran. This is an external Docker-runtime limitation, not a skipped application test.
|
||||||
|
|
||||||
|
## Final verification
|
||||||
|
|
||||||
|
- `pnpm test src tests/db/accounting-migration-sql.test.ts tests/db/download-delivery-migration-sql.test.ts` — 25 files / 157 tests passed.
|
||||||
|
- `pnpm typecheck` — passed.
|
||||||
|
- `pnpm lint` — passed.
|
||||||
|
- `pnpm exec drizzle-kit check` — passed.
|
||||||
|
- `pnpm exec drizzle-kit generate --name stream_delivery_final_noop` — no schema changes.
|
||||||
|
- `git diff --check` — passed.
|
||||||
|
- `pnpm exec next build --webpack` with the repository test environment — passed compilation, TypeScript, page-data collection, 14-page static generation, and build tracing. The intent route, file route, and usage-history page are dynamic server routes.
|
||||||
|
|
||||||
|
## Concern
|
||||||
|
|
||||||
|
- The five new PostgreSQL transition assertions could not execute locally because no container runtime is available. On a Docker-enabled host, run `pnpm test tests/db/download-delivery.test.ts` before release. The suite is unskipped and included in the normal full test command.
|
||||||
|
|
||||||
|
## Fix Round 1
|
||||||
|
|
||||||
|
### Review findings resolved
|
||||||
|
|
||||||
|
- Repeat intent creation, stream claim, and pre-first-byte void now lock the same usage row as their transaction mutex. A repeat is eligible only while the usage is non-voided and a `new_usage` event has already reached `completed|interrupted` with more than zero delivered bytes. This eligibility is rechecked for idempotent existing intents and again immediately before the conditional `authorized -> streaming` claim.
|
||||||
|
- Voiding a new usage preserves every audit/history row and terminally changes all still-`authorized` repeats for that usage to `failed_before_delivery`. A repeat discovered without valid delivery evidence is likewise retained and terminally invalidated instead of deleted. The usage-first lock order plus the conditional event update keeps concurrent claims and voids serializable and prevents a repeat from remaining claimable after a committed void.
|
||||||
|
- History attempt work and payload are globally bounded to 25 terminal events for the current 20-usage page. Exact PostgreSQL microsecond timestamp plus UUID keyset cursors provide stable continuation without a maximum attempt-page ceiling, hidden N+1 queries, or unbounded arrays. The cursor remains opaque in the URL, while editorial scope still comes exclusively from the authenticated principal.
|
||||||
|
- Each usage ledger entry now renders the immutable `price_cents` snapshot and its billing status even when no attempt has reached a terminal state. Effective `billableCents` remains separate, so a voided usage retains its historical price while being marked `Storniert` and nonbillable.
|
||||||
|
- The before-delivery void audit reads `previousValues.billingStatus` from the usage row locked in the same transaction. It therefore records `reopened` truthfully instead of hard-coding `open`.
|
||||||
|
- Dialog dates and history date/times share explicit `Europe/Berlin` formatters, making SSR and browser output independent of the host time zone.
|
||||||
|
|
||||||
|
### State-machine additions
|
||||||
|
|
||||||
|
1. `createRepeatDownload` locks editorial accounting and then the usage row, verifies an actually delivered original event, and only then returns or creates the authorized repeat.
|
||||||
|
2. `claimAuthorized` reads the scoped event, locks its usage row, revalidates non-voided/delivered-original eligibility, and finally performs the conditional claim. A competing claim still loses at the event transition.
|
||||||
|
3. `failBeforeDelivery` reads the streaming event, locks its usage row before the terminal transition, voids an eligible new usage, invalidates every outstanding authorized repeat, and writes the audit with the locked prior billing status in one transaction.
|
||||||
|
4. Completed, interrupted, and failed events remain terminal and immutable. No usage or delivery history is deleted.
|
||||||
|
|
||||||
|
### Fix-round TDD evidence
|
||||||
|
|
||||||
|
- Repeat eligibility RED: `pnpm test src/modules/downloads/eligibility.test.ts` failed because the eligibility module did not exist. GREEN after adding the invariant and repository locking: 4 focused files / 36 tests passed, followed by `pnpm typecheck`.
|
||||||
|
- History bounding RED: the service did not normalize a separate attempt continuation and the UI exposed only usage pagination (2 focused failures). The first bounded-page implementation passed 2 files / 10 tests plus typecheck. It was then tightened to a no-ceiling keyset cursor; the cursor contract/UI tests failed against the offset implementation and passed after the keyset change (2 files / 12 tests).
|
||||||
|
- Usage-level price/status RED: the open/no-terminal-attempt test could not find `Abrechnungsstatus` or the server price (1 failure). The immutable-price regression additionally showed `0,00 EUR` after void instead of the snapshot. Both pass with separate `priceCents` and `billableCents` fields.
|
||||||
|
- Time-zone RED: `pnpm test src/modules/downloads/format.test.ts` failed because the explicit Berlin formatter did not exist. GREEN verifies a Berlin-midnight boundary while the process time zone is `America/Los_Angeles`.
|
||||||
|
- Audit and PostgreSQL sequence/race coverage is unskipped in `tests/db/download-delivery.test.ts`: reopened prior-status truth, repeat rejection before delivered bytes, completed/interrupted eligibility, pre-authorized repeat invalidation on later void, concurrent claim ownership, and keyset access to every bounded attempt. The environment still fails before collection with `Could not find a working container runtime strategy`; exactly 0 PostgreSQL tests execute locally.
|
||||||
|
|
||||||
|
### Migration and final verification
|
||||||
|
|
||||||
|
- No schema migration was required in Fix Round 1; the existing durable `voided` state supports the invariant without deleting history.
|
||||||
|
- `pnpm test src tests/db/accounting-migration-sql.test.ts tests/db/download-delivery-migration-sql.test.ts` — 27 files / 166 tests passed.
|
||||||
|
- `pnpm typecheck` — passed.
|
||||||
|
- `pnpm lint` — passed.
|
||||||
|
- `pnpm exec drizzle-kit check` — passed.
|
||||||
|
- `pnpm exec drizzle-kit generate --name task_9_fix_round_1_final_noop` — no schema changes, nothing to migrate.
|
||||||
|
- `git diff --check` — passed.
|
||||||
|
- `pnpm exec next build --webpack` with the documented `.env.example` values — passed compilation, TypeScript, page-data collection, 14/14 static pages, and build tracing.
|
||||||
|
|
||||||
|
### Remaining concern
|
||||||
|
|
||||||
|
- Real PostgreSQL assertions remain blocked solely by the absent local Docker/container runtime. The expanded suite is not skipped and should be run unchanged on a Docker-enabled CI/release host.
|
||||||
@@ -20,6 +20,7 @@ test("renders every terminal attempt with its immutable usage snapshot", () => {
|
|||||||
reference: "Ausgabe 8/26",
|
reference: "Ausgabe 8/26",
|
||||||
createdAt: new Date("2026-08-09T10:00:00.000Z"),
|
createdAt: new Date("2026-08-09T10:00:00.000Z"),
|
||||||
billingStatus: "open",
|
billingStatus: "open",
|
||||||
|
priceCents: 1_500,
|
||||||
billableCents: 1_500,
|
billableCents: 1_500,
|
||||||
attempts: [
|
attempts: [
|
||||||
{
|
{
|
||||||
@@ -55,6 +56,9 @@ test("renders every terminal attempt with its immutable usage snapshot", () => {
|
|||||||
page: 1,
|
page: 1,
|
||||||
pageSize: 20,
|
pageSize: 20,
|
||||||
hasNext: true,
|
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("Abgeschlossen")).not.toBeNull();
|
||||||
expect(screen.getByText("Unterbrochen")).not.toBeNull();
|
expect(screen.getByText("Unterbrochen")).not.toBeNull();
|
||||||
expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).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.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",
|
"/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", () => {
|
test("renders a directional empty state", () => {
|
||||||
render(
|
render(
|
||||||
<UsageHistoryContent
|
<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.getByText(/noch keine nutzungen/i)).not.toBeNull();
|
||||||
expect(screen.getByRole("link", { name: /zu den alben/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();
|
||||||
|
});
|
||||||
@@ -4,20 +4,28 @@ import { requireEditorial } from "../access";
|
|||||||
import { UsageHistoryContent } from "./usage-history-content";
|
import { UsageHistoryContent } from "./usage-history-content";
|
||||||
|
|
||||||
type UsageHistoryPageProps = Readonly<{
|
type UsageHistoryPageProps = Readonly<{
|
||||||
searchParams: Promise<{ page?: string | string[] }>;
|
searchParams: Promise<{ page?: string | string[]; attemptCursor?: string | string[] }>;
|
||||||
}>;
|
}>;
|
||||||
|
|
||||||
export default async function UsagesPage({ searchParams }: UsageHistoryPageProps) {
|
export default async function UsagesPage({ searchParams }: UsageHistoryPageProps) {
|
||||||
const [principal, parameters] = await Promise.all([requireEditorial(), searchParams]);
|
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 />;
|
if (result.unavailable) return <HistoryUnavailable />;
|
||||||
return <UsageHistoryContent history={result.history} />;
|
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 {
|
try {
|
||||||
return {
|
return {
|
||||||
history: await listEditorialUsageHistory(editorialId, page),
|
history: await listEditorialUsageHistory(editorialId, page, attemptCursor),
|
||||||
unavailable: false as const,
|
unavailable: false as const,
|
||||||
};
|
};
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@@ -1,11 +1,8 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { formatBerlinDateTime } from "@/modules/downloads/format";
|
||||||
import type { UsageHistoryAttempt, UsageHistoryPage } from "@/modules/downloads/stream";
|
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", {
|
const priceFormatter = new Intl.NumberFormat("de-DE", {
|
||||||
style: "currency",
|
style: "currency",
|
||||||
currency: "EUR",
|
currency: "EUR",
|
||||||
@@ -39,7 +36,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
|
|||||||
<li key={usage.usageId}>
|
<li key={usage.usageId}>
|
||||||
<article className="usage-ledger-entry">
|
<article className="usage-ledger-entry">
|
||||||
<header>
|
<header>
|
||||||
<p>{formatDateTime(usage.createdAt)}</p>
|
<p>{formatBerlinDateTime(usage.createdAt)}</p>
|
||||||
<h2>{usage.filename}</h2>
|
<h2>{usage.filename}</h2>
|
||||||
</header>
|
</header>
|
||||||
<dl className="usage-snapshot">
|
<dl className="usage-snapshot">
|
||||||
@@ -51,6 +48,14 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
|
|||||||
<dt>Verwendungszweck</dt>
|
<dt>Verwendungszweck</dt>
|
||||||
<dd>{usage.purpose}</dd>
|
<dd>{usage.purpose}</dd>
|
||||||
</div>
|
</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 ? (
|
{usage.reference ? (
|
||||||
<div>
|
<div>
|
||||||
<dt>Interne Referenz</dt>
|
<dt>Interne Referenz</dt>
|
||||||
@@ -59,7 +64,9 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
|
|||||||
) : null}
|
) : null}
|
||||||
</dl>
|
</dl>
|
||||||
{usage.attempts.length === 0 ? (
|
{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}`}>
|
<ol className="usage-attempts" aria-label={`Auslieferungen für ${usage.filename}`}>
|
||||||
{usage.attempts.map((attempt) => (
|
{usage.attempts.map((attempt) => (
|
||||||
@@ -74,6 +81,7 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
|
|||||||
)}
|
)}
|
||||||
|
|
||||||
<HistoryPagination history={history} />
|
<HistoryPagination history={history} />
|
||||||
|
<AttemptPagination history={history} />
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -81,7 +89,9 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor
|
|||||||
function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
|
function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
|
||||||
return (
|
return (
|
||||||
<li>
|
<li>
|
||||||
<time dateTime={attempt.finishedAt.toISOString()}>{formatDateTime(attempt.finishedAt)}</time>
|
<time dateTime={attempt.finishedAt.toISOString()}>
|
||||||
|
{formatBerlinDateTime(attempt.finishedAt)}
|
||||||
|
</time>
|
||||||
<strong>{statusLabel(attempt.status)}</strong>
|
<strong>{statusLabel(attempt.status)}</strong>
|
||||||
<span>{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"}</span>
|
<span>{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"}</span>
|
||||||
<span>{byteFormatter.format(attempt.transferredBytes)}</span>
|
<span>{byteFormatter.format(attempt.transferredBytes)}</span>
|
||||||
@@ -95,12 +105,36 @@ function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>)
|
|||||||
return (
|
return (
|
||||||
<nav aria-label="Seiten der Nutzungshistorie" className="photo-pagination">
|
<nav aria-label="Seiten der Nutzungshistorie" className="photo-pagination">
|
||||||
{history.page > 1 ? (
|
{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 />
|
<span />
|
||||||
)}
|
)}
|
||||||
{history.hasNext ? (
|
{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}
|
) : null}
|
||||||
</nav>
|
</nav>
|
||||||
);
|
);
|
||||||
@@ -115,6 +149,12 @@ function statusLabel(status: UsageHistoryAttempt["status"]): string {
|
|||||||
return labels[status];
|
return labels[status];
|
||||||
}
|
}
|
||||||
|
|
||||||
function formatDateTime(value: Date): string {
|
function billingStatusLabel(status: UsageHistoryPage["items"][number]["billingStatus"]): string {
|
||||||
return dateTimeFormatter.format(value);
|
const labels: Record<UsageHistoryPage["items"][number]["billingStatus"], string> = {
|
||||||
|
open: "Offen",
|
||||||
|
billed: "Abgerechnet",
|
||||||
|
reopened: "Wieder geöffnet",
|
||||||
|
voided: "Storniert",
|
||||||
|
};
|
||||||
|
return labels[status];
|
||||||
}
|
}
|
||||||
@@ -2,6 +2,7 @@
|
|||||||
|
|
||||||
import { useRef, useState, type FormEvent } from "react";
|
import { useRef, useState, type FormEvent } from "react";
|
||||||
|
|
||||||
|
import { formatBerlinDate } from "@/modules/downloads/format";
|
||||||
import type { DownloadDialogUsage } from "@/modules/downloads/stream";
|
import type { DownloadDialogUsage } from "@/modules/downloads/stream";
|
||||||
|
|
||||||
type UsageDialogProps = Readonly<{
|
type UsageDialogProps = Readonly<{
|
||||||
@@ -23,9 +24,6 @@ const priceFormatter = new Intl.NumberFormat("de-DE", {
|
|||||||
style: "currency",
|
style: "currency",
|
||||||
currency: "EUR",
|
currency: "EUR",
|
||||||
});
|
});
|
||||||
const dateFormatter = new Intl.DateTimeFormat("de-DE", {
|
|
||||||
dateStyle: "medium",
|
|
||||||
});
|
|
||||||
|
|
||||||
export function UsageDialog({
|
export function UsageDialog({
|
||||||
albumId,
|
albumId,
|
||||||
@@ -216,7 +214,7 @@ export function UsageDialog({
|
|||||||
|
|
||||||
function formatDate(value: string): string {
|
function formatDate(value: string): string {
|
||||||
const date = new Date(value);
|
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 {
|
function isLocalDownloadUrl(fileUrl: string, downloadId: string): boolean {
|
||||||
|
|||||||
@@ -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);
|
||||||
|
},
|
||||||
|
);
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -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");
|
||||||
|
});
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@ import "server-only";
|
|||||||
|
|
||||||
import { randomUUID } from "node:crypto";
|
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 type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||||
|
|
||||||
import { db } from "@/db/client";
|
import { db } from "@/db/client";
|
||||||
@@ -23,6 +23,8 @@ import {
|
|||||||
type PersistedDownloadIntent,
|
type PersistedDownloadIntent,
|
||||||
} from "@/modules/usages/service";
|
} from "@/modules/usages/service";
|
||||||
|
|
||||||
|
import { hasDeliveredOriginal, isFreeRepeatEligible } from "./eligibility";
|
||||||
|
|
||||||
export type PersistedRepeatIntent = PersistedDownloadIntent & { kind: "repeat_download" };
|
export type PersistedRepeatIntent = PersistedDownloadIntent & { kind: "repeat_download" };
|
||||||
|
|
||||||
export type RepeatIntentInput = {
|
export type RepeatIntentInput = {
|
||||||
@@ -76,7 +78,13 @@ export function createRepeatDownloadRepository(
|
|||||||
input.editorialId,
|
input.editorialId,
|
||||||
input.idempotencyKey,
|
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
|
const [editorial] = await transaction
|
||||||
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
|
.select({ id: editorialAccounts.id, status: editorialAccounts.status })
|
||||||
@@ -89,18 +97,30 @@ export function createRepeatDownloadRepository(
|
|||||||
}
|
}
|
||||||
|
|
||||||
const [usage] = await transaction
|
const [usage] = await transaction
|
||||||
.select({ id: usages.id, assetId: usages.immichAssetId })
|
.select({
|
||||||
|
id: usages.id,
|
||||||
|
assetId: usages.immichAssetId,
|
||||||
|
billingStatus: usages.billingStatus,
|
||||||
|
})
|
||||||
.from(usages)
|
.from(usages)
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(usages.id, input.usageId),
|
eq(usages.id, input.usageId),
|
||||||
eq(usages.editorialAccountId, input.editorialId),
|
eq(usages.editorialAccountId, input.editorialId),
|
||||||
inArray(usages.billingStatus, ["open", "billed", "reopened"]),
|
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.for("update")
|
.for("update")
|
||||||
.limit(1);
|
.limit(1);
|
||||||
if (!usage) throw new UsageAccountingError("USAGE_NOT_FOUND");
|
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 authorizedAt = new Date();
|
||||||
const [event] = await transaction
|
const [event] = await transaction
|
||||||
|
|||||||
@@ -197,6 +197,7 @@ test("normalizes and bounds history pagination before the scoped repository quer
|
|||||||
page: HISTORY_MAX_PAGE,
|
page: HISTORY_MAX_PAGE,
|
||||||
pageSize: 20,
|
pageSize: 20,
|
||||||
hasNext: false,
|
hasNext: false,
|
||||||
|
attemptPageSize: 25,
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
const history = createDownloadHistoryService({ repository });
|
const history = createDownloadHistoryService({ repository });
|
||||||
@@ -204,11 +205,16 @@ test("normalizes and bounds history pagination before the scoped repository quer
|
|||||||
await history.listEditorialUsageHistory(
|
await history.listEditorialUsageHistory(
|
||||||
"11111111-1111-4111-8111-111111111111",
|
"11111111-1111-4111-8111-111111111111",
|
||||||
"999999999999999999999999",
|
"999999999999999999999999",
|
||||||
|
"1786314600000000.22222222-2222-4222-8222-222222222222",
|
||||||
);
|
);
|
||||||
|
|
||||||
expect(repository.listEditorialUsageHistory).toHaveBeenCalledWith(
|
expect(repository.listEditorialUsageHistory).toHaveBeenCalledWith(
|
||||||
"11111111-1111-4111-8111-111111111111",
|
"11111111-1111-4111-8111-111111111111",
|
||||||
HISTORY_MAX_PAGE,
|
HISTORY_MAX_PAGE,
|
||||||
|
{
|
||||||
|
authorizedAtMicros: "1786314600000000",
|
||||||
|
downloadId: "22222222-2222-4222-8222-222222222222",
|
||||||
|
},
|
||||||
);
|
);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+209
-59
@@ -1,6 +1,6 @@
|
|||||||
import "server-only";
|
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 type { NodePgDatabase } from "drizzle-orm/node-postgres";
|
||||||
|
|
||||||
import { db } from "@/db/client";
|
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 type * as schema from "@/db/schema";
|
||||||
import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types";
|
import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types";
|
||||||
|
|
||||||
|
import { hasDeliveredOriginal, isFreeRepeatEligible } from "./eligibility";
|
||||||
|
|
||||||
export const HISTORY_PAGE_SIZE = 20;
|
export const HISTORY_PAGE_SIZE = 20;
|
||||||
export const HISTORY_MAX_PAGE = 1_000;
|
export const HISTORY_MAX_PAGE = 1_000;
|
||||||
|
export const HISTORY_ATTEMPT_PAGE_SIZE = 25;
|
||||||
|
|
||||||
export type ClaimedDownload = {
|
export type ClaimedDownload = {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -127,57 +130,80 @@ export function createDownloadDeliveryRepository(
|
|||||||
return {
|
return {
|
||||||
async claimAuthorized(editorialId, downloadId) {
|
async claimAuthorized(editorialId, downloadId) {
|
||||||
return database.transaction(async (transaction) => {
|
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
|
const [claimed] = await transaction
|
||||||
.update(downloadEvents)
|
.update(downloadEvents)
|
||||||
.set({ status: "streaming", startedAt: new Date() })
|
.set({ status: "streaming", startedAt: new Date() })
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(downloadEvents.id, downloadId),
|
eq(downloadEvents.id, candidate.id),
|
||||||
eq(downloadEvents.editorialAccountId, editorialId),
|
eq(downloadEvents.editorialAccountId, editorialId),
|
||||||
eq(downloadEvents.status, "authorized"),
|
eq(downloadEvents.status, "authorized"),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
.returning({
|
.returning({ id: downloadEvents.id });
|
||||||
id: downloadEvents.id,
|
if (!claimed) return { outcome: "not_authorized" } as const;
|
||||||
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;
|
|
||||||
|
|
||||||
return {
|
return {
|
||||||
outcome: "claimed",
|
outcome: "claimed",
|
||||||
download: {
|
download: {
|
||||||
...claimed,
|
id: candidate.id,
|
||||||
|
usageId: candidate.usageId,
|
||||||
|
assetId: candidate.assetId,
|
||||||
filename: usage.filename,
|
filename: usage.filename,
|
||||||
intentKind: claimedIntentKind(claimed.intentKind),
|
intentKind,
|
||||||
},
|
},
|
||||||
} as const;
|
} as const;
|
||||||
});
|
});
|
||||||
@@ -186,6 +212,33 @@ export function createDownloadDeliveryRepository(
|
|||||||
async failBeforeDelivery(downloadId, options) {
|
async failBeforeDelivery(downloadId, options) {
|
||||||
return database.transaction(async (transaction) => {
|
return database.transaction(async (transaction) => {
|
||||||
const terminalAt = new Date();
|
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
|
const [failed] = await transaction
|
||||||
.update(downloadEvents)
|
.update(downloadEvents)
|
||||||
.set({
|
.set({
|
||||||
@@ -196,22 +249,17 @@ export function createDownloadDeliveryRepository(
|
|||||||
.where(
|
.where(
|
||||||
and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming")),
|
and(eq(downloadEvents.id, downloadId), eq(downloadEvents.status, "streaming")),
|
||||||
)
|
)
|
||||||
.returning({
|
.returning({ id: downloadEvents.id });
|
||||||
usageId: downloadEvents.usageId,
|
|
||||||
editorialId: downloadEvents.editorialAccountId,
|
|
||||||
intentKind: downloadEvents.intentKind,
|
|
||||||
requestId: downloadEvents.requestId,
|
|
||||||
});
|
|
||||||
if (!failed) return false;
|
if (!failed) return false;
|
||||||
|
|
||||||
if (options.voidNewUsage && failed.intentKind === "new_usage") {
|
if (options.voidNewUsage && candidate.intentKind === "new_usage") {
|
||||||
const [voided] = await transaction
|
const [voided] = await transaction
|
||||||
.update(usages)
|
.update(usages)
|
||||||
.set({ billingStatus: "voided" })
|
.set({ billingStatus: "voided" })
|
||||||
.where(
|
.where(
|
||||||
and(
|
and(
|
||||||
eq(usages.id, failed.usageId),
|
eq(usages.id, candidate.usageId),
|
||||||
eq(usages.editorialAccountId, failed.editorialId),
|
eq(usages.editorialAccountId, candidate.editorialId),
|
||||||
inArray(usages.billingStatus, ["open", "reopened"]),
|
inArray(usages.billingStatus, ["open", "reopened"]),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
@@ -219,19 +267,34 @@ export function createDownloadDeliveryRepository(
|
|||||||
if (!voided) {
|
if (!voided) {
|
||||||
throw new Error("Billable usage could not be voided before delivery");
|
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({
|
await transaction.insert(auditEvents).values({
|
||||||
eventType: "billable_usage_voided_before_delivery",
|
eventType: "billable_usage_voided_before_delivery",
|
||||||
actorType: "system",
|
actorType: "system",
|
||||||
entityType: "usage",
|
entityType: "usage",
|
||||||
entityId: failed.usageId,
|
entityId: candidate.usageId,
|
||||||
previousValues: { billingStatus: "open" },
|
previousValues: { billingStatus: usage.billingStatus },
|
||||||
newValues: {
|
newValues: {
|
||||||
billingStatus: "voided",
|
billingStatus: "voided",
|
||||||
downloadId,
|
downloadId,
|
||||||
reason: "failed_before_delivery",
|
reason: "failed_before_delivery",
|
||||||
},
|
},
|
||||||
occurredAt: terminalAt,
|
occurredAt: terminalAt,
|
||||||
requestId: failed.requestId,
|
requestId: candidate.requestId,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
return true;
|
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(
|
async function markTerminal(
|
||||||
database: NodePgDatabase<typeof schema>,
|
database: NodePgDatabase<typeof schema>,
|
||||||
downloadId: string,
|
downloadId: string,
|
||||||
@@ -287,6 +367,7 @@ export type UsageHistoryItem = {
|
|||||||
reference?: string;
|
reference?: string;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
billingStatus: "open" | "billed" | "reopened" | "voided";
|
billingStatus: "open" | "billed" | "reopened" | "voided";
|
||||||
|
priceCents: number;
|
||||||
billableCents: number;
|
billableCents: number;
|
||||||
attempts: UsageHistoryAttempt[];
|
attempts: UsageHistoryAttempt[];
|
||||||
};
|
};
|
||||||
@@ -296,10 +377,22 @@ export type UsageHistoryPage = {
|
|||||||
page: number;
|
page: number;
|
||||||
pageSize: number;
|
pageSize: number;
|
||||||
hasNext: boolean;
|
hasNext: boolean;
|
||||||
|
attemptPageSize: number;
|
||||||
|
attemptCursor?: string;
|
||||||
|
nextAttemptCursor?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type HistoryAttemptCursor = {
|
||||||
|
authorizedAtMicros: string;
|
||||||
|
downloadId: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type DownloadHistoryRepository = {
|
export type DownloadHistoryRepository = {
|
||||||
listEditorialUsageHistory(editorialId: string, page: number): Promise<UsageHistoryPage>;
|
listEditorialUsageHistory(
|
||||||
|
editorialId: string,
|
||||||
|
page: number,
|
||||||
|
attemptCursor: HistoryAttemptCursor | undefined,
|
||||||
|
): Promise<UsageHistoryPage>;
|
||||||
};
|
};
|
||||||
|
|
||||||
export function createDownloadHistoryService({
|
export function createDownloadHistoryService({
|
||||||
@@ -308,11 +401,20 @@ export function createDownloadHistoryService({
|
|||||||
repository: DownloadHistoryRepository;
|
repository: DownloadHistoryRepository;
|
||||||
}) {
|
}) {
|
||||||
return {
|
return {
|
||||||
async listEditorialUsageHistory(editorialId: string, rawPage: unknown) {
|
async listEditorialUsageHistory(
|
||||||
return repository.listEditorialUsageHistory(
|
editorialId: string,
|
||||||
|
rawPage: unknown,
|
||||||
|
rawAttemptCursor?: unknown,
|
||||||
|
) {
|
||||||
|
const attemptCursor = normalizeAttemptCursor(rawAttemptCursor);
|
||||||
|
const result = await repository.listEditorialUsageHistory(
|
||||||
normalizeUuid(editorialId),
|
normalizeUuid(editorialId),
|
||||||
normalizeHistoryPage(rawPage),
|
normalizeHistoryPage(rawPage),
|
||||||
|
attemptCursor,
|
||||||
);
|
);
|
||||||
|
return attemptCursor
|
||||||
|
? { ...result, attemptCursor: encodeAttemptCursor(attemptCursor) }
|
||||||
|
: result;
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -321,7 +423,7 @@ export function createPostgresDownloadHistoryRepository(
|
|||||||
database: NodePgDatabase<typeof schema>,
|
database: NodePgDatabase<typeof schema>,
|
||||||
): DownloadHistoryRepository {
|
): DownloadHistoryRepository {
|
||||||
return {
|
return {
|
||||||
async listEditorialUsageHistory(editorialId, page) {
|
async listEditorialUsageHistory(editorialId, page, attemptCursor) {
|
||||||
const offset = (page - 1) * HISTORY_PAGE_SIZE;
|
const offset = (page - 1) * HISTORY_PAGE_SIZE;
|
||||||
const usageRows = await database
|
const usageRows = await database
|
||||||
.select({
|
.select({
|
||||||
@@ -342,11 +444,21 @@ export function createPostgresDownloadHistoryRepository(
|
|||||||
const hasNext = usageRows.length > HISTORY_PAGE_SIZE;
|
const hasNext = usageRows.length > HISTORY_PAGE_SIZE;
|
||||||
const pageRows = usageRows.slice(0, HISTORY_PAGE_SIZE);
|
const pageRows = usageRows.slice(0, HISTORY_PAGE_SIZE);
|
||||||
if (pageRows.length === 0) {
|
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 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({
|
.select({
|
||||||
downloadId: downloadEvents.id,
|
downloadId: downloadEvents.id,
|
||||||
usageId: downloadEvents.usageId,
|
usageId: downloadEvents.usageId,
|
||||||
@@ -355,6 +467,7 @@ export function createPostgresDownloadHistoryRepository(
|
|||||||
finishedAt: downloadEvents.completedAt,
|
finishedAt: downloadEvents.completedAt,
|
||||||
transferredBytes: downloadEvents.transferredBytes,
|
transferredBytes: downloadEvents.transferredBytes,
|
||||||
intentKind: downloadEvents.intentKind,
|
intentKind: downloadEvents.intentKind,
|
||||||
|
authorizedAtMicros,
|
||||||
})
|
})
|
||||||
.from(downloadEvents)
|
.from(downloadEvents)
|
||||||
.where(
|
.where(
|
||||||
@@ -366,9 +479,21 @@ export function createPostgresDownloadHistoryRepository(
|
|||||||
"interrupted",
|
"interrupted",
|
||||||
"failed_before_delivery",
|
"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>();
|
const eventsByUsage = new Map<string, typeof eventRows>();
|
||||||
for (const event of eventRows) {
|
for (const event of eventRows) {
|
||||||
@@ -388,6 +513,7 @@ export function createPostgresDownloadHistoryRepository(
|
|||||||
...(usage.reference === null ? {} : { reference: usage.reference }),
|
...(usage.reference === null ? {} : { reference: usage.reference }),
|
||||||
createdAt: usage.createdAt,
|
createdAt: usage.createdAt,
|
||||||
billingStatus: usage.billingStatus,
|
billingStatus: usage.billingStatus,
|
||||||
|
priceCents: usage.priceCents,
|
||||||
billableCents,
|
billableCents,
|
||||||
attempts: (eventsByUsage.get(usage.usageId) ?? []).map((event) => ({
|
attempts: (eventsByUsage.get(usage.usageId) ?? []).map((event) => ({
|
||||||
downloadId: event.downloadId,
|
downloadId: event.downloadId,
|
||||||
@@ -406,6 +532,8 @@ export function createPostgresDownloadHistoryRepository(
|
|||||||
page,
|
page,
|
||||||
pageSize: HISTORY_PAGE_SIZE,
|
pageSize: HISTORY_PAGE_SIZE,
|
||||||
hasNext,
|
hasNext,
|
||||||
|
attemptPageSize: HISTORY_ATTEMPT_PAGE_SIZE,
|
||||||
|
...(nextAttemptCursor ? { nextAttemptCursor } : {}),
|
||||||
};
|
};
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
@@ -430,14 +558,36 @@ function claimedIntentKind(value: string): ClaimedDownload["intentKind"] {
|
|||||||
}
|
}
|
||||||
|
|
||||||
function normalizeHistoryPage(value: unknown): number {
|
function normalizeHistoryPage(value: unknown): number {
|
||||||
|
return normalizeBoundedPage(value, HISTORY_MAX_PAGE);
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizeBoundedPage(value: unknown, maximum: number): number {
|
||||||
let page = 1;
|
let page = 1;
|
||||||
if (typeof value === "number" && Number.isSafeInteger(value)) {
|
if (typeof value === "number" && Number.isSafeInteger(value)) {
|
||||||
page = value;
|
page = value;
|
||||||
} else if (typeof value === "string" && /^\d+$/.test(value)) {
|
} else if (typeof value === "string" && /^\d+$/.test(value)) {
|
||||||
const parsed = Number(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 = {
|
export type DownloadDialogUsage = {
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import {
|
|||||||
createDownloadDeliveryRepository,
|
createDownloadDeliveryRepository,
|
||||||
createDownloadHistoryService,
|
createDownloadHistoryService,
|
||||||
createPostgresDownloadHistoryRepository,
|
createPostgresDownloadHistoryRepository,
|
||||||
|
HISTORY_ATTEMPT_PAGE_SIZE,
|
||||||
} from "@/modules/downloads/stream";
|
} from "@/modules/downloads/stream";
|
||||||
import { createDownloadService, createRepeatDownloadRepository } from "@/modules/downloads/service";
|
import { createDownloadService, createRepeatDownloadRepository } from "@/modules/downloads/service";
|
||||||
import { startPostgres } from "./postgres";
|
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 seed = await testDb.seedEditorialWithUsage();
|
||||||
const id = randomUUID();
|
const id = randomUUID();
|
||||||
await testDb.insertDownload({ ...seed, idempotencyKey: randomUUID(), id });
|
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);
|
const repository = createDownloadDeliveryRepository(testDb.database);
|
||||||
await repository.claimAuthorized(seed.editorialId, id);
|
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],
|
[seed.usageId],
|
||||||
);
|
);
|
||||||
const audit = await testDb.pool.query(
|
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],
|
[seed.usageId],
|
||||||
);
|
);
|
||||||
expect(event.rows[0]).toMatchObject({ status: "failed_before_delivery" });
|
expect(event.rows[0]).toMatchObject({ status: "failed_before_delivery" });
|
||||||
expect(Number(event.rows[0].transferred_bytes)).toBe(0);
|
expect(Number(event.rows[0].transferred_bytes)).toBe(0);
|
||||||
expect(usage.rows[0]).toEqual({ billing_status: "voided" });
|
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({
|
const repeats = createDownloadService({
|
||||||
repository: createRepeatDownloadRepository(testDb.database),
|
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" });
|
).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 () => {
|
test("a failed repeat attempt never mutates the original usage", async () => {
|
||||||
const seed = await testDb.seedEditorialWithUsage();
|
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();
|
const id = randomUUID();
|
||||||
await testDb.insertDownload({
|
await testDb.insertDownload({
|
||||||
...seed,
|
...seed,
|
||||||
@@ -78,7 +169,6 @@ test("a failed repeat attempt never mutates the original usage", async () => {
|
|||||||
id,
|
id,
|
||||||
intentKind: "repeat_download",
|
intentKind: "repeat_download",
|
||||||
});
|
});
|
||||||
const repository = createDownloadDeliveryRepository(testDb.database);
|
|
||||||
await repository.claimAuthorized(seed.editorialId, id);
|
await repository.claimAuthorized(seed.editorialId, id);
|
||||||
|
|
||||||
await repository.failBeforeDelivery(id, { voidNewUsage: false });
|
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 === ownAuthorized)).toBe(false);
|
||||||
expect(page.items[0].attempts.some((attempt) => attempt.downloadId === foreignCompleted)).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));
|
||||||
|
});
|
||||||
Reference in new issue
Block a user