fix(ui): align project overview counts and complete functional labels
Device Core qualification / qualify (push) Successful in 8m43s

This commit is contained in:
DCCONSTRUCTIONS
2026-09-30 21:27:53 +03:00
parent b3b0f900c5
commit a860b00310
5 changed files with 80 additions and 33 deletions
@@ -1,4 +1,5 @@
import { Children, isValidElement, useEffect, useMemo, useRef, useState, type FormEvent, type ReactNode } from "react";
import { auditEventLabel, capabilityLabel, projectRoleLabel } from './presentationLabels';
import {
Button,
ConfirmationModal,
@@ -1056,7 +1057,6 @@ function CommandsView({ workspace, canDispatch, onRefresh, onError }: {
? "Выберите устройство и введите его шестизначный код."
: "Для этого подключения отправка команд ещё не настроена."}</p>
</div>
<StatusBadge tone={enabled ? "success" : "warning"}>{workspace.policies.commandTransport}</StatusBadge>
</div>
{enabled ? (
<div>
@@ -1119,10 +1119,10 @@ function AuditView({ workspace }: { workspace: ProjectWorkspace }) {
{workspace.auditEvents.map((event) => (
<ResourceRow
key={event.auditEventRef}
title={event.eventType}
title={auditEventLabel(event.eventType)}
description={`${event.actorRef} · ${formatDate(event.occurredAt)}`}
status="recorded"
trailing={event.deviceRef || event.discoveryRef || "project"}
trailing={event.deviceRef || event.discoveryRef || "Проект"}
/>
))}
</ResourceList>
@@ -1146,9 +1146,9 @@ function AccessView({ workspace, canManage, onCreate }: {
<ResourceRow
key={grant.grantRef}
title={grant.principalRef}
description={`${grant.principalKind} · ${grant.projectRole}`}
description={`${({ user: 'Пользователь', group: 'Группа', service: 'Приложение' } as Record<string, string>)[grant.principalKind] || grant.principalKind} · ${projectRoleLabel(grant.projectRole)}`}
status={grant.lifecycleState}
trailing={grant.capabilityDeny.length ? `deny: ${grant.capabilityDeny.join(", ")}` : "Права роли"}
trailing={grant.capabilityDeny.length ? `Исключения: ${grant.capabilityDeny.map(capabilityLabel).join(", ")}` : "Права роли"}
/>
))}
</ResourceList>
@@ -1727,7 +1727,7 @@ function ResourceList({ children, empty }: { children: ReactNode; empty: string
function ResourceRow({ title, description, status, trailing }: { title: string; description: string; status: string; trailing: ReactNode }) {
return <CanonicalResourceRow title={title} description={description}
status={<StatusBadge variant="indicator" tone={statusTone(status)} aria-label={status} title={status} />} statusPlacement="leading"
status={<StatusBadge variant="indicator" tone={statusTone(status)} aria-label={statusLabel(status)} title={statusLabel(status)} />} statusPlacement="leading"
metadata={[statusLabel(status), typeof trailing === "string" ? trailing : null].filter(Boolean).join(" · ")}
actions={typeof trailing === "string" ? undefined : trailing} />;
}
+27 -21
View File
@@ -58,6 +58,8 @@ import type {
ProjectWorkspace,
} from "./types";
import { EnvironmentMediaPlaylistEditor } from "./EnvironmentMediaPlaylistEditor";
import { useB2Inventory } from "./b2/useB2Inventory";
import { capabilityLabel, projectRoleLabel } from "./presentationLabels";
import {
DeviceControlView,
type ControlViewId,
@@ -779,14 +781,6 @@ function EnvironmentBackdrop({
);
}
function Metric({ label, value, detail, tone = "neutral" }: { label: string; value: number; detail: string; tone?: "neutral" | "success" | "warning" }) {
return (
<SettingsCard title={label}>
<ResourceRow title={String(value)} metadata={detail} status={<StatusBadge variant="indicator" tone={tone} aria-label={label} />} />
</SettingsCard>
);
}
function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManageCollections, canClaim, canConfigure, canManageProject, inventoryDetail, session, onRefresh, onPoll, onError, onCreateCollection, onClaim, onInventoryDetailChange }: {
selectedHostRef: string | null;
onSelectHost: (hostRef: string | null) => void;
@@ -849,16 +843,28 @@ function ProjectView({ selectedHostRef, onSelectHost, view, workspace, canManage
/>
</div>
);
return <ProjectOverview key={workspace.project.projectRef} workspace={workspace} />;
}
function ProjectOverview({ workspace }: { workspace: ProjectWorkspace }) {
const b2 = useB2Inventory(workspace.project.projectRef, workspace);
const [showPermissions, setShowPermissions] = useState(false);
const incomplete = !b2.data || b2.data.hosts.some((host) => !host.reachable);
const deviceCount = incomplete ? null : workspace.devices.filter((device) => !['suspended', 'retired'].includes(device.lifecycleState)).length + b2.data!.items.length;
const deviceDetail = !incomplete ? 'В реестре' : (b2.error || b2.data) ? 'Данные VPS недоступны' : 'Загрузка…';
const metrics = [
{ label: 'Устройства', value: deviceCount, detail: deviceDetail },
{ label: 'Ожидают проверки', value: workspace.discoveries.filter((item) => item.lifecycleState === 'quarantine').length, detail: 'Обнаружены' },
{ label: 'Коллекции', value: workspace.collections.length, detail: 'Группы устройств' },
];
return (
<div className="device-manager-overview-grid">
<Metric label="Устройства" value={workspace.devices.length} detail="В реестре" />
<Metric label="Ожидают проверки" value={workspace.discoveries.filter((item) => item.lifecycleState === "quarantine").length} detail="Обнаружены" />
<Metric label="Коллекции" value={workspace.collections.length} detail="Группы устройств" />
<SettingsCard title="Права проекта" description={workspace.project.access.projectRole || "read"}>
<div className="device-manager-capabilities">
{workspace.project.access.capabilities.map((capability) => <StatusBadge key={capability}>{capability}</StatusBadge>)}
</div>
</SettingsCard>
<ResourceList>{metrics.map((metric) => <li key={metric.label}><ResourceRow title={metric.label} metadata={metric.detail} status={<StatusBadge>{metric.value ?? '—'}</StatusBadge>} /></li>)}</ResourceList>
<ResourceRow title="Ваш доступ" metadata={projectRoleLabel(workspace.project.access.projectRole || 'read')}
actions={<IconButton label="Права в проекте" aria-expanded={showPermissions} aria-controls="project-permissions" onClick={() => setShowPermissions(!showPermissions)}><Icon name={showPermissions ? 'chevron-up' : 'chevron-down'} /></IconButton>} />
{showPermissions ? <div id="project-permissions"><ResourceList>
{workspace.project.access.capabilities.map((capability) => <li key={capability}><ResourceRow title={capabilityLabel(capability)} /></li>)}
</ResourceList></div> : null}
</div>
);
}
@@ -1460,11 +1466,11 @@ function viewTitle(view: ViewId) {
collections: "Коллекции",
catalog: "Модели и адаптеры",
hosts: "VPS и хосты",
infrastructure: "Edges и маршруты",
sessions: "Gateway sessions",
bindings: "Data bindings",
commands: "Command ledger",
audit: "Immutable audit",
infrastructure: "Узлы и маршруты",
sessions: "Подключения устройств",
bindings: "Связи с Foundry",
commands: "Команды",
audit: "Аудит",
access: "Доступ к проекту",
settings: "Настройки и конфигурации",
})[view];
@@ -116,7 +116,7 @@ export function B2HostSettings({ host, workspace, onClose, onChanged, onError }:
<ResourceList>{apps.map(applicationRow)}</ResourceList>
{!apps.length && creating !== item.projectRef ? <p>Ключи приложений ещё не выданы</p> : null}
{creating === item.projectRef ? <div className="b2-settings">
<TextField label="Название приложения" value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={(event) => setName(event.target.value)} />
<TextField label="Название приложения" autoFocus value={name} disabled={busy || Boolean(creationIntent)} maxLength={160} onChange={(event) => setName(event.target.value)} />
<div className="b2-actions"><Button disabled={busy} onClick={() => { setCreating(''); setCreationIntent(null); }}>Отмена</Button><Button loading={pending === 'application-connect'} disabled={busy || !name.trim()} onClick={() => {
const intent = creationIntent || { id: crypto.randomUUID().replaceAll('-', ''), name: name.trim() };
setCreationIntent(intent);
+4 -5
View File
@@ -3,20 +3,19 @@ import { b2Request, type B2Device } from './api';
export type B2HostState = { hostRef: string; name: string; endpoint: string; contours: number; reachable: boolean; checkedAt: string; devices: number | null };
export type B2Inventory = { items: Array<B2Device & { hostRef: string; hostName: string }>; hosts: B2HostState[] };
export function useB2Inventory(projectRef: string, refreshSignal: unknown) {
const [data, setData] = useState<B2Inventory | null>(null);
const [error, setError] = useState('');
const [snapshot, setSnapshot] = useState<{ projectRef: string; data: B2Inventory | null; error: string } | null>(null);
useEffect(() => {
let active = true, timer: ReturnType<typeof setTimeout>;
async function load() {
try {
const next = await b2Request<B2Inventory>(projectRef, '', 'inventory');
if (active) { setData(next); setError(''); }
if (active) setSnapshot({ projectRef, data: next, error: '' });
} catch (reason) {
if (active) { setData(null); setError(reason instanceof Error ? reason.message : 'VPS недоступен'); }
if (active) setSnapshot({ projectRef, data: null, error: reason instanceof Error ? reason.message : 'VPS недоступен' });
} finally { if (active) timer = setTimeout(load, 30_000); }
}
void load();
return () => { active = false; clearTimeout(timer); };
}, [projectRef, refreshSignal]);
return { data, error };
return snapshot?.projectRef === projectRef ? snapshot : { data: null, error: '' };
}
@@ -0,0 +1,42 @@
const roles: Record<string, string> = {
owner: 'Владелец', admin: 'Администратор', operator: 'Оператор',
maintainer: 'Сопровождение', viewer: 'Наблюдатель', read: 'Просмотр',
};
export const projectRoleLabel = (role: string) => roles[role] || role;
const capabilities: Record<string, string> = {
'access.manage': 'Управление доступом', 'asset.manage': 'Управление объектами',
'audit.read': 'Просмотр аудита', 'binding.manage': 'Управление связями с Foundry',
'collection.manage': 'Управление коллекциями', 'command.confirm': 'Подтверждение команд',
'command.dispatch': 'Отправка команд', 'command.plan': 'Подготовка команд',
'configuration.manage': 'Изменение настроек устройств', 'configuration.read': 'Просмотр настроек устройств',
'credential.manage': 'Управление ключами', 'device.claim': 'Привязка устройств',
'device.enroll': 'Регистрация устройств', 'device.transfer': 'Перенос устройств',
'infrastructure.manage': 'Изменение инфраструктуры', 'infrastructure.read': 'Просмотр инфраструктуры',
'inventory.read': 'Просмотр реестра', 'observation.write': 'Запись наблюдений',
'project.manage': 'Управление проектом', 'project.read': 'Просмотр проекта',
'route.manage': 'Управление маршрутами', 'telemetry.observe': 'Просмотр телеметрии',
};
export const capabilityLabel = (capability: string) => capabilities[capability] || capability;
const eventObjects: Record<string, string> = {
owner_scope: 'Компания', project: 'Проект', collection: 'Коллекция',
project_grant: 'Доступ к проекту', command: 'Команда', device: 'Устройство',
discovery: 'Обнаруженное устройство', enrollment_intent: 'Регистрация устройства',
device_credential_binding: 'Ключ устройства', device_binding: 'Связь устройства',
device_configuration_revision: 'Версия настроек', device_configuration: 'Настройки устройства',
asset: 'Объект', asset_binding: 'Привязка объекта', edge: 'Узел', route: 'Маршрут',
infrastructure_host: 'VPS', infrastructure_endpoint: 'Точка подключения',
infrastructure_deployment: 'Развёртывание', infrastructure_service_instance: 'Сервис',
health_observation: 'Наблюдение',
};
const eventActions: Record<string, string> = {
created: 'создание', updated: 'изменение', archived: 'архивирование', restored: 'восстановление',
revoked: 'отзыв', claimed: 'привязка', queued: 'добавление в очередь', dispatched: 'отправка',
verified: 'подтверждение', confirmed: 'подтверждение', closed: 'закрытие', recorded: 'запись',
desired_changed: 'сохранение изменений', transferred_in: 'перенос в проект', transferred_out: 'перенос из проекта',
};
export function auditEventLabel(event: string) {
const [object, action] = event.split('.');
return eventObjects[object] && eventActions[action] ? `${eventObjects[object]} · ${eventActions[action]}` : event;
}