feat(ui): add tracker provisioning, SIM policies, command history and firmware archive

This commit is contained in:
DCCONSTRUCTIONS
2026-09-28 18:44:18 +03:00
parent f3a7592d90
commit 031e01a99b
24 changed files with 929 additions and 4 deletions
@@ -2,6 +2,7 @@ import {useId,useState,type FormEvent} from 'react';
import {Button,Select,SettingsCard,TextAreaField,TextField,StatusBadge} from '@nodedc/ui-react';
import {fleetRequest,type FleetPreview,type Vehicle} from '../../core/fleet/useFleet';
import type {SensorEnrollmentProps} from '../../../../../packages/sensor-ui/src/extensions';
import {InstallerCard} from './equipment/InstallerCard';
export const platforms=[{value:'ugv',label:'Наземный (UGV)'},{value:'uav',label:'Воздушный (UAV)'},{value:'stationary',label:'Стационарный'},{value:'other',label:'Другой'}];
export const platformLabel=(value:string)=>platforms.find(item=>item.value===value)?.label??value;
@@ -31,6 +32,7 @@ export function NodeInvitationForm({vehicle,onClose,onComplete,renderWindow}:{ve
const replacing=!!vehicle&&vehicle.enrollment!=='revoked';
return renderWindow({busy:pending,actions:<><Button disabled={pending} onClick={onClose}>Отмена</Button>{preview?<Button loading={pending} disabled={pending||(!vehicle&&!name.trim())} onClick={()=>void attach()}>{vehicle?(replacing?'Заменить БК':'Подключить БК'):'Добавить аппарат'}</Button>:<Button loading={pending} type="submit" form={form} disabled={pending||!code.trim()}>Проверить БК</Button>}</>,content:
<form id={form} className="fleet-form" onSubmit={inspect} aria-busy={pending}>
{!preview&&<InstallerCard kind="node"/>}
{!vehicle&&<><Select label="Класс аппарата" value={platform} options={platforms} onChange={setPlatform} disabled={pending}/><TextField label="Название аппарата" value={name} maxLength={80} onChange={e=>setName(e.target.value)} disabled={pending} autoComplete="off"/></>}
{vehicle&&<SettingsCard title={vehicle.name} description={replacing?'Новый БК заменит текущий. Аппарат, его название и раскладки сохранятся; прежняя привязка будет отозвана.':'Подключите БК к этому аппарату по приглашению Mission Core Node.'}/>}
{preview?<SettingsCard title={preview.name} description="Идентичность БК проверена по приглашению"><dl className="fleet-facts"><div><dt>Идентификатор БК</dt><dd>{preview.node_id}</dd></div><div><dt>Система</dt><dd>{preview.host.os} · {preview.host.architecture}</dd></div><div><dt>Адрес БК</dt><dd>{preview.endpoint}</dd></div></dl><Button disabled={pending} onClick={()=>setPreview(null)}>Другое приглашение</Button></SettingsCard>:<TextAreaField label="Код приглашения из Node" value={code} rows={5} maxLength={4096} spellCheck={false} autoComplete="off" disabled={pending} onChange={e=>setCode(e.target.value)}/>}
@@ -1,10 +1,11 @@
import {useEffect,useSyncExternalStore} from 'react';
import {Button,Icon,IconButton,Inspector,LoadingRegion} from '@nodedc/ui-react';
import {Button,Icon,Inspector,LoadingRegion} from '@nodedc/ui-react';
import type {BoardLayoutStore} from '../../../../../packages/sensor-ui/src/boardLayout';
import type {SensorBoardContent} from '../../../../../packages/sensor-ui/src/SensorWorkspace';
import type {Vehicle} from '../../core/fleet/useFleet';
import {VehicleIdentitySettings} from './VehicleIdentitySettings';
import {BoardComputerRow} from './BoardComputer';
import {IndependentEquipment} from './equipment/IndependentEquipment';
export function VehicleEquipment({vehicle,enabled,layout,content,onAddComputer,onSettings,onMonitor,onUpdated}:{vehicle:Vehicle;enabled:boolean;layout:BoardLayoutStore;content:SensorBoardContent;onAddComputer:()=>void;onSettings:()=>void;onMonitor:()=>void;onUpdated:(vehicle:Vehicle)=>void}){
const state=useSyncExternalStore(layout.subscribe,layout.getSnapshot);
@@ -19,10 +20,9 @@ export function VehicleEquipment({vehicle,enabled,layout,content,onAddComputer,o
<Inspector variant="panel" openSections={state.value.open_sections.filter(id=>id!=='computer')} onOpenSectionsChange={changeSections} sections={[
{id:'settings',label:'Настройки аппарата',icon:<Icon name="sliders"/>,disabled:!state.ready,content:<div className="sensor-content"><VehicleIdentitySettings key={vehicle.id} vehicle={vehicle} onUpdated={onUpdated}/>{content.settings}</div>},
{id:'devices',label:'Оборудование',icon:<Icon name="apps"/>,disabled:!state.ready,content:<div className="sensor-content">
<div className="sensor-actions sensor-inventory-toolbar"><span className="sensor-note">Бортовой компьютер и подключённые к нему устройства</span><div className="sensor-actions"><IconButton label="Подключить бортовой компьютер" onClick={onAddComputer}><Icon name="plus"/></IconButton><IconButton label="Обновить оборудование" onClick={()=>void content.refresh()}><Icon name="refresh"/></IconButton></div></div>
<div><BoardComputerRow vehicle={vehicle} enabled={enabled} showingSavedDevices={content.showingSavedDevices} open={computerOpen} onToggle={toggleComputer} onSettings={onSettings} onMonitor={onMonitor} onAdd={content.canAddDevice?content.addDevice:undefined}/>
<IndependentEquipment key={vehicle.id} vehicle={vehicle} onComputer={onAddComputer} onRefresh={()=>void content.refresh()} computer={<div><BoardComputerRow vehicle={vehicle} enabled={enabled} showingSavedDevices={content.showingSavedDevices} open={computerOpen} onToggle={toggleComputer} onSettings={onSettings} onMonitor={onMonitor} onAdd={content.canAddDevice?content.addDevice:undefined}/>
{computerOpen&&<div className="fleet-computer-devices">{content.devices}</div>}
</div>
</div>}/>
</div>},
]}/>
</LoadingRegion>
@@ -0,0 +1,32 @@
import {Button,ResourceList,ResourceRow,SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {commandPending,commandDate,commandDuration,commandReason,commandReceipt,commandEntryStatus,commandStatus,commandTone,type CommandEntry} from '../../../core/fleet/commandRuntime';
import {useCommandAttempts} from '../../../core/fleet/useCommandAttempts';
export function CommandHistory({identifier,items,selected,onSelect,onCancel,working,cancelling}:{identifier:string;items:CommandEntry[];selected:string;onSelect:(id:string)=>void;onCancel:(id:string)=>void;working:boolean;cancelling:string}){
return <ResourceList aria-label="Журнал команд B2">{items.map(item=><li key={item.id}><ResourceRow title={item.description.label??'Операция B2'} description={commandDate(item.created_at)} metadata={`${item.durable?`Попыток: ${item.attempt_count??0} · `:''}Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandEntryStatus(item)}</StatusBadge>} actions={<><Button aria-pressed={item.id===selected} onClick={()=>onSelect(item.id===selected?'':item.id)}>Подробнее</Button>{(item.state==='waiting'||item.durable&&commandPending(item.state))&&<Button loading={cancelling===item.id} disabled={working||item.stop_requested} onClick={()=>onCancel(item.id)}>{item.state==='waiting'?'Отменить':item.stop_requested?'Остановка повторов':'Остановить повторы'}</Button>}</>}/>{item.id===selected&&<CommandDetails key={item.id} identifier={identifier} current={item}/>}</li>)}</ResourceList>;
}
function CommandDetails({identifier,current}:{identifier:string;current:CommandEntry}){
const attempts=useCommandAttempts(identifier,current);
return <SettingsCard title={current.description.label??'Операция B2'} description={`ID ${current.id} · ПО ${current.firmware??'неизвестно'}`}>
{current.description.wire&&<p><code>{current.description.wire}</code></p>}
<dl className="fleet-facts">
<div><dt>Принято Core</dt><dd>{commandDate(current.created_at)}</dd></div>
{current.durable?<><div><dt>Попыток</dt><dd>{current.attempt_count??0}</dd></div>{current.attempt_expires_at!==undefined&&<div><dt>Срок текущей попытки</dt><dd>{commandDate(current.attempt_expires_at)}</dd></div>}</>:<><div><dt>Срок отправки из Core</dt><dd>{commandDate(current.queue_deadline)}</dd></div><div><dt>Срок ожидания ответа</dt><dd>{commandDate(current.expires_at)}</dd></div></>}
<div><dt>Отправлено B2</dt><dd>{commandDate(current.dispatched_at)}</dd></div><div><dt>Ответ B2</dt><dd>{commandDate(current.received_at)}</dd></div>
{current.device_accepted_at!==undefined&&<div><dt>Принято B2</dt><dd>{commandDate(current.device_accepted_at)}</dd></div>}
{current.scope==='command'&&<div><dt>Результат B2</dt><dd>{commandReceipt(current)}</dd></div>}
<div><dt>До ответа</dt><dd>{commandDuration(current.roundtrip_seconds)}</dd></div>
{current.reconnected_at!==undefined&&<div><dt>Возвращение на связь</dt><dd>{commandDate(current.reconnected_at)}</dd></div>}
</dl>
{commandReason(current)&&<p>{commandReason(current)}</p>}
<p>{current.description.confirmation}</p>
{current.stop_requested&&<p>Новые попытки остановлены или ожидают остановки на VPS. Уже переданная попытка может завершиться.</p>}
{current.durable&&<>
<ResourceList aria-label="Попытки доставки">{attempts.items.map(item=><li key={item.id}><ResourceRow title={`Попытка ${item.number}${item.phase==='inspect'?' · проверка состояния':''}`} description={`Отправлено: ${commandDate(item.dispatched_at)} · Ответ: ${commandDate(item.received_at)} · ${commandDuration(item.roundtrip_seconds)}`} status={<StatusBadge tone={commandTone(item.state)}>{commandStatus(item.state)}</StatusBadge>} metadata={item.device_code!==undefined?commandReceipt({...current,device_code:item.device_code}):undefined}/></li>)}</ResourceList>
{attempts.error&&<><p>{attempts.error}</p><Button onClick={attempts.refresh}>Повторить чтение попыток</Button></>}
{attempts.next_before!==null&&<Button loading={attempts.working} onClick={()=>void attempts.more()}>Предыдущие попытки</Button>}
</>}
<ResourceList aria-label="Этапы операции">{[...current.events].sort((a,b)=>(a.occurred_at??a.observed_at)-(b.occurred_at??b.observed_at)).map((event,index)=><li key={index}><ResourceRow title={`${commandStatus(event.state)}${event.attempt?` ${event.attempt}`:''}`} description={event.stage?({preflight:'Чтение настроек',write:'Запись',verify:'Проверка',restart:'Ожидание после перезапуска'} as Record<string,string>)[event.stage]:undefined} metadata={`${commandDate(event.occurred_at??event.observed_at)}${event.historical?' · восстановлено из истории':''}`}/></li>)}</ResourceList>
</SettingsCard>;
}
@@ -0,0 +1,26 @@
import {SettingsCard,StatusBadge} from '@nodedc/ui-react';
import {cellularCardOperator,cellularFresh,cellularNetworkLabel,cellularSimLabel,cellularSlotView} from '../../../core/fleet/cellular';
import type {EquipmentObservation} from '../../../core/fleet/equipment';
import type {TrackerTelemetry} from '../../../core/fleet/vps';
export function EquipmentCellular({telemetry,observed}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation}){
const status=telemetry?.cellular?.status;
const configTime=observed.configuration_read_at??observed.read_at;
return <div className="fleet-form">
{(['1','2'] as const).map(slot=>{
const view=cellularSlotView(telemetry,slot),network=view.network;
const fresh=!!telemetry?.online&&cellularFresh(network);
const apn=slot==='1'?observed.configuration.apn1:observed.configuration.apn2;
return <SettingsCard key={slot} title={`SIM ${slot}`} description={view.absent?'B2 не обнаружил карту. Вставленная резервная SIM может определиться при переходе на неё.':cellularCardOperator(telemetry,slot)??cellularNetworkLabel(network)} actions={<StatusBadge tone={view.internet?'success':'neutral'}>{view.role}</StatusBadge>}>
<dl className="fleet-facts">
<div><dt>Регистрация</dt><dd>{cellularSimLabel(status?.sim_states[slot])}</dd></div>
{!view.absent&&network&&<>
<div><dt>Сигнал</dt><dd>{network.signal===null?'Неизвестен':`${network.signal} из 31`}</dd></div>
<div><dt>{fresh?'Сеть измерена':'Последнее измерение сети'}</dt><dd>{new Date(network.measured_at*1000).toLocaleString('ru-RU')}</dd></div>
</>}
<div><dt>APN из настроек B2</dt><dd>{apn||'Не задан'}<br/>Прочитан {new Date(configTime*1000).toLocaleString('ru-RU')}</dd></div>
</dl>
</SettingsCard>;
})}
</div>;
}
@@ -0,0 +1,36 @@
import {useState} from 'react';
import {Button,LoadingRegion,Select,SettingsCard,StatusBadge,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {commandPending} from '../../../core/fleet/commandRuntime';
import {useCommandRuntime} from '../../../core/fleet/useCommandRuntime';
import {telemetryLabel,type TrackerTelemetry} from '../../../core/fleet/vps';
import type {IndependentDevice} from '../../../core/fleet/equipment';
import {CommandHistory} from './CommandHistory';
export function EquipmentCommandWindow({device,telemetry,onClose}:{device:IndependentDevice;telemetry?:TrackerTelemetry;onClose:()=>void}){
const runtime=useCommandRuntime(device.id);
const [preset,setPreset]=useState('position'),[filter,setFilter]=useState('all'),[selected,setSelected]=useState('');
const data=runtime.data,chosen=data?.catalog.find(value=>value.id===(runtime.intent?.preset_id??preset));
const pending=Object.entries(data?.counts??{}).reduce((total,[state,n])=>total+(commandPending(state)?n:0),0);
const items=runtime.items.filter(item=>filter==='all'||(filter==='active'?commandPending(item.state):!commandPending(item.state)));
return <><Window open title="Команды ARNavi B2" subtitle={data?.device.name??device.name} size="lg" onClose={onClose}>
<div className="fleet-form">
<StatusBadge tone={telemetry?.online?'success':'neutral'}>{telemetryLabel(telemetry)}</StatusBadge>
<LoadingRegion loading={!data&&!runtime.error} label="Загрузка команд и журнала">
{data&&<>
<SettingsCard title="Отправить команду" description={`B2 · ПО ${data.device.observed.firmware}`}>
<Select label="Команда" value={runtime.intent?.preset_id??preset} options={data.catalog.map(value=>({value:value.id,label:value.label,disabled:!!value.unavailable}))} disabled={runtime.working||!!runtime.intent} onChange={setPreset}/>
{chosen&&<><dl className="fleet-facts"><div><dt>{chosen.encoding} · тело</dt><dd><code>{chosen.wire}</code></dd></div></dl><p>{chosen.confirmation} {data.durable_kinds?.includes(chosen.command.kind)?'Задание сохраняется до результата или остановки повторов. При потере связи VPS уточняет результат и повторяет неподтверждённые попытки.':`Ожидание отправки: до ${chosen.queue_seconds} с. Отправленная команда автоматически не повторяется.`}{chosen.encoding.includes('FC')&&' Пароль скрыт.'}</p>{chosen.unavailable&&<p>{chosen.unavailable}</p>}</>}
<WindowFooterActions><Button loading={runtime.activity==='send'} disabled={runtime.working||(!runtime.intent&&(!chosen||!!chosen.unavailable||pending>=data.capacity))} onClick={()=>void runtime.send(preset)}>{runtime.intent?'Уточнить отправку':'Отправить'}</Button></WindowFooterActions>
</SettingsCard>
<SettingsCard title="Журнал операций" description={`Незавершённых: ${pending} · Вместимость очереди: ${data.capacity}`}>
<Select label="Показать операции" value={filter} onChange={setFilter} options={[{value:'all',label:'Все операции'},{value:'active',label:'В очереди и выполняются'},{value:'finished',label:'Завершённые'}]}/>
{!items.length&&<p>{runtime.items.length?'В загруженной части истории таких операций нет.':'Команд пока нет.'}</p>}
<CommandHistory identifier={device.id} items={items} selected={selected} onSelect={setSelected} onCancel={id=>void runtime.cancel(id)} working={runtime.working} cancelling={runtime.activity}/>
{runtime.before!==null&&<WindowFooterActions><Button loading={runtime.activity==='more'} disabled={runtime.working} onClick={()=>void runtime.more()}>Загрузить предыдущие</Button></WindowFooterActions>}
</SettingsCard>
</>}
</LoadingRegion>
{!data&&runtime.error&&<Button onClick={()=>void runtime.refresh().catch(()=>undefined)}>Повторить чтение</Button>}
</div>
</Window><ToastStack items={runtime.error?[{id:'command-runtime-error',title:runtime.error,tone:'error',durationMs:null}]:[]} onDismiss={()=>runtime.setError('')}/></>;
}
@@ -0,0 +1,29 @@
import {useState} from 'react';
import {Button,Select,SettingsCard,StatusBadge,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {equipmentRequest,type EquipmentCandidate,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
import {NodeInvitationForm} from '../NodeInvitationForm';
import {VPSHostSettings} from './VPSHostSettings';
import type {VPSHost} from '../../../core/fleet/vps';
import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/src/extensions';
import type {Vehicle} from '../../../core/fleet/useFleet';
export function EquipmentConnect({vehicle,vehicles,models,profiles,hosts,onComputer,onVPS,onClose,onAdded}:{vehicle:Vehicle;vehicles:Vehicle[];models:EquipmentModel[];profiles:EquipmentProfile[];hosts:VPSHost[];onComputer:()=>void;onVPS:()=>void;onClose:()=>void;onAdded:(item:IndependentDevice)=>void}){
const [type,setType]=useState('computer'),[name,setName]=useState(''),[target,setTarget]=useState(vehicle.id),[profile,setProfile]=useState('');
const [candidate,setCandidate]=useState<EquipmentCandidate|null>(null),[busy,setBusy]=useState(false),[error,setError]=useState('');
const model=models.find(m=>m.id===type),selectedProfile=profiles.find(p=>p.id===profile);
async function inspect(){setBusy(true);setError('');setCandidate(null);try{const value=await equipmentRequest<EquipmentCandidate>('/inspect','POST',{model_id:type});setCandidate(value);setName(current=>current||`${model?.label??''} · ${value.observed.device_id}`);}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать устройство.');}finally{setBusy(false);}}
async function add(){if(!candidate)return;setBusy(true);setError('');try{onAdded(await equipmentRequest<IndependentDevice>('/instances','POST',{candidate_id:candidate.id,name:name.trim(),vehicle_id:target,profile_id:profile||null}));}catch(e){setError(e instanceof Error?e.message:'Не удалось добавить устройство.');}finally{setBusy(false);}}
const renderWindow:SensorEnrollmentProps['renderWindow']=({content,actions,busy:pending})=><Window open title="Подключить независимое устройство" subtitle={vehicle.name} size="md" closeOnBackdrop={false} closeOnEscape={!pending} onClose={()=>{if(!pending)onClose();}} footer={<WindowFooterActions>{actions}</WindowFooterActions>}><div className="fleet-form"><Select label="Тип устройства" value={type} options={[{value:'computer',label:'Бортовой компьютер'},...models.map(m=>({value:m.id,label:m.label})),{value:'vps-host',label:'VPS Host ARNavi'}]} disabled={pending} onChange={value=>{setType(value);setCandidate(null);setName('');setProfile('');}}/>{content}</div></Window>;
if(type==='computer')return <NodeInvitationForm vehicle={vehicle} onClose={onClose} onComplete={()=>onComputer()} renderWindow={renderWindow}/>;
if(type==='vps-host')return <VPSHostSettings hosts={hosts} vehicle={vehicle} vehicles={vehicles} onClose={onClose} onSaved={onVPS} renderWindow={renderWindow}/>;
return <>{renderWindow({busy,actions:<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!candidate||!name.trim()||!target} onClick={()=>void add()}>Добавить к аппарату</Button></>,content:<div className="fleet-form">
{model&&<><TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
<Select label="Аппарат" value={target} options={vehicles.map(v=>({value:v.id,label:v.name}))} onChange={setTarget} disabled={busy}/>
<Select label="Профиль настроек" value={profile} options={[{value:'',label:'Прочитать настройки трекера'},...profiles.filter(p=>p.model_id===type).map(p=>({value:p.id,label:`${p.name} · ${new Date(p.created_at*1000).toLocaleString('ru-RU')}`}))]} onChange={setProfile} disabled={busy}/>
{selectedProfile&&<SettingsCard title={selectedProfile.name} description={selectedProfile.settings.endpoint?`${selectedProfile.settings.endpoint.host}:${selectedProfile.settings.endpoint.port} · сервер ${selectedProfile.settings.endpoint.slot}`:'Адрес сервера сохраняется из трекера'}/>}
<SettingsCard title="USB на этом Mac" description="Подключите один трекер кабелем с передачей данных. Проверка считает модель, идентификатор и настройки."><Button loading={busy} disabled={busy} onClick={()=>void inspect()}>{candidate?'Прочитать повторно':'Проверить USB'}</Button></SettingsCard>
{candidate&&<SettingsCard title={`${candidate.observed.model} · ${candidate.observed.device_id}`} description={`IMEI …${candidate.observed.imei_suffix} · ПО ${candidate.observed.firmware}`}><StatusBadge tone="success">Настройки прочитаны</StatusBadge><p>Устройство будет добавлено в реестр. Передача на ваш сервер ещё не подтверждена; выбранный профиль будет сохранён для настройки.</p></SettingsCard>}
</>}
</div>
})}<ToastStack items={error?[{id:'equipment-connect',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
}
@@ -0,0 +1,44 @@
import {useEffect,useRef,useState} from 'react';
import {Button,Icon,LoadingRegion,Select,SettingsCard,StatusBadge,ToastStack} from '@nodedc/ui-react';
import type {IndependentDevice} from '../../../core/fleet/equipment';
import {downloadFirmware,readFirmware,uploadFirmware,type FirmwareCatalog} from '../../../core/fleet/firmware';
export function EquipmentFirmware({device}:{device:IndependentDevice}){
const [catalog,setCatalog]=useState<FirmwareCatalog|null>(null),[selected,setSelected]=useState('');
const [loading,setLoading]=useState(true),[uploading,setUploading]=useState(false),[downloading,setDownloading]=useState(false);
const [loadError,setLoadError]=useState(''),[error,setError]=useState(''),[notice,setNotice]=useState(''),[reload,setReload]=useState(0);
const picker=useRef<HTMLInputElement>(null);
useEffect(()=>{let active=true;setLoading(true);setLoadError('');
readFirmware(device.model_id).then(value=>{if(active){setCatalog(value);setSelected(current=>value.items.some(item=>item.id===current)?current:value.items[0]?.id??'');}})
.catch(e=>{if(active)setLoadError(e instanceof Error?e.message:'Не удалось прочитать архив прошивок.');})
.finally(()=>{if(active)setLoading(false);});return()=>{active=false;};
},[device.model_id,reload]);
const item=catalog?.items.find(image=>image.id===selected);
async function add(file:File){setUploading(true);setError('');setNotice('');try{
const image=await uploadFirmware(device.model_id,file);setSelected(image.id);setReload(value=>value+1);setNotice('Файл сохранён в Mission Core. Прошивка трекера не изменена.');
}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить файл.');}finally{setUploading(false);}}
async function download(){if(!item)return;setDownloading(true);setError('');try{await downloadFirmware(item);}catch(e){setError(e instanceof Error?e.message:'Не удалось скачать файл.');}finally{setDownloading(false);}}
const recordedVersion=device.observed.firmware;
return <>
<SettingsCard title="Прошивка трекера" description="Последняя считанная версия устройства.">
<dl className="fleet-facts"><div><dt>Версия</dt><dd>{recordedVersion||'Нет сведений'}</dd></div><div><dt>Считана</dt><dd>{device.observed.read_at?new Date(device.observed.read_at*1000).toLocaleString('ru-RU'):'Нет сведений'}</dd></div></dl>
<p>Обновление прошивки через Mission Core недоступно. Файлы ниже хранятся отдельно от настроек трекера.</p>
</SettingsCard>
<SettingsCard title="Файлы прошивок" description="Архив Mission Core. Добавление и выбор файла не запускают установку.">
<input ref={picker} type="file" accept=".dfw" hidden aria-label="Файл прошивки .dfw" onChange={e=>{const file=e.target.files?.[0];e.target.value='';if(file)void add(file);}}/>
<Button icon={<Icon name="upload"/>} loading={uploading} disabled={uploading||downloading} onClick={()=>picker.current?.click()}>Добавить файл .dfw</Button>
<LoadingRegion loading={loading} label="Читаем архив прошивок">
{loadError?<><p>{loadError}</p><Button onClick={()=>setReload(value=>value+1)}>Повторить загрузку</Button></>:catalog?.items.length?<>
<Select label="Файл прошивки" value={selected} onChange={setSelected} disabled={uploading||downloading} options={catalog.items.map(image=>({value:image.id,label:image.version?`${image.version} · ${image.filename}`:image.filename}))}/>
{item&&<>
<StatusBadge tone="neutral">{item.source==='manufacturer'?'Файл производителя':'Файл пользователя · совместимость не проверена'}</StatusBadge>
<dl className="fleet-facts"><div><dt>Версия файла</dt><dd>{item.version??'Не определена'}</dd></div><div><dt>Размер</dt><dd>{new Intl.NumberFormat('ru-RU').format(item.bytes)} байт</dd></div><div><dt>Сохранён</dt><dd>{new Date(item.added_at*1000).toLocaleString('ru-RU')}</dd></div></dl>
<Button icon={<Icon name="download"/>} loading={downloading} disabled={uploading||downloading} onClick={()=>void download()}>Скачать файл</Button>
</>}
{recordedVersion&&!catalog.items.some(image=>image.source==='manufacturer'&&image.version===recordedVersion)&&<p>Образ считанной версии {recordedVersion} в архиве не найден. Сохранённые настройки не являются копией прошивки.</p>}
</>:<p>Файлов прошивок пока нет. Добавьте файл .dfw с компьютера.</p>}
</LoadingRegion>
</SettingsCard>
<ToastStack items={error?[{id:'firmware-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'firmware-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/>
</>;
}
@@ -0,0 +1,26 @@
import {Select,SettingsCard,Switch,TextField} from '@nodedc/ui-react';
import {cellularFresh,cellularSimOptions} from '../../../core/fleet/cellular';
import {allowBothInternetSims,selectInternetSim,type ConnectivityPreset,type EquipmentObservation,type EquipmentPolicy} from '../../../core/fleet/equipment';
import type {TrackerTelemetry} from '../../../core/fleet/vps';
export function EquipmentInternet({telemetry,observed,presets,value,onChange,disabled}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation;presets:ConnectivityPreset[];value:EquipmentPolicy;onChange:(value:EquipmentPolicy)=>void;disabled:boolean}){
const options=cellularSimOptions(telemetry);
const preferred=['both','native'].includes(value.connectivity.strategy)?value.connectivity.strategy:value.connectivity.activate?String(value.connectivity.sim_slot??1):'';
const both=['both','native'].includes(preferred);
const slot=both?preferred:options.some(option=>option.value===preferred)?preferred:'';
const current=slot==='1'?observed.configuration.apn1:observed.configuration.apn2;
const connection=value.connectivity;
const automatic=connection.strategy==='sim'&&connection.automatic===true;
const access=telemetry?.internet_access?.[slot];
const targeted=String(connection.sim_slot??1)===slot;
const apn=connection.strategy==='sim'&&targeted?connection.apn??current:connection.strategy==='operator'&&targeted?presets.find(p=>p.id===connection.preset_id)?.apn??current:connection.strategy==='manual'?(slot==='1'?connection.apn1:connection.apn2):current;
return <SettingsCard title="Интернет"><div className="fleet-form">
<Select label="SIM для интернета" value={slot} options={[{value:'',label:'Выберите режим SIM',disabled:true},{value:'native',label:'Обе SIM — без заданного APN'},{value:'both',label:'Обе SIM — сохранить APN'},...options.map(option=>({...option,label:`Только ${option.label}`}))]} disabled={disabled} onChange={next=>onChange(['both','native'].includes(next)?allowBothInternetSims(value,next==='native'):selectInternetSim(value,Number(next)))}/>
<p>{slot==='native'?'Оба слота разрешены. APN, логин и пароль обеих SIM будут очищены; B2 попробует подключиться без них. Для тарифов со специальным APN сохраните текущие параметры. После применения B2 перезапустится, результат проверим по новой связи.':slot==='both'?'B2 сможет использовать любую из установленных SIM. APN обеих карт сохранятся. Одновременно работает одна SIM; срок автоматического переключения не гарантирован. После сохранения B2 перезапустится.':'Выберите одну SIM для принудительного подключения или разрешите обе. При выборе одной интернет на другой запрещается. Если выбранная SIM не подключится, для восстановления может потребоваться USB.'}</p>
{!!options.length&&(!telemetry?.online||!cellularFresh(telemetry.cellular?.status))&&<p>Показаны последние обнаруженные SIM. Ожидаем обновления связи с B2.</p>}
{slot&&!both?<>
<Switch label="Подбирать интернет для этой карты" checked={automatic} disabled={disabled} onChange={checked=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:checked,apn:checked?null:apn,apn1:'',apn2:'',preset_id:null}})}/>
{automatic?<p>{access?.state==='ready'?`${access.source==='verified_card'?'Проверенные настройки этой карты':'Стандартные настройки оператора'}: ${access.apn}. После сохранения проверим запись и подключение выбранной SIM.`:access?.state==='unknown_card'?'Карта ещё не распознана. Прочитайте её через USB или отключите автоподбор и задайте APN.':access?.state==='unsupported_operator'?'Для этой карты нет сохранённых настроек. Отключите автоподбор и задайте APN.':'Ожидаем подтверждение карты в выбранном слоте.'}</p>:<TextField label="APN" value={apn} maxLength={29} disabled={disabled} hint={`В B2 прочитан: ${current||'не задан'}. Изменение будет отправлено при сохранении настроек.`} onChange={event=>onChange({...value,connectivity:{strategy:'sim',sim_slot:Number(slot),activate:true,automatic:false,apn:event.target.value,apn1:'',apn2:'',preset_id:null}})}/>}
</>:!both&&!options.length&&<p>Ожидаем актуальные сведения о SIM от трекера.</p>}
</div></SettingsCard>;
}
@@ -0,0 +1,17 @@
import {Select,SettingsCard,Switch,TextField} from '@nodedc/ui-react';
import type {TrackerTelemetry,VPSHost} from '../../../core/fleet/vps';
import type {ConnectivityPreset,EquipmentField,EquipmentObservation,EquipmentPolicy} from '../../../core/fleet/equipment';
import {EquipmentInternet} from './EquipmentInternet';
export function EquipmentPolicyFields({hosts,section,fields,presets,telemetry,observed,value,onChange,disabled}:{telemetry?:TrackerTelemetry;observed:EquipmentObservation;hosts:VPSHost[];section:string;fields:EquipmentField[];presets:ConnectivityPreset[];value:EquipmentPolicy;onChange:(value:EquipmentPolicy)=>void;disabled:boolean}){
if(section==='connection')return <div className="fleet-form">
<EquipmentInternet telemetry={telemetry} observed={observed} presets={presets} value={value} onChange={onChange} disabled={disabled}/>
<SettingsCard title="Сервер мониторинга" description="Используйте постоянное DNS-имя: при переезде VPS можно сохранить адрес в трекерах.">
<div className="fleet-form"><Select label="Зарегистрированный VPS" value={hosts.find(h=>h.status?.tracker.host===value.endpoint?.host&&h.status?.tracker.port===value.endpoint?.port)?.id??''} options={[{value:'',label:'Сохранить адрес или указать вручную'},...hosts.filter(h=>h.status).map(h=>({value:h.id,label:h.name}))]} disabled={disabled} onChange={id=>{const host=hosts.find(h=>h.id===id);if(host?.status)onChange({...value,endpoint:{...host.status.tracker,slot:value.endpoint?.slot??2}});}}/><Switch label="Задать сервер в профиле" checked={value.endpoint!==null} disabled={disabled} onChange={enabled=>onChange({...value,endpoint:enabled?{host:'',port:0,slot:1}:null})}/>
{value.endpoint&&<><TextField label="DNS/IP сервера" value={value.endpoint.host} maxLength={49} disabled={disabled} onChange={e=>onChange({...value,endpoint:{...value.endpoint!,host:e.target.value}})}/><TextField label="Порт" type="number" min={1} max={65535} value={value.endpoint.port||''} disabled={disabled} onChange={e=>onChange({...value,endpoint:{...value.endpoint!,port:Number(e.target.value)}})}/><Select label="Слот сервера" value={String(value.endpoint.slot)} options={[1,2,3,4].map(n=>({value:String(n),label:`Сервер ${n}`}))} disabled={disabled} onChange={slot=>onChange({...value,endpoint:{...value.endpoint!,slot:Number(slot)}})}/><p>Протокол INTERNAL. Остальные серверы сохраняются.</p></>}
</div>
</SettingsCard>
</div>;
return <div className="fleet-form"><p>Пустое поле — сохранить значение конкретного трекера. Ноль — задать нулевое значение.</p>{fields.filter(f=>f.group===section).map(field=><TextField key={field.key} label={field.label} type="number" min={field.min} max={field.max} step={1} hint={`${field.min} … ${field.max}`} value={value.parameters[field.key]??''} disabled={disabled} onChange={e=>{const parameters={...value.parameters};if(e.target.value==='')delete parameters[field.key];else parameters[field.key]=Number(e.target.value);onChange({...value,parameters});}}/>)}</div>;
}
@@ -0,0 +1,55 @@
import {useEffect,useRef,useState} from 'react';
import {Button,FeatureSettingsWindow,Select,SettingsCard,StatusBadge,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {configurationWriteNotStarted,simSelectionIntent,equipmentPolicyEqual,equipmentApplyMessage,equipmentRequest,networkOperationMessage,networkOperationProgress,policyError,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
import {cellularSimCurrent} from '../../../core/fleet/cellular';
import type {Vehicle} from '../../../core/fleet/useFleet';
import {telemetryLabel,type TrackerTelemetry,type VPSHost} from '../../../core/fleet/vps';
import {EquipmentPolicyFields} from './EquipmentPolicyFields';
import {EquipmentCellular} from './EquipmentCellular';
import {EquipmentFirmware} from './EquipmentFirmware';
export function EquipmentSettings({device,model,hosts,telemetry,vehicles,profiles,onClose,onObserved,onProfile,onCommands}:{device:IndependentDevice;model:EquipmentModel;hosts:VPSHost[];telemetry?:TrackerTelemetry;vehicles:Vehicle[];profiles:EquipmentProfile[];onClose:()=>void;onObserved:(item:IndependentDevice)=>void;onProfile:()=>void;onCommands:()=>void}){
const [name,setName]=useState(device.name),[target,setTarget]=useState(device.vehicle_id),[settings,setSettings]=useState(device.settings),[section,setSection]=useState('identity');
const [profileName,setProfileName]=useState(''),[profileOpen,setProfileOpen]=useState(false),[working,setBusy]=useState(false),[error,setError]=useState(''),[notice,setNotice]=useState(''),[selectedProfile,setSelectedProfile]=useState('');
const contentRef=useRef<HTMLDivElement>(null);
const [simRequested,setSimRequested]=useState(false);
const selectSim=simSelectionIntent(settings,device.settings,simRequested);
function changeSettings(value:typeof settings){if(value.connectivity!==settings.connectivity)setSimRequested(true);setSettings(value);}
const [now,setNow]=useState(()=>Date.now()/1000);
const progress=networkOperationProgress(device.network_operation,now);
const networkPending=progress.pending;
useEffect(()=>{if(!networkPending)return;setNow(Date.now()/1000);const timer=setInterval(()=>setNow(Date.now()/1000),1000);return()=>clearInterval(timer);},[networkPending,device.network_operation?.id]);
const busy=working||networkPending;
useEffect(()=>{if(!networkPending)return;let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await equipmentRequest<{items:IndependentDevice[]}>('/instances');const current=value.items.find(d=>d.id===device.id);if(active&&current)onObserved(current);}catch{/* Keep the pending operation visible; the VPS owns its bounded expiry. */}finally{if(active)timer=setTimeout(()=>void poll(),3000);}}timer=setTimeout(()=>void poll(),3000);return()=>{active=false;clearTimeout(timer);};},[device.id,networkPending,onObserved]);
const observed=device.observed;
const secondary=observed.configuration.servers.find(s=>s.slot===2);
const fullSettings=hosts.some(h=>h.state==='paired'&&h.vehicle_ids.includes(device.vehicle_id)&&['0.1.15','0.1.16','0.1.17','0.1.18','0.1.19','0.1.20','0.1.21','0.1.22','0.1.23','0.1.24','0.1.25','0.1.26','0.1.27','0.1.28','0.1.29','0.1.30','0.1.31','0.1.32','0.1.33','0.1.34','0.1.35','0.1.36','0.1.37','0.1.38','0.1.39','0.1.40','0.1.41'].includes(h.status?.version??'')&&h.status?.tracker.host===secondary?.host&&h.status?.tracker.port===secondary?.port);
const supported=observed.supported_profile_fields??Object.keys(device.settings.parameters);
const fields=model.fields.filter(f=>supported.includes(f.key));
const validation=policyError(settings,fields)||(selectSim&&settings.connectivity.strategy==='sim'&&!cellularSimCurrent(telemetry,settings.connectivity.sim_slot??1)?'Ожидаем свежие данные выбранной SIM перед отправкой настроек.':'');
const dirty=name!==device.name||target!==device.vehicle_id||!equipmentPolicyEqual(settings,device.settings);
const writable=model.usb_write_firmware?.includes(observed.firmware)??false;
const [applying,setApplying]=useState(false),[saving,setSaving]=useState(false),[readingUsb,setReadingUsb]=useState(false);
async function applyUsb(){setBusy(true);setApplying(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/apply`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Результат записи не получен. Прочитайте USB повторно.');}finally{setBusy(false);setApplying(false);}}
const sections=[{id:'identity',label:'Устройство и аппарат'},{id:'connection',label:'Сервер и связь'},{id:'commands',label:'Команды'},{id:'firmware',label:'Прошивка'},...Array.from(new Set(fields.map(f=>f.group))).map(group=>({id:group,label:group,group:'Параметры профиля'}))];
async function readNetwork(){setBusy(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/inspect-network`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Чтение через VPS не подтверждено.');}finally{setBusy(false);}}
async function applyNetwork(item:IndependentDevice=device,selection=selectSim){setBusy(true);setError('');contentRef.current?.scrollIntoView({block:'start'});try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${item.id}/apply-network`,'POST',{expected_revision:item.revision,select_sim:selection}));setSimRequested(false);}catch(e){setError(e instanceof Error?e.message:'Отправка через VPS не подтверждена.');}finally{setBusy(false);}}
async function save(){setBusy(true);setSaving(true);setError('');setNotice('');try{const changed=!equipmentPolicyEqual(settings,device.settings);const retrySelection=selectSim;if(!dirty&&!retrySelection){setNotice('Изменений настроек нет. Команда трекеру не отправлена.');return;}const item=dirty?await equipmentRequest<IndependentDevice>(`/instances/${device.id}`,'PUT',{expected_revision:device.revision,name:name.trim(),vehicle_id:target,settings}):device;onObserved(item);if(changed||retrySelection)await applyNetwork(item,selectSim);else setNotice('Изменения сохранены в Mission Core.');}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить настройки.');}finally{setBusy(false);setSaving(false);}}
async function readUsb(){setBusy(true);setReadingUsb(true);setError('');try{onObserved(await equipmentRequest<IndependentDevice>(`/instances/${device.id}/inspect`,'POST',{expected_revision:device.revision}));}catch(e){setError(e instanceof Error?e.message:'Не удалось прочитать USB.');}finally{setBusy(false);setReadingUsb(false);}}
async function saveProfile(){setBusy(true);setError('');try{await equipmentRequest('/profiles','POST',{name:profileName.trim(),model_id:device.model_id,settings});setProfileOpen(false);setNotice('Профиль сохранён и доступен при подключении новых трекеров.');onProfile();}catch(e){setError(e instanceof Error?e.message:'Не удалось сохранить профиль.');}finally{setBusy(false);}}
return <><FeatureSettingsWindow open={!profileOpen} title="Настройки устройства" subtitle={device.name} identity={{title:model.label,subtitle:`IMEI …${observed.imei_suffix}`,avatarLabel:model.label}} sections={sections} activeSection={section} onSectionChange={setSection} onClose={()=>{if(!working)onClose();}} footer={section==='firmware'?undefined:<WindowFooterActions><Button loading={saving} disabled={busy||!!validation||!name.trim()||!target} onClick={()=>void save()}>Сохранить настройки</Button><Button disabled={working||!!validation} onClick={()=>{setProfileName(`${model.label} — ${name}`.slice(0,80));setProfileOpen(true);}}>Сохранить профиль</Button></WindowFooterActions>}>
<div className="fleet-form" ref={contentRef}><StatusBadge tone={telemetry?.online?'success':'neutral'}>{telemetryLabel(telemetry)}</StatusBadge>{section!=='commands'&&section!=='firmware'&&<SettingsCard title="Настройки через VPS" description={fullSettings?"Параметры профиля записываются через VPS. Текущие настройки читаются перед записью, а результат проверяется повторным чтением. Адрес резервного сервера сохраняется.":"По сети доступна смена адреса и порта сервера 1. Сервер 2 сохраняет связь с текущим VPS. Для полной конфигурации нужен обновлённый VPS."}><p>{equipmentApplyMessage(configurationWriteNotStarted(device.network_operation)?'not_started':device.policy_state)}</p>{device.network_server1&&<p>Последний подтверждённый сервер 1: {device.network_server1.host}:{device.network_server1.port}.</p>}<p>{networkOperationMessage(device.network_operation?.scope!=='command'?device.network_operation:undefined)}</p>{networkPending&&device.network_operation?.scope!=='command'&&<p>{device.network_operation?.durable?`Попыток: ${device.network_operation.attempt_count??0}. Окно можно закрыть — задание сохранено. Повторы можно остановить в журнале команд.`:progress.overdue?'Срок ожидания истёк. Уточняем результат у VPS; повторная отправка заблокирована до получения результата.':`До окончания ожидания: ${progress.remaining??'—'} с. Окно можно закрыть — операция продолжится на VPS.`}</p>}<Button loading={progress.waiting&&device.network_operation?.scope!=='command'&&!device.network_operation?.read_only} disabled={busy||dirty||!!validation||!writable} onClick={()=>void applyNetwork()}>Отправить через VPS</Button><Button loading={progress.waiting&&device.network_operation?.scope!=='command'&&device.network_operation?.read_only} disabled={busy||dirty} onClick={()=>void readNetwork()}>Прочитать через VPS</Button></SettingsCard>}
{section==='connection'&&<EquipmentCellular telemetry={telemetry} observed={observed}/>}
{section==='firmware'?<EquipmentFirmware device={device}/>:section==='identity'?<>
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
<Select label="Привязка к аппарату" value={target} options={vehicles.map(v=>({value:v.id,label:v.name}))} onChange={setTarget} disabled={busy}/>
<Select label="Загрузить сохранённый профиль" value={selectedProfile} options={[{value:'',label:'Текущие настройки'},...profiles.filter(p=>p.model_id===device.model_id).map(p=>({value:p.id,label:`${p.name} · ${new Date(p.created_at*1000).toLocaleString('ru-RU')}`}))]} disabled={busy} onChange={id=>{setSelectedProfile(id);const p=profiles.find(p=>p.id===id);changeSettings(p?.settings??device.settings);}}/>
<SettingsCard title="Сведения B2" description={`ID ${observed.device_id} · ПО ${observed.firmware} · идентификация по USB ${new Date(observed.read_at*1000).toLocaleString('ru-RU')}`}>{observed.configuration_read_at&&<p>Настройки прочитаны через VPS: {new Date(observed.configuration_read_at*1000).toLocaleString('ru-RU')}.</p>}<dl className="fleet-facts"><div><dt>Основная SIM</dt><dd>{observed.sim1_iccid_reported_suffix?`…${observed.sim1_iccid_reported_suffix} (${observed.sim1_iccid_reported_length} цифр в ответе)`:'Нет сведений'}</dd></div><div><dt>Вторая SIM</dt><dd>{observed.sim2_iccid_reported_suffix?`…${observed.sim2_iccid_reported_suffix} (${observed.sim2_iccid_reported_length} цифр в ответе)`:'Нет сведений'}</dd></div><div><dt>APN основной SIM</dt><dd>{observed.configuration.apn1||'Не задан'}</dd></div><div><dt>APN второй SIM</dt><dd>{observed.configuration.apn2||'Не задан'}</dd></div>{observed.configuration.servers.filter(s=>s.host).map(s=><div key={s.slot}><dt>Сервер {s.slot}</dt><dd>{s.host}:{s.port}</dd></div>)}</dl><Button loading={readingUsb} disabled={busy||dirty} onClick={()=>void readUsb()}>Прочитать USB повторно</Button><Button loading={applying} disabled={busy||dirty||!!validation||!writable} onClick={()=>void applyUsb()}>Первоначальная настройка по USB</Button>{applying&&<p>Запись и проверка настроек. Не отсоединяйте USB.</p>}</SettingsCard>
</>:section==='commands'?<SettingsCard title="Команды и журнал" description="Отправка команд, очередь и история обмена с B2."><Button disabled={working||dirty} onClick={onCommands}>Открыть команды</Button>{dirty&&<p>Сохраните изменения перед переходом к командам.</p>}</SettingsCard>:<EquipmentPolicyFields telemetry={telemetry} observed={observed} hosts={hosts.filter(h=>h.vehicle_ids.includes(target))} section={section} fields={fields} presets={model.connectivity_presets??[]} value={settings} onChange={changeSettings} disabled={busy}/>}
{section!=='firmware'&&validation&&<StatusBadge tone="warning">{validation}</StatusBadge>}
</div>
</FeatureSettingsWindow>
<Window open={profileOpen} title="Сохранить профиль" subtitle="Общие настройки для новых трекеров" onClose={()=>{if(!working)setProfileOpen(false);}} closeOnEscape={!working} closeOnBackdrop={false} footer={<WindowFooterActions><Button disabled={working} onClick={()=>setProfileOpen(false)}>Отмена</Button><Button loading={working} disabled={working||!profileName.trim()||!!validation} onClick={()=>void saveProfile()}>Сохранить профиль</Button></WindowFooterActions>}><div className="fleet-form"><TextField label="Название профиля" value={profileName} maxLength={80} disabled={working} onChange={e=>setProfileName(e.target.value)}/><p>Сохранятся параметры работы, выбранный сервер и настройки связи. IMEI, номера SIM, личные пароли и привязка к аппарату не входят в профиль. Настройки уже добавленных устройств не изменятся.</p></div></Window>
<ToastStack items={error?[{id:'equipment-settings-error',title:error,tone:'error',durationMs:null}]:notice?[{id:'equipment-profile-saved',title:notice,tone:'success'}]:[]} onDismiss={()=>{setError('');setNotice('');}}/>
</>;
}
@@ -0,0 +1,40 @@
import {useCallback,useEffect,useState,type ReactNode} from 'react';
import {Button,Icon,IconButton,LoadingRegion,ResourceList,ResourceRow,StatusBadge,ToastStack} from '@nodedc/ui-react';
import {equipmentRequest,type EquipmentModel,type EquipmentProfile,type IndependentDevice} from '../../../core/fleet/equipment';
import {fleetRequest,type Vehicle} from '../../../core/fleet/useFleet';
import {EquipmentConnect} from './EquipmentConnect';
import {EquipmentSettings} from './EquipmentSettings';
import {EquipmentCommandWindow} from './EquipmentCommandWindow';
import {hostOnline,telemetryLabel,useTrackerTelemetry,vpsRequest,type VPSHost} from '../../../core/fleet/vps';
import {VPSHostSettings} from './VPSHostSettings';
import './equipment.css';
export function IndependentEquipment({vehicle,computer,onRefresh}:{vehicle:Vehicle;computer:ReactNode;onComputer:()=>void;onRefresh:()=>void}){
const [devices,setDevices]=useState<IndependentDevice[]|null>(null),[models,setModels]=useState<EquipmentModel[]>([]),[profiles,setProfiles]=useState<EquipmentProfile[]>([]),[vehicles,setVehicles]=useState<Vehicle[]>([]);
const [hosts,setHosts]=useState<VPSHost[]>([]),[vpsOpen,setVpsOpen]=useState(false),[selectedHost,setSelectedHost]=useState<VPSHost|undefined>();
const telemetry=useTrackerTelemetry(vehicle.id);
const [adding,setAdding]=useState(false),[selected,setSelected]=useState<IndependentDevice|null>(null),[error,setError]=useState('');
const refresh=useCallback(async()=>{
const [items,catalog,policies,fleet,vps]=await Promise.all([equipmentRequest<{items:IndependentDevice[]}>(`/instances?vehicle_id=${encodeURIComponent(vehicle.id)}`),equipmentRequest<{models:EquipmentModel[]}>('/catalog'),equipmentRequest<{items:EquipmentProfile[]}>('/profiles'),fleetRequest<{items:Vehicle[]}>(),vpsRequest<{items:VPSHost[]}>()]);
setHosts(vps.items);setDevices(items.items);setModels(catalog.models);setProfiles(policies.items);setVehicles(fleet.items);setError('');
},[vehicle.id]);
const observe=useCallback((item:IndependentDevice)=>{setSelected(item);void refresh().catch(()=>setError('Не удалось обновить независимое оборудование.'));},[refresh]);
const reload=()=>{void refresh().catch(()=>setError('Не удалось обновить независимое оборудование. Повторите запрос.'));};
useEffect(()=>{let active=true;void refresh().catch(()=>{if(active)setError('Не удалось получить независимое оборудование.');});return()=>{active=false;};},[refresh]);
useEffect(()=>{let active=true;let timer:ReturnType<typeof setTimeout>;async function poll(){try{const value=await vpsRequest<{items:VPSHost[]}>();if(active)setHosts(value.items);}catch{/* Existing timestamps expire when the connection is unavailable. */}finally{if(active)timer=setTimeout(()=>void poll(),5000);}}void poll();return()=>{active=false;clearTimeout(timer);};},[]);
const [commandDevice,setCommandDevice]=useState<IndependentDevice|null>(null);
const model=selected&&models.find(m=>m.id===selected.model_id);
const selectedTelemetry=telemetry.items.find(t=>t.instance_id===selected?.id);
return <>
<div className="sensor-actions sensor-inventory-toolbar"><span className="sensor-note">Бортовой компьютер и независимые устройства</span><div className="sensor-actions"><IconButton label="Подключить независимое устройство" onClick={()=>setAdding(true)}><Icon name="plus"/></IconButton><IconButton label="Обновить оборудование" onClick={()=>{reload();onRefresh();}}><Icon name="refresh"/></IconButton></div></div>
{computer}
{!devices?<LoadingRegion loading={!error} label="Загрузка независимых устройств"/>:<ResourceList aria-label="Независимые устройства">{devices.map(device=><li key={device.id}><ResourceRow icon={<Icon name="network"/>} title={device.name} description={`${models.find(m=>m.id===device.model_id)?.label??device.model_id} · IMEI …${device.observed.imei_suffix}`} metadata={telemetry.unavailable?'Связь с сервером не проверена':telemetryLabel(telemetry.items.find(t=>t.instance_id===device.id))} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={!telemetry.unavailable&&telemetry.items.find(t=>t.instance_id===device.id)?.online?'success':'neutral'} aria-label={telemetryLabel(telemetry.items.find(t=>t.instance_id===device.id))}/>} actions={<><IconButton label={`Команды: ${device.name}`} onClick={()=>setCommandDevice(device)}><Icon name="terminal"/></IconButton><IconButton label={`Настройки: ${device.name}`} onClick={()=>setSelected(device)}><Icon name="settings"/></IconButton></>}/></li>)}</ResourceList>}
<ResourceList aria-label="VPS Host ARNavi">{hosts.filter(h=>h.vehicle_ids.includes(vehicle.id)).map(host=><li key={host.id}><ResourceRow icon={<Icon name="database"/>} title={host.name} description="VPS Host ARNavi" metadata={`${host.endpoint} · Аппаратов: ${host.vehicle_ids.length}`} statusPlacement="leading" status={<StatusBadge variant="indicator" tone={hostOnline(host)?'success':'neutral'} aria-label={hostOnline(host)?'VPS на связи':'Нет связи с VPS'}/>} actions={<IconButton label={`Настройки: ${host.name}`} onClick={()=>{setSelectedHost(host);setVpsOpen(true);}}><Icon name="settings"/></IconButton>}/></li>)}</ResourceList>
{vpsOpen&&<VPSHostSettings host={hosts.find(h=>h.id===selectedHost?.id)} hosts={hosts} vehicle={vehicle} vehicles={vehicles} onClose={()=>setVpsOpen(false)} onSaved={()=>{setVpsOpen(false);reload();}}/>}
{error&&!devices&&<Button onClick={reload}>Повторить</Button>}
{adding&&<EquipmentConnect vehicle={vehicle} vehicles={vehicles} models={models} profiles={profiles} hosts={hosts} onClose={()=>setAdding(false)} onComputer={()=>{setAdding(false);onRefresh();}} onVPS={()=>{setAdding(false);reload();}} onAdded={item=>{setAdding(false);if(item.vehicle_id===vehicle.id)setSelected(item);reload();}}/>}
{selected&&model&&<EquipmentSettings key={selected.id} device={selected} model={model} hosts={hosts} telemetry={telemetry.unavailable&&selectedTelemetry?{...selectedTelemetry,online:false}:selectedTelemetry} vehicles={vehicles} profiles={profiles} onClose={()=>setSelected(null)} onObserved={observe} onProfile={reload} onCommands={()=>{setCommandDevice(selected);setSelected(null);}}/>}
{commandDevice&&<EquipmentCommandWindow key={commandDevice.id} device={commandDevice} telemetry={telemetry.items.find(t=>t.instance_id===commandDevice.id)} onClose={()=>{setCommandDevice(null);reload();}}/>}
<ToastStack items={error?[{id:'independent-equipment-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/>
</>;
}
@@ -0,0 +1,11 @@
import {Fragment,useEffect,useState} from 'react';
import {Button,Icon,SettingsCard} from '@nodedc/ui-react';
type Installer={id:string;label:string;version:string;os:string;filename:string;download_url:string;instructions:string[]};
export function InstallerCard({kind}:{kind:'node'|'vps-arnavi'}){
const [item,setItem]=useState<Installer|null>(null),[failed,setFailed]=useState(false);
useEffect(()=>{let active=true;void fetch('/api/v1/fleet/installers',{cache:'no-store'}).then(async r=>{if(!r.ok)throw Error();return r.json() as Promise<{items:Installer[]}>;}).then(v=>{if(active){setItem(v.items.find(i=>i.id===kind)??null);setFailed(!v.items.some(i=>i.id===kind));}}).catch(()=>{if(active)setFailed(true);});return()=>{active=false;};},[kind]);
return <SettingsCard title="Установка" description={item?<>{`${item.label} ${item.version} · Только ${item.os}`}<br/><br/>{item.instructions.map((step,index)=><Fragment key={step}>{index>0&&<br/>}{index+1}. {step}</Fragment>)}</>:failed?'Установщик пока недоступен в этом Mission Core.':'Получение установщика…'}>
<Button disabled={!item} icon={<Icon name="download"/>} onClick={()=>{if(item){const link=document.createElement('a');link.href=item.download_url;link.download=item.filename;link.click();}}}>Скачать установщик</Button>
</SettingsCard>;
}
@@ -0,0 +1,29 @@
import {useEffect,useState} from 'react';
import {Button,FeatureSettingsWindow,Select,SettingsCard,StatusBadge,Switch,TextAreaField,TextField,ToastStack,Window,WindowFooterActions} from '@nodedc/ui-react';
import {hostOnline,vpsRequest,type VPSHost} from '../../../core/fleet/vps';
import type {SensorEnrollmentProps} from '../../../../../../packages/sensor-ui/src/extensions';
import {InstallerCard} from './InstallerCard';
import type {Vehicle} from '../../../core/fleet/useFleet';
export function VPSHostSettings({host,hosts,vehicle,vehicles,onClose,onSaved,renderWindow}:{host?:VPSHost;hosts:VPSHost[];vehicle:Vehicle;vehicles:Vehicle[];onClose:()=>void;onSaved:()=>void;renderWindow?:SensorEnrollmentProps['renderWindow']}){
const [existing,setExisting]=useState(''),[name,setName]=useState(host?.name??'VPS Host ARNavi'),[code,setCode]=useState(''),[selected,setSelected]=useState(host?.vehicle_ids??[vehicle.id]);
const [advanced,setAdvanced]=useState(false),[replaces,setReplaces]=useState('');
const [network,setNetwork]=useState(host?.network_interface??''),[interfaces,setInterfaces]=useState<{id:string;label:string}[]>([]);
useEffect(()=>{let active=true;void vpsRequest<{items:{id:string;label:string}[]}>('/interfaces').then(v=>{if(active)setInterfaces(v.items);}).catch(()=>{});return()=>{active=false;};},[]);
const [busy,setBusy]=useState(false),[error,setError]=useState('');
const current=host??hosts.find(h=>h.id===existing);
async function save(){setBusy(true);setError('');try{if(current){await vpsRequest(`/${current.id}`,'PUT',{name:name.trim(),vehicle_ids:selected,network_interface:network||null,expected_revision:current.revision});}else{await vpsRequest('','POST',{code:code.trim(),name:name.trim(),vehicle_ids:selected,network_interface:network||null,replaces_id:replaces||null});}onSaved();}catch(e){setError(e instanceof Error?e.message:'Не удалось подключить VPS.');}finally{setBusy(false);}}
const actions=<><Button disabled={busy} onClick={onClose}>Отмена</Button><Button loading={busy} disabled={busy||!name.trim()||(!current&&!code.trim())} onClick={()=>void save()}>{current?'Применить':'Подключить VPS'}</Button></>;
const footer=<WindowFooterActions>{actions}</WindowFooterActions>;
const content=<div className="fleet-form">
{!host&&<Select label="VPS Host ARNavi" value={existing} options={[{value:'',label:'Подключить новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:h.name}))]} disabled={busy} onChange={id=>{setExisting(id);const value=hosts.find(h=>h.id===id);setName(value?.name??'VPS Host ARNavi');setNetwork(value?.network_interface??'');setSelected(Array.from(new Set([...(value?.vehicle_ids??[]),vehicle.id])));}}/>}
{!current&&<InstallerCard kind="vps-arnavi"/>}
<TextField label="Название" value={name} maxLength={80} disabled={busy} onChange={e=>setName(e.target.value)}/>
{!current&&<TextAreaField label="Ключ подключения VPS" value={code} rows={5} disabled={busy} onChange={e=>setCode(e.target.value)} hint="После установки VPS Host ARNavi ключ находится в /opt/nodedc-mission-vps/connect.key. Он действует 24 часа и используется один раз."/>}
{!current&&hosts.some(h=>h.state==='paired')&&<Select label="После переустановки" value={replaces} options={[{value:'',label:'Это новый VPS'},...hosts.filter(h=>h.state==='paired').map(h=>({value:h.id,label:`Заменить ${h.name}`}))]} onChange={setReplaces} disabled={busy}/>}
{interfaces.length>0&&<><Button disabled={busy} onClick={()=>setAdvanced(v=>!v)}>{advanced?'Скрыть параметры подключения':'Параметры подключения при использовании VPN'}</Button>{advanced&&<SettingsCard title="Подключение с этого компьютера" description="Если VPN мешает доступу к VPS, выберите прямое подключение. Это влияет только на соединение Mission Core с этим сервером."><Select label="Способ подключения" value={network} options={[{value:'',label:'Обычное подключение (с учётом VPN)'},...interfaces.map(i=>({value:i.id,label:`Напрямую · ${i.label}`}))]} disabled={busy} onChange={setNetwork}/></SettingsCard>}</>}
{current&&<SettingsCard title="Связь с VPS" description={current.endpoint}><StatusBadge tone={hostOnline(current)?'success':'neutral'}>{hostOnline(current)?'На связи':current.state==='pending'?'Подключение не завершено':'Нет связи'}</StatusBadge><dl className="fleet-facts"><div><dt>Версия</dt><dd>{current.status?.version??'Нет сведений'}</dd></div><div><dt>Последняя синхронизация</dt><dd>{current.last_sync_at?new Date(current.last_sync_at*1000).toLocaleString('ru-RU'):'Ещё не было'}</dd></div><div><dt>Приём ARNavi B2</dt><dd>{current.status?`${current.status.tracker.host}:${current.status.tracker.port}`:'Не подтверждён'}</dd></div><div><dt>Трекеры</dt><dd>{current.status?.devices??0}</dd></div></dl></SettingsCard>}
<SettingsCard title="Обслуживаемые аппараты" description="Один VPS может обслуживать несколько аппаратов. Его настройки общие для всех привязок."><div className="fleet-form">{vehicles.map(v=><Switch key={v.id} label={v.name} checked={selected.includes(v.id)} disabled={busy} onChange={checked=>setSelected(ids=>checked?[...ids,v.id]:ids.filter(id=>id!==v.id))}/>)}</div></SettingsCard>
</div>;
return <>{renderWindow?renderWindow({content,actions,busy}):host?<FeatureSettingsWindow open title="Настройки VPS Host ARNavi" subtitle={host.name} identity={{title:'VPS Host ARNavi',subtitle:host.endpoint,avatarLabel:'VPS'}} sections={[{id:'host',label:'Сервер и аппараты'}]} activeSection="host" onSectionChange={()=>{}} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</FeatureSettingsWindow>:<Window open title="Подключить VPS Host ARNavi" subtitle={vehicle.name} size="md" closeOnEscape={!busy} closeOnBackdrop={false} onClose={()=>{if(!busy)onClose();}} footer={footer}>{content}</Window>}<ToastStack items={error?[{id:'vps-host-error',title:error,tone:'error',durationMs:null}]:[]} onDismiss={()=>setError('')}/></>;
}
@@ -0,0 +1 @@
.equipment-settings-title { display:flex; align-items:center; flex-wrap:wrap; gap:var(--nodedc-space-4); }