134 lines
14 KiB
TypeScript
134 lines
14 KiB
TypeScript
import { useEffect, useRef, useState } from 'react';
|
|
import { Button, FeatureSettingsWindow, Icon, IconButton, Select, SettingsCard, StatusBadge, TextField, TextAreaField, WindowFooterActions, ConfirmationModal, ResourceList, ResourceRow } from '@nodedc/ui-react';
|
|
import { loadProjects } from '../api';
|
|
import type { InfrastructureHostView, ProjectSummary, ProjectWorkspace } from '../types';
|
|
import { b2Request, type B2Status } from './api';
|
|
import './b2.css';
|
|
|
|
type Section = 'connection' | 'contours';
|
|
type Form = 'contour' | 'application' | 'project' | null;
|
|
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('');
|
|
const connectionFile = useRef<HTMLInputElement>(null);
|
|
const [key, setKey] = useState(''), [name, setName] = useState('');
|
|
const [contourId, setContourId] = useState(''), [applicationId, setApplicationId] = useState('');
|
|
const [form, setForm] = useState<Form>(null);
|
|
const [showHistory, setShowHistory] = useState(false), [showInactive, setShowInactive] = useState(false);
|
|
const [targetProject, setTargetProject] = useState(project.projectRef);
|
|
const [projects, setProjects] = useState<ProjectSummary[]>([]);
|
|
const [issued, setIssued] = useState('');
|
|
const [confirm, setConfirm] = useState<{ action: string; fields: Record<string, unknown>; text: string } | null>(null);
|
|
const request = <T,>(action: string, data: Record<string, unknown> = {}) => b2Request<T>(project.projectRef, host.hostRef, action, data);
|
|
const refresh = () => request<B2Status>('status').then(setStatus);
|
|
useEffect(() => {
|
|
let active = true;
|
|
Promise.all([request<B2Status>('status'), loadProjects()]).then(([value, available]) => {
|
|
if (!active) return;
|
|
setStatus(value); if (!value.connected) setSection('connection');
|
|
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]);
|
|
async function run(action: string, data: Record<string, unknown> = {}) {
|
|
setPending(action);
|
|
try {
|
|
const result = await request<{ connection?: unknown; id?: string }>(action, data);
|
|
if (result.connection) setIssued(JSON.stringify(result.connection, null, 2));
|
|
if (action === 'connect') { setConnection(''); setSection('contours'); }
|
|
if (action === 'contour-create' && result.id) { setContourId(result.id); setApplicationId(''); }
|
|
if (action === 'application-create' && result.id) setApplicationId(result.id);
|
|
setForm(null); setName(''); setKey('');
|
|
// A successful mutation must not be presented as failed if a subsequent read fails.
|
|
try { await refresh(); await onChanged(); } catch (error) { onError(error); }
|
|
return true;
|
|
} catch (error) { onError(error); return false; } finally { setPending(''); }
|
|
}
|
|
const contours = status?.contours || [], selected = contours.find((item) => item.id === contourId);
|
|
const linkedProject = status?.links?.find((item) => item.contourId === contourId)?.projectRef;
|
|
const applications = (status?.applications || []).filter((app) => app.authority !== 'host' && app.key !== 'legacy-mission-core' && app.grants[contourId]);
|
|
const application = applications.find((app) => app.id === applicationId);
|
|
const inactive = (app: typeof applications[number]) => app.credentials.length > 0 && !app.credentials.some((item) => item.enabled);
|
|
const busy = Boolean(pending), canManage = status?.authority === 'host';
|
|
const begin = (value: Form) => { setForm(value); setName(''); setKey(''); setTargetProject(project.projectRef); };
|
|
const back = () => {
|
|
setIssued(''); setShowHistory(false);
|
|
if (form) setForm(null); else if (applicationId) setApplicationId(''); else { setContourId(''); setShowInactive(false); }
|
|
};
|
|
function downloadIssuedKey() {
|
|
const url = URL.createObjectURL(new Blob([issued + '\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);
|
|
}
|
|
return <>
|
|
<FeatureSettingsWindow open title="Настройки VPS" subtitle={project.ownerScope.displayName}
|
|
identity={{ title: host.displayName, subtitle: status?.endpoint || 'ARNavi VPS', avatarLabel: 'VPS' }}
|
|
sections={[{ id: 'connection', label: 'Подключение', icon: 'network' }, { id: 'contours', label: 'Контуры', icon: 'layers', disabled: !status?.connected }]}
|
|
activeSection={section} onSectionChange={(value) => { setSection(value); setForm(null); setIssued(''); }} onClose={onClose}
|
|
footer={<WindowFooterActions>
|
|
{section === 'contours' && (selected || form) ? <IconButton label={form ? 'Отменить создание' : application ? 'К приложениям контура' : 'К списку контуров'} disabled={busy} onClick={back}><Icon name="chevron-left" /></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>
|
|
</WindowFooterActions>}>
|
|
<div className="b2-settings" aria-busy={busy}>
|
|
{section === 'connection' ? <>
|
|
<ResourceRow title={host.displayName} description={status?.endpoint} status={<StatusBadge tone={status?.connected ? 'success' : 'neutral'}>{status?.connected ? 'Подключён' : pending === 'load' ? 'Подключение…' : 'Не подключён'}</StatusBadge>} />
|
|
<SettingsCard title={status?.connected ? 'Заменить ключ сервера' : 'Подключить сервер'}>
|
|
<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('Не удалось прочитать файл ключа VPS.')); } finally { setPending(''); }
|
|
}} />
|
|
<TextAreaField label="Ключ сервера" value={connection} autoComplete="off" spellCheck={false} onChange={(event) => setConnection(event.target.value)} rows={4} />
|
|
<Button loading={pending === 'connect'} disabled={busy || !connection.trim()} onClick={() => void run('connect', { connection })}>Подключить</Button>
|
|
</div>
|
|
</SettingsCard>
|
|
</> : null}
|
|
{section === 'contours' ? <>
|
|
<div className="b2-path" aria-label="Текущий раздел">{[host.displayName, selected?.name, application?.name].filter(Boolean).join(' / ')}</div>
|
|
{form === 'contour' || form === 'application' ? <SettingsCard title={form === 'contour' ? 'Новый контур' : 'Новое приложение'}>
|
|
<div className="b2-settings">
|
|
{form === 'application' ? <ResourceRow title={selected?.name} metadata="Контур" /> : null}
|
|
<TextField label="Название" value={name} maxLength={160} onChange={(e) => setName(e.target.value)} />
|
|
<TextField label="Код" value={key} placeholder={form === 'contour' ? 'robot2b' : 'delivery-app'} onChange={(e) => setKey(e.target.value.toLowerCase())} />
|
|
<div className="b2-actions"><Button onClick={() => setForm(null)} disabled={busy}>Отмена</Button><Button loading={busy} disabled={busy || !name.trim() || !/^[a-z][a-z0-9-]{0,63}$/.test(key)} onClick={() => void run(form === 'contour' ? 'contour-create' : 'application-create', { key, name, ...(form === 'application' ? { contourId } : {}) })}>Создать</Button></div>
|
|
</div>
|
|
</SettingsCard> : form === 'project' ? <SettingsCard title="Проект Device Core"><div className="b2-settings">
|
|
<ResourceRow title={selected?.name} metadata="Контур VPS" /><Select label="Проект" value={targetProject} onChange={setTargetProject} options={projects.map((p) => ({ value: p.projectRef, label: p.name }))} />
|
|
<div className="b2-actions"><Button disabled={busy} onClick={() => setForm(null)}>Отмена</Button><Button disabled={busy || !targetProject} loading={pending === 'link'} onClick={() => void run('link', { contourId, targetProjectRef: targetProject })}>Связать</Button></div>
|
|
</div></SettingsCard> : !selected ? <SettingsCard title="Контуры" actions={canManage ? <IconButton label="Создать контур" disabled={busy} onClick={() => begin('contour')}><Icon name="plus" /></IconButton> : undefined}>
|
|
<ResourceList>{contours.map((item) => {
|
|
const link = status?.links?.find((value) => value.contourId === item.id), projectName = projects.find((p) => p.projectRef === link?.projectRef)?.name;
|
|
return <li key={item.id}><ResourceRow title={item.name} metadata={projectName ? `Проект: ${projectName}` : 'Проект не связан'} actions={<IconButton label={`Открыть контур ${item.name}`} disabled={busy} onClick={() => { setContourId(item.id); setApplicationId(''); }}><Icon name="chevron-right" /></IconButton>} /></li>;
|
|
})}</ResourceList>{!contours.length ? <p>Контуров пока нет</p> : null}
|
|
</SettingsCard> : !application ? <>
|
|
<SettingsCard title={selected.name} actions={<StatusBadge>Контур</StatusBadge>}><ResourceRow title={projects.find((p) => p.projectRef === linkedProject)?.name || 'Не выбран'} metadata="Проект Device Core" actions={!linkedProject ? <Button disabled={busy} onClick={() => begin('project')}>Выбрать проект</Button> : undefined} /></SettingsCard>
|
|
<SettingsCard title="Приложения" actions={canManage ? <IconButton label={`Добавить приложение в ${selected.name}`} disabled={busy} onClick={() => begin('application')}><Icon name="plus" /></IconButton> : undefined}>
|
|
<ResourceList>{applications.filter((app) => showInactive || !inactive(app)).map((app) => <li key={app.id}><ResourceRow title={app.name} status={<StatusBadge tone={app.credentials.some((c) => c.enabled) ? 'success' : 'neutral'}>{app.credentials.some((c) => c.enabled) ? 'Ключ действует' : 'Нет активного ключа'}</StatusBadge>} actions={<IconButton label={`Ключи ${app.name}`} disabled={busy} onClick={() => { setApplicationId(app.id); setShowHistory(false); }}><Icon name="key" /></IconButton>} /></li>)}</ResourceList>
|
|
{!applications.filter((app) => showInactive || !inactive(app)).length ? <p>Нет подключённых приложений</p> : null}
|
|
{applications.some(inactive) ? <Button variant="ghost" onClick={() => setShowInactive(!showInactive)}>{showInactive ? 'Скрыть отключённые' : `Отключённые приложения · ${applications.filter(inactive).length}`}</Button> : null}
|
|
</SettingsCard>
|
|
</> : <>
|
|
{issued ? <SettingsCard title="Новый ключ" description="Сохраните ключ — повторный просмотр недоступен."><div className="b2-settings"><TextAreaField label="Ключ подключения" value={issued} readOnly rows={4} /><div className="b2-actions"><Button onClick={downloadIssuedKey}>Скачать файл</Button><Button onClick={() => navigator.clipboard.writeText(issued).catch(onError)}>Скопировать</Button><Button onClick={() => setIssued('')}>Скрыть</Button></div></div></SettingsCard> : null}
|
|
<SettingsCard title="Ключи приложения" actions={<Button disabled={busy} onClick={() => setConfirm({ action: 'key-issue', fields: { integrationId: application.id, replace: true }, text: `Выдать новый ключ для «${application.name}»? Прежний ключ перестанет работать. Устройства сохранятся.` })}>{application.credentials.some((c) => c.enabled) ? 'Перевыпустить ключ' : 'Выдать ключ'}</Button>}>
|
|
<ResourceList>{application.credentials.filter((c) => c.enabled || showHistory).map((credential) => <li key={credential.client_id}><ResourceRow metadata="ID ключа" title={<code className="b2-key-id" title={credential.client_id}>{credential.client_id}</code>} status={<StatusBadge tone={credential.enabled ? 'success' : 'neutral'}>{credential.enabled ? 'Действует' : 'Отозван'}</StatusBadge>} actions={credential.enabled ? <Button size="compact" disabled={busy} onClick={() => setConfirm({ action: 'key-revoke', fields: { clientId: credential.client_id }, text: `Отозвать ключ приложения «${application.name}»?` })}>Отозвать</Button> : undefined} /></li>)}</ResourceList>
|
|
{!application.credentials.some((c) => c.enabled) ? <p>Нет активного ключа</p> : null}
|
|
{application.credentials.some((c) => !c.enabled) ? <Button variant="ghost" onClick={() => setShowHistory(!showHistory)}>{showHistory ? 'Скрыть историю' : `История ключей · ${application.credentials.filter((c) => !c.enabled).length}`}</Button> : null}
|
|
</SettingsCard>
|
|
</>}
|
|
</> : null}
|
|
</div>
|
|
</FeatureSettingsWindow>
|
|
<ConfirmationModal open={Boolean(confirm)} title="Ключ приложения" description={confirm?.text} confirmLabel="Подтвердить" cancelLabel="Отмена" onClose={() => setConfirm(null)} onConfirm={async () => { if (confirm && await run(confirm.action, confirm.fields)) setConfirm(null); }} />
|
|
</>;
|
|
}
|