Compare commits

..
6 Commits
Author SHA1 Message Date
cacto a7d61b9fcc Подсказка external_id из уже увиденных устройств при добавлении
Поле External ID при создании/изменении устройства теперь input+datalist:
можно вписать значение вручную (как раньше) или выбрать из подсказок —
идентификаторы устройств, от которых device-control-service уже
получал MQTT-телеметрию/ack (Redis-множество devices:known), но
которые ещё не зарегистрированы в Postgres. Уже зарегистрированные
id из списка подсказок исключаются.

DeviceShadow::knownExternalIds() — новый read-метод (SMEMBERS
devices:known), зеркалит то же множество, что Go-сервисы уже читают/
пишут для health-check/online-детекции.
2026-08-18 03:08:53 +05:00
cacto 2c542fe097 Управление типами устройств из UI (список + создание)
Раньше device_types заводились только через сидер — теперь owner может
посмотреть все типы (карточки: иконка по категории, capabilities
тегами, число устройств этого типа) и добавить новый прямо из
интерфейса: код, категория, возможности вводятся тегами (можно
вписать вручную и добавить по Enter/кнопке). Ссылка на список — со
страницы устройств.

DeviceTypePolicy зеркалит остальные Policy (view — всем, create —
только owner). DeviceTypeResource получил devices_count через
whenCounted — опционально, не ломает существующий API-эндпоинт
(там withCount не вызывается, поле просто не появляется).
2026-08-18 03:07:07 +05:00
cacto e452217cc7 Merge branch 'feature/zone-devices-view' into feature/health-check-service 2026-08-13 13:07:43 +05:00
cacto f7aa0ba88e Страница зоны со всеми её устройствами и live-статусом
Раньше зона в списке была просто строкой без возможности провалиться
внутрь — все устройства смотрелись только через общий плоский список
/devices с колонкой "Зона". Теперь клик по зоне открывает её страницу
с карточками устройств (иконка по категории, статус online/offline/
unknown точкой с пульсацией для online, external_id) — ровно то, что
просили: все устройства и их статус на одном экране при выборе зоны.

Заодно список зон переведён с голой таблицы на карточки для
консистентности с новой страницей — вся карточка кликабельна и ведёт
на show, кнопки изменить/удалить остаются только у owner.

