Align tracker receipt states and attempt history with Mission Core
Device Core qualification / qualify (push) Successful in 6m37s
Device Core qualification / qualify (push) Successful in 6m37s
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
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 { trackerRequest, newIntent, operationName, stateName, operationTone, formatTime, type TrackerRef, type TrackerState, type Policy, type Operation } from './tracker';
|
||||
import { B2RequestError } from './api';
|
||||
import './b2.css';
|
||||
|
||||
@@ -76,7 +76,7 @@ export function B2TrackerSettings({projectRef,device,initialSection='identity',o
|
||||
{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}
|
||||
{latest?<StatusBadge tone={operationTone(latest.state)}>{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>
|
||||
@@ -131,14 +131,14 @@ function B2CommandWindow({projectRef,device,data,canCommand,onClose,onError}:{pr
|
||||
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} />
|
||||
<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,disabled:'pin' in item.command&&data?.observed?.output_modes[String(item.command.pin)]!==1}))} 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}
|
||||
<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={operationTone(row.state)}>{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]} onMore={before=>void request<{items:Operation[];next_before:number|null}>({action:'attempts',operation:row.id,before}).then(value=>setHistory(old=>({...old,[row.id]:{...value,items:[...((old[row.id] as {items:Operation[]})?.items||[]),...value.items]}}))).catch(onError)} /></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; }
|
||||
function AttemptRows({value,onMore}:{value:unknown;onMore:(before:number)=>void}) { const page=value as {items?:Operation[];next_before?:number|null}|undefined;return page?.items?.length?<><ResourceList>{page.items.map((item,index)=><li key={item.id||index}><ResourceRow title={`Попытка ${item.number??index+1}`} metadata={formatTime(item.dispatched_at)} status={<StatusBadge tone={operationTone(item.state)}>{stateName(item.state)}</StatusBadge>} /></li>)}</ResourceList>{page.next_before?<Button onClick={()=>onMore(page.next_before!)}>Предыдущие попытки</Button>:null}</>:null; }
|
||||
|
||||
@@ -17,5 +17,6 @@ export function trackerRequest<T>(projectRef: string, device: TrackerRef, reques
|
||||
}
|
||||
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 stateName = (state: string) => ({queued:'В очереди VPS',dispatched:'Отправлено B2',observed:'Настройки прочитаны',verified:'Настройки проверены',accepted:'Принято B2',device_accepted:'Принято B2, выполняется',device_confirmed:'Подтверждено B2',device_rejected:'Отклонено B2',sim_selected:'SIM подключена',reconnected:'Связь после перезапуска подтверждена',delivered:'Доставлено',stopped:'Повторы остановлены',cancelled:'Отменено до отправки',rejected:'Отклонено',uncertain:'Результат неизвестен',unconfirmed:'Результат не подтверждён',not_applied:'Не применено',expired:'Попытка завершилась без ответа',failed:'Ошибка'}[state] || 'Неизвестный статус');
|
||||
export const operationTone = (state:string):'success'|'warning'|'neutral' => ['accepted','device_confirmed','reconnected','observed','verified','sim_selected'].includes(state)?'success':['unconfirmed','uncertain','device_rejected','rejected','not_applied','expired'].includes(state)?'warning':'neutral';
|
||||
export const formatTime = (value?: number | null) => value ? new Date(value*1000).toLocaleString('ru-RU') : '—';
|
||||
|
||||
Reference in New Issue
Block a user