224 lines
24 KiB
TypeScript
224 lines
24 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
||
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react';
|
||
import { archiveHost, loadProjects } from '../api';
|
||
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
|
||
import { b2Request, type B2Status, type B2Application } from './api';
|
||
import './b2.css';
|
||
|
||
type Section = 'connection' | 'contours';
|
||
export function B2HostSettings({ host, workspace, onClose, onChanged, onError }: {
|
||
host: InfrastructureHostView; workspace: ProjectWorkspace; onClose: () => void;
|
||
onChanged: () => Promise<void>; onError: (error: unknown) => void;
|
||
}) {
|
||
const project = workspace.project;
|
||
const [section, setSection] = useState<Section>('contours');
|
||
const [status, setStatus] = useState<B2Status | null>(null);
|
||
const [pending, setPending] = useState('load');
|
||
const [connection, setConnection] = useState(''), [importOpen, setImportOpen] = useState(false);
|
||
const connectionFile = useRef<HTMLInputElement>(null);
|
||
const [projects, setProjects] = useState<ProjectSummary[]>([]);
|
||
const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]);
|
||
const [creating, setCreating] = useState(''), [name, setName] = useState('');
|
||
const [access, setAccess] = useState('read');
|
||
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string; access: string } | null>(null);
|
||
const [newContour, setNewContour] = useState(false), [contourName, setContourName] = useState('');
|
||
const [targetProject, setTargetProject] = useState(project.projectRef);
|
||
const [contourIntent, setContourIntent] = useState<{ id: string; name: string; projectRef: string } | null>(null);
|
||
const [syncError, setSyncError] = useState('');
|
||
const [archiveConfirm, setArchiveConfirm] = useState(false);
|
||
const [issued, setIssued] = useState<{ applicationId: string; clientId: string; value: string } | null>(null);
|
||
const [credentialRows, setCredentialRows] = useState<string[]>([]);
|
||
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
|
||
const request = <T,>(action: string, data: Record<string, unknown> = {}, requestId?: string) => b2Request<T>(project.projectRef, host.hostRef, action, data, requestId);
|
||
const refresh = async () => { const value = await request<B2Status>('status'); setStatus(value); setSyncError(''); return value; };
|
||
useEffect(() => {
|
||
let active = true;
|
||
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
|
||
if (!active) return;
|
||
setStatus(value); if (!value.connected) { setSection('connection'); setImportOpen(true); }
|
||
setProjects(available.filter((item) => item.ownerScope.ownerScopeRef === project.ownerScope.ownerScopeRef));
|
||
}).catch((error) => { if (active) onError(error); }).finally(() => { if (active) setPending(''); });
|
||
return () => { active = false; };
|
||
}, [host.hostRef, project.projectRef]);
|
||
useEffect(() => {
|
||
if (pending) return;
|
||
let active = true, timer: number;
|
||
async function sync() {
|
||
try {
|
||
if (document.visibilityState === 'visible') {
|
||
const value = await request<B2Status>('status');
|
||
if (active) { setStatus(value); setSyncError(''); }
|
||
}
|
||
} catch { if (active) setSyncError('Не удалось обновить список VPS. Показаны последние полученные сведения.'); }
|
||
finally { if (active) timer = window.setTimeout(sync, 30000); }
|
||
}
|
||
timer = window.setTimeout(sync, 30000);
|
||
return () => { active = false; window.clearTimeout(timer); };
|
||
}, [host.hostRef, project.projectRef, pending]);
|
||
async function run(action: string, data: Record<string, unknown> = {}, requestId?: string) {
|
||
setPending(action);
|
||
try {
|
||
const result = await request<{ connection?: { integration_id: string; client_id: string }; id?: string; contourId?: string }>(action, data, requestId);
|
||
if (result.connection) {
|
||
const { integration_id: applicationId, client_id: clientId } = result.connection;
|
||
setIssued({ applicationId, clientId, value: JSON.stringify(result.connection, null, 2) });
|
||
setKeyRows((rows) => [...new Set([...rows, applicationId])]);
|
||
setCredentialRows((rows) => [...new Set([...rows, clientId])]);
|
||
}
|
||
if (action === 'key-revoke' && issued?.clientId === data.clientId) setIssued(null);
|
||
if (action === 'application-delete' && issued?.applicationId === data.integrationId) setIssued(null);
|
||
if (action === 'connect') { setConnection(''); setImportOpen(false); setSection('contours'); }
|
||
if (action === 'contour-connect') {
|
||
setNewContour(false); setContourName(''); setContourIntent(null);
|
||
if (result.contourId) setExpanded(rows => [...new Set([...rows, result.contourId!])]);
|
||
}
|
||
setCreating(''); setName(''); setCreationIntent(null);
|
||
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
|
||
return true;
|
||
} catch (error) {
|
||
const value = await refresh().catch(() => null);
|
||
const recovered = action === 'application-connect' && requestId
|
||
? value?.applications?.find(app => app.key === 'app-' + requestId) : null;
|
||
if (recovered) {
|
||
setCreating(''); setName(''); setCreationIntent(null);
|
||
setKeyRows(rows => [...new Set([...rows, recovered.id])]);
|
||
onError(new Error('Приложение создано, но ключ не получен. Откройте его ключи и выпустите новый. Секрет повторно не показывается.'));
|
||
} else onError(error);
|
||
return false;
|
||
} finally { setPending(''); }
|
||
}
|
||
const busy = Boolean(pending), canManage = status?.authority === 'host';
|
||
const toggle = (items: string[], id: string) => items.includes(id) ? items.filter((value) => value !== id) : [...items, id];
|
||
function downloadIssuedKey() {
|
||
if (!issued) return;
|
||
const url = URL.createObjectURL(new Blob([issued.value + '\n'], { type: 'application/json' }));
|
||
const link = document.createElement('a'); link.href = url; link.download = 'arnavi-application-key.json';
|
||
document.body.append(link); link.click(); link.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||
}
|
||
function applicationRow(app: B2Application) {
|
||
const legacy = app.key === 'legacy-mission-core';
|
||
const open = keyRows.includes(app.id), active = app.credentials.some((item) => item.enabled);
|
||
return <li key={app.id} className="b2-disclosure">
|
||
<ResourceRow title={app.name} metadata={legacy ? 'Подключение Mission Core · v1' : active ? 'Ключ выдан' : 'Нет действующего ключа'}
|
||
actions={<>
|
||
{open && !legacy ? <>
|
||
{canManage ? <>
|
||
<IconButton label={`${active ? 'Перевыпустить' : 'Выдать'} ключ ${app.name}`} disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: app.id, replace: active }, text: active ? `Перевыпустить ключ «${app.name}»? Прежний ключ перестанет работать.` : `Выдать ключ «${app.name}»?` })}><Icon name="plus" /></IconButton>
|
||
<IconButton label={`Удалить приложение ${app.name}`} disabled={busy} onClick={() => setConfirm({ action: 'application-delete', fields: { integrationId: app.id }, text: `Удалить «${app.name}» со всеми ключами и связями с контурами на этом VPS? Доступ приложения прекратится. Устройства, данные контуров и другие приложения сохранятся.` })}><Icon name="trash" /></IconButton>
|
||
</> : null}
|
||
</> : null}
|
||
<IconButton label={`Ключи ${app.name}`} aria-expanded={open} aria-controls={`keys-${app.id}`} onClick={() => setKeyRows(toggle(keyRows, app.id))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>
|
||
</>} />
|
||
{open ? <div id={`keys-${app.id}`} className="b2-disclosure__body">
|
||
{legacy ? <>
|
||
<dl className="b2-tracker-facts"><dt>Тип подключения</dt><dd>Прямая привязка Mission Core</dd><dt>ID приложения</dt><dd>{app.id}</dd></dl>
|
||
<p>Это прежняя привязка сервера, без OAuth-ключа. Выпуск и отзыв ключей ниже относятся к приложениям API v2 и не изменяют эту привязку.</p>
|
||
</> : <>
|
||
<dl className="b2-tracker-facts"><dt>Доступ приложения</dt><dd>{Object.entries(app.grants).map(([contourId, grant]) => `${status?.contours?.find(contour => contour.id === contourId)?.name || contourId}: ${{ read: 'чтение', control: 'чтение и команды', manage: 'управление устройствами' }[grant] || grant}`).join('; ')}</dd></dl>
|
||
<ResourceList>{app.credentials.map((item) => {
|
||
const keyOpen = credentialRows.includes(item.client_id);
|
||
const secret = issued?.applicationId === app.id && issued.clientId === item.client_id ? issued : null;
|
||
return <li key={item.client_id} className="b2-disclosure">
|
||
<ResourceRow title={`Ключ · …${item.client_id.slice(-8)}`} status={<StatusBadge tone={item.enabled ? 'success' : 'neutral'}>{item.enabled ? 'Действует' : 'Отозван'}</StatusBadge>}
|
||
actions={<IconButton label={`Сведения ключа ${item.client_id}`} aria-expanded={keyOpen} aria-controls={`credential-${item.client_id}`} onClick={() => setCredentialRows(toggle(credentialRows, item.client_id))}><Icon name={keyOpen ? 'chevron-up' : 'chevron-down'} /></IconButton>} />
|
||
{keyOpen ? <div id={`credential-${item.client_id}`} className="b2-disclosure__body">
|
||
<dl className="b2-tracker-facts"><dt>ID для сверки</dt><dd><code className="b2-key-id">{item.client_id}</code></dd><dt>VPS</dt><dd>{status?.endpoint}</dd></dl>
|
||
{secret ? <SettingsCard title="Ключ подключения приложения" description="Импортируйте файл в приложение с поддержкой ARNavi API v2. Секрет показывается один раз."><div className="b2-settings">
|
||
<TextAreaField label="Файл подключения" value={secret.value} readOnly rows={4} />
|
||
<div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(secret.value).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued(null)}>Скрыть секрет</Button></div>
|
||
</div></SettingsCard> : <p>Секрет скрыт. ID ключа можно сверить с полем client_id в сохранённом файле подключения.</p>}
|
||
{item.enabled && canManage ? <div className="b2-actions"><Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: item.client_id }, text: `Отозвать ключ «${app.name}»?` })}>Отозвать ключ</Button></div> : null}
|
||
</div> : null}
|
||
</li>;
|
||
})}</ResourceList>
|
||
{!app.credentials.length ? <p>Ключи ещё не выданы</p> : null}
|
||
</>}
|
||
</div> : null}
|
||
</li>;
|
||
}
|
||
return <>
|
||
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
|
||
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
|
||
sections={[{ id: 'connection', label: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]}
|
||
activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||
headerActions={<>
|
||
{section === 'contours' && canManage ? <IconButton label="Создать контур VPS" disabled={busy} onClick={() => { setNewContour(true); setContourName(''); setTargetProject(project.projectRef); setContourIntent(null); }}><Icon name="plus" /></IconButton> : null}
|
||
{project.access.capabilities.includes('infrastructure.manage') ? <IconButton label={host.lifecycleState === 'suspended' ? 'Восстановить VPS' : 'Перенести VPS в архив'} disabled={busy} onClick={() => setArchiveConfirm(true)}><Icon name={host.lifecycleState === 'suspended' ? 'refresh' : 'trash'} /></IconButton> : null}
|
||
<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
|
||
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
|
||
}}><Icon name="refresh" /></IconButton></>}>
|
||
<div className="b2-settings" aria-busy={busy}>
|
||
{syncError ? <p role="status">{syncError}</p> : null}
|
||
{section === 'connection' ? <>
|
||
<ResourceRow title={host.displayName} description={status?.endpoint} metadata="Подключение Device Core к серверу ARNavi"
|
||
status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Доступен' : pending === 'load' ? 'Проверка…' : 'Не подключён'}</StatusBadge>}
|
||
actions={<IconButton label="Импортировать ключ доступа Device Core" aria-expanded={importOpen} onClick={() => setImportOpen(!importOpen)}><Icon name="key" /></IconButton>} />
|
||
{importOpen ? <SettingsCard title="Доступ Device Core к VPS" description="Файл доступа выдаёт администратор этого VPS."><div className="b2-settings">
|
||
<Button disabled={busy} onClick={() => connectionFile.current?.click()}><Icon name="upload" />Загрузить файл доступа</Button>
|
||
<input ref={connectionFile} type="file" accept=".json,application/json" hidden aria-label="Файл доступа к VPS" disabled={busy} onChange={async (event) => {
|
||
const file = event.currentTarget.files?.[0]; event.currentTarget.value = ''; if (!file) return; setPending('file');
|
||
try { if (file.size > 16384) throw new Error(); const text = await file.text(); JSON.parse(text); setConnection(text); }
|
||
catch { onError(new Error('Не удалось прочитать файл доступа.')); } finally { setPending(''); }
|
||
}} />
|
||
<TextAreaField label="Содержимое файла доступа" value={connection} autoComplete="off" spellCheck={false} onChange={(event) => setConnection(event.target.value)} rows={4} />
|
||
<div className="b2-actions"><Button disabled={busy} onClick={() => { setImportOpen(false); setConnection(''); }}>Отмена</Button><Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>{status?.connected ? 'Обновить доступ Device Core' : 'Подключить Device Core'}</Button></div>
|
||
</div></SettingsCard> : null}
|
||
</> : null}
|
||
{section === 'contours' ? <>
|
||
{newContour ? <SettingsCard title="Новый контур VPS" description="Создаётся на этом VPS и связывается с выбранным проектом Device Core."><div className="b2-settings">
|
||
<TextField label="Название контура" value={contourName} disabled={busy || Boolean(contourIntent)} maxLength={160} autoFocus onChange={event => setContourName(event.target.value)} />
|
||
<Select label="Проект Device Core" value={targetProject} disabled={busy || Boolean(contourIntent)} options={projects.filter(item => item.access.capabilities.includes('infrastructure.manage')).map(item => ({ value: item.projectRef, label: item.name }))} onChange={setTargetProject} />
|
||
<div className="b2-actions"><Button disabled={busy} onClick={() => { setNewContour(false); setContourIntent(null); }}>Отмена</Button><Button disabled={busy || !contourName.trim() || !targetProject} loading={pending === 'contour-connect'} onClick={() => {
|
||
const intent = contourIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: contourName.trim(), projectRef: targetProject };
|
||
setContourIntent(intent); void run('contour-connect', { name: intent.name, targetProjectRef: intent.projectRef }, intent.id);
|
||
}}>{contourIntent ? 'Уточнить создание' : 'Создать контур'}</Button></div>
|
||
</div></SettingsCard> : null}
|
||
{!status?.contours?.length && !busy ? <p>На VPS ещё нет контуров. Создайте первый кнопкой «+» в шапке настроек.</p> : null}
|
||
<ResourceList>{(status?.contours || []).map(contour => {
|
||
const links = (status?.links || []).filter(link => link.contourId === contour.id);
|
||
const open = expanded.includes(contour.id);
|
||
const apps = (status?.applications || []).filter(app => app.authority !== 'host' && app.grants[contour.id]);
|
||
const available = projects.filter(item => item.access.capabilities.includes('infrastructure.manage') && !links.some(link => link.projectRef === item.projectRef));
|
||
const projectNames = links.map(link => projects.find(item => item.projectRef === link.projectRef)?.name || 'Недоступный проект');
|
||
return <li key={contour.id} className="b2-disclosure">
|
||
<ResourceRow title={contour.name} metadata={links.length ? `Проекты: ${projectNames.join(', ')}` : 'Не связан с проектами Device Core'} actions={<>
|
||
{open && canManage ? <IconButton label={`Добавить приложение в ${contour.name}`} disabled={busy} onClick={() => { setCreating(contour.id); setName(''); setAccess('read'); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : null}
|
||
<IconButton label={`Контур ${contour.name}`} aria-expanded={open} aria-controls={`contour-${contour.id}`} onClick={() => setExpanded(toggle(expanded, contour.id))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>
|
||
</>} />
|
||
{open ? <div id={`contour-${contour.id}`} className="b2-disclosure__body">
|
||
<div className="b2-section-heading"><strong>Проекты Device Core</strong></div>
|
||
<p>Связанные проекты видят один реестр устройств этого контура. Ключи внешних приложений управляются отдельно.</p>
|
||
{links.length ? <ResourceList>{links.map(link => {
|
||
const item = projects.find(value => value.projectRef === link.projectRef);
|
||
return <li key={link.projectRef}><ResourceRow title={item?.name || 'Недоступный проект'} actions={item?.access.capabilities.includes('infrastructure.manage') ? <IconButton label={`Отвязать проект ${item.name}`} disabled={busy} onClick={() => setConfirm({ action: 'unlink', fields: { contourId: contour.id, targetProjectRef: link.projectRef }, text: `Отвязать «${item.name}» от «${contour.name}»? Устройства перестанут отображаться в этом проекте. Контур, устройства и ключи внешних приложений сохранятся.` })}><Icon name="trash" /></IconButton> : undefined} /></li>;
|
||
})}</ResourceList> : null}
|
||
{available.length ? <Select label="Подключить проект к контуру" value="" disabled={busy || (links.length > 0 && !status?.sharedProjects)} options={[{ value: '', label: 'Выбрать проект Device Core' }, ...available.map(item => ({ value: item.projectRef, label: item.name }))]} onChange={projectRef => {
|
||
if (projectRef) setConfirm({ action: 'link', fields: { contourId: contour.id, targetProjectRef: projectRef }, text: `Подключить «${projects.find(item => item.projectRef === projectRef)?.name}» к «${contour.name}»? Участники проекта получат доступ к устройствам контура в пределах своих прав проекта.` });
|
||
}} /> : null}
|
||
{links.length > 0 && available.length > 0 && !status?.sharedProjects ? <p>Для подключения второго проекта нужна миграция общих контуров на сервере Device Core.</p> : null}
|
||
<div className="b2-section-heading"><strong>Приложения и ключи</strong></div>
|
||
<ResourceList>{apps.map(applicationRow)}</ResourceList>
|
||
{!apps.length && creating !== contour.id ? <p>Ключи приложений ещё не выданы</p> : null}
|
||
{creating === contour.id ? <div className="b2-settings">
|
||
<TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={event => setName(event.target.value)} />
|
||
<Select label="Доступ приложения" value={access} disabled={busy || Boolean(creationIntent)} options={[{ value: 'read', label: 'Чтение устройств и данных' }, { value: 'control', label: 'Чтение и команды' }, { value: 'manage', label: 'Управление устройствами контура' }]} onChange={setAccess} />
|
||
<div className="b2-actions"><Button disabled={busy} onClick={() => { setCreating(''); setCreationIntent(null); }}>Отмена</Button><Button loading={pending === 'application-connect'} disabled={busy || !name.trim()} onClick={() => {
|
||
const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim(), access };
|
||
setCreationIntent(intent);
|
||
void run('application-connect', { name: intent.name, contourId: contour.id, access: intent.access }, intent.id);
|
||
}}>{creationIntent ? 'Уточнить создание' : 'Создать ключ'}</Button></div>
|
||
</div> : null}
|
||
</div> : null}
|
||
</li>;
|
||
})}</ResourceList>
|
||
</> : null}
|
||
</div>
|
||
</FeatureSettingsWindow>
|
||
<ConfirmationModal open={archiveConfirm} title={host.lifecycleState === 'suspended' ? 'Восстановить VPS?' : 'Перенести VPS в архив?'} description={`${host.displayName}. Изменится только запись в этом проекте. Сервер, устройства и подключения других проектов сохранятся.`} confirmLabel={host.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => setArchiveConfirm(false)} onConfirm={async () => {
|
||
if (busy) return; setPending('archive');
|
||
try { await archiveHost(project.projectRef, host.hostRef, host.lifecycleState !== 'suspended'); setArchiveConfirm(false); await onChanged(); onClose(); } catch (error) { onError(error); } finally { setPending(''); }
|
||
}} />
|
||
<ConfirmationModal open={Boolean(confirm)} title={confirm?.action === 'application-delete' ? 'Удалить приложение' : ['link', 'unlink'].includes(confirm?.action || '') ? 'Связь проекта и контура' : 'Ключ приложения'} description={confirm?.text} confirmLabel={confirm?.action === 'application-delete' ? 'Удалить приложение' : 'Подтвердить'} cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && !busy && await run(confirm.action, confirm.fields)) setConfirm(null); }} />
|
||
</>;
|
||
}
|