Complete shared contour project linking and scoped application onboarding
This commit is contained in:
@@ -19,13 +19,18 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
const [projects, setProjects] = useState<ProjectSummary[]>([]);
|
||||
const [expanded, setExpanded] = useState<string[]>([]), [keyRows, setKeyRows] = useState<string[]>([]);
|
||||
const [creating, setCreating] = useState(''), [name, setName] = useState('');
|
||||
const [creationIntent, setCreationIntent] = useState<{ id: string; name: string } | null>(null);
|
||||
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 = () => request<B2Status>('status').then(setStatus);
|
||||
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]) => {
|
||||
@@ -35,10 +40,25 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
}).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 }>(action, data, requestId);
|
||||
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) });
|
||||
@@ -48,10 +68,24 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
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) { onError(error); await refresh().catch(() => undefined); return false; } finally { setPending(''); }
|
||||
} 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];
|
||||
@@ -80,6 +114,7 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
<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;
|
||||
@@ -107,11 +142,13 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
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>}
|
||||
@@ -127,43 +164,60 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
<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' ? <ResourceList>{projects.map((item) => {
|
||||
const links = (status?.links || []).filter((link) => link.projectRef === item.projectRef);
|
||||
const linked = links.length > 0, open = expanded.includes(item.projectRef);
|
||||
const apps = (status?.applications || []).filter((app) => app.authority !== 'host' && links.some((link) => app.grants[link.contourId]));
|
||||
const available = (status?.contours || []).filter((contour) => !status?.links?.some((link) => link.contourId === contour.id));
|
||||
return <li key={item.projectRef} className="b2-disclosure">
|
||||
<ResourceRow title={item.name} metadata={linked ? 'Контур VPS связан с проектом' : 'Проект Device Core'}
|
||||
actions={<>
|
||||
{open && linked && canManage ? <IconButton label={`Добавить приложение в ${item.name}`} disabled={busy} onClick={() => { setCreating(item.projectRef); setName(''); setCreationIntent(null); }}><Icon name="plus" /></IconButton> : null}
|
||||
<IconButton label={`Контур ${item.name}`} aria-expanded={open} aria-controls={`contour-${item.projectRef}`} onClick={() => setExpanded(toggle(expanded, item.projectRef))}><Icon name={open ? 'chevron-up' : 'chevron-down'} /></IconButton>
|
||||
{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-${item.projectRef}`} className="b2-disclosure__body">
|
||||
{!linked ? <>
|
||||
{canManage ? <Button disabled={busy} loading={pending === 'project-connect'} onClick={() => void run('project-connect', { targetProjectRef: item.projectRef })}>Подключить проект к VPS</Button> : null}
|
||||
{available.length ? <Select label="Связать с существующим контуром" value="" options={[{ value: '', label: 'Выбрать контур VPS' }, ...available.map((c) => ({ value: c.id, label: c.name }))]} onChange={(contourId) => { if (contourId) void run('link', { contourId, targetProjectRef: item.projectRef }); }} disabled={busy} /> : null}
|
||||
</> : <>
|
||||
{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 !== item.projectRef ? <p>Ключи приложений ещё не выданы</p> : null}
|
||||
{creating === item.projectRef ? <div className="b2-settings">
|
||||
<TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={(event) => setName(event.target.value)} />
|
||||
{!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() };
|
||||
const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim(), access };
|
||||
setCreationIntent(intent);
|
||||
void run('application-connect', { name: intent.name, contourId: links[0].contourId }, intent.id);
|
||||
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> : 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' ? 'Удалить приложение' : 'Ключ приложения'} 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); }} />
|
||||
<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); }} />
|
||||
</>;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user