Bring Device Core settings to Mission UI and expose scoped B2 controls
Device Core qualification / qualify (push) Successful in 6m40s
Device Core qualification / qualify (push) Successful in 6m40s
This commit is contained in:
@@ -31,6 +31,8 @@ import type {
|
||||
SessionView,
|
||||
} from "./types";
|
||||
|
||||
import { B2TrackerSettings } from "./b2/B2TrackerSettings";
|
||||
import type { TrackerRef } from "./b2/tracker";
|
||||
import { useB2Inventory } from "./b2/useB2Inventory";
|
||||
|
||||
export type DeviceInventoryDetailState = {
|
||||
@@ -60,6 +62,7 @@ export function DeviceInventoryView({
|
||||
onError: (reason: unknown) => void;
|
||||
onDetailChange: (detail: DeviceInventoryDetailState | null) => void;
|
||||
}) {
|
||||
const [tracker, setTracker] = useState<{ device: TrackerRef; projectRef: string; section: string } | null>(null);
|
||||
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
|
||||
const [typeFilter, setTypeFilter] = useState("all");
|
||||
const [archiveTarget, setArchiveTarget] = useState<DeviceView | null>(null);
|
||||
@@ -115,6 +118,7 @@ export function DeviceInventoryView({
|
||||
const count = workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + (b2.data?.items.length || 0);
|
||||
return (
|
||||
<div className="device-inventory">
|
||||
{tracker && tracker.projectRef===workspace.project.projectRef ? <B2TrackerSettings key={`${tracker.projectRef}:${tracker.device.id}`} projectRef={tracker.projectRef} device={tracker.device} initialSection={tracker.section} onClose={()=>setTracker(null)} onError={onError} onChanged={onPoll} canConfigure={canConfigure} canCommand={workspace.project.access.capabilities.includes('command.dispatch')} /> : null}
|
||||
{selectedDevice && detail ? <DeviceDetailView key={selectedDevice.deviceRef} device={selectedDevice} detail={detail} workspace={workspace}
|
||||
canConfigure={canConfigure} canManageProject={canManageProject} onDetailChange={onDetailChange} onSaved={onPoll} onError={onError} onBack={() => onDetailChange(null)} /> : null}
|
||||
<ConfirmationModal open={Boolean(archiveTarget)} title={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить устройство?' : 'Перенести устройство в архив?'} description={archiveTarget?.displayName} confirmLabel={archiveTarget?.lifecycleState === 'suspended' ? 'Восстановить' : 'В архив'} cancelLabel="Отмена" onClose={() => { if (!archiving) setArchiveTarget(null); }} onConfirm={async () => {
|
||||
@@ -161,7 +165,7 @@ export function DeviceInventoryView({
|
||||
{statusFilter !== 'pending' ? <ResourceList>
|
||||
{remoteRows.map((device) => <li key={`${device.hostRef}:${device.id}`}><ResourceRow
|
||||
icon={<Icon name="apps" />} title={device.name || `ARNavi B2 · ${device.number}`} metadata={`ARNavi B2 · ${device.number} · IMEI ${device.identifier.masked}`} description={device.hostName}
|
||||
status={<StatusBadge>{device.active ? 'Зарегистрирован на VPS' : 'Отключён на VPS'}</StatusBadge>} /></li>)}
|
||||
actions={<><IconButton label={`Команды: ${device.name || 'ARNavi B2'}`} onClick={()=>setTracker({device,projectRef:workspace.project.projectRef,section:'commands'})}><Icon name="terminal" /></IconButton><IconButton label={`Настройки: ${device.name || 'ARNavi B2'}`} onClick={()=>setTracker({device,projectRef:workspace.project.projectRef,section:'identity'})}><Icon name="settings" /></IconButton></>} /></li>)}
|
||||
{deviceRows.map(({ device, online, lastSeenAt }) => <li key={device.deviceRef}><ResourceRow
|
||||
icon={<Icon name="apps" />} title={device.displayName} metadata={`${profileLabel(workspace, device)} · ${deviceIdentifierDisplayValue(device) || 'IMEI не назначен'}`}
|
||||
description={lastSeenAt ? formatDate(lastSeenAt) : undefined}
|
||||
|
||||
@@ -237,6 +237,7 @@ export function DeviceManagerApp() {
|
||||
useEffect(() => {
|
||||
applyNodedcTheme(document.documentElement, {
|
||||
theme: presentation.environment.theme,
|
||||
appearance: "mission",
|
||||
accent: hexToRgb(presentation.environment.accentHex),
|
||||
});
|
||||
}, [presentation.environment.accentHex, presentation.environment.theme]);
|
||||
|
||||
@@ -74,7 +74,7 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
|
||||
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 }]}
|
||||
sections={[{ id: 'connection', label: 'Сервер' }, { id: 'contours', label: 'Контуры', disabled: !status?.connected }]}
|
||||
activeSection={section} onSectionChange={setSection} onClose={onClose}
|
||||
headerActions={<IconButton label="Обновить состояние VPS" loading={pending === 'refresh'} disabled={busy} onClick={async () => {
|
||||
setPending('refresh'); try { await refresh(); } catch (error) { onError(error); } finally { setPending(''); }
|
||||
|
||||
@@ -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'&§ion!=='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&§ion!=='commands'&§ion!=='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; }
|
||||
@@ -6,6 +6,10 @@ export type B2Status = { connected: boolean; endpoint?: string; authority?: 'hos
|
||||
links?: Array<{ contourId: string; projectRef: string }> };
|
||||
export type B2Device = { id: string; identifier: { masked: string }; name: string; active: boolean; number: number; contourId: string };
|
||||
const messages: Record<string, string> = {
|
||||
b2_settings_revision_changed: 'Настройки изменились. Обновите сведения о трекере перед отправкой.',
|
||||
b2_settings_initial_read_required: 'Сначала прочитайте настройки трекера через VPS.',
|
||||
b2_settings_sim_observation_required: 'Нет свежих данных выбранной SIM. Дождитесь регистрации карты и обновите сведения.',
|
||||
b2_request_invalid: 'Проверьте параметры: VPS отклонил запрос.',
|
||||
b2_infrastructure_unavailable: 'Подключение ARNavi пока не настроено на сервере Device Core.',
|
||||
b2_host_unavailable: 'VPS не отвечает. Проверьте доступность сервера.',
|
||||
b2_host_not_connected: 'Сначала подключите VPS.',
|
||||
@@ -20,6 +24,9 @@ const messages: Record<string, string> = {
|
||||
b2_company_mismatch: 'Выберите проект той же компании.',
|
||||
device_owner_scope_access_denied: 'Настройки общего VPS доступны администратору компании.',
|
||||
};
|
||||
export class B2RequestError extends Error {
|
||||
constructor(message: string, public readonly rejected: boolean) { super(message); }
|
||||
}
|
||||
export async function b2Request<T>(projectRef: string, hostRef: string, action: string, fields: Record<string, unknown> = {}, requestId = crypto.randomUUID().replaceAll('-', '')): Promise<T> {
|
||||
const response = await fetch('/api/device-manager/b2/infrastructure', {
|
||||
method: 'POST', credentials: 'same-origin',
|
||||
@@ -27,6 +34,6 @@ export async function b2Request<T>(projectRef: string, hostRef: string, action:
|
||||
body: JSON.stringify({ projectRef, hostRef, action, ...fields }),
|
||||
});
|
||||
const body = await response.json().catch(() => null);
|
||||
if (!response.ok || body?.ok !== true) throw new Error(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.');
|
||||
if (!response.ok || body?.ok !== true) throw new B2RequestError(messages[body?.error] || 'Не удалось выполнить действие на VPS. Обновите сведения о подключении.', response.status >= 400 && response.status < 500);
|
||||
return body.result as T;
|
||||
}
|
||||
|
||||
@@ -6,3 +6,8 @@
|
||||
.b2-disclosure { display: grid; gap: var(--nodedc-space-2); }
|
||||
.b2-disclosure__body { display: grid; gap: var(--nodedc-space-3); padding: var(--nodedc-space-2) var(--nodedc-space-3) var(--nodedc-space-4); }
|
||||
.b2-section-heading { display: flex; align-items: center; justify-content: space-between; gap: var(--nodedc-space-3); font-size: var(--nodedc-font-size-sm); }
|
||||
|
||||
.b2-tracker-form { display: grid; min-width: 0; gap: 1rem; }
|
||||
.b2-tracker-facts { display: grid; grid-template-columns: minmax(8rem, 1fr) minmax(0, 2fr); gap: .65rem 1rem; margin: 0; font-size: var(--nodedc-font-size-sm); }
|
||||
.b2-tracker-facts dt { color: var(--nodedc-text-muted); }
|
||||
.b2-tracker-facts dd { margin: 0; overflow-wrap: anywhere; }
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import { b2Request, type B2Device } from './api';
|
||||
export type TrackerRef = B2Device & { hostRef: string; hostName: string };
|
||||
export type Policy = { parameters: Record<string, number>; connectivity: { mode: string; apn1?: string; apn2?: string; preset1?: string; preset2?: string }; endpoint?: { host: string; port: number; slot: number } | null };
|
||||
export type Operation = { command?:Record<string,unknown>;repeatable?:boolean;number?:number; id: string; kind: string; state: string; runtime_phase?: string; reason?: string; sequence?: number; created_at?: number; received_at?: number; dispatched_at?: number; verified_at?: number; delivered_at?: number; attempt_count?: number; roundtrip_seconds?: number; delivery_seconds?: number; stop_requested?: boolean };
|
||||
export type TrackerState = { id: string; name: string; number: number; identifier: string; revision: number; firmware: string | null; policy: Policy;
|
||||
observed: { sha256: string; received_at: number; parameters: Record<string, number>; servers: Array<{slot:number;host:string;port:number}>; apn1:string;apn2:string;internet_mode:string;output_modes:Record<string,number> } | null;
|
||||
carrier_presets: Array<{id:string;label:string;apn:string}>;
|
||||
cellular: {measured_at?:number;status?:{sim_states:Record<string,number>};networks?:Record<string,{mcc:number|null;mnc:number;signal:number|null}>};
|
||||
fields: Array<{id:string;label:string;group:string;minimum:number;maximum:number}>;
|
||||
profiles: Array<{id:string;name:string;policy:Policy}>;
|
||||
firmwares: Array<{sha256:string;filename:string;bytes:number;complete:boolean;added_at:number}>;
|
||||
latest_operation:Operation|null; last_seen_at: number | null; modem: {active_sim:number;measured_at:number} | null; sims: Record<string,{identifier:string;measured_at:number|null}>;
|
||||
capabilities: {configuration:boolean;firmware_archive:boolean;firmware_install:boolean};
|
||||
};
|
||||
export function trackerRequest<T>(projectRef: string, device: TrackerRef, request: Record<string, unknown>) {
|
||||
return b2Request<T>(projectRef,device.hostRef,'tracker',{contourId:device.contourId,deviceId:device.id,request});
|
||||
}
|
||||
export const newIntent = () => crypto.randomUUID().replaceAll('-','');
|
||||
export const operationName = (kind: string, command?:Record<string,unknown>) => command?.pin ? `${kind==='pulse-output'?'Импульс':command.enabled?'Включить':'Выключить'} PIN${command.pin}${kind==='pulse-output'?` · ${command.seconds} с`:''}` : ({'request-position':'Запросить координаты',restart:'Перезапустить B2','read-configuration':'Прочитать настройки','configure-all':'Применить настройки','select-sim':'Изменить режим SIM','set-output':'Переключить выход','pulse-output':'Импульс выхода'}[kind] || 'Операция B2');
|
||||
export const stateName = (state: string) => ({queued:'Ожидает связи',dispatched:'Отправляется',observed:'Настройки прочитаны',verified:'Подтверждено чтением',confirmed:'Получен ответ',delivered:'Доставлено',restarted:'Связь восстановлена',stopped:'Остановлено',rejected:'Отклонено',uncertain:'Результат не подтверждён',unconfirmed:'Ответ не получен',not_applied:'Не применено',failed:'Ошибка'}[state] || state);
|
||||
export const formatTime = (value?: number | null) => value ? new Date(value*1000).toLocaleString('ru-RU') : '—';
|
||||
@@ -0,0 +1,42 @@
|
||||
# Device Core · Mission Core visual reference
|
||||
|
||||
Reference inspected in the running Mission Core on 2026-09-30: environment
|
||||
settings; VPS settings; B2 identity, connection, commands, firmware and every
|
||||
profile section. The actual application is authoritative for appearance; its
|
||||
rover domain is not imported into Device Core.
|
||||
|
||||
The shared `appearance: "mission"` profile lives in Design Guideline/ui-core.
|
||||
Device Core applies it on documentElement so portals inherit it. Existing Window,
|
||||
FeatureSettingsWindow, SettingsCard, ResourceRow, Select, Button and StatusBadge
|
||||
remain the component source. No application-local replica of the modal is added.
|
||||
|
||||
Reference measurements in dark mode: modal rgba(15,15,17,.97), radius28px,
|
||||
plain avatar, selected navigation rgba(247,248,244,.14), control height46px,
|
||||
settings-card padding16px, status dot6.72px. The material rim and gradient are
|
||||
removed from this opt-in profile. Light mode keeps the same neutral hierarchy.
|
||||
Other applications retain their previous appearance unless opting in.
|
||||
|
||||
| Surface | Device Core behavior |
|
||||
| --- | --- |
|
||||
| B2 inventory | terminal and gear at right; no redundant registered badge |
|
||||
| B2 settings | persistent left navigation, identity, connection, commands, firmware,86parameters |
|
||||
| VPS settings | same window; project contours expand inline; refresh at top |
|
||||
| Keys | application belongs to expanded project contour; server generates identity |
|
||||
| Project switch | retained active application section; no foreign project device window |
|
||||
| Product model | company/project permissions remain Device Core's |
|
||||
| Overview | existing yellow video retained |
|
||||
|
||||
Network settings go through the VPS product API documented in the server repo's
|
||||
TRACKER_SETTINGS_API.md. The backend checks capability, linked project/contour and
|
||||
server identity. Unknown/private configuration records and recovery endpoint are
|
||||
preserved. Saving a portable profile is separate from applying it to a tracker.
|
||||
|
||||
The web app has no connection to the operator's local USB. USB provisioning stays
|
||||
in local Mission Core; new network-reachable devices support initial config read
|
||||
with their installed firmware and configuration password. Firmware controls match
|
||||
the reference archive/import/download scope; no network flashing is advertised.
|
||||
|
||||
Validation: Device Core TypeScript/production build,286server/application tests,
|
||||
15B2permission/transport tests; VPS298tests; Mission Core71compatibility tests.
|
||||
Live deployment and UI acceptance are recorded in Ops MISSIONCOR-86 after release;
|
||||
these local results are not a production acceptance claim.
|
||||
@@ -5,7 +5,7 @@
|
||||
"dependencies": {
|
||||
"NODEDC_DESIGN_GUIDELINE": {
|
||||
"url": "https://git.dcserve.ru/SILVER/NODEDC_DESIGN_GUIDELINE.git",
|
||||
"commit": "2d23a0262e869adb4c6850abdc353c71facc2ca4"
|
||||
"commit": "a6e6c8f2d9c3de8d98b60c30da6a70d9538c1ef2"
|
||||
},
|
||||
"NODEDC_LAUNCHER": {
|
||||
"url": "https://git.dcserve.ru/SILVER/NODEDC_LAUNCHER.git",
|
||||
|
||||
@@ -149,7 +149,9 @@ export function createB2Client(input, { fetchImpl } = {}) {
|
||||
const value = await res.json().catch(() => null);
|
||||
if (!res.ok) {
|
||||
if (res.status === 401 || res.status === 403) { token = null; throw b2Error('b2_access_denied', 403); }
|
||||
if (res.status === 409 && ['settings_revision_changed', 'settings_initial_read_required', 'settings_sim_observation_required'].includes(value?.error)) throw b2Error('b2_' + value.error, 409);
|
||||
if (res.status === 409) throw b2Error('b2_conflict', 409);
|
||||
if (res.status === 400) throw b2Error('b2_request_invalid', 400);
|
||||
throw b2Error('b2_host_request_failed', 502);
|
||||
}
|
||||
if (!value || typeof value !== 'object') throw b2Error('b2_response_invalid', 502);
|
||||
|
||||
@@ -70,8 +70,43 @@ export class B2Infrastructure {
|
||||
}));
|
||||
return { items: results.flatMap((result) => result.items), hosts: results.map((result) => result.host) };
|
||||
}
|
||||
async tracker(actor, input) {
|
||||
fields(input, ['contourId', 'deviceId', 'request']);
|
||||
const projectId = ref(input.projectRef, 'project'), hostId = ref(input.hostRef, 'host');
|
||||
const contourId = opaque(input.contourId), deviceId = opaque(input.deviceId);
|
||||
const request = input.request;
|
||||
const permissions = {
|
||||
state: 'configuration.read', journal: 'audit.read', attempts: 'audit.read',
|
||||
'firmware-download': 'configuration.read', 'firmware-upload': 'configuration.manage',
|
||||
save: 'configuration.manage', 'profile-save': 'configuration.manage',
|
||||
read: 'command.dispatch', apply: 'configuration.manage', command: 'command.dispatch', cancel: 'command.dispatch',
|
||||
};
|
||||
if (!request || typeof request !== 'object' || !permissions[request.action]) throw b2Error('b2_request_invalid');
|
||||
const db = await this.pool.connect();
|
||||
let source;
|
||||
try {
|
||||
await db.query('begin');
|
||||
await findProjectWithCapability(db, actor, projectId, permissions[request.action]);
|
||||
if (request.action === 'apply') await findProjectWithCapability(db, actor, projectId, 'command.dispatch');
|
||||
source = (await db.query(`select s.* from device_b2_hosts s
|
||||
join device_b2_host_views v on v.source_id=s.id
|
||||
join device_b2_contour_links l on l.source_id=s.id and l.project_id=v.project_id
|
||||
join device_infrastructure_hosts h on h.id=v.host_id and h.project_id=v.project_id
|
||||
where v.host_id=$1 and v.project_id=$2 and l.contour_id=$3 and h.lifecycle_state='active'`,
|
||||
[hostId, projectId, contourId])).rows[0];
|
||||
if (!source) throw b2Error('b2_access_denied', 403);
|
||||
await db.query('commit');
|
||||
} catch (error) { await db.query('rollback'); throw error; } finally { db.release(); }
|
||||
const remote = await this.clientFor(source);
|
||||
const identity = await remote.call('/v2/identity');
|
||||
if (identity.host_id !== source.remote_host_id) throw b2Error('b2_host_identity_mismatch');
|
||||
// VPS checks the device's actual contour as well; a forged device ID cannot
|
||||
// borrow the host administrator credential from another project.
|
||||
return remote.call(`/v2/contours/${contourId}/devices/${deviceId}/settings`, request);
|
||||
}
|
||||
async execute(actor, input, requestId) {
|
||||
if (input.action === 'inventory') return this.inventory(actor, input);
|
||||
if (input.action === 'tracker') return this.tracker(actor, input);
|
||||
const projectId = ref(input.projectRef, 'project');
|
||||
const hostId = ref(input.hostRef, 'host');
|
||||
const action = input.action;
|
||||
|
||||
@@ -234,3 +234,33 @@ test('application creation and issuance use one server-generated request identit
|
||||
await assert.rejects(service.execute(actor, { action: 'application-connect', projectRef: `project:${projectId}`, hostRef: `host:${hostId}`, name: 'Other', contourId: 'f'.repeat(32) }, requestId), /b2_access_denied/);
|
||||
assert.equal(calls.length, 2);
|
||||
});
|
||||
|
||||
test('tracker settings keep project and contour authority across remote calls', async () => {
|
||||
const contour = 'c'.repeat(32), device = 'd'.repeat(32), calls = [];
|
||||
const repo = repository({ role: 'viewer' }); const db = await repo.pool.connect();
|
||||
let released = false; const original = db.query;
|
||||
db.release = () => { released = true; };
|
||||
db.query = async (sql, values) => {
|
||||
if (sql.includes('from device_b2_hosts')) {
|
||||
assert.match(sql, /l.project_id=v.project_id/);
|
||||
assert.match(sql, /h.lifecycle_state='active'/);
|
||||
assert.deepEqual(values, [hostId, projectId, contour]);
|
||||
return { rows: [source] };
|
||||
}
|
||||
return original(sql, values);
|
||||
};
|
||||
const service = new B2Infrastructure({ pool: repo.pool, secrets: { read: async () => pkg }, clientFactory: () => ({ async call(path, body) {
|
||||
assert.equal(released, true); calls.push({path,body});
|
||||
return path === '/v2/identity' ? {host_id:pkg.host_id} : {revision:1};
|
||||
} }) });
|
||||
const input = {action:'tracker',projectRef:`project:${projectId}`,hostRef:`host:${hostId}`,contourId:contour,deviceId:device,request:{action:'state'}};
|
||||
assert.deepEqual(await service.execute({...actor,hubRole:'member'},input), {revision:1});
|
||||
assert.equal(calls[1].path, `/v2/contours/${contour}/devices/${device}/settings`);
|
||||
for (const action of ['save','apply','read','command','cancel','firmware-upload','profile-save']) {
|
||||
await assert.rejects(service.execute({...actor,hubRole:'member'},{...input,request:{action}}));
|
||||
}
|
||||
assert.equal(calls.length,2);
|
||||
db.query = async (sql,values) => sql.includes('from device_b2_hosts') ? {rows:[]} : original(sql,values);
|
||||
await assert.rejects(service.execute(actor,input), /b2_access_denied/);
|
||||
assert.equal(calls.length,2);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user