@@ -0,0 +1,125 @@
import { useEffect , useState } from 'react' ;
import { Button , FeatureSettingsWindow , Icon , IconButton , Select , SettingsCard , StatusBadge ,
TextField , TextAreaField , WindowFooterActions , ConfirmationModal } 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' | 'applications' ;
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 > ( 'connection' ) ;
const [ status , setStatus ] = useState < B2Status | null > ( null ) ;
const [ pending , setPending ] = useState ( '' ) ;
const [ connection , setConnection ] = useState ( '' ) ;
const [ key , setKey ] = useState ( '' ) ; const [ name , setName ] = useState ( '' ) ;
const [ contour , setContour ] = useState ( '' ) ;
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 ;
setPending ( 'load' ) ;
Promise . all ( [ request < B2Status > ( 'status' ) , loadProjects ( ) ] ) . then ( ( [ value , available ] ) = > {
if ( ! active ) return ;
setStatus ( value ) ;
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 } > ( action , data ) ;
if ( result . connection ) setIssued ( JSON . stringify ( result . connection , null , 2 ) ) ;
if ( action === 'connect' ) setConnection ( '' ) ;
await refresh ( ) ; await onChanged ( ) ;
} catch ( error ) { onError ( error ) ; } finally { setPending ( '' ) ; }
}
const contours = status ? . contours || [ ] ;
const canManage = status ? . authority === 'host' ;
const busy = Boolean ( pending ) ;
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 } ,
{ id : 'applications' , label : 'Приложения и ключи' , icon : 'key' , disabled : ! status ? . connected } ] }
activeSection = { section } onSectionChange = { ( value ) = > { setSection ( value ) ; setKey ( '' ) ; setName ( '' ) ; } } onClose = { onClose }
footer = { < WindowFooterActions > < Button onClick = { onClose } > З а к р ы т ь < / Button >
< 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" >
{ section === 'connection' ? < >
< SettingsCard title = "ARNavi VPS" description = "Одно подключение сервера для проектов компании. Устройства разделяются контурами." >
< StatusBadge tone = { status ? . connected ? 'success' : 'neutral' } > { status ? . connected ? 'Подключён' : pending === 'load' ? 'Проверяем подключение' : status ? 'Не подключён' : 'Состояние не получено' } < / StatusBadge >
{ status ? . endpoint ? < p > { status . endpoint } < / p > : null }
< / SettingsCard >
< SettingsCard title = { status ? . connected ? 'Заменить ключ подключения' : 'Подключить сервер' } description = "Вставьте ключ, выданный на VPS. После подключения он хранится только на сервере Device Core." >
< div className = "b2-settings" >
< TextAreaField label = "Ключ подключения" value = { connection } autoComplete = "off" spellCheck = { false }
onChange = { ( event ) = > setConnection ( event . target . value ) } rows = { 5 } / >
< Button loading = { pending === 'connect' } disabled = { busy || ! connection . trim ( ) } onClick = { ( ) = > void run ( 'connect' , { connection } ) } > П о д к л ю ч и т ь < / Button >
< / div >
< / SettingsCard >
< / > : null }
{ section === 'contours' ? < >
< SettingsCard title = "Контуры на VPS" description = "Связь с проектом определяет, где появятся устройства. Один контур можно подключить к нескольким приложениям." >
< div className = "b2-settings" >
{ contours . map ( ( item ) = > {
const link = status ? . links ? . find ( ( value ) = > value . contourId === item . id ) ;
return < div className = "b2-resource" key = { item . id } > < div > < strong > { item . name } < / strong > < small > { item . key } < / small > < / div >
< StatusBadge tone = { link ? 'success' : 'neutral' } > { link ? projects . find ( ( p ) = > p . projectRef === link . projectRef ) ? . name || 'Связан с проектом' : 'Не связан' } < / StatusBadge > < / div > ;
} ) }
{ ! contours . length ? < p > Н а VPS п о к а н е т к о н т у р о в . < / p > : null }
< Select label = "Контур" value = { contour } onChange = { setContour } options = { contours . map ( ( item ) = > ( { value : item.id , label : item.name } ) ) } / >
< Select label = "Проект" value = { targetProject } onChange = { setTargetProject } options = { projects . map ( ( item ) = > ( { value : item.projectRef , label : item.name } ) ) } / >
< Button loading = { pending === 'link' } disabled = { busy || ! contour || ! targetProject } onClick = { ( ) = > void run ( 'link' , { contourId : contour , targetProjectRef : targetProject } ) } > С в я з а т ь с п р о е к т о м < / Button >
< / div >
< / SettingsCard >
{ canManage ? < SettingsCard title = "Новый контур" description = "Контур создаётся на VPS и получает собственный реестр устройств." >
< div className = "b2-settings" > < TextField label = "Название" value = { name } onChange = { ( e ) = > setName ( e . target . value ) } / >
< TextField label = "Код контура" value = { key } placeholder = "robot2b" onChange = { ( e ) = > setKey ( e . target . value ) } / >
< Button loading = { pending === 'contour-create' } disabled = { busy || ! /^[a-z][a-z0-9-]{0,63}$/ . test ( key ) || ! name . trim ( ) }
onClick = { ( ) = > void run ( 'contour-create' , { key , name } ) } > С о з д а т ь к о н т у р < / Button > < / div >
< / SettingsCard > : null }
< / > : null }
{ section === 'applications' ? < >
{ issued ? < SettingsCard title = "Новый ключ приложения" description = "Скопируйте ключ и передайте в подключаемое приложение. Позже его можно перевыпустить без потери устройств." >
< div className = "b2-settings" > < TextAreaField label = "Ключ" value = { issued } readOnly rows = { 6 } / >
< Button onClick = { ( ) = > navigator . clipboard . writeText ( issued ) . catch ( onError ) } > С к о п и р о в а т ь к л ю ч < / Button >
< Button onClick = { ( ) = > setIssued ( '' ) } > С к р ы т ь < / Button > < / div >
< / SettingsCard > : null }
{ ( status ? . applications || [ ] ) . filter ( ( app ) = > app . authority !== 'host' && app . key !== 'legacy-mission-core' ) . map ( ( app ) = > < SettingsCard key = { app . id } title = { app . name }
description = { Object . keys ( app . grants ) . map ( ( id ) = > contours . find ( ( item ) = > item . id === id ) ? . name || id ) . join ( ', ' ) } >
< div className = "b2-settings" >
{ app . credentials . map ( ( credential ) = > < div className = "b2-resource" key = { credential . client_id } >
< div > < small > { credential . client_id } < / small > < StatusBadge tone = { credential . enabled ? 'success' : 'neutral' } > { credential . enabled ? 'Действует' : 'Отозван' } < / StatusBadge > < / div >
{ credential . enabled ? < Button size = "compact" disabled = { busy } onClick = { ( ) = > setConfirm ( { action : 'key-revoke' , fields : { clientId : credential.client_id } , text : ` Отозвать ключ приложения « ${ app . name } »? Подключённый клиент потеряет доступ. ` } ) } > О т о з в а т ь < / Button > : null }
< / div > ) }
< Button disabled = { busy } onClick = { ( ) = > setConfirm ( { action : 'key-issue' , fields : { integrationId : app.id , replace : true } , text : ` Выдать новый ключ для « ${ app . name } »? Предыдущие ключи этого приложения перестанут работать. Устройства и история сохранятся. ` } ) } > { app . credentials . some ( ( c ) = > c . enabled ) ? 'Перевыпустить ключ' : 'Выдать ключ' } < / Button >
< / div >
< / SettingsCard > ) }
{ canManage ? < SettingsCard title = "Подключить новое приложение" description = "Для каждого приложения создайте отдельный ключ. Несколько приложений могут работать с одним контуром независимо." >
< div className = "b2-settings" > < TextField label = "Название приложения" value = { name } onChange = { ( e ) = > setName ( e . target . value ) } / >
< TextField label = "Код приложения" value = { key } placeholder = "robot2b-client" onChange = { ( e ) = > setKey ( e . target . value ) } / >
< Select label = "Контур" value = { contour } onChange = { setContour } options = { contours . map ( ( item ) = > ( { value : item.id , label : item.name } ) ) } / >
< Button loading = { pending === 'application-create' } disabled = { busy || ! contour || ! name . trim ( ) || ! /^[a-z][a-z0-9-]{0,63}$/ . test ( key ) }
onClick = { ( ) = > void run ( 'application-create' , { key , name , contourId : contour } ) } > С о з д а т ь п р и л о ж е н и е < / Button > < / div >
< / SettingsCard > : < SettingsCard title = "Доступ к контуру" description = "Управление ключами доступно через управляющее подключение VPS." / > }
< / > : 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 ) ; } } / >
< / > ;
}