Lock down access control and add image previews, file locations and cropping to the CMS.
Security: - only admins can assign user roles; profile updates are whitelisted - SBP payment confirmation requires an HMAC-signed webhook or an admin, and is idempotent - patient receipts and documents are private media owned by the patient, downloaded via the site - patients cannot change booking price or payment status, forge invoices or write for other accounts CMS images: - every upload field shows a large preview, focal point, server file path and public URL - crop/resize keeps the original in media/originals with a "restore original" action - legacy image URL fields show where the file really lives and can be moved into the media library - specialties get a visual icon picker (Untitled UI) and an optional custom icon upload Fixes: saving the cabinet profile, receipt PDF generation, uploaded doctor photos on the site. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
959e693dcc
commit
0b447e67bf
@@ -0,0 +1,116 @@
|
||||
'use client'
|
||||
|
||||
import React, { useMemo, useState } from 'react'
|
||||
import type { TextFieldClientComponent } from 'payload'
|
||||
import { FieldDescription, FieldError, FieldLabel, useField } from '@payloadcms/ui'
|
||||
import * as Icons from '@untitledui/icons'
|
||||
import { iconComponentName, iconKebabName, MEDICAL_ICONS, resolveIconName } from '../../lib/icons'
|
||||
|
||||
type IconComponent = React.ComponentType<{ size?: number; className?: string; 'aria-hidden'?: boolean }>
|
||||
const ICONS = Icons as unknown as Record<string, IconComponent>
|
||||
const ALL_NAMES = Object.keys(ICONS)
|
||||
.filter((name) => /^[A-Z]/.test(name) && typeof ICONS[name] !== 'undefined')
|
||||
.sort()
|
||||
|
||||
const tile = (selected: boolean): React.CSSProperties => ({
|
||||
width: 48,
|
||||
height: 48,
|
||||
borderRadius: 10,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
cursor: 'pointer',
|
||||
border: selected ? '2px solid var(--theme-success-500)' : '1px solid var(--theme-elevation-150)',
|
||||
background: selected ? 'var(--theme-success-50)' : 'var(--theme-elevation-0)',
|
||||
color: 'var(--theme-elevation-800)',
|
||||
padding: 0,
|
||||
})
|
||||
|
||||
/** Visual icon picker for «Направления»: preview as on the site, curated medical set and search. */
|
||||
export const IconPicker: TextFieldClientComponent = ({ field, path, readOnly }) => {
|
||||
const { value, setValue, errorMessage, showError } = useField<string>({ path })
|
||||
const [query, setQuery] = useState('')
|
||||
const current = resolveIconName(value, ICONS)
|
||||
const Current = current ? ICONS[current] : null
|
||||
|
||||
const results = useMemo(() => {
|
||||
const q = query.trim().toLowerCase().replace(/\s+/g, '-')
|
||||
if (!q) return MEDICAL_ICONS.map((n) => iconComponentName(n)).filter((n) => n in ICONS)
|
||||
return ALL_NAMES.filter((n) => iconKebabName(n).includes(q)).slice(0, 80)
|
||||
}, [query])
|
||||
|
||||
const label = typeof field.label === 'string' ? field.label : 'Иконка'
|
||||
|
||||
return (
|
||||
<div className="field-type text" style={{ marginBottom: 24 }}>
|
||||
<FieldLabel label={label} path={path} />
|
||||
<div style={{ display: 'flex', gap: 20, alignItems: 'flex-start', flexWrap: 'wrap' }}>
|
||||
<div style={{ textAlign: 'center' }}>
|
||||
<div
|
||||
style={{
|
||||
width: 88,
|
||||
height: 88,
|
||||
borderRadius: 16,
|
||||
background: 'var(--theme-elevation-100)',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
color: 'var(--theme-elevation-900)',
|
||||
}}
|
||||
>
|
||||
{Current ? <Current size={44} aria-hidden /> : <span style={{ fontSize: 12 }}>нет</span>}
|
||||
</div>
|
||||
<p style={{ fontSize: 11, margin: '6px 0 0', color: 'var(--theme-elevation-500)' }}>
|
||||
{current ? iconKebabName(current) : value ? `«${value}» не найдена` : 'не выбрана'}
|
||||
</p>
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 280 }}>
|
||||
<input
|
||||
type="search"
|
||||
placeholder="Поиск по всем иконкам: heart, eye, user…"
|
||||
value={query}
|
||||
disabled={Boolean(readOnly)}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
style={{ marginBottom: 10 }}
|
||||
/>
|
||||
<div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
|
||||
{results.map((name) => {
|
||||
const Icon = ICONS[name]
|
||||
const kebab = iconKebabName(name)
|
||||
return (
|
||||
<button
|
||||
key={name}
|
||||
type="button"
|
||||
title={kebab}
|
||||
aria-label={kebab}
|
||||
aria-pressed={current === name}
|
||||
disabled={Boolean(readOnly)}
|
||||
onClick={() => setValue(kebab)}
|
||||
style={tile(current === name)}
|
||||
>
|
||||
<Icon size={22} aria-hidden />
|
||||
</button>
|
||||
)
|
||||
})}
|
||||
{!results.length ? (
|
||||
<span style={{ fontSize: 13, color: 'var(--theme-elevation-500)' }}>Ничего не найдено</span>
|
||||
) : null}
|
||||
</div>
|
||||
{value ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--style-secondary btn--size-small"
|
||||
style={{ marginTop: 10 }}
|
||||
disabled={Boolean(readOnly)}
|
||||
onClick={() => setValue('')}
|
||||
>
|
||||
Убрать иконку
|
||||
</button>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
<FieldError message={errorMessage} path={path} showError={showError} />
|
||||
{field.admin?.description ? <FieldDescription description={field.admin.description} path={path} /> : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,132 @@
|
||||
'use client'
|
||||
|
||||
import React, { useEffect, useState } from 'react'
|
||||
import { toast, useField } from '@payloadcms/ui'
|
||||
import { formatBytes, MediaCard } from './media-ui/MediaCard'
|
||||
|
||||
type Resolved = {
|
||||
url: string
|
||||
previewUrl: string
|
||||
localPath: string | null
|
||||
where: string
|
||||
exists: boolean
|
||||
size: number | null
|
||||
remote: boolean
|
||||
}
|
||||
|
||||
const MIME_BY_EXT: Record<string, string> = {
|
||||
jpg: 'image/jpeg',
|
||||
jpeg: 'image/jpeg',
|
||||
png: 'image/png',
|
||||
webp: 'image/webp',
|
||||
gif: 'image/gif',
|
||||
svg: 'image/svg+xml',
|
||||
avif: 'image/avif',
|
||||
mp4: 'video/mp4',
|
||||
webm: 'video/webm',
|
||||
mov: 'video/quicktime',
|
||||
}
|
||||
|
||||
function guessMime(url: string) {
|
||||
const ext = url.split(/[?#]/)[0].split('.').pop()?.toLowerCase() || ''
|
||||
return MIME_BY_EXT[ext] || 'image/jpeg'
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown under legacy "URL фото" fields: preview of the linked file, where it really lives
|
||||
* (apps/web/public/... or the remote address) and a button that moves it into the media library
|
||||
* so it gets the normal preview and editor.
|
||||
*/
|
||||
export function LegacyUrlPreview({
|
||||
path,
|
||||
field,
|
||||
}: {
|
||||
path: string
|
||||
field?: { admin?: { custom?: { uploadField?: string } } }
|
||||
}) {
|
||||
const { value, setValue } = useField<string>({ path })
|
||||
const uploadName = field?.admin?.custom?.uploadField
|
||||
const uploadPath = uploadName ? path.replace(/[^.]+$/, uploadName) : ''
|
||||
const upload = useField<unknown>({ path: uploadPath || path })
|
||||
const [resolved, setResolved] = useState<Resolved | null>(null)
|
||||
const [error, setError] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
const url = (value || '').trim()
|
||||
setResolved(null)
|
||||
setError('')
|
||||
if (!url) return
|
||||
const timer = setTimeout(async () => {
|
||||
const res = await fetch(`/api/custom/media-tools/resolve-url?url=${encodeURIComponent(url)}`, {
|
||||
credentials: 'include',
|
||||
})
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (res.ok) setResolved(data as Resolved)
|
||||
else setError(data.error || 'Не удалось разобрать ссылку')
|
||||
}, 300)
|
||||
return () => clearTimeout(timer)
|
||||
}, [value])
|
||||
|
||||
if (!value) return null
|
||||
if (error) return <p style={{ fontSize: 12, color: 'var(--theme-error-500)' }}>{error}</p>
|
||||
if (!resolved) return null
|
||||
|
||||
const where = resolved.remote ? 'Внешняя ссылка' : resolved.exists ? 'Где лежит файл' : 'Файл не найден'
|
||||
|
||||
return (
|
||||
<MediaCard
|
||||
info={{
|
||||
previewUrl: resolved.exists ? resolved.previewUrl : null,
|
||||
publicUrl: resolved.previewUrl,
|
||||
storagePath: null,
|
||||
mimeType: guessMime(resolved.url),
|
||||
filesize: resolved.size,
|
||||
}}
|
||||
actions={
|
||||
uploadPath ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--style-primary btn--size-small"
|
||||
style={{ margin: 0 }}
|
||||
disabled={busy || (!resolved.remote && !resolved.exists)}
|
||||
onClick={async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
const res = await fetch('/api/custom/media-tools/import-url', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ url: resolved.url }),
|
||||
})
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось перенести файл')
|
||||
upload.setValue(data.doc.id)
|
||||
setValue('')
|
||||
toast.success('Файл перенесён в медиатеку. Сохраните документ.')
|
||||
} catch (e) {
|
||||
toast.error(e instanceof Error ? e.message : 'Ошибка')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
Перенести в медиатеку
|
||||
</button>
|
||||
) : null
|
||||
}
|
||||
notice={
|
||||
<div style={{ marginTop: 10, display: 'grid', gap: 4, fontSize: 12 }}>
|
||||
<span style={{ color: 'var(--theme-elevation-500)' }}>{where}</span>
|
||||
<code style={{ wordBreak: 'break-all' }}>
|
||||
{resolved.remote ? resolved.url : resolved.localPath || resolved.where}
|
||||
</code>
|
||||
{resolved.size ? <span style={{ color: 'var(--theme-elevation-500)' }}>{formatBytes(resolved.size)}</span> : null}
|
||||
<span style={{ color: 'var(--theme-elevation-500)' }}>
|
||||
Это старая ссылка на файл. Чтобы обрезать фото или поменять точку фокуса, перенесите его в медиатеку.
|
||||
</span>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
'use client'
|
||||
|
||||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import { toast, useDocumentInfo } from '@payloadcms/ui'
|
||||
import { CopyRow, fetchMediaDoc, mediaInfo, restoreOriginal, type MediaDoc } from './media-ui/MediaCard'
|
||||
|
||||
/** Sidebar of a media file: exact file location, public address and "restore original". */
|
||||
export function MediaLocation() {
|
||||
const { id, lastUpdateTime } = useDocumentInfo() as { id?: number | string; lastUpdateTime?: number }
|
||||
const [doc, setDoc] = useState<MediaDoc | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (id == null) return setDoc(null)
|
||||
setDoc(await fetchMediaDoc(id))
|
||||
}, [id])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load, lastUpdateTime])
|
||||
|
||||
if (!doc) return null
|
||||
const info = mediaInfo(doc)
|
||||
|
||||
return (
|
||||
<div style={{ display: 'grid', gap: 10, marginBottom: 24 }}>
|
||||
{info.storagePath ? <CopyRow title="Где лежит файл" value={info.storagePath} /> : null}
|
||||
{info.publicUrl ? <CopyRow title="Адрес на сайте" value={info.publicUrl} /> : null}
|
||||
{info.originalPath ? (
|
||||
<>
|
||||
<CopyRow title="Оригинал до редактирования" value={info.originalPath} />
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--style-secondary btn--size-small"
|
||||
style={{ margin: 0 }}
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await restoreOriginal(doc.id)
|
||||
toast.success('Оригинал восстановлен, обновите страницу')
|
||||
await load()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'Ошибка')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
Вернуть оригинал
|
||||
</button>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
'use client'
|
||||
|
||||
import React, { useCallback, useEffect, useState } from 'react'
|
||||
import { toast, useDocumentDrawer, useField } from '@payloadcms/ui'
|
||||
import { fetchMediaDoc, MediaCard, mediaInfo, restoreOriginal, type MediaDoc } from './media-ui/MediaCard'
|
||||
|
||||
function relationId(value: unknown): number | string | null {
|
||||
if (value == null || value === '') return null
|
||||
if (typeof value === 'object') {
|
||||
const id = (value as { id?: unknown; value?: unknown }).id ?? (value as { value?: unknown }).value
|
||||
return typeof id === 'string' || typeof id === 'number' ? id : null
|
||||
}
|
||||
return typeof value === 'string' || typeof value === 'number' ? value : null
|
||||
}
|
||||
|
||||
/**
|
||||
* Shown under every upload field: large preview, where the file lives on the server,
|
||||
* its public address, and quick access to the image editor (crop / size / focal point).
|
||||
*/
|
||||
export function MediaPreview({ path }: { path: string }) {
|
||||
const { value } = useField<unknown>({ path })
|
||||
const id = relationId(value)
|
||||
const [doc, setDoc] = useState<MediaDoc | null>(null)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
const load = useCallback(async () => {
|
||||
if (id == null) return setDoc(null)
|
||||
setDoc(await fetchMediaDoc(id))
|
||||
}, [id])
|
||||
|
||||
useEffect(() => {
|
||||
void load()
|
||||
}, [load])
|
||||
|
||||
const [EditDrawer, , { openDrawer }] = useDocumentDrawer({
|
||||
collectionSlug: 'media',
|
||||
id: id == null ? undefined : Number(id),
|
||||
})
|
||||
|
||||
if (id == null || !doc) return null
|
||||
const info = mediaInfo(doc)
|
||||
const isImage = Boolean(doc.mimeType?.startsWith('image/'))
|
||||
|
||||
return (
|
||||
<>
|
||||
<MediaCard
|
||||
info={info}
|
||||
actions={
|
||||
<>
|
||||
<button type="button" className="btn btn--style-primary btn--size-small" style={{ margin: 0 }} onClick={openDrawer}>
|
||||
{isImage ? 'Редактировать изображение' : 'Открыть файл'}
|
||||
</button>
|
||||
{doc.originalFile ? (
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--style-secondary btn--size-small"
|
||||
style={{ margin: 0 }}
|
||||
disabled={busy}
|
||||
onClick={async () => {
|
||||
setBusy(true)
|
||||
try {
|
||||
await restoreOriginal(doc.id)
|
||||
toast.success('Оригинал восстановлен')
|
||||
await load()
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : 'Ошибка')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}}
|
||||
>
|
||||
Вернуть оригинал
|
||||
</button>
|
||||
) : null}
|
||||
</>
|
||||
}
|
||||
notice={
|
||||
isImage ? (
|
||||
<p style={{ margin: '10px 0 0', fontSize: 12, color: 'var(--theme-elevation-500)' }}>
|
||||
В редакторе нажмите «Редактировать изображение»: кадрирование, размер в пикселях и точка фокуса.
|
||||
Оригинал сохраняется перед первой обрезкой.
|
||||
</p>
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
<EditDrawer onSave={() => void load()} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,204 @@
|
||||
'use client'
|
||||
|
||||
import React, { useState } from 'react'
|
||||
|
||||
export type MediaInfo = {
|
||||
previewUrl?: string | null
|
||||
publicUrl?: string | null
|
||||
storagePath?: string | null
|
||||
originalPath?: string | null
|
||||
mimeType?: string | null
|
||||
width?: number | null
|
||||
height?: number | null
|
||||
filesize?: number | null
|
||||
focalX?: number | null
|
||||
focalY?: number | null
|
||||
}
|
||||
|
||||
export function formatBytes(bytes?: number | null) {
|
||||
if (!bytes) return ''
|
||||
if (bytes < 1024) return `${bytes} Б`
|
||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} КБ`
|
||||
return `${(bytes / 1024 / 1024).toFixed(1)} МБ`
|
||||
}
|
||||
|
||||
const box: React.CSSProperties = {
|
||||
border: '1px solid var(--theme-elevation-150)',
|
||||
borderRadius: 8,
|
||||
padding: 12,
|
||||
marginTop: 8,
|
||||
background: 'var(--theme-elevation-0)',
|
||||
}
|
||||
|
||||
const pathRow: React.CSSProperties = {
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
gap: 8,
|
||||
fontFamily: 'var(--font-mono, monospace)',
|
||||
fontSize: 12,
|
||||
background: 'var(--theme-elevation-50)',
|
||||
borderRadius: 4,
|
||||
padding: '6px 8px',
|
||||
wordBreak: 'break-all',
|
||||
}
|
||||
|
||||
const label: React.CSSProperties = { fontSize: 12, color: 'var(--theme-elevation-500)', margin: '0 0 4px' }
|
||||
|
||||
export function CopyRow({ title, value }: { title: string; value: string }) {
|
||||
const [copied, setCopied] = useState(false)
|
||||
return (
|
||||
<div>
|
||||
<p style={label}>{title}</p>
|
||||
<div style={pathRow}>
|
||||
<span style={{ flex: 1 }}>{value}</span>
|
||||
<button
|
||||
type="button"
|
||||
className="btn btn--style-secondary btn--size-small"
|
||||
style={{ margin: 0, flexShrink: 0 }}
|
||||
onClick={() => {
|
||||
navigator.clipboard?.writeText(value).then(() => {
|
||||
setCopied(true)
|
||||
setTimeout(() => setCopied(false), 1500)
|
||||
})
|
||||
}}
|
||||
>
|
||||
{copied ? 'Скопировано' : 'Копировать'}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Large preview with focal point, file facts and exact file locations. */
|
||||
export function MediaCard({
|
||||
info,
|
||||
actions,
|
||||
notice,
|
||||
}: {
|
||||
info: MediaInfo
|
||||
actions?: React.ReactNode
|
||||
notice?: React.ReactNode
|
||||
}) {
|
||||
const isImage = Boolean(info.mimeType?.startsWith('image/'))
|
||||
const isVideo = Boolean(info.mimeType?.startsWith('video/'))
|
||||
const facts = [
|
||||
info.width && info.height ? `${info.width} × ${info.height}` : '',
|
||||
info.mimeType ? info.mimeType.split('/')[1]?.toUpperCase() : '',
|
||||
formatBytes(info.filesize),
|
||||
].filter(Boolean)
|
||||
|
||||
return (
|
||||
<div style={box}>
|
||||
<div style={{ display: 'flex', gap: 16, flexWrap: 'wrap', alignItems: 'flex-start' }}>
|
||||
<div
|
||||
style={{
|
||||
position: 'relative',
|
||||
width: 220,
|
||||
maxWidth: '100%',
|
||||
borderRadius: 6,
|
||||
overflow: 'hidden',
|
||||
background: 'var(--theme-elevation-100)',
|
||||
minHeight: 120,
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
{info.previewUrl && isImage ? (
|
||||
// eslint-disable-next-line @next/next/no-img-element
|
||||
<img src={info.previewUrl} alt="" style={{ display: 'block', width: '100%', height: 'auto' }} />
|
||||
) : info.previewUrl && isVideo ? (
|
||||
<video src={info.previewUrl} controls preload="metadata" style={{ display: 'block', width: '100%' }} />
|
||||
) : (
|
||||
<span style={{ fontSize: 13, color: 'var(--theme-elevation-500)', padding: 16 }}>
|
||||
{info.mimeType ? `Файл ${info.mimeType}` : 'Нет превью'}
|
||||
</span>
|
||||
)}
|
||||
{isImage && info.focalX != null && info.focalY != null ? (
|
||||
<span
|
||||
title="Точка фокуса"
|
||||
style={{
|
||||
position: 'absolute',
|
||||
left: `${info.focalX}%`,
|
||||
top: `${info.focalY}%`,
|
||||
width: 14,
|
||||
height: 14,
|
||||
marginLeft: -7,
|
||||
marginTop: -7,
|
||||
borderRadius: '50%',
|
||||
border: '2px solid #fff',
|
||||
boxShadow: '0 0 0 1px rgba(0,0,0,.5)',
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<div style={{ flex: 1, minWidth: 260, display: 'grid', gap: 10 }}>
|
||||
{facts.length ? (
|
||||
<p style={{ margin: 0, fontSize: 13, color: 'var(--theme-elevation-700)' }}>{facts.join(' · ')}</p>
|
||||
) : null}
|
||||
{info.storagePath ? <CopyRow title="Где лежит файл" value={info.storagePath} /> : null}
|
||||
{info.publicUrl ? <CopyRow title="Адрес на сайте" value={info.publicUrl} /> : null}
|
||||
{info.originalPath ? <CopyRow title="Оригинал до редактирования" value={info.originalPath} /> : null}
|
||||
{actions ? <div style={{ display: 'flex', gap: 8, flexWrap: 'wrap' }}>{actions}</div> : null}
|
||||
</div>
|
||||
</div>
|
||||
{notice}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
export type MediaDoc = {
|
||||
id: number | string
|
||||
url?: string | null
|
||||
filename?: string | null
|
||||
mimeType?: string | null
|
||||
width?: number | null
|
||||
height?: number | null
|
||||
filesize?: number | null
|
||||
focalX?: number | null
|
||||
focalY?: number | null
|
||||
storagePath?: string | null
|
||||
originalFile?: string | null
|
||||
updatedAt?: string
|
||||
}
|
||||
|
||||
export async function fetchMediaDoc(id: number | string): Promise<MediaDoc | null> {
|
||||
const res = await fetch(`/api/media/${encodeURIComponent(String(id))}?depth=0`, {
|
||||
credentials: 'include',
|
||||
cache: 'no-store',
|
||||
})
|
||||
if (!res.ok) return null
|
||||
return (await res.json()) as MediaDoc
|
||||
}
|
||||
|
||||
export function mediaInfo(doc: MediaDoc): MediaInfo {
|
||||
const bust = doc.updatedAt ? `?v=${encodeURIComponent(doc.updatedAt)}` : ''
|
||||
const origin = typeof window !== 'undefined' ? window.location.origin : ''
|
||||
const storagePath = doc.storagePath || null
|
||||
return {
|
||||
previewUrl: doc.url ? `${doc.url}${bust}` : null,
|
||||
publicUrl: doc.url ? (doc.url.startsWith('http') ? doc.url : `${origin}${doc.url}`) : null,
|
||||
storagePath,
|
||||
originalPath:
|
||||
doc.originalFile && storagePath
|
||||
? storagePath.replace(/[^/\\]+$/, `originals/${doc.originalFile}`)
|
||||
: null,
|
||||
mimeType: doc.mimeType,
|
||||
width: doc.width,
|
||||
height: doc.height,
|
||||
filesize: doc.filesize,
|
||||
focalX: doc.focalX,
|
||||
focalY: doc.focalY,
|
||||
}
|
||||
}
|
||||
|
||||
export async function restoreOriginal(id: number | string) {
|
||||
const res = await fetch('/api/custom/media-tools/restore-original', {
|
||||
method: 'POST',
|
||||
credentials: 'include',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ id }),
|
||||
})
|
||||
const data = await res.json().catch(() => ({}))
|
||||
if (!res.ok) throw new Error(data.error || 'Не удалось восстановить оригинал')
|
||||
}
|
||||
Reference in New Issue
Block a user