Refactor media storage and management functionalities: enhance IMediaStorage interface with manual inbox handling, update FileSystemMediaStorage to support manual file imports, and improve MediaPathResolver for better path management. Extend MediaEndpoints to include new manual inbox features and update frontend components for improved media management experience.
build / backend (push) Successful in 2m8s
build / frontend (push) Successful in 36s
tests / backend-tests (push) Successful in 1m35s

This commit is contained in:
Leonid Pershin
2026-07-26 15:16:55 +03:00
parent 2445ba56b5
commit b602d099ca
16 changed files with 1750 additions and 1039 deletions
@@ -0,0 +1,189 @@
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query'
import { useState } from 'react'
import { useTranslation } from 'react-i18next'
import { listShows } from '@/features/admin/shows/api'
import { HttpError } from '@/shared/api/client'
import { Badge } from '@/shared/ui/badge'
import { Button } from '@/shared/ui/button'
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/shared/ui/dialog'
import { Input } from '@/shared/ui/input'
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/shared/ui/select'
import { toast } from '@/shared/ui/toast-store'
import { importManualInbox, listManualInbox } from './api'
/** Байты → «1,4 ГБ»: в ручном разборе размер — главный ориентир, что это за файл. */
function formatSize(bytes: number): string {
const units = ['Б', 'КБ', 'МБ', 'ГБ', 'ТБ']
let value = bytes
let unit = 0
while (value >= 1024 && unit < units.length - 1) {
value /= 1024
unit++
}
return `${value.toFixed(value >= 10 || unit === 0 ? 0 : 1)} ${units[unit]}`
}
/**
* Ручной inbox (см. `manual/`): каталог не сканируется, файлы выбирает админ и сразу указывает шоу.
* Импортированные файлы уходят из каталога — ровно как из обычного inbox.
*/
export function ManualInboxDialog({ onClose }: { onClose: () => void }) {
const { t } = useTranslation()
const queryClient = useQueryClient()
const [selected, setSelected] = useState<string[]>([])
const [showId, setShowId] = useState('')
const [query, setQuery] = useState('')
const { data, isLoading } = useQuery({
queryKey: ['admin', 'media', 'manual'],
queryFn: listManualInbox,
})
const { data: shows } = useQuery({ queryKey: ['admin', 'shows'], queryFn: () => listShows() })
const importMutation = useMutation({
mutationFn: () => importManualInbox(selected, showId),
onSuccess: (result) => {
if (result.imported > 0)
toast.success(t('admin.media.manualImported', { count: result.imported }))
// Отказы показываем по одному: у каждого своя причина, и файл остаётся в каталоге.
for (const failure of result.failed)
toast.error(`${failure.relativePath}: ${failure.reason}`)
setSelected([])
void queryClient.invalidateQueries({ queryKey: ['admin', 'media'] })
void queryClient.invalidateQueries({ queryKey: ['admin', 'shows'] })
if (result.failed.length === 0) onClose()
},
onError: (error: unknown) =>
toast.error(error instanceof HttpError ? error.detail : t('common.error')),
})
const files = (data?.files ?? []).filter((file) =>
query.trim() ? file.relativePath.toLowerCase().includes(query.trim().toLowerCase()) : true,
)
const importable = files.filter((f) => f.isSupported && !f.alreadyImported)
const toggle = (path: string) =>
setSelected((current) =>
current.includes(path) ? current.filter((p) => p !== path) : [...current, path],
)
return (
<Dialog open onOpenChange={(open) => !open && onClose()}>
<DialogContent className="max-w-3xl">
<DialogHeader>
<DialogTitle>{t('admin.media.manualTitle')}</DialogTitle>
<DialogDescription>{t('admin.media.manualHint')}</DialogDescription>
</DialogHeader>
<div className="flex flex-col gap-3">
<div className="flex flex-wrap items-center gap-2">
<Input
className="max-w-xs"
placeholder={t('common.search')}
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<Button
size="sm"
variant="outline"
disabled={importable.length === 0}
onClick={() =>
setSelected(
selected.length === importable.length
? []
: importable.map((f) => f.relativePath),
)
}
>
{t('admin.media.manualSelectAll')}
</Button>
<span className="text-xs text-muted-foreground">
{t('admin.media.manualSelected', { count: selected.length })}
</span>
</div>
<ul className="crt-panel max-h-80 divide-y divide-border overflow-y-auto rounded-md text-sm">
{isLoading && (
<li className="px-3 py-2 text-muted-foreground">{t('common.loading')}</li>
)}
{!isLoading && files.length === 0 && (
<li className="px-3 py-2 text-muted-foreground">{t('admin.media.manualEmpty')}</li>
)}
{files.map((file) => {
const blocked = !file.isSupported || file.alreadyImported
return (
<li key={file.relativePath} className="flex items-center gap-2 px-3 py-1.5">
<input
type="checkbox"
className="shrink-0"
disabled={blocked}
checked={selected.includes(file.relativePath)}
onChange={() => toggle(file.relativePath)}
/>
<span
className={`min-w-0 flex-1 truncate ${blocked ? 'text-muted-foreground' : ''}`}
title={file.relativePath}
>
{file.relativePath}
</span>
{!file.isSupported && (
<Badge variant="muted">{t('admin.media.manualUnsupported')}</Badge>
)}
{file.alreadyImported && (
<Badge variant="muted">{t('admin.media.manualAlready')}</Badge>
)}
<span className="shrink-0 tabular-nums text-muted-foreground">
{formatSize(file.sizeBytes)}
</span>
</li>
)
})}
</ul>
{data?.truncated && (
<p className="text-xs text-amber-500">{t('admin.media.manualTruncated')}</p>
)}
<div className="flex flex-wrap items-center gap-2">
<Select value={showId} onValueChange={setShowId}>
<SelectTrigger className="w-72">
<SelectValue placeholder={t('admin.media.manualPickShow')} />
</SelectTrigger>
<SelectContent>
{(shows ?? []).map((show) => (
<SelectItem key={show.id} value={show.id}>
{show.name}
</SelectItem>
))}
</SelectContent>
</Select>
<span className="text-xs text-muted-foreground">
{t('admin.media.manualOrderHint')}
</span>
</div>
</div>
<DialogFooter>
<Button size="sm" variant="outline" onClick={onClose}>
{t('common.cancel')}
</Button>
<Button
size="sm"
disabled={selected.length === 0 || !showId || importMutation.isPending}
onClick={() => importMutation.mutate()}
>
{t('admin.media.manualImport')}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)
}