@@ -0,0 +1,144 @@
import { useEffect , useRef , useState } from 'react' ;
import { Button , FeatureSettingsWindow , Icon , IconButton , ResourceList , ResourceRow , Select , SettingsCard , StatusBadge , Switch , TextField , Window } from '@nodedc/ui-react' ;
import { trackerRequest , newIntent , operationName , stateName , formatTime , type TrackerRef , type TrackerState , type Policy , type Operation } from './tracker' ;
import { B2RequestError } from './api' ;
import './b2.css' ;
type Props = { projectRef :string ; device :TrackerRef ; initialSection? :string ; onClose : ( ) = > void ; onError : ( error :unknown ) = > void ; onChanged : ( ) = > Promise < void > ; canConfigure :boolean ; canCommand :boolean } ;
export function B2TrackerSettings ( { projectRef , device , initialSection = 'identity' , onClose , onError , onChanged , canConfigure , canCommand } : Props ) {
const [ section , setSection ] = useState ( initialSection === 'commands' ? 'commands' : 'identity' ) ;
const [ data , setData ] = useState < TrackerState | null > ( null ) , [ name , setName ] = useState ( device . name ) ;
const [ policy , setPolicy ] = useState < Policy > ( { parameters : { } , connectivity : { mode : 'preserve' } } ) ;
const [ profile , setProfile ] = useState ( '' ) , [ profileName , setProfileName ] = useState ( '' ) , [ profileOpen , setProfileOpen ] = useState ( false ) ;
const [ busy , setBusy ] = useState ( 'load' ) , [ dirty , setDirty ] = useState ( false ) , [ commandsOpen , setCommandsOpen ] = useState ( initialSection === 'commands' ) ;
const [ bootstrapFirmware , setBootstrapFirmware ] = useState ( '' ) , [ bootstrapPassword , setBootstrapPassword ] = useState ( '' ) ;
const profileIntent = useRef < Record < string , unknown > | null > ( null ) ;
const [ latest , setLatest ] = useState < Operation | null > ( null ) ;
const request = < T , > ( body :Record < string , unknown > ) = > trackerRequest < T > ( projectRef , device , body ) ;
const alive = useRef ( true ) , intent = useRef < { action :string ; request :Record < string , unknown > } | null > ( null ) ;
const file = useRef < HTMLInputElement > ( null ) ;
useEffect ( ( ) = > {
alive . current = true ;
request < TrackerState > ( { action : 'state' } ) . then ( value = > { if ( alive . current ) { setData ( value ) ; setLatest ( value . latest_operation ) ; setName ( value . name ) ; setPolicy ( value . policy ) ; } } ) . catch ( onError ) . finally ( ( ) = > { if ( alive . current ) setBusy ( '' ) ; } ) ;
return ( ) = > { alive . current = false ; } ;
} , [ device . id , projectRef ] ) ;
async function refresh() { const next = await request < TrackerState > ( { action : 'state' } ) ; if ( alive . current ) { setData ( next ) ; setLatest ( next . latest_operation ) ; } return next ; }
useEffect ( ( ) = > {
if ( ! latest || ! [ 'queued' , 'dispatched' ] . includes ( latest . state ) ) return ;
let active = true ;
const timer = setTimeout ( async ( ) = > { try { const result = await request < { items :Operation [ ] } > ( { action : 'journal' } ) ; const item = result . items . find ( row = > row . id === latest . id ) ; if ( active && item ) { setLatest ( item ) ; if ( ! [ 'queued' , 'dispatched' ] . includes ( item . state ) ) await refresh ( ) ; } } catch ( error ) { if ( active ) onError ( error ) ; } } , 3000 ) ;
return ( ) = > { active = false ; clearTimeout ( timer ) ; } ;
} , [ latest ] ) ;
const edit = ( value :Policy ) = > { setPolicy ( value ) ; setDirty ( true ) ; } ;
async function run ( label :string , work : ( ) = > Promise < void > ) { setBusy ( label ) ; try { await work ( ) ; } catch ( error ) { onError ( error ) ; } finally { if ( alive . current ) setBusy ( '' ) ; } }
async function save() {
if ( ! data ) return 0 ;
const result = await request < { revision :number } > ( { action : 'save' , revision :data.revision , name , policy } ) ;
setData ( { . . . data , revision :result.revision , name , policy } ) ; setDirty ( false ) ; await onChanged ( ) ; return result . revision ;
}
async function operation ( action : 'read' | 'apply' ) {
if ( ! data ) return ;
const pending = intent . current ;
if ( pending && pending . action !== action ) throw new Error ( 'Сначала уточните результат предыдущей отправки.' ) ;
if ( ! pending ) {
const revision = action === 'apply' && dirty ? await save ( ) : data . revision ;
intent . current = { action , request : { action , id :newIntent ( ) , . . . ( action === 'apply' ? { revision , expected_sha256 :data.observed?.sha256 } : ! data . observed ? { bootstrap : { firmware :bootstrapFirmware , password :bootstrapPassword } } : { } ) } } ;
}
try { const result = await request < Operation > ( intent . current ! . request ) ; intent . current = null ; setBootstrapPassword ( '' ) ; setLatest ( result ) ; } catch ( error ) { if ( error instanceof B2RequestError && error . rejected ) intent . current = null ; throw error ; }
}
const groupNames = [ . . . new Set ( data ? . fields . map ( field = > field . group ) || [ ] ) ] ;
const pending = Boolean ( latest && [ 'queued' , 'dispatched' ] . includes ( latest . state ) ) ;
const disabled = Boolean ( busy ) || pending || ! canConfigure ;
const connected = Boolean ( data ? . last_seen_at && Date . now ( ) / 1000 - data . last_seen_at < 120 ) ;
async function uploadFirmware ( value : File ) {
if ( ! / \ .dfw $ / i.test ( value.name ) | | value.size > 4 * 1024 * 1024 || ! value . size ) throw new Error ( 'Выберите непустой файл .dfw до 4 МБ.' ) ;
const bytes = new Uint8Array ( await value . arrayBuffer ( ) ) ;
const digest = Array . from ( new Uint8Array ( await crypto . subtle . digest ( 'SHA-256' , bytes ) ) , n = > n . toString ( 16 ) . padStart ( 2 , '0' ) ) . join ( '' ) ;
for ( let offset = 0 ; offset < bytes.length ; offset + = 24576 ) { const chunk = btoa ( String.fromCharCode ( ...bytes.slice ( offset , offset + 24576 ) ) ) ; await request ( { action : 'firmware-upload' , digest , filename : value.name , size : bytes.length , offset , chunk } ) ; }
await refresh ( ) ;
}
async function downloadFirmware ( digest : string ) {
const chunks : Uint8Array < ArrayBuffer > [ ] = [ ] ; let offset = 0 , size = 1 , filename = 'firmware.dfw' ;
while ( offset < size ) { const result = await request < { chunk : string ; size : number ; filename : string } > ( { action : 'firmware-download' , digest , offset } ) ; size = result.size ; filename = result.filename ; const bytes = Uint8Array.from ( atob ( result.chunk ) , c = > c . charCodeAt ( 0 ) ) ; if ( ! bytes . length ) throw new Error ( 'Неполный файл прошивки' ) ; chunks . push ( bytes ) ; offset += bytes . length ; }
const blob = new Blob ( chunks ) ; const actual = Array . from ( new Uint8Array ( await crypto . subtle . digest ( 'SHA-256' , await blob . arrayBuffer ( ) ) ) , n = > n . toString ( 16 ) . padStart ( 2 , '0' ) ) . join ( '' ) ;
if ( actual !== digest ) throw new Error ( 'Контрольная сумма файла не совпала' ) ;
const url = URL . createObjectURL ( blob ) , link = document . createElement ( 'a' ) ; link . href = url ; link . download = filename ; link . click ( ) ; setTimeout ( ( ) = > URL . revokeObjectURL ( url ) , 1000 ) ;
}
return < >
< FeatureSettingsWindow open = { ! profileOpen && ! commandsOpen } title = "Настройки устройства" subtitle = { ` ARNavi B2 · ${ device . number } ` }
identity = { { title : 'ARNavi B2' , subtitle : ` IMEI ${ device . identifier . masked } ` , avatarLabel : 'AR' } }
sections = { [ { id : 'identity' , label : 'Устройство и проект' } , { id : 'connection' , label : 'Сервер и связь' } , { id : 'commands' , label : 'Команды' } , { id : 'firmware' , label : 'Прошивка' } , . . . groupNames . map ( ( group , index ) = > ( { id :group , label :group , group :index === 0 ? 'Параметры профиля' : undefined } ) ) ] }
activeSection = { section } onSectionChange = { setSection } onClose = { onClose }
headerActions = { < IconButton label = "Обновить сведения о трекере" disabled = { Boolean ( busy ) } loading = { busy === 'refresh' } onClick = { ( ) = > void run ( 'refresh' , async ( ) = > { await refresh ( ) ; } ) } > < Icon name = "refresh" / > < / IconButton > }
footer = { section !== 'commands' && section !== 'firmware' ? < > < Button disabled = { disabled || ! dirty || ! data } loading = { busy === 'save' } onClick = { ( ) = > void run ( 'save' , async ( ) = > { await save ( ) ; } ) } > С о х р а н и т ь н а с т р о й к и < / Button > < Button disabled = { disabled || ! data } onClick = { ( ) = > { profileIntent . current = null ; setProfileName ( '' ) ; setProfileOpen ( true ) ; } } > С о х р а н и т ь п р о ф и л ь < / Button > < / > : undefined } >
< div className = "b2-tracker-form" aria-busy = { Boolean ( busy ) } >
< StatusBadge tone = { connected ? 'success' : 'neutral' } > { connected ? 'Передаёт данные на VPS' : data ? 'Нет свежих данных' : 'Загрузка…' } < / StatusBadge >
{ data && section !== 'commands' && section !== 'firmware' ? < SettingsCard title = "Настройки через VPS" >
< div className = "b2-tracker-form" >
< span > { data . observed ? ` Последнее чтение: ${ formatTime ( data . observed . received_at ) } ` : 'Настройки трекера ещё не прочитаны' } < / span >
{ latest ? < StatusBadge tone = { [ 'verified' , 'observed' , 'delivered' , 'confirmed' ] . includes ( latest . state ) ? 'success' : 'neutral' } > { stateName ( latest . state ) } < / StatusBadge > : null } { pending ? < span > З а д а н и е с о х р а н е н о н а VPS . О к н о м о ж н о з а к р ы т ь . < / span > : null }
< Button disabled = { Boolean ( busy ) || pending || ! canConfigure || ! canCommand || ! data . capabilities . configuration } loading = { busy === 'apply' } onClick = { ( ) = > void run ( 'apply' , ( ) = > operation ( 'apply' ) ) } > { intent . current ? . action === 'apply' ? 'Уточнить отправку' : 'Отправить через VPS' } < / Button >
{ ! data . observed ? < > < Select label = "Версия прошивки B2" value = { bootstrapFirmware } disabled = { Boolean ( busy ) || ! canCommand } onChange = { setBootstrapFirmware } options = { [ { value : '' , label : 'Выберите установленную версию' } , { value : '0.01' , label : '0.01' } , { value : '0.06' , label : '0.06' } ] } / > < TextField label = "Пароль конфигурации трекера" type = "password" autoComplete = "off" maxLength = { 6 } value = { bootstrapPassword } disabled = { Boolean ( busy ) || ! canCommand } onChange = { event = > setBootstrapPassword ( event . target . value ) } / > < / > : null }
< Button disabled = { Boolean ( busy ) || pending || ! canCommand || ( ! data . capabilities . configuration && ! intent . current && ( ! bootstrapFirmware || ! /^\d{6}$/ . test ( bootstrapPassword ) ) ) } loading = { busy === 'read' } onClick = { ( ) = > void run ( 'read' , ( ) = > operation ( 'read' ) ) } > { intent . current ? . action === 'read' ? 'Уточнить чтение' : 'Прочитать через VPS' } < / Button >
< / div >
< / SettingsCard > : null }
{ section === 'identity' && data ? < >
< TextField label = "Название" value = { name } disabled = { disabled } onChange = { event = > { setName ( event . target . value ) ; setDirty ( true ) ; } } / >
< Select label = "Сохранённый профиль" value = { profile } disabled = { disabled } options = { [ { value : '' , label : 'Без профиля' } , . . . data . profiles . map ( item = > ( { value :item.id , label :item.name } ) ) ] } onChange = { id = > { setProfile ( id ) ; const selected = data . profiles . find ( item = > item . id === id ) ; if ( selected ) edit ( structuredClone ( selected . policy ) ) ; } } / >
< SettingsCard title = "Сведения об устройстве" > < dl className = "b2-tracker-facts" > < dt > М о д е л ь < / dt > < dd > ARNavi B2 · 231 < / dd > < dt > Н о м е р < / dt > < dd > { data . number } < / dd > < dt > IMEI < / dt > < dd > { data . identifier } < / dd > < dt > П р о ш и в к а < / dt > < dd > { data . firmware || 'Не прочитана' } < / dd > < dt > П о с л е д н и е д а н н ы е < / dt > < dd > { formatTime ( data . last_seen_at ) } < / dd > < / dl > < / SettingsCard >
< / > : null }
{ section === 'connection' && data ? < >
{ [ 1 , 2 ] . map ( slot = > < SettingsCard key = { slot } title = { ` SIM ${ slot } ` } actions = { data . modem ? . active_sim === slot && Date . now ( ) / 1000 - data . modem . measured_at < 90 ? < StatusBadge tone = "success" > Интернет < / StatusBadge > : undefined } >
< div className = "b2-tracker-form" > < span > { data . sims [ String ( slot ) ] ? . identifier || 'Нет сведений о карте' } < / span > < dl className = "b2-tracker-facts" > < dt > Р е г и с т р а ц и я < / dt > < dd > { ( { 0 : 'Не обнаружена' , 1 : 'В домашней сети' , 2 : 'Поиск сети' , 3 : 'Отказ регистрации' , 4 : 'Нет сведений' , 5 : 'Роуминг' } as Record < number , string > ) [ data . cellular . status ? . sim_states [ String ( slot ) ] ? ? 4 ] } < / dd > < dt > С и г н а л < / dt > < dd > { data . cellular . networks ? . [ String ( slot ) ] ? . signal != null ? ` ${ data . cellular . networks [ String ( slot ) ] . signal } / 31 ` : '—' } < / dd > < dt > Н а б л ю д е н и е < / dt > < dd > { formatTime ( data . cellular . measured_at ) } < / dd > < dt > APN < / dt > < dd > { ( slot === 1?data.observed?.apn1 :data.observed?.apn2 ) || 'Автоматически' } < / dd > < / dl >
< Select label = { ` Настройки оператора SIM ${ slot } ` } value = { policy . connectivity [ slot === 1 ? 'preset1' : 'preset2' ] || '' } disabled = { disabled || policy . connectivity . mode === 'native' } options = { [ { value : '' , label : 'Сохранить или указать APN' } , . . . data . carrier_presets . map ( item = > ( { value :item.id , label :item.label } ) ) ] } onChange = { preset = > { const connectivity = { . . . policy . connectivity } ; const key = slot === 1 ? 'preset1' : 'preset2' ; if ( preset ) connectivity [ key ] = preset ; else delete connectivity [ key ] ; edit ( { . . . policy , connectivity } ) ; } } / >
< TextField label = { ` APN SIM ${ slot } ` } placeholder = "Сохранить текущее значение" value = { policy . connectivity [ slot === 1 ? 'apn1' : 'apn2' ] ? ? '' } disabled = { disabled || policy . connectivity . mode === 'native' || Boolean ( policy . connectivity [ slot === 1 ? 'preset1' : 'preset2' ] ) } onChange = { event = > edit ( { . . . policy , connectivity : { . . . policy . connectivity , [ slot === 1 ? 'apn1' : 'apn2' ] : event . target . value } } ) } / >
< / div >
< / SettingsCard > ) }
< Select label = "Режим интернета" value = { policy . connectivity . mode } disabled = { disabled } onChange = { mode = > edit ( { . . . policy , connectivity : { . . . policy . connectivity , mode } } ) } options = { [ { value : 'preserve' , label : 'Сохранить режим трекера' } , { value : 'native' , label : 'Автоматический режим без заданного APN' } , { value : 'both' , label : 'Автоматический режим — сохранить APN' } , { value : 'sim1' , label : 'Только SIM1' } , { value : 'sim2' , label : 'Только SIM2' } ] } / >
< SettingsCard title = "Сервер мониторинга" > < div className = "b2-tracker-form" >
< Switch label = "Задать сервер в профиле" checked = { Boolean ( policy . endpoint ) } disabled = { disabled } onChange = { checked = > edit ( { . . . policy , endpoint :checked? { slot :1 , host :data.observed?.servers [ 0 ] ? . host || '' , port :data.observed?.servers [ 0 ] ? . port || 9922 } : null } ) } / >
{ policy.endpoint ? < > < TextField label = "DNS/IP сервера" value = { policy . endpoint . host } disabled = { disabled } onChange = { event = > edit ( { . . . policy , endpoint : { . . . policy . endpoint ! , host :event.target.value } } ) } / > < TextField label = "Порт" type = "number" min = { 1 } max = { 65535 } value = { policy . endpoint . port } disabled = { disabled } onChange = { event = > edit ( { . . . policy , endpoint : { . . . policy . endpoint ! , port :Number ( event . target . value ) } } ) } / > < Select label = "Слот сервера" value = { String ( policy . endpoint . slot ) } disabled = { disabled } options = { [ 1 , 3 , 4 ] . map ( slot = > ( { value :String ( slot ) , label : ` Сервер ${ slot } ` } ) ) } onChange = { slot = > edit ( { . . . policy , endpoint : { . . . policy . endpoint ! , slot :Number ( slot ) } } ) } / > < / > : null }
< ResourceList > { data.observed ? .servers.map ( server = > < li key = { server . slot } > < ResourceRow title = { ` Сервер ${ server . slot } ` } metadata = { ` ${ server . host } : ${ server . port } ` } description = { server . slot === 2 ? 'Связь с текущим VPS' : undefined } / > < / li > ) } < / ResourceList >
< / div > < / SettingsCard >
< / > : null }
{ groupNames . includes ( section ) && data ? < > < span > П у с т о е п о л е — с о х р а н и т ь з н а ч е н и е т р е к е р а . < / span > { data . fields . filter ( field = > field . group === section ) . map ( field = > < TextField key = { field . id } label = { field . label } hint = { ` ${ field . minimum } … ${ field . maximum } ` } type = "number" step = { 1 } min = { field . minimum } max = { field . maximum } disabled = { disabled || ! Object . hasOwn ( data . observed ? . parameters || { } , field . id ) } placeholder = { String ( data . observed ? . parameters [ field . id ] ? ? 'Недоступно на этой прошивке' ) } value = { policy . parameters [ field . id ] ? ? '' } onChange = { event = > { const parameters = { . . . policy . parameters } ; if ( event . target . value === '' ) delete parameters [ field . id ] ; else parameters [ field . id ] = Number ( event . target . value ) ; edit ( { . . . policy , parameters } ) ; } } / > ) } < / > : null }
{ section === 'commands' ? < SettingsCard title = "Команды устройства" > < Button onClick = { ( ) = > setCommandsOpen ( true ) } > О т к р ы т ь к о н с о л ь к о м а н д < / Button > < / SettingsCard > : null }
{ section === 'firmware' && data ? < > < SettingsCard title = "Прошивка устройства" > < ResourceRow title = { ` Установлена ${ data . firmware || 'неизвестная версия' } ` } metadata = "Архив файлов · установка по сети недоступна" / > < / SettingsCard >
< SettingsCard title = "Архив прошивок" actions = { < IconButton label = "Добавить прошивку" disabled = { disabled } onClick = { ( ) = > file . current ? . click ( ) } > < Icon name = "plus" / > < / IconButton > } >
< input ref = { file } type = "file" accept = ".dfw" hidden onChange = { event = > { const selected = event . target . files ? . [ 0 ] ; event . target . value = '' ; if ( selected ) void run ( 'firmware' , ( ) = > uploadFirmware ( selected ) ) ; } } / >
< ResourceList > { data . firmwares . map ( item = > < li key = { item . sha256 } > < ResourceRow title = { item . filename } metadata = { ` ${ item . bytes . toLocaleString ( 'ru-RU' ) } байт · ${ formatTime ( item . added_at ) } ` } description = { item . complete ? undefined : 'Загрузка не завершена — выберите файл повторно' } actions = { < IconButton label = { ` Скачать ${ item . filename } ` } disabled = { ! item . complete || Boolean ( busy ) } onClick = { ( ) = > void run ( 'firmware' , ( ) = > downloadFirmware ( item . sha256 ) ) } > < Icon name = "download" / > < / IconButton > } / > < / li > ) } < / ResourceList >
{ ! data . firmwares . length ? < span > Н е т с о х р а н ё н н ы х ф а й л о в < / span > : null }
< / SettingsCard > < / > : null }
< / div >
< / FeatureSettingsWindow >
{ commandsOpen ? < B2CommandWindow projectRef = { projectRef } device = { device } data = { data } canCommand = { canCommand } onClose = { ( ) = > setCommandsOpen ( false ) } onError = { onError } / > : null }
< Window open = { profileOpen } title = "Сохранить профиль" size = "sm" onClose = { ( ) = > setProfileOpen ( false ) } footer = { < Button loading = { busy === 'profile' } disabled = { Boolean ( busy ) || ! profileName . trim ( ) } onClick = { ( ) = > void run ( 'profile' , async ( ) = > { profileIntent . current || = { action : 'profile-save' , id :newIntent ( ) , name :profileName , policy } ; try { await request ( profileIntent . current ) ; profileIntent . current = null ; } catch ( error ) { if ( error instanceof B2RequestError && error . rejected ) profileIntent . current = null ; throw error ; } setProfileOpen ( false ) ; await refresh ( ) ; } ) } > С о х р а н и т ь п р о ф и л ь < / Button > } > < TextField label = "Название профиля" disabled = { Boolean ( busy ) || Boolean ( profileIntent . current ) } autoFocus value = { profileName } onChange = { event = > setProfileName ( event . target . value ) } / > < / Window >
< / > ;
}
const presets = [ { id : 'position' , label : 'Запросить координаты' , command : { kind : 'request-position' } } , { id : 'restart' , label : 'Перезапустить B2' , command : { kind : 'restart' } } , . . . [ 4 , 5 , 6 ] . flatMap ( pin = > [ . . . ( [ true , false ] as const ) . map ( enabled = > ( { id : ` pin ${ pin } - ${ enabled } ` , label : ` ${ enabled ? 'Включить' : 'Выключить' } выход PIN ${ pin } ` , command : { kind : 'set-output' , pin , enabled } } ) ) , { id : ` pin ${ pin } -pulse ` , label : ` Импульс PIN ${ pin } · 5 с ` , command : { kind : 'pulse-output' , pin , seconds :5 } } ] ) ] ;
function B2CommandWindow ( { projectRef , device , data , canCommand , onClose , onError } : { projectRef :string ; device :TrackerRef ; data :TrackerState | null ; canCommand :boolean ; onClose : ( ) = > void ; onError : ( error :unknown ) = > void } ) {
const [ filter , setFilter ] = useState ( 'all' ) ;
const [ selection , setSelection ] = useState ( 'position' ) , [ rows , setRows ] = useState < Operation [ ] > ( [ ] ) , [ before , setBefore ] = useState < number | null > ( null ) , [ busy , setBusy ] = useState ( false ) , [ details , setDetails ] = useState < string [ ] > ( [ ] ) , [ history , setHistory ] = useState < Record < string , unknown > > ( { } ) ;
const intent = useRef < Record < string , unknown > | null > ( null ) , alive = useRef ( true ) ;
const request = < T , > ( body :Record < string , unknown > ) = > trackerRequest < T > ( projectRef , device , body ) ;
async function refresh ( append = false ) { const result = await request < { items :Operation [ ] ; before :number | null } > ( { action : 'journal' , . . . ( append && before ? { before } : { } ) } ) ; if ( alive . current ) { setRows ( old = > append ? [ . . . old , . . . result . items ] : result . items ) ; setBefore ( result . before ) ; } }
useEffect ( ( ) = > { alive . current = true ; void refresh ( ) . catch ( onError ) ; return ( ) = > { alive . current = false ; } ; } , [ ] ) ;
useEffect ( ( ) = > { if ( ! rows . some ( row = > [ 'queued' , 'dispatched' ] . includes ( row . state ) ) ) return ; const timer = setTimeout ( ( ) = > void refresh ( ) . catch ( onError ) , 3000 ) ; return ( ) = > clearTimeout ( timer ) ; } , [ rows ] ) ;
const selected = presets . find ( item = > item . id === selection ) ! ;
const pin = 'pin' in selected.command?selected.command.pin :null ;
const available = data ? . capabilities . configuration && ( ! pin || data . observed ? . output_modes [ String ( pin ) ] === 1 ) ;
async function send ( command :Record < string , unknown > = selected . command ) { setBusy ( true ) ; try { intent . current || = { action : 'command' , id :newIntent ( ) , command } ; await request ( intent . current ) ; intent . current = null ; await refresh ( ) ; } catch ( error ) { if ( error instanceof B2RequestError && error . rejected ) intent . current = null ; onError ( error ) ; } finally { setBusy ( false ) ; } }
return < Window open title = "Команды устройства" subtitle = { ` ARNavi B2 · ${ device . number } ` } size = "lg" onClose = { onClose } headerActions = { < IconButton label = "Обновить журнал команд" disabled = { busy } onClick = { ( ) = > void refresh ( ) . catch ( onError ) } > < Icon name = "refresh" / > < / IconButton > } >
< div className = "b2-tracker-form" >
< SettingsCard title = "Отправка команды" > < div className = "b2-tracker-form" > < Select label = "Команда" value = { selection } disabled = { busy || Boolean ( intent . current ) } options = { presets . map ( item = > ( { value :item.id , label :item.label } ) ) } onChange = { setSelection } / >
{ pin ? < span > П о д т в е р ж д е н и е д о с т а в к и н е о п р е д е л я е т п о л о ж е н и е к о н т а к т о в р е л е . < / span > : null }
< Button loading = { busy } disabled = { busy || ! canCommand || ! available } onClick = { ( ) = > void send ( ) } > { intent . current ? 'Уточнить отправку' : 'Отправить' } < / Button >
< / div > < / SettingsCard >
< SettingsCard title = "Журнал команд" > < Select label = "Показать команды" value = { filter } onChange = { setFilter } options = { [ { value : 'all' , label : 'Все команды' } , { value : 'pending' , label : 'Ожидают результата' } , { value : 'finished' , label : 'Завершённые' } ] } / > < ResourceList > { rows . filter ( row = > filter === 'all' || ( filter === 'pending' ) === [ 'queued' , 'dispatched' ] . includes ( row . state ) ) . map ( row = > < li key = { row . id } > < ResourceRow title = { operationName ( row . kind , row . command ) } metadata = { formatTime ( row . created_at ) } status = { < StatusBadge tone = { [ 'verified' , 'observed' , 'delivered' , 'confirmed' ] . includes ( row . state ) ? 'success' : 'neutral' } > { stateName ( row . state ) } < / StatusBadge > } actions = { < > { canCommand && row . repeatable && row . command ? < IconButton label = { ` Повторить ${ operationName ( row . kind , row . command ) } ` } disabled = { busy || Boolean ( intent . current ) } onClick = { ( ) = > { const preset = presets . find ( item = > JSON . stringify ( item . command ) === JSON . stringify ( row . command ) ) ; if ( preset ) setSelection ( preset . id ) ; void send ( row . command ) ; } } > < Icon name = "refresh" / > < / IconButton > : null } < IconButton label = { ` Подробнее ${ row . id } ` } aria-expanded = { details . includes ( row . id ) } onClick = { ( ) = > { setDetails ( old = > old . includes ( row . id ) ? old . filter ( id = > id !== row . id ) : [ . . . old , row . id ] ) ; void request ( { action : 'attempts' , operation :row.id } ) . then ( value = > setHistory ( old = > ( { . . . old , [ row . id ] : value } ) ) ) . catch ( onError ) ; } } > < Icon name = { details . includes ( row . id ) ? 'chevron-up' : 'chevron-down' } / > < / IconButton > { canCommand && [ 'queued' , 'dispatched' ] . includes ( row . state ) ? < IconButton label = { ` Остановить ${ row . id } ` } onClick = { ( ) = > void request ( { action : 'cancel' , operation :row.id , kind :row.kind } ) . then ( ( ) = > refresh ( ) ) . catch ( onError ) } > < Icon name = "close" / > < / IconButton > : null } < / > } / >
{ details . includes ( row . id ) ? < div className = "b2-disclosure__body" > < dl className = "b2-tracker-facts" > < dt > П о п ы т к и < / dt > < dd > { row . attempt_count ? ? 0 } < / dd > < dt > О т п р а в л е н а < / dt > < dd > { formatTime ( row . dispatched_at ) } < / dd > < dt > О т в е т < / dt > < dd > { formatTime ( row . received_at || row . delivered_at || row . verified_at ) } < / dd > < dt > Р е з у л ь т а т < / dt > < dd > { stateName ( row . state ) } < / dd > < dt > ID < / dt > < dd > { row . id } < / dd > < / dl > < AttemptRows value = { history [ row . id ] } / > < / div > : null }
< / li > ) } < / ResourceList > { ! rows . length ? < span > К о м а н д п о к а н е т < / span > : null } { before ? < Button onClick = { ( ) = > void refresh ( true ) . catch ( onError ) } > П р е д ы д у щ и е к о м а н д ы < / Button > : null } < / SettingsCard >
< / div >
< / Window > ;
}
function AttemptRows ( { value } : { value :unknown } ) { const items = ( value as { items? :Operation [ ] } | undefined ) ? . items ; return items ? . length ? < ResourceList > { items . map ( ( item , index ) = > < li key = { item . id || index } > < ResourceRow title = { ` Попытка ${ item . number ? ? index + 1 } ` } metadata = { formatTime ( item . dispatched_at ) } status = { < StatusBadge > { stateName ( item . state ) } < / StatusBadge > } / > < / li > ) } < / ResourceList > : null ; }