Files
home_automatization/laravel-app/resources/js/Pages/Devices/Show.vue
cacto be1f238f89 Перевод защищённой части приложения на Vue.js + Inertia
Дашборд, зоны, устройства, правила автоматизации и профиль теперь
Vue 3 + Inertia вместо Blade+Alpine — гостевые страницы Breeze
(логин/регистрация) сознательно оставлены на Blade, чтобы не трогать
уже протестированную аутентификацию. Контроллеры возвращают
Inertia::render() вместо view(), переиспользуют существующие
API Resources и FormRequest.

Ключевой нюанс: Resource/ResourceCollection, переданные напрямую в
проп Inertia, заворачиваются в ключ "data" (Inertia вызывает
toResponse() у Responsable-объектов) — везде используется ->resolve()
и явное резолвление вложенных ресурсов (zone/device_type внутри
Device и т.п.), иначе вложенные поля тоже задваивались бы обёрткой.

Alpine.js и все Blade-вьюхи защищённой части удалены как мёртвый код.
Тесты (ZoneControllerTest/DeviceControllerTest) переведены на
assertInertia(). UserFactory теперь явно задаёт role=owner — без
этого Eloquent не подтягивает DB-default обратно в модель после
create(), что уронило бы общий auth.user проп на любой странице.
2026-08-12 10:52:04 +05:00

133 lines
6.4 KiB
Vue

<script setup>
import { computed } from 'vue';
import { useForm, usePage } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import StatusBadge from '@/Components/StatusBadge.vue';
import { routes } from '@/routes';
const props = defineProps({
device: { type: Object, required: true },
shadow: { type: Object, required: true },
telemetry: { type: Array, required: true },
});
const isOwner = computed(() => usePage().props.auth.user?.role === 'owner');
const capabilities = computed(() => props.device.device_type.capabilities ?? []);
const hasControls = computed(() => capabilities.value.some((c) => ['turn_on', 'turn_off', 'set_level'].includes(c)));
const lastSeenLabel = computed(() => (
props.shadow.last_seen ? new Date(props.shadow.last_seen).toLocaleString('ru-RU') : 'нет данных'
));
const levelForm = useForm({ level: '' });
function turnOn() {
useForm({}).post(routes.devices.turnOn(props.device.id));
}
function turnOff() {
useForm({}).post(routes.devices.turnOff(props.device.id));
}
function setLevel() {
levelForm.post(routes.devices.setLevel(props.device.id));
}
</script>
<template>
<AppLayout>
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">{{ device.name }}</h2>
</template>
<div class="py-12">
<div class="max-w-4xl mx-auto sm:px-6 lg:px-8 space-y-6">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<h3 class="font-semibold mb-4">Живое состояние (Redis device shadow)</h3>
<dl class="grid grid-cols-2 gap-4 text-sm">
<div>
<dt class="text-gray-500">Статус</dt>
<dd class="mt-1"><StatusBadge :status="device.status" /></dd>
</div>
<div>
<dt class="text-gray-500">Последняя активность</dt>
<dd>{{ lastSeenLabel }}</dd>
</div>
<div>
<dt class="text-gray-500">Желаемое состояние (desired)</dt>
<dd class="font-mono text-xs">{{ JSON.stringify(shadow.desired_state) }}</dd>
</div>
<div>
<dt class="text-gray-500">Подтверждённое состояние (reported)</dt>
<dd class="font-mono text-xs">{{ JSON.stringify(shadow.reported_state) }}</dd>
</div>
</dl>
</div>
<div v-if="isOwner && hasControls" class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<h3 class="font-semibold mb-4">Ручное управление</h3>
<div class="flex items-center gap-4 flex-wrap">
<button
v-if="capabilities.includes('turn_on')"
type="button"
class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700"
@click="turnOn"
>
Включить
</button>
<button
v-if="capabilities.includes('turn_off')"
type="button"
class="inline-flex items-center px-4 py-2 bg-white border border-gray-300 rounded-md font-semibold text-xs text-gray-700 uppercase tracking-widest hover:bg-gray-50"
@click="turnOff"
>
Выключить
</button>
<form v-if="capabilities.includes('set_level')" class="flex items-center gap-2" @submit.prevent="setLevel">
<input
v-model="levelForm.level"
type="number"
step="any"
required
placeholder="уровень"
class="border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm text-sm"
>
<button
type="submit"
class="inline-flex items-center px-4 py-2 bg-gray-800 border border-transparent rounded-md font-semibold text-xs text-white uppercase tracking-widest hover:bg-gray-700"
>
Установить уровень
</button>
</form>
</div>
</div>
<div v-if="device.device_type.category === 'sensor'" class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<h3 class="font-semibold mb-4">Последние показания (ClickHouse)</h3>
<table class="w-full text-left text-sm">
<thead>
<tr class="border-b">
<th class="py-2">Тип</th>
<th class="py-2">Значение</th>
<th class="py-2">Время</th>
</tr>
</thead>
<tbody>
<tr v-if="telemetry.length === 0">
<td colspan="3" class="py-4 text-gray-500">Показаний пока нет.</td>
</tr>
<tr v-for="(row, i) in telemetry" :key="i" class="border-b">
<td class="py-2">{{ row.sensor_type }}</td>
<td class="py-2">{{ row.value }}</td>
<td class="py-2">{{ row.recorded_at }}</td>
</tr>
</tbody>
</table>
</div>
<a :href="routes.devices.index" class="text-sm text-gray-600 hover:underline"> Назад к устройствам</a>
</div>
</div>
</AppLayout>
</template>