Add release blocklist feature

Introduce a per-request release blocklist to auto-block permanently failing releases and provide admin management. Changes include:

- Database: add BlockedRelease model (blocked_releases) to Prisma schema with unique (requestId, releaseKey) and indexes; documented in backend database docs.
- Service & utils: new blocklist.service, release-key and filter helpers for normalization and matching; processors updated to emit auto-blocks (monitor-download, organize-files, search processors, RSS).
- HTTP API: add admin endpoints GET/DELETE /api/admin/blocklist, DELETE /api/admin/blocklist/[id], and GET /api/admin/blocklist/by-request/[requestId].
- Admin UI: new /admin/blocklist page and numerous React components (toolbar, filters, table, rows, pagination, skeleton, chips, date picker) with URL-driven state hook and per-row unblock UX.
- Tests: add unit/integration tests for service, routes, utils, and updated processor tests.

The blocklist is idempotent (upsert), filters search results before ranking (interactive search shows badges only), and admin-only APIs require auth. This commit wires docs, API, DB, frontend and tests for the new feature.
This commit is contained in:
kikootwo
2026-05-18 12:15:51 -04:00
parent fb0445d95f
commit b1492fc32e
41 changed files with 4098 additions and 12 deletions
@@ -0,0 +1,110 @@
/**
* Component: Blocklist — Active Filter Chips
* Documentation: documentation/admin-features/release-blocklist.md
*
* Dismissable chip strip showing every active filter PLUS the search term.
* Each chip is a real <button> with aria-label="Remove filter: <name>" and a
* visible × glyph (per zach.md UX rule on intentional affordances).
*/
'use client';
import {
DATE_PRESETS,
getActivePresetId,
} from '@/lib/constants/log-filters';
import { useBlocklistUrlState } from '../hooks/useBlocklistUrlState';
import { SOURCE_LABELS } from '../types';
export default function BlocklistActiveFilterChips() {
const { filters, setFilters, removeFilter } = useBlocklistUrlState();
const chips: ChipDescriptor[] = [];
if (filters.search !== '') {
chips.push({
key: 'search',
name: 'search',
label: `Search: "${filters.search}"`,
onRemove: () => removeFilter('search'),
});
}
if (filters.source !== 'all') {
chips.push({
key: 'source',
name: 'source',
label: `Source: ${SOURCE_LABELS[filters.source] ?? filters.source}`,
onRemove: () => removeFilter('source'),
});
}
if (filters.requestId !== null) {
chips.push({
key: 'requestId',
name: 'request',
label: `Request: ${filters.requestId}`,
onRemove: () => removeFilter('requestId'),
});
}
if (filters.dateFrom !== null || filters.dateTo !== null) {
chips.push({
key: 'date',
name: 'date range',
label: `Date: ${formatDateChipLabel(filters.dateFrom, filters.dateTo)}`,
onRemove: () => setFilters({ dateFrom: null, dateTo: null }),
});
}
if (chips.length === 0) return null;
return (
<div className="mb-4 flex flex-wrap gap-2" role="group" aria-label="Active filters">
{chips.map((chip) => (
<Chip key={chip.key} chip={chip} />
))}
</div>
);
}
interface ChipDescriptor {
key: string;
name: string;
label: string;
onRemove: () => void;
}
function Chip({ chip }: { chip: ChipDescriptor }) {
return (
<button
type="button"
onClick={chip.onRemove}
aria-label={`Remove filter: ${chip.name}`}
className="inline-flex items-center gap-1.5 pl-3 pr-2 py-1.5 bg-blue-50 dark:bg-blue-900/30 border border-blue-200 dark:border-blue-800 text-blue-800 dark:text-blue-200 rounded-full text-sm font-medium hover:bg-blue-100 dark:hover:bg-blue-900/50 transition-colors min-h-[36px]"
>
<span className="truncate max-w-[20rem]">{chip.label}</span>
<svg className="w-3.5 h-3.5 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
);
}
function formatDateChipLabel(dateFrom: string | null, dateTo: string | null): string {
const presetId = getActivePresetId(dateFrom, dateTo);
if (presetId === 'custom') {
return `${formatLocal(dateFrom)} ${formatLocal(dateTo)}`;
}
const preset = DATE_PRESETS.find((p) => p.id === presetId);
return preset?.label ?? 'Custom';
}
function formatLocal(iso: string | null): string {
if (!iso) return '…';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '…';
return d.toLocaleString([], {
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
}
@@ -0,0 +1,131 @@
/**
* Component: Blocklist — Date Range Picker
* Documentation: documentation/admin-features/release-blocklist.md
*
* Sibling of admin/logs/components/DateRangePicker — no pause-on-interact
* registration since the blocklist page has no auto-refresh. Same preset list
* (defined in @/lib/constants/log-filters which is shared, not logs-only).
*/
'use client';
import { useMemo, useState } from 'react';
import {
DATE_PRESETS,
getActivePresetId,
presetToRange,
type DatePresetId,
} from '@/lib/constants/log-filters';
import { INPUT_CLASS, LABEL_CLASS } from '@/app/admin/logs/components/filter-styles';
interface BlocklistDateRangePickerProps {
dateFrom: string | null;
dateTo: string | null;
onChange: (next: { dateFrom: string | null; dateTo: string | null }) => void;
}
export default function BlocklistDateRangePicker({
dateFrom,
dateTo,
onChange,
}: BlocklistDateRangePickerProps) {
const [forceCustom, setForceCustom] = useState(false);
const derivedPreset = useMemo(
() => getActivePresetId(dateFrom, dateTo),
[dateFrom, dateTo]
);
const activePreset: DatePresetId = forceCustom ? 'custom' : derivedPreset;
const showCustom = activePreset === 'custom';
const handlePresetChange = (id: DatePresetId) => {
if (id === 'custom') {
setForceCustom(true);
return;
}
setForceCustom(false);
onChange(presetToRange(id));
};
const handleCustomChange = (next: { dateFrom: string | null; dateTo: string | null }) => {
setForceCustom(true);
onChange(next);
};
return (
<div>
<label className={LABEL_CLASS} htmlFor="blocklist-date-preset">Date Range</label>
<select
id="blocklist-date-preset"
value={activePreset}
onChange={(e) => handlePresetChange(e.target.value as DatePresetId)}
className={INPUT_CLASS}
>
{DATE_PRESETS.map((p) => (
<option key={p.id} value={p.id}>{p.label}</option>
))}
</select>
{showCustom && (
<CustomDateInputs dateFrom={dateFrom} dateTo={dateTo} onChange={handleCustomChange} />
)}
</div>
);
}
function CustomDateInputs({
dateFrom,
dateTo,
onChange,
}: {
dateFrom: string | null;
dateTo: string | null;
onChange: (next: { dateFrom: string | null; dateTo: string | null }) => void;
}) {
const fromLocal = useMemo(() => isoToLocalInputValue(dateFrom), [dateFrom]);
const toLocal = useMemo(() => isoToLocalInputValue(dateTo), [dateTo]);
return (
<div className="mt-2 space-y-2">
<div className="grid grid-cols-2 gap-2">
<input
type="datetime-local"
aria-label="Date from"
value={fromLocal}
onChange={(e) =>
onChange({ dateFrom: localInputToIso(e.target.value), dateTo })
}
className={INPUT_CLASS}
/>
<input
type="datetime-local"
aria-label="Date to"
value={toLocal}
onChange={(e) =>
onChange({ dateFrom, dateTo: localInputToIso(e.target.value) })
}
className={INPUT_CLASS}
/>
</div>
<p className="text-xs text-gray-500 dark:text-gray-400">
Times are in your local timezone (sent as UTC).
</p>
</div>
);
}
function isoToLocalInputValue(iso: string | null): string {
if (!iso) return '';
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return '';
const pad = (n: number) => String(n).padStart(2, '0');
return (
`${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}` +
`T${pad(d.getHours())}:${pad(d.getMinutes())}`
);
}
function localInputToIso(value: string): string | null {
if (!value) return null;
const d = new Date(value);
if (Number.isNaN(d.getTime())) return null;
return d.toISOString();
}
@@ -0,0 +1,84 @@
/**
* Component: Admin Blocklist — Filter Picker Row
* Documentation: documentation/admin-features/release-blocklist.md
*
* Two visible filter controls in v1: Source dropdown + Date Range.
* Plus a "Clear all filters" affordance when any filter or search is active.
*
* Mirrors the logs/components/LogsFilters layout. Consumes
* useBlocklistUrlState() directly — no prop drilling.
*/
'use client';
import { useBlocklistUrlState } from '../hooks/useBlocklistUrlState';
import {
BlockSourceFilter,
hasActiveFilters,
hasActiveSearch,
SOURCE_LABELS,
VALID_SOURCES,
} from '../types';
import BlocklistDateRangePicker from './BlocklistDateRangePicker';
import { INPUT_CLASS, LABEL_CLASS } from '@/app/admin/logs/components/filter-styles';
export default function BlocklistFilters() {
const { filters, setFilters, clearAll } = useBlocklistUrlState();
const showClearAll = hasActiveFilters(filters) || hasActiveSearch(filters);
return (
<div className="mb-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4">
<SourceDropdown
value={filters.source}
onChange={(value) => setFilters({ source: value })}
/>
<BlocklistDateRangePicker
dateFrom={filters.dateFrom}
dateTo={filters.dateTo}
onChange={(next) => setFilters(next)}
/>
</div>
{showClearAll && (
<div className="mt-3 flex justify-end">
<button
type="button"
onClick={clearAll}
className="inline-flex items-center gap-1.5 px-3 py-2 text-sm font-medium text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-100 rounded-lg hover:bg-gray-100 dark:hover:bg-gray-700/60 transition-colors min-h-[44px]"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
Clear all filters
</button>
</div>
)}
</div>
);
}
function SourceDropdown({
value,
onChange,
}: {
value: BlockSourceFilter;
onChange: (value: BlockSourceFilter) => void;
}) {
return (
<div>
<label className={LABEL_CLASS} htmlFor="blocklist-source-filter">Source</label>
<select
id="blocklist-source-filter"
value={value}
onChange={(e) => onChange(e.target.value as BlockSourceFilter)}
className={INPUT_CLASS}
>
{VALID_SOURCES.map((opt) => (
<option key={opt} value={opt}>
{SOURCE_LABELS[opt]}
</option>
))}
</select>
</div>
);
}
@@ -0,0 +1,129 @@
/**
* Component: BlocklistPagination
* Documentation: documentation/admin-features/release-blocklist.md
*
* Prev/next + jump-to-page + page-size selector + "Page X of Y · N total".
* Keyboard accessible. Each interactive element ≥ 44×44 touch target.
*
* Not reusing LogsPagination because that file is wired into the logs page's
* auto-refresh pause registry (useAutoRefreshControl). The blocklist page has
* no auto-refresh, so importing the logs version would force adding a
* provider for plumbing the blocklist page doesn't need.
*/
'use client';
import { useEffect, useState } from 'react';
import { VALID_LIMITS, ValidLimit, BlocklistPagination as PaginationData } from '../types';
interface BlocklistPaginationProps {
pagination: PaginationData;
onPageChange: (next: number) => void;
onLimitChange: (next: ValidLimit) => void;
}
export function BlocklistPagination({
pagination,
onPageChange,
onLimitChange,
}: BlocklistPaginationProps) {
const { page, limit, total, totalPages } = pagination;
const [jumpValue, setJumpValue] = useState(String(page));
useEffect(() => {
setJumpValue(String(page));
}, [page]);
const submitJump = () => {
const parsed = Number.parseInt(jumpValue, 10);
if (!Number.isFinite(parsed)) {
setJumpValue(String(page));
return;
}
const clamped = Math.min(Math.max(1, parsed), Math.max(1, totalPages));
if (clamped !== page) onPageChange(clamped);
setJumpValue(String(clamped));
};
return (
<div className="mt-6 flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div className="flex flex-wrap items-center gap-3 sm:gap-4 text-sm text-gray-600 dark:text-gray-400">
<span data-testid="blocklist-pagination-summary">
Page <span className="font-medium text-gray-900 dark:text-gray-100">{page}</span> of{' '}
<span className="font-medium text-gray-900 dark:text-gray-100">{Math.max(1, totalPages)}</span>
{' · '}
<span className="font-medium text-gray-900 dark:text-gray-100">
{total.toLocaleString()}
</span>{' '}
{total === 1 ? 'entry' : 'entries'}
</span>
<label className="flex items-center gap-2 text-sm">
<span className="text-gray-600 dark:text-gray-400">Per page</span>
<select
value={limit}
onChange={(e) => onLimitChange(Number(e.target.value) as ValidLimit)}
className="min-h-[44px] px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
aria-label="Page size"
>
{VALID_LIMITS.map((opt) => (
<option key={opt} value={opt}>
{opt}
</option>
))}
</select>
</label>
</div>
<div className="flex items-center gap-2">
<button
type="button"
onClick={() => onPageChange(page - 1)}
disabled={page <= 1}
className="inline-flex items-center gap-1.5 min-h-[44px] px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
aria-label="Previous page"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" />
</svg>
<span className="hidden sm:inline">Previous</span>
</button>
<label className="flex items-center gap-2">
<span className="text-sm text-gray-600 dark:text-gray-400 sr-only sm:not-sr-only">
Go to
</span>
<input
type="number"
min={1}
max={Math.max(1, totalPages)}
value={jumpValue}
onChange={(e) => setJumpValue(e.target.value)}
onBlur={submitJump}
onKeyDown={(e) => {
if (e.key === 'Enter') {
e.preventDefault();
submitJump();
}
}}
className="min-h-[44px] w-20 px-3 py-2 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm text-center"
aria-label="Jump to page"
/>
</label>
<button
type="button"
onClick={() => onPageChange(page + 1)}
disabled={page >= totalPages}
className="inline-flex items-center gap-1.5 min-h-[44px] px-4 py-2 text-sm font-medium text-gray-700 dark:text-gray-300 bg-white dark:bg-gray-700 border border-gray-300 dark:border-gray-600 rounded-lg hover:bg-gray-50 dark:hover:bg-gray-600 disabled:opacity-50 disabled:cursor-not-allowed transition-colors"
aria-label="Next page"
>
<span className="hidden sm:inline">Next</span>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
</button>
</div>
</div>
);
}
@@ -0,0 +1,284 @@
/**
* Component: Blocklist Row (desktop + mobile)
* Documentation: documentation/admin-features/release-blocklist.md
*
* Per-row Unblock is a real <button> with intentional treatment (per zach.md).
* Expand chevron explicitly discloses the long reason detail when present.
* No accidental tap targets, no surprise expansions.
*
* Release name is rendered VERBATIM from the source — chips/badges add context,
* they don't replace (per zach.md "displayed source data stays true to source").
*/
'use client';
import { useState } from 'react';
import { useToast } from '@/components/ui/Toast';
import { fetchWithAuth } from '@/lib/utils/api';
import { BlockedReleaseRow, SOURCE_BADGE_LABEL } from '../types';
interface BlocklistRowProps {
entry: BlockedReleaseRow;
/** Optimistic removal — called immediately on click so the row disappears. */
onUnblocked: (id: string) => void;
/** Called when the API call fails so the row can be reinserted. */
onUnblockFailed: (entry: BlockedReleaseRow, error: string) => void;
}
function formatTimestamp(iso: string): { absolute: string; relative: string } {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) {
return { absolute: '—', relative: '—' };
}
const absolute = d.toLocaleString([], {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
});
const diffMs = Date.now() - d.getTime();
const diffMin = Math.floor(diffMs / 60000);
let relative: string;
if (diffMin < 1) relative = 'just now';
else if (diffMin < 60) relative = `${diffMin}m ago`;
else if (diffMin < 60 * 24) relative = `${Math.floor(diffMin / 60)}h ago`;
else relative = `${Math.floor(diffMin / (60 * 24))}d ago`;
return { absolute, relative };
}
function SourceBadge({ source }: { source: string }) {
const label = SOURCE_BADGE_LABEL[source] ?? source;
const styles: Record<string, string> = {
organize_fail: 'bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-300',
download_fail: 'bg-rose-100 text-rose-800 dark:bg-rose-900/30 dark:text-rose-300',
manual: 'bg-slate-100 text-slate-800 dark:bg-slate-700 dark:text-slate-200',
};
const cls = styles[source] ?? 'bg-gray-100 text-gray-800 dark:bg-gray-700 dark:text-gray-200';
return (
<span className={`inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium ${cls}`}>
{label}
</span>
);
}
function useUnblock(
entry: BlockedReleaseRow,
onUnblocked: (id: string) => void,
onUnblockFailed: (entry: BlockedReleaseRow, error: string) => void
) {
const toast = useToast();
const [isUnblocking, setIsUnblocking] = useState(false);
const unblock = async () => {
if (isUnblocking) return;
setIsUnblocking(true);
onUnblocked(entry.id);
try {
const response = await fetchWithAuth(`/api/admin/blocklist/${entry.id}`, {
method: 'DELETE',
});
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(body.error || body.message || 'Failed to unblock');
}
toast.success(`Unblocked: ${entry.releaseName}`);
} catch (error) {
const message = error instanceof Error ? error.message : 'Failed to unblock';
onUnblockFailed(entry, message);
toast.error(message);
} finally {
setIsUnblocking(false);
}
};
return { isUnblocking, unblock };
}
function RequestRelation({ entry }: { entry: BlockedReleaseRow }) {
const r = entry.request;
if (!r || !r.audiobook) {
return <span className="text-gray-400 dark:text-gray-500"></span>;
}
return (
<div className="min-w-0">
<div className="flex items-center gap-1.5 min-w-0">
<span className="text-sm font-medium text-gray-900 dark:text-gray-100 truncate" title={r.audiobook.title}>
{r.audiobook.title}
</span>
{r.deletedAt && (
<span
className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-semibold uppercase tracking-wide bg-gray-200 text-gray-700 dark:bg-gray-700 dark:text-gray-300 flex-shrink-0"
title={`Request deleted at ${new Date(r.deletedAt).toLocaleString()}`}
>
Deleted
</span>
)}
</div>
<div className="text-xs text-gray-500 dark:text-gray-400 truncate" title={r.audiobook.author}>
{r.audiobook.author}
{r.user && <span> · {r.user.plexUsername}</span>}
</div>
</div>
);
}
function ReasonCell({
entry,
isExpanded,
onToggle,
}: {
entry: BlockedReleaseRow;
isExpanded: boolean;
onToggle: () => void;
}) {
const hasDetail = !!entry.reasonDetail && entry.reasonDetail.trim().length > 0;
return (
<div className="min-w-0">
<div className="flex items-start gap-1.5">
<p className={`text-sm text-gray-700 dark:text-gray-300 ${isExpanded ? 'whitespace-pre-wrap break-words' : 'truncate'}`}>
{entry.reason}
</p>
{hasDetail && (
<button
type="button"
onClick={onToggle}
aria-expanded={isExpanded}
aria-label={isExpanded ? 'Hide reason detail' : 'Show reason detail'}
className="flex-shrink-0 p-1.5 -my-1 rounded-md text-gray-400 hover:text-gray-700 hover:bg-gray-100 dark:text-gray-500 dark:hover:text-gray-300 dark:hover:bg-gray-700 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-500/40 transition-colors"
>
<svg
className={`w-3 h-3 transition-transform duration-200 ease-out ${isExpanded ? 'rotate-90' : ''}`}
fill="currentColor"
viewBox="0 0 20 20"
aria-hidden="true"
>
<path fillRule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clipRule="evenodd" />
</svg>
</button>
)}
</div>
{isExpanded && hasDetail && (
<pre className="mt-1.5 text-xs text-gray-600 dark:text-gray-400 whitespace-pre-wrap break-words font-mono bg-gray-50 dark:bg-gray-900/40 rounded px-2 py-1.5 border border-gray-100 dark:border-gray-700/50">
{entry.reasonDetail}
</pre>
)}
</div>
);
}
function UnblockButton({ isUnblocking, onClick }: { isUnblocking: boolean; onClick: () => void }) {
return (
<button
type="button"
onClick={onClick}
disabled={isUnblocking}
aria-label="Unblock release"
className="inline-flex items-center gap-1.5 min-h-[36px] px-3 py-1.5 text-sm font-medium text-blue-700 dark:text-blue-300 bg-blue-50 dark:bg-blue-900/30 hover:bg-blue-100 dark:hover:bg-blue-900/50 rounded-lg transition-colors disabled:opacity-50 disabled:cursor-not-allowed"
>
{isUnblocking ? (
<svg className="w-3.5 h-3.5 animate-spin" fill="none" viewBox="0 0 24 24" aria-hidden="true">
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" />
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z" />
</svg>
) : (
<svg className="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 13l4 4L19 7" />
</svg>
)}
<span>Unblock</span>
</button>
);
}
// ---------------------------------------------------------------------------
// Desktop row — <tr>
// ---------------------------------------------------------------------------
function DesktopRow({ entry, onUnblocked, onUnblockFailed }: BlocklistRowProps) {
const { isUnblocking, unblock } = useUnblock(entry, onUnblocked, onUnblockFailed);
const [reasonExpanded, setReasonExpanded] = useState(false);
const { absolute, relative } = formatTimestamp(entry.createdAt);
return (
<tr className="hover:bg-gray-50 dark:hover:bg-gray-900/40 transition-colors">
<td className="px-6 py-4 align-top">
<p
className="text-sm font-medium text-gray-900 dark:text-gray-100 break-words"
title={entry.releaseName}
>
{entry.releaseName}
</p>
</td>
<td className="px-6 py-4 align-top">
<ReasonCell entry={entry} isExpanded={reasonExpanded} onToggle={() => setReasonExpanded((v) => !v)} />
</td>
<td className="px-6 py-4 align-top">
<SourceBadge source={entry.source} />
</td>
<td className="px-6 py-4 align-top">
<RequestRelation entry={entry} />
</td>
<td className="px-6 py-4 align-top text-sm text-gray-700 dark:text-gray-300">
{entry.indexerName ?? <span className="text-gray-400 dark:text-gray-500"></span>}
</td>
<td className="px-6 py-4 align-top text-sm text-gray-500 dark:text-gray-400" title={absolute}>
{relative}
</td>
<td className="px-6 py-4 align-top text-right">
<UnblockButton isUnblocking={isUnblocking} onClick={unblock} />
</td>
</tr>
);
}
// ---------------------------------------------------------------------------
// Mobile card
// ---------------------------------------------------------------------------
function MobileRow({ entry, onUnblocked, onUnblockFailed }: BlocklistRowProps) {
const { isUnblocking, unblock } = useUnblock(entry, onUnblocked, onUnblockFailed);
const [reasonExpanded, setReasonExpanded] = useState(false);
const { absolute, relative } = formatTimestamp(entry.createdAt);
return (
<div className="bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-lg p-4 space-y-3">
<div className="flex items-start justify-between gap-3">
<div className="flex items-center gap-2 flex-wrap">
<SourceBadge source={entry.source} />
<span className="text-xs text-gray-500 dark:text-gray-400" title={absolute}>
{relative}
</span>
</div>
<UnblockButton isUnblocking={isUnblocking} onClick={unblock} />
</div>
<p
className="text-sm font-medium text-gray-900 dark:text-gray-100 break-words"
title={entry.releaseName}
>
{entry.releaseName}
</p>
<ReasonCell entry={entry} isExpanded={reasonExpanded} onToggle={() => setReasonExpanded((v) => !v)} />
{entry.request?.audiobook && (
<div className="pt-2 border-t border-gray-100 dark:border-gray-700/60">
<p className="text-[10px] uppercase tracking-wide font-semibold text-gray-400 dark:text-gray-500 mb-0.5">
Associated request
</p>
<RequestRelation entry={entry} />
</div>
)}
{entry.indexerName && (
<p className="text-xs text-gray-500 dark:text-gray-400">
Indexer: <span className="font-medium text-gray-700 dark:text-gray-300">{entry.indexerName}</span>
</p>
)}
</div>
);
}
export const BlocklistRow = {
Desktop: DesktopRow,
Mobile: MobileRow,
};
@@ -0,0 +1,20 @@
/**
* Component: Blocklist Skeleton
* Documentation: documentation/admin-features/release-blocklist.md
*/
export function BlocklistSkeleton() {
return (
<div className="space-y-2" data-testid="blocklist-skeleton">
{Array.from({ length: 6 }).map((_, i) => (
<div
key={i}
className="bg-white dark:bg-gray-800 rounded-lg border border-gray-200 dark:border-gray-700 p-4 animate-pulse"
>
<div className="h-4 bg-gray-200 dark:bg-gray-700 rounded w-3/4 mb-2" />
<div className="h-3 bg-gray-100 dark:bg-gray-700/60 rounded w-1/2" />
</div>
))}
</div>
);
}
@@ -0,0 +1,130 @@
/**
* Component: BlocklistTable
* Documentation: documentation/admin-features/release-blocklist.md
*
* Desktop = sortable table, mobile = stacked cards. Sortable columns clickable
* with explicit affordance (cursor + sort icon) — per zach.md UX rule on
* intentional affordances.
*/
'use client';
import { useBlocklistUrlState } from '../hooks/useBlocklistUrlState';
import { BlockedReleaseRow, SortField } from '../types';
import { BlocklistRow } from './BlocklistRow';
interface BlocklistTableProps {
entries: BlockedReleaseRow[];
onUnblocked: (id: string) => void;
onUnblockFailed: (entry: BlockedReleaseRow, error: string) => void;
}
interface SortableHeaderProps {
field: SortField;
label: string;
className?: string;
}
function SortableHeader({ field, label, className = '' }: SortableHeaderProps) {
const { filters, setFilters } = useBlocklistUrlState();
const isActive = filters.sortBy === field;
const order = filters.sortOrder;
const handleClick = () => {
if (isActive) {
setFilters({ sortOrder: order === 'asc' ? 'desc' : 'asc' });
} else {
setFilters({ sortBy: field, sortOrder: 'desc' });
}
};
return (
<th
className={`px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider ${className}`}
>
<button
type="button"
onClick={handleClick}
className="inline-flex items-center gap-1.5 hover:text-gray-900 dark:hover:text-gray-100 transition-colors uppercase tracking-wider font-medium"
aria-label={`Sort by ${label}`}
>
{label}
<SortGlyph active={isActive} order={order} />
</button>
</th>
);
}
function SortGlyph({ active, order }: { active: boolean; order: 'asc' | 'desc' }) {
if (!active) {
return (
<svg className="w-3.5 h-3.5 text-gray-300 dark:text-gray-600" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 9l4-4 4 4m0 6l-4 4-4-4" />
</svg>
);
}
return order === 'asc' ? (
<svg className="w-3.5 h-3.5 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M5 15l7-7 7 7" />
</svg>
) : (
<svg className="w-3.5 h-3.5 text-blue-600 dark:text-blue-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
</svg>
);
}
export function BlocklistTable({ entries, onUnblocked, onUnblockFailed }: BlocklistTableProps) {
return (
<>
{/* Mobile cards */}
<div className="space-y-3 sm:hidden">
{entries.map((entry) => (
<BlocklistRow.Mobile
key={entry.id}
entry={entry}
onUnblocked={onUnblocked}
onUnblockFailed={onUnblockFailed}
/>
))}
</div>
{/* Desktop table */}
<div className="hidden sm:block bg-white dark:bg-gray-800 rounded-lg shadow overflow-hidden">
<div className="overflow-x-auto">
<table className="min-w-full divide-y divide-gray-200 dark:divide-gray-700">
<thead className="bg-gray-50 dark:bg-gray-900">
<tr>
<SortableHeader field="releaseName" label="Release name" />
<SortableHeader field="reason" label="Reason" />
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Source
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Associated request
</th>
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Indexer
</th>
<SortableHeader field="createdAt" label="Blocked at" />
<th className="px-6 py-3 text-right text-xs font-medium text-gray-500 dark:text-gray-400 uppercase tracking-wider">
Actions
</th>
</tr>
</thead>
<tbody className="bg-white dark:bg-gray-800 divide-y divide-gray-200 dark:divide-gray-700">
{entries.map((entry) => (
<BlocklistRow.Desktop
key={entry.id}
entry={entry}
onUnblocked={onUnblocked}
onUnblockFailed={onUnblockFailed}
/>
))}
</tbody>
</table>
</div>
</div>
</>
);
}
@@ -0,0 +1,131 @@
/**
* Component: BlocklistToolbar
* Documentation: documentation/admin-features/release-blocklist.md
*
* Sticky header with title, back-to-dashboard link, search input, and a
* "Clear filtered (N)" affordance that opens the typed-token confirm modal.
*
* The "Clear filtered" button is intentionally visible AND distinct (red-tinted)
* per zach.md UX rule: "UI affordances must be visibly intentional. First-time
* user should grok what's tappable from the design."
*/
'use client';
import Link from 'next/link';
import { useState } from 'react';
import { useBlocklistUrlState } from '../hooks/useBlocklistUrlState';
import {
BlocklistFilterState,
buildBulkClearQueryString,
hasActiveFilters,
hasActiveSearch,
} from '../types';
import { ClearFilteredConfirmModal } from './ClearFilteredConfirmModal';
interface BlocklistToolbarProps {
/** Total rows matching current filters (drives "Clear filtered (N)" label). */
total: number;
/** Called after successful bulk clear so the page can refresh data. */
onCleared: () => void;
}
export function BlocklistToolbar({ total, onCleared }: BlocklistToolbarProps) {
const { filters, searchInput, setSearchInput, removeFilter } = useBlocklistUrlState();
const [confirmOpen, setConfirmOpen] = useState(false);
const filtersActive = hasActiveFilters(filters) || hasActiveSearch(filters);
const canClear = total > 0;
return (
<div className="sticky top-0 z-10 mb-6 sm:mb-8 bg-gray-50 dark:bg-gray-900 py-4 -mx-4 px-4 sm:-mx-6 sm:px-6 lg:-mx-8 lg:px-8 border-b border-gray-200 dark:border-gray-800">
{/* Row 1: title + back link */}
<div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between">
<div>
<h1 className="text-2xl sm:text-3xl font-bold text-gray-900 dark:text-gray-100">
Release Blocklist
</h1>
<p className="text-sm text-gray-600 dark:text-gray-400 mt-1">
Releases auto-blocked from download or organize failures. Unblock to allow re-grabbing.
</p>
</div>
<Link
href="/admin"
className="inline-flex items-center gap-2 min-h-[44px] px-4 py-2.5 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-900 dark:text-gray-100 rounded-lg transition-colors text-sm font-medium self-start sm:self-auto flex-shrink-0"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10 19l-7-7m0 0l7-7m-7 7h18" />
</svg>
<span>Back to Dashboard</span>
</Link>
</div>
{/* Row 2: "Clear filtered (N)" button — only when something would be cleared */}
{canClear && (
<div className="flex flex-wrap items-center gap-2 mt-4">
<button
type="button"
onClick={() => setConfirmOpen(true)}
className="inline-flex items-center gap-1.5 min-h-[44px] px-3.5 py-2 rounded-lg text-sm font-medium bg-red-50 text-red-700 hover:bg-red-100 dark:bg-red-900/20 dark:text-red-300 dark:hover:bg-red-900/40 transition-colors"
aria-label={
filtersActive
? `Clear ${total} filtered blocklist entries`
: `Clear all ${total} blocklist entries`
}
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
</svg>
{filtersActive ? `Clear filtered (${total.toLocaleString()})` : `Clear all (${total.toLocaleString()})`}
</button>
<span className="text-xs text-gray-500 dark:text-gray-400">
{filtersActive
? 'Unblocks every entry matching the current filters.'
: 'Unblocks every entry. Apply a filter first to scope.'}
</span>
</div>
)}
{/* Row 3: search input */}
<div className="mt-3 relative">
<span className="pointer-events-none absolute inset-y-0 left-3 flex items-center">
<svg className="w-4 h-4 text-gray-400" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-5.197-5.197m0 0A7.5 7.5 0 105.196 5.196a7.5 7.5 0 0010.607 10.607z" />
</svg>
</span>
<input
type="search"
value={searchInput}
onChange={(e) => setSearchInput(e.target.value)}
placeholder="Search release name or reason…"
aria-label="Search blocklist"
className="w-full min-h-[44px] pl-9 pr-10 py-2.5 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-blue-500 text-sm"
/>
{searchInput && (
<button
type="button"
onClick={() => {
setSearchInput('');
removeFilter('search');
}}
aria-label="Clear search"
className="absolute inset-y-0 right-2 my-auto inline-flex items-center justify-center w-8 h-8 rounded-full text-gray-400 hover:text-gray-700 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-700 transition-colors"
>
<svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
</svg>
</button>
)}
</div>
<ClearFilteredConfirmModal
isOpen={confirmOpen}
onClose={() => setConfirmOpen(false)}
onCleared={onCleared}
total={total}
filtersActive={filtersActive}
queryString={buildBulkClearQueryString(filters as BlocklistFilterState)}
/>
</div>
);
}
@@ -0,0 +1,135 @@
/**
* Component: Clear Filtered Confirm Modal
* Documentation: documentation/admin-features/release-blocklist.md
*
* Bulk-clear guardrail: admin must type "CLEAR" before the destructive button
* activates. UI-only friction (not a server security boundary — auth+admin is).
* Per product brief: "red confirmation modal, requires typing 'CLEAR' or similar."
*/
'use client';
import { useEffect, useState } from 'react';
import { Modal } from '@/components/ui/Modal';
import { Button } from '@/components/ui/Button';
import { useToast } from '@/components/ui/Toast';
import { fetchWithAuth } from '@/lib/utils/api';
const REQUIRED_TOKEN = 'CLEAR';
interface ClearFilteredConfirmModalProps {
isOpen: boolean;
onClose: () => void;
onCleared: () => void;
total: number;
filtersActive: boolean;
/** Pre-built filter query string (no page/limit/sort) — DELETE body. */
queryString: string;
}
export function ClearFilteredConfirmModal({
isOpen,
onClose,
onCleared,
total,
filtersActive,
queryString,
}: ClearFilteredConfirmModalProps) {
const toast = useToast();
const [token, setToken] = useState('');
const [isClearing, setIsClearing] = useState(false);
// Reset typed token whenever the modal opens.
useEffect(() => {
if (isOpen) setToken('');
}, [isOpen]);
const canConfirm = token.trim().toUpperCase() === REQUIRED_TOKEN && !isClearing;
const handleConfirm = async () => {
if (!canConfirm) return;
setIsClearing(true);
try {
const url = queryString
? `/api/admin/blocklist?${queryString}`
: '/api/admin/blocklist';
const response = await fetchWithAuth(url, { method: 'DELETE' });
if (!response.ok) {
const body = await response.json().catch(() => ({}));
throw new Error(body.error || 'Failed to clear blocklist');
}
const { count } = await response.json();
toast.success(
count === 1
? 'Unblocked 1 release'
: `Unblocked ${count.toLocaleString()} releases`
);
onCleared();
onClose();
} catch (error) {
toast.error(
error instanceof Error ? error.message : 'Failed to clear blocklist'
);
} finally {
setIsClearing(false);
}
};
const title = filtersActive ? 'Clear filtered entries' : 'Clear all entries';
const description = filtersActive
? `This will unblock ${total.toLocaleString()} ${total === 1 ? 'release' : 'releases'} matching the current filters. Future searches will be free to grab them again.`
: `This will unblock all ${total.toLocaleString()} ${total === 1 ? 'release' : 'releases'} in the blocklist. Future searches will be free to grab them again.`;
return (
<Modal isOpen={isOpen} onClose={isClearing ? () => {} : onClose} title={title} size="sm" showCloseButton={false}>
<div className="space-y-5">
<p className="text-sm text-gray-700 dark:text-gray-300 leading-relaxed">
{description}
</p>
<div className="rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800/60 px-4 py-3">
<p className="text-sm font-medium text-red-800 dark:text-red-200">
This cannot be undone.
</p>
<p className="text-xs text-red-700 dark:text-red-300 mt-1">
Type <span className="font-mono font-bold">CLEAR</span> below to confirm.
</p>
</div>
<div>
<label
htmlFor="blocklist-clear-token"
className="block text-xs font-semibold text-gray-500 dark:text-gray-400 uppercase tracking-wide mb-1.5"
>
Confirmation
</label>
<input
id="blocklist-clear-token"
type="text"
value={token}
onChange={(e) => setToken(e.target.value)}
disabled={isClearing}
autoComplete="off"
placeholder="Type CLEAR"
aria-label="Type CLEAR to confirm"
className="w-full px-3 py-2.5 bg-white dark:bg-gray-700 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-lg focus:ring-2 focus:ring-red-500 focus:outline-none text-sm font-mono uppercase min-h-[44px]"
/>
</div>
<div className="flex gap-3 justify-end">
<Button onClick={onClose} variant="outline" disabled={isClearing}>
Cancel
</Button>
<Button
onClick={handleConfirm}
variant="danger"
loading={isClearing}
disabled={!canConfirm}
>
{filtersActive ? `Clear ${total.toLocaleString()}` : `Clear all ${total.toLocaleString()}`}
</Button>
</div>
</div>
</Modal>
);
}