ZonePolicy::view уже был публичным (true всем) — новый роут
zones.show использует его без изменений.
2026-08-13 13:07:01 +05:00
cacto 6f8a6b49aa Merge branch 'fix/docker-tailwind-build' into feature/health-check-service 2026-08-13 12:39:50 +05:00
cacto 11d210839d Исправлена сборка фронтенда в Docker: Tailwind не компилировался
В Dockerfile этап сборки ассетов (node:22-alpine) копировал
vite.config.js, но не postcss.config.js и tailwind.config.js — без них
PostCSS внутри контейнера вообще не запускался, и Vite отдавал
собранный CSS как сырой непроцессенный исходник ("@tailwind base;
@tailwind components; @tailwind utilities;", 57 байт вместо ~30-50 КБ).
Все страницы рендерились полностью без стилей — баг был с самого
Stage 2 (Blade+Alpine), просто не всплывал при проверках через
get_page_text, а не через реальный скриншот.

Локальный `npm run build` (вне Docker) всегда работал корректно —
проблема была только в наборе файлов, копируемых в Docker build context.
2026-08-13 11:47:31 +05:00
23 changed files with 648 additions and 41 deletions
+1 -1
View File
@@ -16,7 +16,7 @@ WORKDIR /app
COPY package.json package-lock.json ./ COPY package.json package-lock.json ./
RUN npm ci RUN npm ci
COPY resources/ resources/ COPY resources/ resources/
COPY vite.config.js ./ COPY vite.config.js postcss.config.js tailwind.config.js ./
RUN npm run build RUN npm run build
# --- final: php-fpm + nginx in one container, supervised --- # --- final: php-fpm + nginx in one container, supervised ---
@@ -59,11 +59,11 @@ class DeviceController extends Controller
]); ]);
} }
public function create() public function create(DeviceShadow $shadow)
{ {
$this->authorize('create', Device::class); $this->authorize('create', Device::class);
return Inertia::render('Devices/Create', $this->formOptions()); return Inertia::render('Devices/Create', $this->formOptions($shadow));
} }
public function store(DeviceRequest $request) public function store(DeviceRequest $request)
@@ -75,13 +75,13 @@ class DeviceController extends Controller
return redirect()->route('devices.index')->with('status', 'Устройство добавлено.'); return redirect()->route('devices.index')->with('status', 'Устройство добавлено.');
} }
public function edit(Device $device) public function edit(Device $device, DeviceShadow $shadow)
{ {
$this->authorize('update', $device); $this->authorize('update', $device);
return Inertia::render('Devices/Edit', [ return Inertia::render('Devices/Edit', [
'device' => $device->only(['id', 'name', 'zone_id', 'device_type_id', 'external_id', 'protocol']), 'device' => $device->only(['id', 'name', 'zone_id', 'device_type_id', 'external_id', 'protocol']),
...$this->formOptions(), ...$this->formOptions($shadow),
]); ]);
} }
@@ -150,11 +150,21 @@ class DeviceController extends Controller
/** /**
* @return array<string, mixed> * @return array<string, mixed>
*/ */
private function formOptions(): array private function formOptions(DeviceShadow $shadow): array
{ {
$registeredIds = Device::pluck('external_id')->all();
$unregisteredExternalIds = collect($shadow->knownExternalIds())
->diff($registeredIds)
->sort()
->values();
return [ return [
'zones' => ZoneResource::collection(Zone::orderBy('name')->get())->resolve(), 'zones' => ZoneResource::collection(Zone::orderBy('name')->get())->resolve(),
'deviceTypes' => DeviceTypeResource::collection(DeviceType::orderBy('code')->get())->resolve(), 'deviceTypes' => DeviceTypeResource::collection(DeviceType::orderBy('code')->get())->resolve(),
// external_id of devices device-control-service has already seen
// over MQTT but nobody has registered yet — offered as
// suggestions (not a closed list) when adding/editing a device.
'unregisteredExternalIds' => $unregisteredExternalIds,
]; ];
} }
} }
@@ -0,0 +1,36 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\DeviceTypeRequest;
use App\Http\Resources\DeviceTypeResource;
use App\Models\DeviceType;
use Inertia\Inertia;
class DeviceTypeController extends Controller
{
public function index()
{
$this->authorize('viewAny', DeviceType::class);
$deviceTypes = DeviceType::withCount('devices')->orderBy('code')->get();
return Inertia::render('DeviceTypes/Index', [
'deviceTypes' => DeviceTypeResource::collection($deviceTypes)->resolve(),
]);
}
public function create()
{
$this->authorize('create', DeviceType::class);
return Inertia::render('DeviceTypes/Create');
}
public function store(DeviceTypeRequest $request)
{
DeviceType::create($request->validated());
return redirect()->route('device-types.index')->with('status', 'Тип устройства создан.');
}
}
@@ -3,8 +3,10 @@
namespace App\Http\Controllers; namespace App\Http\Controllers;
use App\Http\Requests\ZoneRequest; use App\Http\Requests\ZoneRequest;
use App\Http\Resources\DeviceResource;
use App\Http\Resources\ZoneResource; use App\Http\Resources\ZoneResource;
use App\Models\Zone; use App\Models\Zone;
use App\Services\DeviceShadow;
use Inertia\Inertia; use Inertia\Inertia;
class ZoneController extends Controller class ZoneController extends Controller
@@ -20,6 +22,20 @@ class ZoneController extends Controller
]); ]);
} }
public function show(Zone $zone, DeviceShadow $shadow)
{
$this->authorize('view', $zone);
$devices = $zone->devices()->with('deviceType')->orderBy('name')->get();
$statuses = $shadow->statuses($devices->pluck('external_id')->all());
$devices->each(fn ($d) => $d->live_status = $statuses[$d->external_id] ?? 'unknown');
return Inertia::render('Zones/Show', [
'zone' => (new ZoneResource($zone))->resolve(),
'devices' => DeviceResource::collection($devices)->resolve(),
]);
}
public function create() public function create()
{ {
$this->authorize('create', Zone::class); $this->authorize('create', Zone::class);
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Requests;
use App\Enums\DeviceCategory;
use App\Models\DeviceType;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class DeviceTypeRequest extends FormRequest
{
public function authorize(): bool
{
return $this->user()->can('create', DeviceType::class);
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'code' => ['required', 'string', 'max:255', 'alpha_dash', Rule::unique('device_types', 'code')],
'category' => ['required', Rule::enum(DeviceCategory::class)],
'capabilities' => ['array'],
'capabilities.*' => ['string', 'max:255'],
];
}
}
@@ -17,6 +17,7 @@ class DeviceTypeResource extends JsonResource
'code' => $this->code, 'code' => $this->code,
'category' => $this->category->value, 'category' => $this->category->value,
'capabilities' => $this->capabilities, 'capabilities' => $this->capabilities,
'devices_count' => $this->whenCounted('devices'),
]; ];
} }
} }
@@ -0,0 +1,25 @@
<?php
namespace App\Policies;
use App\Models\DeviceType;
use App\Models\User;
/** See ZonePolicy for the household-wide RBAC rationale. */
class DeviceTypePolicy
{
public function viewAny(User $user): bool
{
return true;
}
public function view(User $user, DeviceType $deviceType): bool
{
return true;
}
public function create(User $user): bool
{
return $user->isOwner();
}
}
+14
View File
@@ -54,4 +54,18 @@ class DeviceShadow
return array_combine($externalIds, array_map(fn ($v) => $v ?: 'unknown', $values)); return array_combine($externalIds, array_map(fn ($v) => $v ?: 'unknown', $values));
} }
/**
* external_id of every device device-control-service has ever heard
* from over MQTT (`devices:known`, a Redis Set it maintains) includes
* devices that sent telemetry/ack before anyone registered them in
* Postgres. Used to suggest an external_id when adding a device instead
* of requiring it to be typed exactly from memory.
*
* @return array<int, string>
*/
public function knownExternalIds(): array
{
return Redis::smembers('devices:known');
}
} }
@@ -0,0 +1,20 @@
<script setup>
defineProps({
category: { type: String, required: true },
});
</script>
<template>
<div
class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full"
:class="category === 'sensor' ? 'bg-sky-50 text-sky-600' : 'bg-amber-50 text-amber-600'"
>
<svg v-if="category === 'sensor'" class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8">
<path stroke-linecap="round" stroke-linejoin="round" d="M12 3v10.5a3.5 3.5 0 1 0 3 0" />
<path stroke-linecap="round" stroke-linejoin="round" d="M9.5 6h5" />
</svg>
<svg v-else class="h-5 w-5" viewBox="0 0 24 24" fill="currentColor">
<path d="M13 2 3 13.5h6.5L10.5 22 21 9.5h-6.5L13 2Z" />
</svg>
</div>
</template>
@@ -0,0 +1,31 @@
<script setup>
defineProps({
status: { type: String, required: true },
});
const dotColor = {
online: 'bg-green-500',
offline: 'bg-gray-300',
unknown: 'bg-yellow-400',
};
const label = {
online: 'Онлайн',
offline: 'Офлайн',
unknown: 'Неизвестно',
};
</script>
<template>
<span class="inline-flex items-center gap-1.5">
<span class="relative flex h-2.5 w-2.5">
<span
v-if="status === 'online'"
class="absolute inline-flex h-full w-full animate-ping rounded-full opacity-75"
:class="dotColor[status]"
/>
<span class="relative inline-flex h-2.5 w-2.5 rounded-full" :class="dotColor[status] ?? dotColor.unknown" />
</span>
<span class="text-xs font-medium text-gray-500">{{ label[status] ?? status }}</span>
</span>
</template>
@@ -0,0 +1,124 @@
<script setup>
import { ref } from 'vue';
import { useForm } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import { routes } from '@/routes';
const form = useForm({
code: '',
category: '',
capabilities: [],
});
const capabilityInput = ref('');
function addCapability() {
const value = capabilityInput.value.trim();
if (value && !form.capabilities.includes(value)) {
form.capabilities.push(value);
}
capabilityInput.value = '';
}
function removeCapability(index) {
form.capabilities.splice(index, 1);
}
function submit() {
form.post(routes.deviceTypes.store);
}
</script>
<template>
<AppLayout>
<template #header>
<h2 class="font-semibold text-xl text-gray-800 leading-tight">Новый тип устройства</h2>
</template>
<div class="py-12">
<div class="max-w-xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<form @submit.prevent="submit">
<div>
<label for="code" class="block font-medium text-sm text-gray-700">Код</label>
<input
id="code"
v-model="form.code"
type="text"
required
autofocus
placeholder="например, smart_socket"
class="mt-1 block w-full font-mono border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
>
<p class="mt-1 text-xs text-gray-400">Только латиница, цифры, дефис и подчёркивание используется как идентификатор.</p>
<div v-if="form.errors.code" class="mt-2 text-sm text-red-600">{{ form.errors.code }}</div>
</div>
<div class="mt-4">
<label for="category" class="block font-medium text-sm text-gray-700">Категория</label>
<select
id="category"
v-model="form.category"
required
class="mt-1 block w-full border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
>
<option value=""> выбрать </option>
<option value="sensor">Датчик</option>
<option value="actuator">Исполнитель</option>
</select>
<div v-if="form.errors.category" class="mt-2 text-sm text-red-600">{{ form.errors.category }}</div>
</div>
<div class="mt-4">
<label for="capability" class="block font-medium text-sm text-gray-700">Возможности</label>
<p class="mt-1 text-xs text-gray-400">
Для датчика типы показаний (например, temperature). Для исполнителя команды
(например, turn_on, turn_off, set_level).
</p>
<div class="mt-2 flex gap-2">
<input
id="capability"
v-model="capabilityInput"
type="text"
placeholder="turn_on"
class="block w-full font-mono border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
@keydown.enter.prevent="addCapability"
>
<button
type="button"
class="shrink-0 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="addCapability"
>
Добавить
</button>
</div>
<div v-if="form.capabilities.length" class="mt-3 flex flex-wrap gap-1.5">
<span
v-for="(capability, index) in form.capabilities"
:key="capability"
class="inline-flex items-center gap-1 rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600"
>
{{ capability }}
<button type="button" class="text-gray-400 hover:text-red-600" @click="removeCapability(index)">×</button>
</span>
</div>
<div v-if="form.errors.capabilities" class="mt-2 text-sm text-red-600">{{ form.errors.capabilities }}</div>
</div>
<div class="mt-6 flex items-center gap-4">
<button
type="submit"
:disabled="form.processing"
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 disabled:opacity-50"
>
Сохранить
</button>
<a :href="routes.deviceTypes.index" class="text-sm text-gray-600 hover:underline">Отмена</a>
</div>
</form>
</div>
</div>
</div>
</AppLayout>
</template>
@@ -0,0 +1,74 @@
<script setup>
import { computed } from 'vue';
import { Link, usePage } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import DeviceTypeIcon from '@/Components/DeviceTypeIcon.vue';
import { routes } from '@/routes';
defineProps({
deviceTypes: { type: Array, required: true },
});
const isOwner = computed(() => usePage().props.auth.user?.role === 'owner');
const categoryLabel = { sensor: 'Датчик', actuator: 'Исполнитель' };
</script>
<template>
<AppLayout>
<template #header>
<div class="flex justify-between items-center">
<div>
<Link :href="routes.devices.index" class="text-sm text-gray-500 hover:text-gray-700"> Устройства</Link>
<h2 class="mt-1 font-semibold text-xl text-gray-800 leading-tight">Типы устройств</h2>
</div>
<Link
v-if="isOwner"
:href="routes.deviceTypes.create"
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"
>
Добавить тип
</Link>
</div>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div v-if="deviceTypes.length === 0" class="bg-white rounded-xl border border-dashed border-gray-300 p-10 text-center text-sm text-gray-500">
Типов устройств пока нет.
</div>
<div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
<div
v-for="type in deviceTypes"
:key="type.id"
class="flex flex-col gap-4 rounded-xl border border-gray-200 bg-white p-5"
>
<div class="flex items-center gap-3">
<DeviceTypeIcon :category="type.category" />
<div>
<div class="font-medium text-gray-900">{{ type.code }}</div>
<div class="text-xs text-gray-500">{{ categoryLabel[type.category] ?? type.category }}</div>
</div>
</div>
<div class="flex flex-wrap gap-1.5">
<span
v-for="capability in type.capabilities"
:key="capability"
class="rounded-full bg-gray-100 px-2 py-0.5 text-xs text-gray-600"
>
{{ capability }}
</span>
<span v-if="type.capabilities.length === 0" class="text-xs text-gray-400">Без возможностей</span>
</div>
<div class="border-t border-gray-100 pt-3 text-xs text-gray-400">
{{ type.devices_count }} {{ type.devices_count === 1 ? 'устройство' : 'устройств' }}
</div>
</div>
</div>
</div>
</div>
</AppLayout>
</template>
@@ -5,6 +5,7 @@ import Form from '@/Pages/Devices/Form.vue';
defineProps({ defineProps({
zones: { type: Array, required: true }, zones: { type: Array, required: true },
deviceTypes: { type: Array, required: true }, deviceTypes: { type: Array, required: true },
unregisteredExternalIds: { type: Array, default: () => [] },
}); });
</script> </script>
@@ -17,7 +18,7 @@ defineProps({
<div class="py-12"> <div class="py-12">
<div class="max-w-xl mx-auto sm:px-6 lg:px-8"> <div class="max-w-xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6"> <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<Form :zones="zones" :device-types="deviceTypes" /> <Form :zones="zones" :device-types="deviceTypes" :unregistered-external-ids="unregisteredExternalIds" />
</div> </div>
</div> </div>
</div> </div>
@@ -6,6 +6,7 @@ defineProps({
device: { type: Object, required: true }, device: { type: Object, required: true },
zones: { type: Array, required: true }, zones: { type: Array, required: true },
deviceTypes: { type: Array, required: true }, deviceTypes: { type: Array, required: true },
unregisteredExternalIds: { type: Array, default: () => [] },
}); });
</script> </script>
@@ -18,7 +19,7 @@ defineProps({
<div class="py-12"> <div class="py-12">
<div class="max-w-xl mx-auto sm:px-6 lg:px-8"> <div class="max-w-xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6"> <div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6">
<Form :device="device" :zones="zones" :device-types="deviceTypes" /> <Form :device="device" :zones="zones" :device-types="deviceTypes" :unregistered-external-ids="unregisteredExternalIds" />
</div> </div>
</div> </div>
</div> </div>
@@ -6,6 +6,7 @@ const props = defineProps({
device: { type: Object, default: null }, device: { type: Object, default: null },
zones: { type: Array, required: true }, zones: { type: Array, required: true },
deviceTypes: { type: Array, required: true }, deviceTypes: { type: Array, required: true },
unregisteredExternalIds: { type: Array, default: () => [] },
}); });
const isEdit = !!props.device; const isEdit = !!props.device;
@@ -76,9 +77,17 @@ function submit() {
id="external_id" id="external_id"
v-model="form.external_id" v-model="form.external_id"
type="text" type="text"
list="unregistered-external-ids"
required required
placeholder="можно ввести вручную или выбрать увиденное устройство"
class="mt-1 block w-full font-mono border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm" class="mt-1 block w-full font-mono border-gray-300 focus:border-indigo-500 focus:ring-indigo-500 rounded-md shadow-sm"
> >
<datalist id="unregistered-external-ids">
<option v-for="id in unregisteredExternalIds" :key="id" :value="id" />
</datalist>
<p v-if="unregisteredExternalIds.length" class="mt-1 text-xs text-gray-400">
От {{ unregisteredExternalIds.length }} {{ unregisteredExternalIds.length === 1 ? 'устройства' : 'устройств' }} уже приходил сигнал, но они ещё не зарегистрированы начните вводить, чтобы увидеть подсказки.
</p>
<div v-if="form.errors.external_id" class="mt-2 text-sm text-red-600">{{ form.errors.external_id }}</div> <div v-if="form.errors.external_id" class="mt-2 text-sm text-red-600">{{ form.errors.external_id }}</div>
</div> </div>
@@ -23,13 +23,16 @@ function destroy(device) {
<template #header> <template #header>
<div class="flex justify-between items-center"> <div class="flex justify-between items-center">
<h2 class="font-semibold text-xl text-gray-800 leading-tight">Устройства</h2> <h2 class="font-semibold text-xl text-gray-800 leading-tight">Устройства</h2>
<Link <div class="flex items-center gap-3">
v-if="isOwner" <Link :href="routes.deviceTypes.index" class="text-sm text-gray-500 hover:text-gray-700">Типы устройств</Link>
:href="routes.devices.create" <Link
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" v-if="isOwner"
> :href="routes.devices.create"
Добавить устройство 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"
</Link> >
Добавить устройство
</Link>
</div>
</div> </div>
</template> </template>
+26 -25
View File
@@ -34,31 +34,32 @@ function destroy(zone) {
<div class="py-12"> <div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8"> <div class="max-w-7xl mx-auto sm:px-6 lg:px-8">
<div class="bg-white overflow-hidden shadow-sm sm:rounded-lg p-6"> <div v-if="zones.length === 0" class="bg-white rounded-xl border border-dashed border-gray-300 p-10 text-center text-sm text-gray-500">
<table class="w-full text-left text-sm"> Зон пока нет.
<thead> </div>
<tr class="border-b">
<th class="py-2">Название</th> <div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
<th class="py-2">Описание</th> <div
<th class="py-2">Устройств</th> v-for="zone in zones"
<th class="py-2" /> :key="zone.id"
</tr> class="group relative flex flex-col gap-3 rounded-xl border border-gray-200 bg-white p-5 transition hover:border-indigo-200 hover:shadow-md"
</thead> >
<tbody> <Link :href="routes.zones.show(zone.id)" class="absolute inset-0" :aria-label="zone.name" />
<tr v-if="zones.length === 0">
<td colspan="4" class="py-4 text-gray-500">Зон пока нет.</td> <div class="flex items-start justify-between">
</tr> <h3 class="font-medium text-gray-900 group-hover:text-indigo-600">{{ zone.name }}</h3>
<tr v-for="zone in zones" :key="zone.id" class="border-b"> <span class="rounded-full bg-gray-100 px-2 py-0.5 text-xs font-medium text-gray-600">
<td class="py-2">{{ zone.name }}</td> {{ zone.devices_count }} {{ zone.devices_count === 1 ? 'устройство' : 'устройств' }}
<td class="py-2 text-gray-500">{{ zone.description }}</td> </span>
<td class="py-2">{{ zone.devices_count }}</td> </div>
<td class="py-2 text-right space-x-2">
<Link v-if="isOwner" :href="routes.zones.edit(zone.id)" class="text-indigo-600 hover:underline">Изменить</Link> <p class="text-sm text-gray-500 min-h-5">{{ zone.description }}</p>
<button v-if="isOwner" type="button" class="text-red-600 hover:underline" @click="destroy(zone)">Удалить</button>
</td> <div v-if="isOwner" class="relative z-10 mt-2 flex items-center gap-3 border-t border-gray-100 pt-3 text-sm">
</tr> <Link :href="routes.zones.edit(zone.id)" class="text-indigo-600 hover:underline">Изменить</Link>
</tbody> <button type="button" class="text-red-600 hover:underline" @click="destroy(zone)">Удалить</button>
</table> </div>
</div>
</div> </div>
</div> </div>
</div> </div>
@@ -0,0 +1,76 @@
<script setup>
import { computed } from 'vue';
import { Link, usePage } from '@inertiajs/vue3';
import AppLayout from '@/Layouts/AppLayout.vue';
import DeviceTypeIcon from '@/Components/DeviceTypeIcon.vue';
import StatusDot from '@/Components/StatusDot.vue';
import { routes } from '@/routes';
const props = defineProps({
zone: { type: Object, required: true },
devices: { type: Array, required: true },
});
const isOwner = computed(() => usePage().props.auth.user?.role === 'owner');
const onlineCount = computed(() => props.devices.filter((d) => d.status === 'online').length);
</script>
<template>
<AppLayout>
<template #header>
<div class="flex items-center justify-between">
<div>
<Link :href="routes.zones.index" class="text-sm text-gray-500 hover:text-gray-700"> Зоны</Link>
<h2 class="mt-1 font-semibold text-xl text-gray-800 leading-tight">{{ zone.name }}</h2>
</div>
<Link
v-if="isOwner"
:href="routes.zones.edit(zone.id)"
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"
>
Изменить зону
</Link>
</div>
</template>
<div class="py-12">
<div class="max-w-7xl mx-auto sm:px-6 lg:px-8 space-y-6">
<div v-if="zone.description" class="text-sm text-gray-600">{{ zone.description }}</div>
<div class="flex items-center gap-2 text-sm text-gray-500">
<span class="font-medium text-gray-700">{{ devices.length }}</span> устройств,
<span class="font-medium text-green-600">{{ onlineCount }}</span> онлайн
</div>
<div v-if="devices.length === 0" class="bg-white rounded-xl border border-dashed border-gray-300 p-10 text-center text-sm text-gray-500">
В этой зоне пока нет устройств.
</div>
<div v-else class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
<Link
v-for="device in devices"
:key="device.id"
:href="routes.devices.show(device.id)"
class="group flex flex-col gap-4 rounded-xl border border-gray-200 bg-white p-5 transition hover:border-indigo-200 hover:shadow-md"
>
<div class="flex items-start justify-between gap-3">
<div class="flex items-center gap-3">
<DeviceTypeIcon :category="device.device_type.category" />
<div>
<div class="font-medium text-gray-900 group-hover:text-indigo-600">{{ device.name }}</div>
<div class="text-xs text-gray-500">{{ device.device_type.code }}</div>
</div>
</div>
</div>
<div class="flex items-center justify-between border-t border-gray-100 pt-3">
<StatusDot :status="device.status" />
<span class="font-mono text-xs text-gray-400">{{ device.external_id }}</span>
</div>
</Link>
</div>
</div>
</div>
</AppLayout>
</template>
+6
View File
@@ -6,6 +6,7 @@ export const routes = {
dashboard: '/dashboard', dashboard: '/dashboard',
zones: { zones: {
index: '/zones', index: '/zones',
show: (id) => `/zones/${id}`,
create: '/zones/create', create: '/zones/create',
store: '/zones', store: '/zones',
edit: (id) => `/zones/${id}/edit`, edit: (id) => `/zones/${id}/edit`,
@@ -24,6 +25,11 @@ export const routes = {
turnOff: (id) => `/devices/${id}/turn-off`, turnOff: (id) => `/devices/${id}/turn-off`,
setLevel: (id) => `/devices/${id}/set-level`, setLevel: (id) => `/devices/${id}/set-level`,
}, },
deviceTypes: {
index: '/device-types',
create: '/device-types/create',
store: '/device-types',
},
automationRules: { automationRules: {
index: '/automation-rules', index: '/automation-rules',
create: '/automation-rules/create', create: '/automation-rules/create',
+3 -1
View File
@@ -2,6 +2,7 @@
use App\Http\Controllers\AutomationRuleController; use App\Http\Controllers\AutomationRuleController;
use App\Http\Controllers\DeviceController; use App\Http\Controllers\DeviceController;
use App\Http\Controllers\DeviceTypeController;
use App\Http\Controllers\ProfileController; use App\Http\Controllers\ProfileController;
use App\Http\Controllers\ZoneController; use App\Http\Controllers\ZoneController;
use App\Models\AutomationRule; use App\Models\AutomationRule;
@@ -30,8 +31,9 @@ Route::get('/dashboard', function (DeviceShadow $shadow) {
})->middleware(['auth', 'verified'])->name('dashboard'); })->middleware(['auth', 'verified'])->name('dashboard');
Route::middleware(['auth', 'verified'])->group(function () { Route::middleware(['auth', 'verified'])->group(function () {
Route::resource('zones', ZoneController::class)->except('show'); Route::resource('zones', ZoneController::class);
Route::resource('devices', DeviceController::class); Route::resource('devices', DeviceController::class);
Route::resource('device-types', DeviceTypeController::class)->only(['index', 'create', 'store']);
Route::resource('automation-rules', AutomationRuleController::class) Route::resource('automation-rules', AutomationRuleController::class)
->except('show') ->except('show')
->parameters(['automation-rules' => 'automation_rule']); ->parameters(['automation-rules' => 'automation_rule']);
@@ -130,4 +130,23 @@ class DeviceControllerTest extends TestCase
->where('telemetry.0.value', 24.5) ->where('telemetry.0.value', 24.5)
); );
} }
public function test_create_form_suggests_unregistered_external_ids(): void
{
$owner = User::factory()->create(['role' => UserRole::Owner]);
// Already registered — must be excluded even though device-control-service still knows it.
$this->makeDevice($owner, ['turn_on']);
$this->mock(DeviceShadow::class, function ($mock) {
$mock->shouldReceive('knownExternalIds')->once()->andReturn(['fan-1', 'sensor-2']);
});
$response = $this->actingAs($owner)->get(route('devices.create'));
$response->assertOk();
$response->assertInertia(fn (Assert $page) => $page
->component('Devices/Create')
->where('unregisteredExternalIds', ['sensor-2'])
);
}
} }
@@ -0,0 +1,76 @@
<?php
namespace Tests\Feature;
use App\Enums\UserRole;
use App\Models\DeviceType;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase;
class DeviceTypeControllerTest extends TestCase
{
use RefreshDatabase;
public function test_owner_can_create_device_type(): void
{
$owner = User::factory()->create(['role' => UserRole::Owner]);
$response = $this->actingAs($owner)->post(route('device-types.store'), [
'code' => 'smart_socket',
'category' => 'actuator',
'capabilities' => ['turn_on', 'turn_off'],
]);
$response->assertRedirect(route('device-types.index'));
$this->assertDatabaseHas('device_types', [
'code' => 'smart_socket',
'category' => 'actuator',
]);
$this->assertSame(
['turn_on', 'turn_off'],
DeviceType::where('code', 'smart_socket')->first()->capabilities,
);
}
public function test_viewer_cannot_create_device_type(): void
{
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
$response = $this->actingAs($viewer)->post(route('device-types.store'), [
'code' => 'smart_socket',
'category' => 'actuator',
]);
$response->assertForbidden();
$this->assertDatabaseMissing('device_types', ['code' => 'smart_socket']);
}
public function test_code_must_be_unique(): void
{
$owner = User::factory()->create(['role' => UserRole::Owner]);
DeviceType::create(['code' => 'fan', 'category' => 'actuator', 'capabilities' => []]);
$response = $this->actingAs($owner)->post(route('device-types.store'), [
'code' => 'fan',
'category' => 'actuator',
]);
$response->assertSessionHasErrors('code');
}
public function test_viewer_can_view_device_types_index(): void
{
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
DeviceType::create(['code' => 'fan', 'category' => 'actuator', 'capabilities' => ['turn_on']]);
$response = $this->actingAs($viewer)->get(route('device-types.index'));
$response->assertOk();
$response->assertInertia(fn (Assert $page) => $page
->component('DeviceTypes/Index')
->where('deviceTypes.0.code', 'fan')
);
}
}
@@ -2,9 +2,13 @@
namespace Tests\Feature; namespace Tests\Feature;
use App\Enums\DeviceCategory;
use App\Enums\UserRole; use App\Enums\UserRole;
use App\Models\Device;
use App\Models\DeviceType;
use App\Models\User; use App\Models\User;
use App\Models\Zone; use App\Models\Zone;
use App\Services\DeviceShadow;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Inertia\Testing\AssertableInertia as Assert; use Inertia\Testing\AssertableInertia as Assert;
use Tests\TestCase; use Tests\TestCase;
@@ -52,6 +56,35 @@ class ZoneControllerTest extends TestCase
); );
} }
public function test_zone_show_lists_its_devices_with_live_status(): void
{
$viewer = User::factory()->create(['role' => UserRole::Viewer]);
$zone = Zone::forceCreate(['user_id' => $viewer->id, 'name' => 'Гроубокс']);
$type = DeviceType::create([
'code' => 'fan',
'category' => DeviceCategory::Actuator,
'capabilities' => ['turn_on'],
]);
Device::forceCreate([
'user_id' => $viewer->id, 'zone_id' => $zone->id, 'device_type_id' => $type->id,
'name' => 'Вентилятор', 'external_id' => 'fan-1', 'protocol' => 'mqtt',
]);
$this->mock(DeviceShadow::class, function ($mock) {
$mock->shouldReceive('statuses')->once()->with(['fan-1'])->andReturn(['fan-1' => 'online']);
});
$response = $this->actingAs($viewer)->get(route('zones.show', $zone));
$response->assertOk();
$response->assertInertia(fn (Assert $page) => $page
->component('Zones/Show')
->where('zone.name', 'Гроубокс')
->where('devices.0.name', 'Вентилятор')
->where('devices.0.status', 'online')
);
}
public function test_viewer_cannot_delete_zone(): void public function test_viewer_cannot_delete_zone(): void
{ {
$viewer = User::factory()->create(['role' => UserRole::Viewer]); $viewer = User::factory()->create(['role' => UserRole::Viewer]);