Compare commits

...
Author SHA1 Message Date
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
cacto e739ef5d38 Добавлен REST API для мобильного приложения (этап 3, без Telegram)
Токен-аутентификация Sanctum (login/logout по устройствам),
эндпоинты /api/v1 для зон/устройств/правил автоматизации с тем же
RBAC (owner/viewer), что и в веб-версии — контроллеры переиспользуют
существующие Policy и FormRequest. Устройства отдают живой статус
из Device Shadow (Redis) и историю телеметрии из ClickHouse, плюс
управление (turn-on/turn-off/set-level) через device-control-service.
2026-08-12 00:21:38 +05:00
cacto 81040eec62 Добавлены метрики Prometheus и дашборды Grafana (этап 2.5)
Все три Go-сервиса (ingest, device-control, rule-engine) отдают
/metrics в формате Prometheus: счётчики MQTT/RabbitMQ/ClickHouse
операций, гистограммы длительности батч-флашей и диспатча правил,
переходы устройств online/offline. Добавлены сервисы prometheus и
grafana в docker-compose с провижининг конфигом (datasource +
два готовых дашборда: "Ingest & Telemetry" и "Automation & Devices").
2026-08-11 21:58:59 +05:00
cacto 3ade5c2512 Дашборд с реальными данными + ручное управление устройствами
device-control-service: HTTP/JSON API (internal/httpapi) рядом с gRPC —
POST /devices/{id}/turn-on|turn-off|set-level, тот же server.Server внутри,
без дублирования логики. Решение вместо gRPC-клиента на PHP: grpc/grpc
через PECL компилируется в Alpine 10-20+ минут и утяжеляет образ, а
диаграмма архитектуры в ТЗ и так допускала HTTP для Laravel→device-control.

Laravel: DeviceShadow (чтение Device Shadow из Redis, MGET одним запросом
для списка устройств), ClickHouseClient (HTTP-интерфейс ClickHouse,
параметризованные {name:Type}-запросы), DeviceControlClient (HTTP-вызовы
к новому Go-эндпоинту). Redis-клиент — predis (чистый PHP), а не phpredis,
по той же причине, что и решение по gRPC — не добавлять ещё одну
C-компиляцию в образ.

DeviceController::show — страница устройства: live-статус/last_seen/
desired-reported state из Redis, история показаний из ClickHouse (для
сенсоров), кнопки ручного управления (для актуаторов, только owner,
с проверкой capability устройства). В devices/index — бейдж online/
offline/unknown. Дашборд дополнен счётчиком онлайн-устройств.

Два реальных бага найдены и исправлены при сквозной проверке:
1. Пустой action_params сериализовался в JSON-массив "[]" (PHP не
   различает пустой список и пустой объект), а Go ждёт объект —
   rule-engine-service падал на unmarshal. Фикс — JsonObjectCast
   (JSON_FORCE_OBJECT) на AutomationRule::action_params.
2. Redis-ключи device shadow — общее пространство имён с Go-сервisами
   (сырые ключи без префикса), а Laravel по умолчанию добавляет ко всем
   ключам префикс "app-name-database-" — Laravel никогда не видел
   реальные данные. Фикс — REDIS_PREFIX="" в окружении контейнера
   (важно: пустое значение в docker-compose YAML нужно задавать явно
   через "", просто "KEY:" означает "взять из окружения хоста").

Проверено сквозным тестом через docker compose: полный цикл телеметрия →
правило → команда воспроизведён вживую с реальным исправлением на лету;
ручное управление (turn_on/turn_off/set_level) из Laravel UI подтверждено
через браузер — HTTP-вызов к device-control-service, обновление
desired_state (merge-patch), реальная MQTT-команда поймана мониторингом
топика. 38/38 тестов Laravel, все Go-тесты device-control-service зелёные.
2026-08-11 19:48:17 +05:00
cacto 467a05542c CRUD зон/устройств/правил автоматизации + RBAC owner/viewer
Policies (ZonePolicy/DevicePolicy/AutomationRulePolicy): не multi-tenant
изоляция по user_id, а household-wide RBAC — все авторизованные видят одни
и те же данные, только owner может создавать/менять/удалять. user_id на
записи — это created_by, а не граница видимости.

Form Requests с authorize() через политики; DeviceRequest учитывает unique
external_id с ignore на update. AutomationRuleRequest: action_type остаётся
строкой (не enum), т.к. это открытый список из device_types.capabilities;
для действия set_level в форме есть отдельное поле "level" (Alpine.js
переключает его видимость), которое контроллер мапит в action_params —
без сырого JSON-редактора для MVP.

Контроллеры без show (index+create/edit достаточно), Blade-формы на базе
Breeze-компонентов. Навигация и дашборд (счётчики зон/устройств/активных
правил) обновлены. Добавлен DemoGrowboxSeeder (демо-зона с датчиком,
вентилятором и правилом) и viewer-пользователь в сидер.

Восстановлен трейт AuthorizesRequests в базовом Controller (Laravel 11+
убрал его по умолчанию) — нужен для $this->authorize().

Проверено: 33/33 теста (включая новые ZoneControllerTest,
AutomationRuleControllerTest — маппинг level→action_params, 403 для
viewer), полный CRUD-цикл вживую через браузер под owner (создание зоны,
правила с set_level, Alpine-переключение поля "Уровень"), доступ viewer
подтверждён как read-only (нет кнопок изменения, прямой заход на
/zones/create отдаёт 403).
2026-08-11 16:54:26 +05:00
cacto bb492785a4 Каркас Laravel-приложения: Breeze+Sanctum, схема БД, модели, Docker
Laravel 13 в laravel-app/, Breeze (Blade) для сессионного логина + Sanctum
для API-токенов (задел под Vue/Flutter на этапе 3). Схема Postgres
перенесена из сырого SQL в Laravel-миграции (владелец схемы теперь Laravel,
Go-сервисы как читали/писали эти таблицы, так и продолжают). Роли/категории/
операторы условий — закрытые PHP-enum'ы (UserRole, DeviceCategory,
ConditionOperator); action_type правил намеренно остаётся строкой — открытый,
управляемый данными список, а не код. Сидер device_types с growbox-типами
как пример данных, не бизнес-логика.

Docker: один контейнер (php-fpm + nginx через supervisord, multi-stage
сборка vendor/assets). Образ пока не --no-dev — сидер использует fake()
для демо-аккаунта.

Проверено: миграции применяются на реальном Postgres (в докере и локально),
дефолтные тесты Breeze проходят (25/25), Breeze-логин подтверждён вживую
через браузер, Sanctum корректно отдаёт 401 на защищённый /api/user без
токена.
2026-07-28 08:15:26 +05:00
206 changed files with 20419 additions and 128 deletions
+15 -2
View File
@@ -30,8 +30,9 @@ RABBITMQ_PASSWORD=change_me
MQTT_HOST=mosquitto
MQTT_PORT=1883
# --- device-control-service (gRPC) ---
# --- device-control-service (gRPC + HTTP) ---
DEVICE_CONTROL_GRPC_PORT=50051
DEVICE_CONTROL_HTTP_PORT=8090
DEVICE_CONTROL_MQTT_CLIENT_ID=device-control-service
DEVICE_CONTROL_HEALTHCHECK_TIMEOUT=60s
DEVICE_CONTROL_HEALTHCHECK_INTERVAL=15s
@@ -42,11 +43,23 @@ INGEST_MQTT_TOPIC=devices/+/telemetry
INGEST_BATCH_MAX_SIZE=500
INGEST_BATCH_FLUSH_INTERVAL=5s
INGEST_BATCH_FLUSH_TIMEOUT=10s
INGEST_METRICS_PORT=9101
# --- rule-engine-service ---
DEVICE_CONTROL_HOST=device-control-service
RULE_ENGINE_CACHE_REFRESH_INTERVAL=15s
RULE_ENGINE_METRICS_PORT=9102
# --- Laravel app (stage 2) ---
APP_KEY=
# Regenerate for anything beyond local dev: php artisan key:generate --show
APP_KEY=base64:bR7XdYPEJB20+lOd+mlpmuMMRJ/SVs69bHEmZrM2R90=
APP_ENV=local
APP_DEBUG=true
APP_URL=http://localhost:8000
LARAVEL_HTTP_PORT=8000
# --- Prometheus + Grafana (stage 2.5) ---
PROMETHEUS_PORT=9090
GRAFANA_PORT=3000
GRAFANA_ADMIN_USER=admin
GRAFANA_ADMIN_PASSWORD=change_me
+1 -7
View File
@@ -9,13 +9,7 @@ services/rule-engine-service/rule-engine-service
services/health-check-service/health-check-service
services/esp32-emulator/esp32-emulator
# Laravel
laravel-app/vendor/
laravel-app/node_modules/
laravel-app/.env
laravel-app/storage/*.key
laravel-app/bootstrap/cache/*
!laravel-app/bootstrap/cache/.gitkeep
# Laravel: laravel-app/ has its own .gitignore (vendor, node_modules, .env, etc.)
# Env / secrets
.env
+2 -1
View File
@@ -66,9 +66,10 @@ services/
health-check-service/ Go — тикер обнаружения офлайн-устройств
esp32-emulator/ Go — фейковое устройство для локальной разработки
laravel-app/ PHP/Laravel — API, авторизация, дашборд (этап 2)
владеет схемой Postgres (database/migrations/*.php:
users, zones, devices, device_types, automation_rules)
proto/ Общие gRPC-контракты (device_control.proto)
migrations/
postgres/ users, zones, devices, device_types, automation_rules
clickhouse/ таблица telemetry
configs/mosquitto/ Конфиг MQTT-брокера
monitoring/ Конфиги Prometheus + Grafana (этап 2.5)
+86 -4
View File
@@ -8,6 +8,8 @@ volumes:
redis-data:
rabbitmq-data:
mosquitto-data:
prometheus-data:
grafana-data:
services:
mosquitto:
@@ -31,7 +33,6 @@ services:
- "${POSTGRES_PORT}:5432"
volumes:
- postgres-data:/var/lib/postgresql/data
- ./migrations/postgres:/docker-entrypoint-initdb.d:ro
networks:
- home-automation
healthcheck:
@@ -93,6 +94,8 @@ services:
ingest-service:
build: ./services/ingest-service
ports:
- "${INGEST_METRICS_PORT}:9101"
environment:
MQTT_HOST: mosquitto
MQTT_PORT: 1883
@@ -105,6 +108,7 @@ services:
RABBITMQ_PORT: 5672
RABBITMQ_USER: ${RABBITMQ_USER}
RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD}
INGEST_METRICS_PORT: 9101
depends_on:
mosquitto:
condition: service_started
@@ -122,8 +126,10 @@ services:
dockerfile: services/device-control-service/Dockerfile
ports:
- "${DEVICE_CONTROL_GRPC_PORT}:50051"
- "${DEVICE_CONTROL_HTTP_PORT}:8090"
environment:
DEVICE_CONTROL_GRPC_PORT: 50051
DEVICE_CONTROL_HTTP_PORT: 8090
MQTT_HOST: mosquitto
MQTT_PORT: 1883
REDIS_HOST: redis
@@ -151,6 +157,8 @@ services:
build:
context: .
dockerfile: services/rule-engine-service/Dockerfile
ports:
- "${RULE_ENGINE_METRICS_PORT}:9102"
environment:
POSTGRES_HOST: postgres
POSTGRES_PORT: 5432
@@ -164,6 +172,7 @@ services:
RABBITMQ_USER: ${RABBITMQ_USER}
RABBITMQ_PASSWORD: ${RABBITMQ_PASSWORD}
RULE_ENGINE_CACHE_REFRESH_INTERVAL: ${RULE_ENGINE_CACHE_REFRESH_INTERVAL}
RULE_ENGINE_METRICS_PORT: 9102
depends_on:
postgres:
condition: service_healthy
@@ -175,6 +184,79 @@ services:
- home-automation
restart: unless-stopped
# Remaining app services (health-check-service, esp32-emulator,
# laravel-app) are added here as they get implemented — see
# services/*/README.md for the plan for each one.
laravel-app:
build: ./laravel-app
ports:
- "${LARAVEL_HTTP_PORT}:80"
environment:
APP_NAME: "Home Automation Platform"
APP_KEY: ${APP_KEY}
APP_ENV: ${APP_ENV}
APP_DEBUG: ${APP_DEBUG}
APP_URL: ${APP_URL}
DB_CONNECTION: pgsql
DB_HOST: postgres
DB_PORT: 5432
DB_DATABASE: ${POSTGRES_DB}
DB_USERNAME: ${POSTGRES_USER}
DB_PASSWORD: ${POSTGRES_PASSWORD}
SESSION_DRIVER: database
CACHE_STORE: database
QUEUE_CONNECTION: sync
REDIS_CLIENT: predis
REDIS_HOST: redis
REDIS_PORT: 6379
REDIS_PASSWORD: ${REDIS_PASSWORD}
# Device Shadow keys are a cross-service keyspace (device-control-service
# writes them raw) — Laravel's default per-app key prefix would hide them.
REDIS_PREFIX: ""
CLICKHOUSE_HOST: clickhouse
CLICKHOUSE_HTTP_PORT: 8123
CLICKHOUSE_DB: ${CLICKHOUSE_DB}
CLICKHOUSE_USER: ${CLICKHOUSE_USER}
CLICKHOUSE_PASSWORD: ${CLICKHOUSE_PASSWORD}
DEVICE_CONTROL_HTTP_URL: http://device-control-service:8090
LOG_CHANNEL: stderr
depends_on:
postgres:
condition: service_healthy
redis:
condition: service_started
clickhouse:
condition: service_healthy
device-control-service:
condition: service_started
networks:
- home-automation
restart: unless-stopped
prometheus:
image: prom/prometheus:v3.1.0
ports:
- "${PROMETHEUS_PORT}:9090"
volumes:
- ./monitoring/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
- prometheus-data:/prometheus
networks:
- home-automation
restart: unless-stopped
grafana:
image: grafana/grafana:11.4.0
ports:
- "${GRAFANA_PORT}:3000"
environment:
GF_SECURITY_ADMIN_USER: ${GRAFANA_ADMIN_USER}
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD}
GF_USERS_ALLOW_SIGN_UP: "false"
volumes:
- grafana-data:/var/lib/grafana
- ./monitoring/grafana/provisioning:/etc/grafana/provisioning:ro
depends_on:
- prometheus
networks:
- home-automation
restart: unless-stopped
# Remaining app services (health-check-service, esp32-emulator) are added
# here as they get implemented — see services/*/README.md for the plan.
+16
View File
@@ -0,0 +1,16 @@
.env
.env.*
!.env.example
vendor/
node_modules/
storage/*.key
storage/logs/*
storage/framework/cache/*
storage/framework/sessions/*
storage/framework/views/*
public/build/
public/hot
.git
.idea
.vscode
tests/
+18
View File
@@ -0,0 +1,18 @@
root = true
[*]
charset = utf-8
end_of_line = lf
indent_size = 4
indent_style = space
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
[*.{yml,yaml}]
indent_size = 2
[{compose,docker-compose}.{yml,yaml}]
indent_size = 4
+78
View File
@@ -0,0 +1,78 @@
APP_NAME=Laravel
APP_ENV=local
APP_KEY=
APP_DEBUG=true
APP_URL=http://localhost
APP_LOCALE=en
APP_FALLBACK_LOCALE=en
APP_FAKER_LOCALE=en_US
APP_MAINTENANCE_DRIVER=file
# APP_MAINTENANCE_STORE=database
# PHP_CLI_SERVER_WORKERS=4
BCRYPT_ROUNDS=12
LOG_CHANNEL=stack
LOG_STACK=single
LOG_DEPRECATIONS_CHANNEL=null
LOG_LEVEL=debug
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=home_automation
DB_USERNAME=home_automation
# DB_PASSWORD=
SESSION_DRIVER=database
SESSION_LIFETIME=120
SESSION_ENCRYPT=false
SESSION_PATH=/
SESSION_DOMAIN=null
BROADCAST_CONNECTION=log
FILESYSTEM_DISK=local
QUEUE_CONNECTION=database
CACHE_STORE=database
# CACHE_PREFIX=
MEMCACHED_HOST=127.0.0.1
REDIS_CLIENT=predis
# Device Shadow keys are a cross-service keyspace (device-control-service
# writes them raw) — Laravel's default per-app key prefix would hide them.
REDIS_PREFIX=
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379
# --- ClickHouse (telemetry history) ---
CLICKHOUSE_HOST=127.0.0.1
CLICKHOUSE_HTTP_PORT=8123
CLICKHOUSE_DB=telemetry
CLICKHOUSE_USER=default
CLICKHOUSE_PASSWORD=change_me
# --- device-control-service (manual device commands, HTTP transport) ---
DEVICE_CONTROL_HTTP_URL=http://127.0.0.1:8090
MAIL_MAILER=log
MAIL_SCHEME=null
MAIL_HOST=127.0.0.1
MAIL_PORT=2525
MAIL_USERNAME=null
MAIL_PASSWORD=null
MAIL_FROM_ADDRESS="hello@example.com"
MAIL_FROM_NAME="${APP_NAME}"
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
AWS_DEFAULT_REGION=us-east-1
AWS_BUCKET=
AWS_USE_PATH_STYLE_ENDPOINT=false
VITE_APP_NAME="${APP_NAME}"
+11
View File
@@ -0,0 +1,11 @@
* text=auto eol=lf
*.blade.php diff=html
*.css diff=css
*.html diff=html
*.md diff=markdown
*.php diff=php
/.github export-ignore
CHANGELOG.md export-ignore
.styleci.yml export-ignore
+27
View File
@@ -0,0 +1,27 @@
*.log
.DS_Store
.env
.env.backup
.env.production
.phpactor.json
.phpunit.result.cache
/.codex
/.cursor/
/.idea
/.nova
/.phpunit.cache
/.vscode
/.zed
/auth.json
/node_modules
/public/build
/public/fonts-manifest.dev.json
/public/hot
/public/storage
/storage/*.key
/storage/pail
/vendor
_ide_helper.php
Homestead.json
Homestead.yaml
Thumbs.db
+2
View File
@@ -0,0 +1,2 @@
ignore-scripts=true
audit=true
+38
View File
@@ -0,0 +1,38 @@
# --- vendor: PHP dependencies ---
# Includes require-dev on purpose: database/seeders relies on fakerphp/faker
# (via Laravel's fake() helper) to seed a demo owner account. This is an MVP
# image seeded with demo data, not a hardened production build — trimming to
# --no-dev is a reasonable follow-up once seeding no longer needs Faker.
FROM composer:2 AS vendor
WORKDIR /app
COPY composer.json composer.lock ./
RUN composer install --no-scripts --no-interaction --prefer-dist --no-progress
COPY . .
RUN composer dump-autoload --optimize
# --- assets: compiled Vite frontend (Breeze's Blade views use @vite) ---
FROM node:22-alpine AS assets
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
COPY resources/ resources/
COPY vite.config.js ./
RUN npm run build
# --- final: php-fpm + nginx in one container, supervised ---
FROM php:8.4-fpm-alpine
RUN apk add --no-cache nginx supervisor postgresql-dev libzip-dev icu-dev oniguruma-dev \
&& docker-php-ext-install pdo_pgsql pgsql bcmath zip intl opcache
WORKDIR /var/www/html
COPY --from=vendor /app ./
COPY --from=assets /app/public/build ./public/build
COPY docker/nginx.conf /etc/nginx/http.d/default.conf
COPY docker/supervisord.conf /etc/supervisord.conf
RUN chown -R www-data:www-data storage bootstrap/cache \
&& mkdir -p /run/nginx
EXPOSE 80
CMD ["supervisord", "-c", "/etc/supervisord.conf"]
+64
View File
@@ -0,0 +1,64 @@
# laravel-app (PHP/Laravel)
Статус: каркас реализован (авторизация, схема БД, модели). CRUD-интерфейсы
и дашборд — в процессе.
Зона ответственности:
- Аутентификация и роли пользователей (Sanctum: сессии для Blade-UI +
токены для будущего API/мобильного клиента), owner/viewer.
- Владеет схемой PostgreSQL (`database/migrations/*.php`) — users, zones,
device_types, devices, automation_rules. Go-сервисы читают/пишут эти же
таблицы, но не управляют их структурой.
- CRUD зон/устройств/правил автоматизации через веб-интерфейс.
- Просмотр истории телеметрии (запрос к ClickHouse) и текущего состояния
устройств (чтение Device Shadow из Redis, который ведёт
device-control-service).
- Ручная отправка команд устройствам — вызов device-control-service.
Не входит в зону ответственности: приём/хранение телеметрии, обработка
правил в реальном времени, отправка MQTT-команд — это Go-сервисы. Laravel
только читает их данные и вызывает device-control-service по gRPC/HTTP для
управления.
## Архитектурные решения
- **Sanctum, а не просто сессии.** Даже при том, что UI сейчас — Blade
(Breeze), Sanctum используется с самого начала, чтобы токенная авторизация
API была готова для будущего Vue/Flutter-клиента (этап 3) без повторной
переделки авторизации.
- **Роли и категории как PHP-enum, а не хардкод строк.** `App\Enums\UserRole`
(owner/viewer), `App\Enums\DeviceCategory` (actuator/sensor),
`App\Enums\ConditionOperator` (>,<,>=,<=,=,!=) — всё это закрытые,
архитектурные множества значений. `action_type` в правилах автоматизации
**намеренно остаётся обычной строкой**, не enum'ом — это открытый,
расширяемый список, управляемый данными в `device_types.capabilities`, а
не кодом (иначе новый тип устройства с новой командой потребовал бы правки
кода — что прямо противоречит идее платформы).
- **device_types — открытый реестр.** Сидер (`DeviceTypeSeeder`) заполняет
типы устройств гроубокса (light, pump, fan, sensor_temp_humidity) как
пример данных, а не как встроенную в код бизнес-логику. Добавление типа
для другой зоны — просто новая строка.
## Docker
Собирается в один контейнер (PHP-FPM + Nginx, управляются через supervisord)
— см. `Dockerfile`. Образ включает `require-dev`-зависимости (в частности
`fakerphp/faker`), так как сидер намеренно создаёт демо-аккаунт через
`fake()`; это MVP-образ с демо-данными, а не hardened prod-сборка.
## Запуск
Локально (вне Docker), с уже поднятыми `postgres`/`redis` из корневого
`docker-compose.yml`:
```bash
cd laravel-app
composer install
cp .env.example .env && php artisan key:generate
php artisan migrate --seed
php artisan serve
```
Через Docker — сервис `laravel-app` в корневом `docker-compose.yml`,
конфигурация берётся из переменных окружения (секция Laravel app в
корневом `.env.example`).
+26
View File
@@ -0,0 +1,26 @@
<?php
namespace App\Casts;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
/**
* Like the built-in 'array' cast, but always serializes as a JSON object
* ({}), never a JSON array ([]). PHP can't tell an empty list from an empty
* map, so `json_encode([])` gives "[]" Go's `json.Unmarshal` into
* map[string]any rejects that. automation_rules.action_params is always a
* flat key-value map (never a genuine list), so forcing object encoding is
* safe here.
*/
class JsonObjectCast implements CastsAttributes
{
public function get($model, string $key, $value, array $attributes): array
{
return $value === null ? [] : json_decode($value, true);
}
public function set($model, string $key, $value, array $attributes): string
{
return json_encode($value ?? [], JSON_FORCE_OBJECT);
}
}
@@ -0,0 +1,13 @@
<?php
namespace App\Enums;
enum ConditionOperator: string
{
case GreaterThan = '>';
case LessThan = '<';
case GreaterOrEqual = '>=';
case LessOrEqual = '<=';
case Equal = '=';
case NotEqual = '!=';
}
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace App\Enums;
enum DeviceCategory: string
{
case Actuator = 'actuator';
case Sensor = 'sensor';
}
+9
View File
@@ -0,0 +1,9 @@
<?php
namespace App\Enums;
enum UserRole: string
{
case Owner = 'owner';
case Viewer = 'viewer';
}
@@ -0,0 +1,52 @@
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Resources\UserResource;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\ValidationException;
class AuthController extends Controller
{
/**
* Issue a Sanctum personal access token for a mobile client. Each
* client names its own token (device_name) so a user can see/revoke
* per-device sessions later without logging everyone out at once.
*/
public function login(Request $request)
{
$credentials = $request->validate([
'email' => ['required', 'email'],
'password' => ['required', 'string'],
'device_name' => ['required', 'string', 'max:255'],
]);
$user = User::where('email', $credentials['email'])->first();
if (! $user || ! Hash::check($credentials['password'], $user->password)) {
throw ValidationException::withMessages([
'email' => ['Неверный email или пароль.'],
]);
}
return response()->json([
'token' => $user->createToken($credentials['device_name'])->plainTextToken,
'user' => new UserResource($user),
]);
}
public function logout(Request $request)
{
$request->user()->currentAccessToken()->delete();
return response()->noContent();
}
public function me(Request $request)
{
return new UserResource($request->user());
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Requests\AutomationRuleRequest;
use App\Http\Resources\AutomationRuleResource;
use App\Models\AutomationRule;
class AutomationRuleController extends Controller
{
public function index()
{
$this->authorize('viewAny', AutomationRule::class);
$rules = AutomationRule::with(['zone', 'targetDevice', 'conditionSourceDevice'])
->orderByDesc('id')
->get();
return AutomationRuleResource::collection($rules);
}
public function store(AutomationRuleRequest $request)
{
$rule = new AutomationRule($this->mapActionParams($request->validated()));
$rule->user()->associate($request->user());
$rule->save();
return (new AutomationRuleResource($rule))->response()->setStatusCode(201);
}
public function update(AutomationRuleRequest $request, AutomationRule $automation_rule)
{
$automation_rule->update($this->mapActionParams($request->validated()));
return new AutomationRuleResource($automation_rule);
}
public function destroy(AutomationRule $automation_rule)
{
$this->authorize('delete', $automation_rule);
$automation_rule->delete();
return response()->noContent();
}
/**
* Mirrors AutomationRuleController@mapActionParams on the web side
* "level" is a friendlier stand-in for action_params over the wire too,
* so mobile clients don't need to know the {"level": ...} shape.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function mapActionParams(array $data): array
{
$data['action_params'] = $data['action_type'] === 'set_level'
? ['level' => $data['level']]
: [];
unset($data['level']);
return $data;
}
}
@@ -0,0 +1,126 @@
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Requests\DeviceRequest;
use App\Http\Resources\DeviceResource;
use App\Models\Device;
use App\Services\ClickHouseClient;
use App\Services\DeviceControlClient;
use App\Services\DeviceShadow;
use Illuminate\Http\Request;
class DeviceController extends Controller
{
public function index(DeviceShadow $shadow)
{
$this->authorize('viewAny', Device::class);
$devices = Device::with(['zone', 'deviceType'])->orderBy('name')->get();
$statuses = $shadow->statuses($devices->pluck('external_id')->all());
$devices->each(fn (Device $d) => $d->live_status = $statuses[$d->external_id] ?? 'unknown');
return DeviceResource::collection($devices);
}
public function show(Device $device, DeviceShadow $shadow, ClickHouseClient $clickHouse)
{
$this->authorize('view', $device);
$device->load(['zone', 'deviceType']);
$snapshot = $shadow->snapshot($device->external_id);
$device->live_status = $snapshot['status'];
$telemetry = [];
if ($device->deviceType->category->value === 'sensor') {
$telemetry = $clickHouse->query(
'SELECT sensor_type, value, recorded_at FROM telemetry
WHERE device_id = {device_id:String}
ORDER BY recorded_at DESC LIMIT 50',
['device_id' => $device->external_id],
);
}
return (new DeviceResource($device))->additional([
'shadow' => [
'last_seen' => $snapshot['last_seen'],
'desired_state' => $snapshot['desired_state'],
'reported_state' => $snapshot['reported_state'],
],
'telemetry' => $telemetry,
]);
}
public function store(DeviceRequest $request)
{
$device = new Device($request->validated());
$device->user()->associate($request->user());
$device->save();
return (new DeviceResource($device))->response()->setStatusCode(201);
}
public function update(DeviceRequest $request, Device $device)
{
$device->update($request->validated());
return new DeviceResource($device);
}
public function destroy(Device $device)
{
$this->authorize('delete', $device);
$device->delete();
return response()->noContent();
}
public function turnOn(Device $device, DeviceControlClient $client)
{
$this->authorize('update', $device);
$this->ensureCapability($device, 'turn_on');
return $this->respondToCommand($client->turnOn($device->external_id));
}
public function turnOff(Device $device, DeviceControlClient $client)
{
$this->authorize('update', $device);
$this->ensureCapability($device, 'turn_off');
return $this->respondToCommand($client->turnOff($device->external_id));
}
public function setLevel(Request $request, Device $device, DeviceControlClient $client)
{
$this->authorize('update', $device);
$this->ensureCapability($device, 'set_level');
$validated = $request->validate(['level' => ['required', 'numeric']]);
return $this->respondToCommand($client->setLevel($device->external_id, (float) $validated['level']));
}
private function ensureCapability(Device $device, string $capability): void
{
abort_unless(
in_array($capability, $device->deviceType->capabilities ?? [], true),
422,
"Устройство не поддерживает действие «{$capability}».",
);
}
/**
* @param array{success: bool, error: ?string} $result
*/
private function respondToCommand(array $result)
{
if (! $result['success']) {
return response()->json(['message' => $result['error'] ?? 'Команда не выполнена.'], 422);
}
return response()->json(['message' => 'Команда отправлена.']);
}
}
@@ -0,0 +1,15 @@
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Resources\DeviceTypeResource;
use App\Models\DeviceType;
class DeviceTypeController extends Controller
{
public function index()
{
return DeviceTypeResource::collection(DeviceType::orderBy('code')->get());
}
}
@@ -0,0 +1,41 @@
<?php
namespace App\Http\Controllers\Api\V1;
use App\Http\Controllers\Controller;
use App\Http\Requests\ZoneRequest;
use App\Http\Resources\ZoneResource;
use App\Models\Zone;
class ZoneController extends Controller
{
public function index()
{
$this->authorize('viewAny', Zone::class);
return ZoneResource::collection(Zone::withCount('devices')->orderBy('name')->get());
}
public function store(ZoneRequest $request)
{
$zone = $request->user()->zones()->create($request->validated());
return (new ZoneResource($zone))->response()->setStatusCode(201);
}
public function update(ZoneRequest $request, Zone $zone)
{
$zone->update($request->validated());
return new ZoneResource($zone);
}
public function destroy(Zone $zone)
{
$this->authorize('delete', $zone);
$zone->delete();
return response()->noContent();
}
}
@@ -0,0 +1,47 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Http\Requests\Auth\LoginRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class AuthenticatedSessionController extends Controller
{
/**
* Display the login view.
*/
public function create(): View
{
return view('auth.login');
}
/**
* Handle an incoming authentication request.
*/
public function store(LoginRequest $request): RedirectResponse
{
$request->authenticate();
$request->session()->regenerate();
return redirect()->intended(route('dashboard', absolute: false));
}
/**
* Destroy an authenticated session.
*/
public function destroy(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect('/');
}
}
@@ -0,0 +1,40 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class ConfirmablePasswordController extends Controller
{
/**
* Show the confirm password view.
*/
public function show(): View
{
return view('auth.confirm-password');
}
/**
* Confirm the user's password.
*/
public function store(Request $request): RedirectResponse
{
if (! Auth::guard('web')->validate([
'email' => $request->user()->email,
'password' => $request->password,
])) {
throw ValidationException::withMessages([
'password' => __('auth.password'),
]);
}
$request->session()->put('auth.password_confirmed_at', time());
return redirect()->intended(route('dashboard', absolute: false));
}
}
@@ -0,0 +1,24 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class EmailVerificationNotificationController extends Controller
{
/**
* Send a new email verification notification.
*/
public function store(Request $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false));
}
$request->user()->sendEmailVerificationNotification();
return back()->with('status', 'verification-link-sent');
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
class EmailVerificationPromptController extends Controller
{
/**
* Display the email verification prompt.
*/
public function __invoke(Request $request): RedirectResponse|View
{
return $request->user()->hasVerifiedEmail()
? redirect()->intended(route('dashboard', absolute: false))
: view('auth.verify-email');
}
}
@@ -0,0 +1,63 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class NewPasswordController extends Controller
{
/**
* Display the password reset view.
*/
public function create(Request $request): View
{
return view('auth.reset-password', ['request' => $request]);
}
/**
* Handle an incoming new password request.
*
* @throws ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'token' => ['required'],
'email' => ['required', 'email'],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$status = Password::reset(
$request->only('email', 'password', 'password_confirmation', 'token'),
function (User $user) use ($request) {
$user->forceFill([
'password' => Hash::make($request->password),
'remember_token' => Str::random(60),
])->save();
event(new PasswordReset($user));
}
);
// If the password was successfully reset, we will redirect the user back to
// the application's home authenticated view. If there is an error we can
// redirect them back to where they came from with their error message.
return $status == Password::PASSWORD_RESET
? redirect()->route('login')->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules\Password;
class PasswordController extends Controller
{
/**
* Update the user's password.
*/
public function update(Request $request): RedirectResponse
{
$validated = $request->validateWithBag('updatePassword', [
'current_password' => ['required', 'current_password'],
'password' => ['required', Password::defaults(), 'confirmed'],
]);
$request->user()->update([
'password' => Hash::make($validated['password']),
]);
return back()->with('status', 'password-updated');
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Password;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class PasswordResetLinkController extends Controller
{
/**
* Display the password reset link request view.
*/
public function create(): View
{
return view('auth.forgot-password');
}
/**
* Handle an incoming password reset link request.
*
* @throws ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'email' => ['required', 'email'],
]);
// We will send the password reset link to this user. Once we have attempted
// to send the link, we will examine the response then see the message we
// need to show to the user. Finally, we'll send out a proper response.
$status = Password::sendResetLink(
$request->only('email')
);
return $status == Password::RESET_LINK_SENT
? back()->with('status', __($status))
: back()->withInput($request->only('email'))
->withErrors(['email' => __($status)]);
}
}
@@ -0,0 +1,51 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use App\Models\User;
use Illuminate\Auth\Events\Registered;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Validation\Rules;
use Illuminate\Validation\ValidationException;
use Illuminate\View\View;
class RegisteredUserController extends Controller
{
/**
* Display the registration view.
*/
public function create(): View
{
return view('auth.register');
}
/**
* Handle an incoming registration request.
*
* @throws ValidationException
*/
public function store(Request $request): RedirectResponse
{
$request->validate([
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'lowercase', 'email', 'max:255', 'unique:'.User::class],
'password' => ['required', 'confirmed', Rules\Password::defaults()],
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'password' => Hash::make($request->password),
]);
event(new Registered($user));
Auth::login($user);
return redirect(route('dashboard', absolute: false));
}
}
@@ -0,0 +1,27 @@
<?php
namespace App\Http\Controllers\Auth;
use App\Http\Controllers\Controller;
use Illuminate\Auth\Events\Verified;
use Illuminate\Foundation\Auth\EmailVerificationRequest;
use Illuminate\Http\RedirectResponse;
class VerifyEmailController extends Controller
{
/**
* Mark the authenticated user's email address as verified.
*/
public function __invoke(EmailVerificationRequest $request): RedirectResponse
{
if ($request->user()->hasVerifiedEmail()) {
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
if ($request->user()->markEmailAsVerified()) {
event(new Verified($request->user()));
}
return redirect()->intended(route('dashboard', absolute: false).'?verified=1');
}
}
@@ -0,0 +1,137 @@
<?php
namespace App\Http\Controllers;
use App\Enums\ConditionOperator;
use App\Enums\DeviceCategory;
use App\Http\Requests\AutomationRuleRequest;
use App\Http\Resources\AutomationRuleResource;
use App\Http\Resources\DeviceResource;
use App\Http\Resources\ZoneResource;
use App\Models\AutomationRule;
use App\Models\Device;
use App\Models\DeviceType;
use App\Models\Zone;
use Illuminate\Support\Collection;
use Inertia\Inertia;
class AutomationRuleController extends Controller
{
public function index()
{
$this->authorize('viewAny', AutomationRule::class);
$rules = AutomationRule::with(['zone', 'targetDevice', 'conditionSourceDevice'])
->orderByDesc('id')
->get();
return Inertia::render('AutomationRules/Index', [
'rules' => AutomationRuleResource::collection($rules)->resolve(),
]);
}
public function create()
{
$this->authorize('create', AutomationRule::class);
return Inertia::render('AutomationRules/Create', $this->formOptions());
}
public function store(AutomationRuleRequest $request)
{
$rule = new AutomationRule($this->mapActionParams($request->validated()));
$rule->user()->associate($request->user());
$rule->save();
return redirect()->route('automation-rules.index')->with('status', 'Правило создано.');
}
public function edit(AutomationRule $automation_rule)
{
$this->authorize('update', $automation_rule);
return Inertia::render('AutomationRules/Edit', [
'rule' => [
'id' => $automation_rule->id,
'zone_id' => $automation_rule->zone_id,
'condition_source_device_id' => $automation_rule->condition_source_device_id,
'condition_sensor_type' => $automation_rule->condition_sensor_type,
'condition_operator' => $automation_rule->condition_operator->value,
'condition_value' => $automation_rule->condition_value,
'target_device_id' => $automation_rule->target_device_id,
'action_type' => $automation_rule->action_type,
'level' => $automation_rule->action_params['level'] ?? '',
'is_active' => $automation_rule->is_active,
],
...$this->formOptions(),
]);
}
public function update(AutomationRuleRequest $request, AutomationRule $automation_rule)
{
$automation_rule->update($this->mapActionParams($request->validated()));
return redirect()->route('automation-rules.index')->with('status', 'Правило обновлено.');
}
public function destroy(AutomationRule $automation_rule)
{
$this->authorize('delete', $automation_rule);
$automation_rule->delete();
return redirect()->route('automation-rules.index')->with('status', 'Правило удалено.');
}
/**
* The "level" form field is a friendlier stand-in for action_params
* only set_level currently takes a parameter, so there's no need for a
* raw JSON editor yet.
*
* @param array<string, mixed> $data
* @return array<string, mixed>
*/
private function mapActionParams(array $data): array
{
$data['action_params'] = $data['action_type'] === 'set_level'
? ['level' => $data['level']]
: [];
unset($data['level']);
return $data;
}
/**
* @return array<string, mixed>
*/
private function formOptions(): array
{
$devices = Device::with(['zone', 'deviceType'])->orderBy('name')->get();
return [
'zones' => ZoneResource::collection(Zone::orderBy('name')->get())->resolve(),
'devices' => DeviceResource::collection($devices)->resolve(),
'actionTypeOptions' => $this->capabilityOptions(DeviceCategory::Actuator),
'sensorTypeOptions' => $this->capabilityOptions(DeviceCategory::Sensor),
'conditionOperatorOptions' => array_map(fn ($case) => $case->value, ConditionOperator::cases()),
];
}
/**
* Distinct capability values across device_types of the given category
* used as friendly select/datalist suggestions, not a hardcoded list.
*
* @return Collection<int, string>
*/
private function capabilityOptions(DeviceCategory $category)
{
return DeviceType::where('category', $category)
->get()
->pluck('capabilities')
->flatten()
->unique()
->sort()
->values();
}
}
@@ -0,0 +1,10 @@
<?php
namespace App\Http\Controllers;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
abstract class Controller
{
use AuthorizesRequests;
}
@@ -0,0 +1,160 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\DeviceRequest;
use App\Http\Resources\DeviceResource;
use App\Http\Resources\DeviceTypeResource;
use App\Http\Resources\ZoneResource;
use App\Models\Device;
use App\Models\DeviceType;
use App\Models\Zone;
use App\Services\ClickHouseClient;
use App\Services\DeviceControlClient;
use App\Services\DeviceShadow;
use Illuminate\Http\Request;
use Inertia\Inertia;
class DeviceController extends Controller
{
public function index(DeviceShadow $shadow)
{
$this->authorize('viewAny', Device::class);
$devices = Device::with(['zone', 'deviceType'])->orderBy('name')->get();
$statuses = $shadow->statuses($devices->pluck('external_id')->all());
$devices->each(fn (Device $d) => $d->live_status = $statuses[$d->external_id] ?? 'unknown');
return Inertia::render('Devices/Index', [
'devices' => DeviceResource::collection($devices)->resolve(),
]);
}
public function show(Device $device, DeviceShadow $shadow, ClickHouseClient $clickHouse)
{
$this->authorize('view', $device);
$device->load(['zone', 'deviceType']);
$snapshot = $shadow->snapshot($device->external_id);
$device->live_status = $snapshot['status'];
$telemetry = [];
if ($device->deviceType->category->value === 'sensor') {
$telemetry = $clickHouse->query(
'SELECT sensor_type, value, recorded_at FROM telemetry
WHERE device_id = {device_id:String}
ORDER BY recorded_at DESC LIMIT 50',
['device_id' => $device->external_id],
);
}
return Inertia::render('Devices/Show', [
'device' => (new DeviceResource($device))->resolve(),
'shadow' => [
'last_seen' => $snapshot['last_seen'],
'desired_state' => $snapshot['desired_state'],
'reported_state' => $snapshot['reported_state'],
],
'telemetry' => $telemetry,
]);
}
public function create()
{
$this->authorize('create', Device::class);
return Inertia::render('Devices/Create', $this->formOptions());
}
public function store(DeviceRequest $request)
{
$device = new Device($request->validated());
$device->user()->associate($request->user());
$device->save();
return redirect()->route('devices.index')->with('status', 'Устройство добавлено.');
}
public function edit(Device $device)
{
$this->authorize('update', $device);
return Inertia::render('Devices/Edit', [
'device' => $device->only(['id', 'name', 'zone_id', 'device_type_id', 'external_id', 'protocol']),
...$this->formOptions(),
]);
}
public function update(DeviceRequest $request, Device $device)
{
$device->update($request->validated());
return redirect()->route('devices.index')->with('status', 'Устройство обновлено.');
}
public function destroy(Device $device)
{
$this->authorize('delete', $device);
$device->delete();
return redirect()->route('devices.index')->with('status', 'Устройство удалено.');
}
public function turnOn(Device $device, DeviceControlClient $client)
{
$this->authorize('update', $device);
$this->ensureCapability($device, 'turn_on');
return $this->respondToCommand($client->turnOn($device->external_id));
}
public function turnOff(Device $device, DeviceControlClient $client)
{
$this->authorize('update', $device);
$this->ensureCapability($device, 'turn_off');
return $this->respondToCommand($client->turnOff($device->external_id));
}
public function setLevel(Request $request, Device $device, DeviceControlClient $client)
{
$this->authorize('update', $device);
$this->ensureCapability($device, 'set_level');
$validated = $request->validate(['level' => ['required', 'numeric']]);
return $this->respondToCommand($client->setLevel($device->external_id, (float) $validated['level']));
}
private function ensureCapability(Device $device, string $capability): void
{
abort_unless(
in_array($capability, $device->deviceType->capabilities ?? [], true),
422,
"Устройство не поддерживает действие «{$capability}».",
);
}
/**
* @param array{success: bool, error: ?string} $result
*/
private function respondToCommand(array $result)
{
return back()->with(
$result['success'] ? 'status' : 'error',
$result['success'] ? 'Команда отправлена.' : ($result['error'] ?? 'Команда не выполнена.'),
);
}
/**
* @return array<string, mixed>
*/
private function formOptions(): array
{
return [
'zones' => ZoneResource::collection(Zone::orderBy('name')->get())->resolve(),
'deviceTypes' => DeviceTypeResource::collection(DeviceType::orderBy('code')->get())->resolve(),
];
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ProfileUpdateRequest;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Redirect;
use Inertia\Inertia;
use Inertia\Response;
class ProfileController extends Controller
{
/**
* Display the user's profile form.
*/
public function edit(Request $request): Response
{
return Inertia::render('Profile/Edit', [
'user' => $request->user()->only(['id', 'name', 'email']),
]);
}
/**
* Update the user's profile information.
*/
public function update(ProfileUpdateRequest $request): RedirectResponse
{
$request->user()->fill($request->validated());
if ($request->user()->isDirty('email')) {
$request->user()->email_verified_at = null;
}
$request->user()->save();
return Redirect::route('profile.edit')->with('status', 'profile-updated');
}
/**
* Delete the user's account.
*/
public function destroy(Request $request): RedirectResponse
{
$request->validateWithBag('userDeletion', [
'password' => ['required', 'current_password'],
]);
$user = $request->user();
Auth::logout();
$user->delete();
$request->session()->invalidate();
$request->session()->regenerateToken();
return Redirect::to('/');
}
}
@@ -0,0 +1,61 @@
<?php
namespace App\Http\Controllers;
use App\Http\Requests\ZoneRequest;
use App\Http\Resources\ZoneResource;
use App\Models\Zone;
use Inertia\Inertia;
class ZoneController extends Controller
{
public function index()
{
$this->authorize('viewAny', Zone::class);
$zones = Zone::withCount('devices')->orderBy('name')->get();
return Inertia::render('Zones/Index', [
'zones' => ZoneResource::collection($zones)->resolve(),
]);
}
public function create()
{
$this->authorize('create', Zone::class);
return Inertia::render('Zones/Create');
}
public function store(ZoneRequest $request)
{
$request->user()->zones()->create($request->validated());
return redirect()->route('zones.index')->with('status', 'Зона создана.');
}
public function edit(Zone $zone)
{
$this->authorize('update', $zone);
return Inertia::render('Zones/Edit', [
'zone' => (new ZoneResource($zone))->resolve(),
]);
}
public function update(ZoneRequest $request, Zone $zone)
{
$zone->update($request->validated());
return redirect()->route('zones.index')->with('status', 'Зона обновлена.');
}
public function destroy(Zone $zone)
{
$this->authorize('delete', $zone);
$zone->delete();
return redirect()->route('zones.index')->with('status', 'Зона удалена.');
}
}
@@ -0,0 +1,36 @@
<?php
namespace App\Http\Middleware;
use App\Http\Resources\UserResource;
use Illuminate\Http\Request;
use Inertia\Middleware;
class HandleInertiaRequests extends Middleware
{
protected $rootView = 'app';
public function version(Request $request): ?string
{
return parent::version($request);
}
/** @return array<string, mixed> */
public function share(Request $request): array
{
return [
...parent::share($request),
'auth' => [
// ->resolve() instead of passing the Resource directly: Inertia
// calls ->toResponse() on Responsable props (Resources are
// Responsable), which triggers Laravel's `data`-key wrapping —
// resolve() returns the plain array Inertia pages actually want.
'user' => $request->user() ? (new UserResource($request->user()))->resolve() : null,
],
'flash' => [
'status' => fn () => $request->session()->get('status'),
'error' => fn () => $request->session()->get('error'),
],
];
}
}
@@ -0,0 +1,86 @@
<?php
namespace App\Http\Requests\Auth;
use Illuminate\Auth\Events\Lockout;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
class LoginRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*/
public function authorize(): bool
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string'],
];
}
/**
* Attempt to authenticate the request's credentials.
*
* @throws ValidationException
*/
public function authenticate(): void
{
$this->ensureIsNotRateLimited();
if (! Auth::attempt($this->only('email', 'password'), $this->boolean('remember'))) {
RateLimiter::hit($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.failed'),
]);
}
RateLimiter::clear($this->throttleKey());
}
/**
* Ensure the login request is not rate limited.
*
* @throws ValidationException
*/
public function ensureIsNotRateLimited(): void
{
if (! RateLimiter::tooManyAttempts($this->throttleKey(), 5)) {
return;
}
event(new Lockout($this));
$seconds = RateLimiter::availableIn($this->throttleKey());
throw ValidationException::withMessages([
'email' => trans('auth.throttle', [
'seconds' => $seconds,
'minutes' => ceil($seconds / 60),
]),
]);
}
/**
* Get the rate limiting throttle key for the request.
*/
public function throttleKey(): string
{
return Str::transliterate(Str::lower($this->string('email')).'|'.$this->ip());
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Http\Requests;
use App\Enums\ConditionOperator;
use App\Models\AutomationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class AutomationRuleRequest extends FormRequest
{
public function authorize(): bool
{
$rule = $this->route('automation_rule');
return $rule
? $this->user()->can('update', $rule)
: $this->user()->can('create', AutomationRule::class);
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'zone_id' => ['required', 'exists:zones,id'],
'target_device_id' => ['required', 'exists:devices,id'],
'condition_source_device_id' => ['required', 'exists:devices,id'],
'condition_sensor_type' => ['required', 'string', 'max:255'],
'condition_operator' => ['required', Rule::enum(ConditionOperator::class)],
'condition_value' => ['required', 'numeric'],
'action_type' => ['required', 'string', 'max:255'],
'level' => ['nullable', 'numeric', 'required_if:action_type,set_level'],
'is_active' => ['boolean'],
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Http\Requests;
use App\Models\Device;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class DeviceRequest extends FormRequest
{
public function authorize(): bool
{
$device = $this->route('device');
return $device
? $this->user()->can('update', $device)
: $this->user()->can('create', Device::class);
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
$device = $this->route('device');
return [
'zone_id' => ['required', 'exists:zones,id'],
'device_type_id' => ['required', 'exists:device_types,id'],
'name' => ['required', 'string', 'max:255'],
'external_id' => [
'required', 'string', 'max:255',
Rule::unique('devices', 'external_id')->ignore($device),
],
'protocol' => ['required', 'string', 'max:255'],
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Requests;
use App\Models\User;
use Illuminate\Contracts\Validation\ValidationRule;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
class ProfileUpdateRequest extends FormRequest
{
/**
* Get the validation rules that apply to the request.
*
* @return array<string, ValidationRule|array<mixed>|string>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => [
'required',
'string',
'lowercase',
'email',
'max:255',
Rule::unique(User::class)->ignore($this->user()->id),
],
];
}
}
@@ -0,0 +1,29 @@
<?php
namespace App\Http\Requests;
use App\Models\Zone;
use Illuminate\Foundation\Http\FormRequest;
class ZoneRequest extends FormRequest
{
public function authorize(): bool
{
$zone = $this->route('zone');
return $zone
? $this->user()->can('update', $zone)
: $this->user()->can('create', Zone::class);
}
/**
* @return array<string, mixed>
*/
public function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'description' => ['nullable', 'string'],
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Http\Resources;
use App\Models\AutomationRule;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin AutomationRule */
class AutomationRuleResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
// See DeviceResource for why nested resources are ->resolve()'d
// rather than returned as bare Resource instances.
'zone' => $this->whenLoaded('zone', fn ($zone) => (new ZoneResource($zone))->resolve()),
'target_device' => $this->whenLoaded('targetDevice', fn ($device) => (new DeviceResource($device))->resolve()),
'condition_source_device' => $this->whenLoaded('conditionSourceDevice', fn ($device) => (new DeviceResource($device))->resolve()),
'condition_sensor_type' => $this->condition_sensor_type,
'condition_operator' => $this->condition_operator->value,
'condition_value' => $this->condition_value,
'action_type' => $this->action_type,
'action_params' => $this->action_params,
'is_active' => $this->is_active,
'created_at' => $this->created_at,
];
}
}
@@ -0,0 +1,38 @@
<?php
namespace App\Http\Resources;
use App\Models\Device;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin Device
*
* `devices.status` in Postgres is only a stale snapshot (see migration
* comment) Redis (Device Shadow) is authoritative. The controller stamps
* the live value onto the model as `live_status` before wrapping it here;
* `status` in the JSON always prefers that when present.
*/
class DeviceResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'external_id' => $this->external_id,
'protocol' => $this->protocol,
'status' => $this->live_status ?? $this->status,
// Nested resources are resolved (not returned as bare Resource
// instances) — a Resource embedded as a value gets wrapped in its
// own `data` key when the parent response goes through Laravel's
// Responsable pipeline (Inertia props, ->response() in the API),
// which would double up with the outer collection's own wrapping.
'zone' => $this->whenLoaded('zone', fn ($zone) => (new ZoneResource($zone))->resolve()),
'device_type' => $this->whenLoaded('deviceType', fn ($type) => (new DeviceTypeResource($type))->resolve()),
'created_at' => $this->created_at,
];
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Resources;
use App\Models\DeviceType;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin DeviceType */
class DeviceTypeResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'code' => $this->code,
'category' => $this->category->value,
'capabilities' => $this->capabilities,
];
}
}
@@ -0,0 +1,22 @@
<?php
namespace App\Http\Resources;
use App\Models\User;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin User */
class UserResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'role' => $this->role->value,
];
}
}
@@ -0,0 +1,23 @@
<?php
namespace App\Http\Resources;
use App\Models\Zone;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/** @mixin Zone */
class ZoneResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
return [
'id' => $this->id,
'name' => $this->name,
'description' => $this->description,
'devices_count' => $this->whenCounted('devices'),
'created_at' => $this->created_at,
];
}
}
+56
View File
@@ -0,0 +1,56 @@
<?php
namespace App\Models;
use App\Casts\JsonObjectCast;
use App\Enums\ConditionOperator;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'zone_id',
'target_device_id',
'condition_source_device_id',
'condition_sensor_type',
'condition_operator',
'condition_value',
'action_type',
'action_params',
'is_active',
])]
class AutomationRule extends Model
{
public $timestamps = false;
protected function casts(): array
{
return [
'condition_operator' => ConditionOperator::class,
'condition_value' => 'float',
'action_params' => JsonObjectCast::class,
'is_active' => 'boolean',
'created_at' => 'datetime',
];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function zone(): BelongsTo
{
return $this->belongsTo(Zone::class);
}
public function targetDevice(): BelongsTo
{
return $this->belongsTo(Device::class, 'target_device_id');
}
public function conditionSourceDevice(): BelongsTo
{
return $this->belongsTo(Device::class, 'condition_source_device_id');
}
}
+46
View File
@@ -0,0 +1,46 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['zone_id', 'device_type_id', 'name', 'external_id', 'protocol', 'status'])]
class Device extends Model
{
public $timestamps = false;
protected function casts(): array
{
return ['created_at' => 'datetime'];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function zone(): BelongsTo
{
return $this->belongsTo(Zone::class);
}
public function deviceType(): BelongsTo
{
return $this->belongsTo(DeviceType::class);
}
/** Rules that this device is the target action of. */
public function targetedRules(): HasMany
{
return $this->hasMany(AutomationRule::class, 'target_device_id');
}
/** Rules that watch this device's readings. */
public function watchingRules(): HasMany
{
return $this->hasMany(AutomationRule::class, 'condition_source_device_id');
}
}
+27
View File
@@ -0,0 +1,27 @@
<?php
namespace App\Models;
use App\Enums\DeviceCategory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['code', 'category', 'capabilities'])]
class DeviceType extends Model
{
public $timestamps = false;
protected function casts(): array
{
return [
'category' => DeviceCategory::class,
'capabilities' => 'array',
];
}
public function devices(): HasMany
{
return $this->hasMany(Device::class);
}
}
+45
View File
@@ -0,0 +1,45 @@
<?php
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Enums\UserRole;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
#[Fillable(['name', 'email', 'password', 'role'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasApiTokens, HasFactory, Notifiable;
/**
* Get the attributes that should be cast.
*
* @return array<string, string>
*/
protected function casts(): array
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'role' => UserRole::class,
];
}
public function isOwner(): bool
{
return $this->role === UserRole::Owner;
}
public function zones()
{
return $this->hasMany(Zone::class);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
#[Fillable(['name', 'description'])]
class Zone extends Model
{
public $timestamps = false;
protected function casts(): array
{
return ['created_at' => 'datetime'];
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function devices(): HasMany
{
return $this->hasMany(Device::class);
}
public function automationRules(): HasMany
{
return $this->hasMany(AutomationRule::class);
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Policies;
use App\Models\AutomationRule;
use App\Models\User;
/** See ZonePolicy for the household-wide RBAC rationale. */
class AutomationRulePolicy
{
public function viewAny(User $user): bool
{
return true;
}
public function view(User $user, AutomationRule $automationRule): bool
{
return true;
}
public function create(User $user): bool
{
return $user->isOwner();
}
public function update(User $user, AutomationRule $automationRule): bool
{
return $user->isOwner();
}
public function delete(User $user, AutomationRule $automationRule): bool
{
return $user->isOwner();
}
}
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Policies;
use App\Models\Device;
use App\Models\User;
/** See ZonePolicy for the household-wide RBAC rationale. */
class DevicePolicy
{
public function viewAny(User $user): bool
{
return true;
}
public function view(User $user, Device $device): bool
{
return true;
}
public function create(User $user): bool
{
return $user->isOwner();
}
public function update(User $user, Device $device): bool
{
return $user->isOwner();
}
public function delete(User $user, Device $device): bool
{
return $user->isOwner();
}
}
+40
View File
@@ -0,0 +1,40 @@
<?php
namespace App\Policies;
use App\Models\User;
use App\Models\Zone;
/**
* Household-wide RBAC, not per-user tenant isolation: every authenticated
* user (owner or viewer) sees the same zones, only `owner` can write.
* `zones.user_id` records who registered the zone, it isn't a visibility
* boundary.
*/
class ZonePolicy
{
public function viewAny(User $user): bool
{
return true;
}
public function view(User $user, Zone $zone): bool
{
return true;
}
public function create(User $user): bool
{
return $user->isOwner();
}
public function update(User $user, Zone $zone): bool
{
return $user->isOwner();
}
public function delete(User $user, Zone $zone): bool
{
return $user->isOwner();
}
}
@@ -0,0 +1,35 @@
<?php
namespace App\Providers;
use App\Services\ClickHouseClient;
use App\Services\DeviceControlClient;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Register any application services.
*/
public function register(): void
{
$this->app->singleton(ClickHouseClient::class, fn () => new ClickHouseClient(
baseUrl: config('clickhouse.url'),
database: config('clickhouse.database'),
username: config('clickhouse.username'),
password: config('clickhouse.password'),
));
$this->app->singleton(DeviceControlClient::class, fn () => new DeviceControlClient(
baseUrl: config('services.device_control.url'),
));
}
/**
* Bootstrap any application services.
*/
public function boot(): void
{
//
}
}
@@ -0,0 +1,49 @@
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
use RuntimeException;
/**
* Minimal client for ClickHouse's HTTP interface used instead of a
* ClickHouse composer package to avoid an extra dependency for what's just
* "POST a query, get JSONEachRow back". Queries are parameterized via
* ClickHouse's own {name:Type} placeholders (sent as param_name=value query
* params), never string-concatenated, so this is safe against injection.
*/
class ClickHouseClient
{
public function __construct(
private readonly string $baseUrl,
private readonly string $database,
private readonly string $username,
private readonly string $password,
) {}
/**
* @param array<string, scalar> $params Bound to {name:Type} placeholders in $sql.
* @return array<int, array<string, mixed>>
*/
public function query(string $sql, array $params = []): array
{
$query = array_merge(
['database' => $this->database, 'default_format' => 'JSONEachRow'],
collect($params)->mapWithKeys(fn ($value, $key) => ["param_{$key}" => $value])->all(),
);
$response = Http::withBasicAuth($this->username, $this->password)
->withBody($sql, 'text/plain')
->post("{$this->baseUrl}/?".http_build_query($query));
if ($response->failed()) {
throw new RuntimeException("ClickHouse query failed ({$response->status()}): {$response->body()}");
}
// JSONEachRow: one JSON object per line, not a JSON array.
return collect(explode("\n", trim($response->body())))
->filter(fn (string $line) => $line !== '')
->map(fn (string $line) => json_decode($line, true))
->all();
}
}
@@ -0,0 +1,64 @@
<?php
namespace App\Services;
use Illuminate\Http\Client\ConnectionException;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Log;
/**
* HTTP client for device-control-service's manual-command API (see that
* service's README for why HTTP instead of gRPC here). Mirrors the
* gRPC CommandResult contract: {success, error} in the body always
* returned as an array here too, never an exception, so callers don't need
* to distinguish "device rejected it" from "service unreachable" to render
* a flash message.
*/
class DeviceControlClient
{
public function __construct(private readonly string $baseUrl) {}
/** @return array{success: bool, error: ?string} */
public function turnOn(string $externalId): array
{
return $this->post("/devices/{$externalId}/turn-on");
}
/** @return array{success: bool, error: ?string} */
public function turnOff(string $externalId): array
{
return $this->post("/devices/{$externalId}/turn-off");
}
/** @return array{success: bool, error: ?string} */
public function setLevel(string $externalId, float $level): array
{
return $this->post("/devices/{$externalId}/set-level", ['level' => $level]);
}
/**
* @param array<string, mixed> $body
* @return array{success: bool, error: ?string}
*/
private function post(string $path, array $body = []): array
{
try {
$response = Http::timeout(5)->post("{$this->baseUrl}{$path}", $body);
} catch (ConnectionException $e) {
Log::error('device-control-service unreachable', ['path' => $path, 'error' => $e->getMessage()]);
return ['success' => false, 'error' => 'device-control-service недоступен'];
}
if ($response->failed()) {
Log::error('device-control-service returned an error status', ['path' => $path, 'status' => $response->status()]);
return ['success' => false, 'error' => 'device-control-service вернул ошибку'];
}
return [
'success' => (bool) $response->json('success'),
'error' => $response->json('error'),
];
}
}
+57
View File
@@ -0,0 +1,57 @@
<?php
namespace App\Services;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Redis;
/**
* Read-only access to device-control-service's Device Shadow in Redis.
* Laravel never writes these keys device-control-service owns them; this
* is purely for the dashboard/device pages to show live state.
*/
class DeviceShadow
{
/**
* Full shadow snapshot for one device, one round-trip via pipeline.
*
* @return array{status: string, last_seen: ?CarbonImmutable, desired_state: array<string, mixed>, reported_state: array<string, mixed>}
*/
public function snapshot(string $externalId): array
{
$results = Redis::pipeline(function ($pipe) use ($externalId) {
$pipe->get("device:{$externalId}:status");
$pipe->get("device:{$externalId}:last_seen");
$pipe->get("device:{$externalId}:desired_state");
$pipe->get("device:{$externalId}:reported_state");
});
[$status, $lastSeen, $desired, $reported] = $results;
return [
'status' => $status ?: 'unknown',
'last_seen' => $lastSeen ? CarbonImmutable::createFromTimestamp((int) $lastSeen) : null,
'desired_state' => $desired ? json_decode($desired, true) : [],
'reported_state' => $reported ? json_decode($reported, true) : [],
];
}
/**
* Status for many devices in a single round-trip (MGET), so the device
* list doesn't do one Redis call per row.
*
* @param array<int, string> $externalIds
* @return array<string, string> external_id => status ("online"/"offline"/"unknown")
*/
public function statuses(array $externalIds): array
{
if (empty($externalIds)) {
return [];
}
$keys = array_map(fn (string $id) => "device:{$id}:status", $externalIds);
$values = Redis::mget($keys);
return array_combine($externalIds, array_map(fn ($v) => $v ?: 'unknown', $values));
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\View\Components;
use Illuminate\View\Component;
use Illuminate\View\View;
class GuestLayout extends Component
{
/**
* Get the view / contents that represents the component.
*/
public function render(): View
{
return view('layouts.guest');
}
}
+18
View File
@@ -0,0 +1,18 @@
#!/usr/bin/env php
<?php
use Illuminate\Foundation\Application;
use Symfony\Component\Console\Input\ArgvInput;
define('LARAVEL_START', microtime(true));
// Register the Composer autoloader...
require __DIR__.'/vendor/autoload.php';
// Bootstrap Laravel and handle the command...
/** @var Application $app */
$app = require_once __DIR__.'/bootstrap/app.php';
$status = $app->handleCommand(new ArgvInput);
exit($status);
+25
View File
@@ -0,0 +1,25 @@
<?php
use App\Http\Middleware\HandleInertiaRequests;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Illuminate\Http\Request;
return Application::configure(basePath: dirname(__DIR__))
->withRouting(
web: __DIR__.'/../routes/web.php',
api: __DIR__.'/../routes/api.php',
commands: __DIR__.'/../routes/console.php',
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
$middleware->web(append: [
HandleInertiaRequests::class,
]);
})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen(
fn (Request $request) => $request->is('api/*'),
);
})->create();
+2
View File
@@ -0,0 +1,2 @@
*
!.gitignore
+7
View File
@@ -0,0 +1,7 @@
<?php
use App\Providers\AppServiceProvider;
return [
AppServiceProvider::class,
];
+90
View File
@@ -0,0 +1,90 @@
{
"$schema": "https://getcomposer.org/schema.json",
"name": "laravel/laravel",
"type": "project",
"description": "The skeleton application for the Laravel framework.",
"keywords": ["laravel", "framework"],
"license": "MIT",
"require": {
"php": "^8.3",
"inertiajs/inertia-laravel": "^3.3",
"laravel/framework": "^13.8",
"laravel/sanctum": "^4.0",
"laravel/tinker": "^3.0",
"predis/predis": "^3.5"
},
"require-dev": {
"fakerphp/faker": "^1.23",
"laravel/breeze": "^2.4",
"laravel/pail": "^1.2.5",
"laravel/pao": "^1.0.6",
"laravel/pint": "^1.27",
"mockery/mockery": "^1.6",
"nunomaduro/collision": "^8.6",
"phpunit/phpunit": "^12.5.12"
},
"autoload": {
"psr-4": {
"App\\": "app/",
"Database\\Factories\\": "database/factories/",
"Database\\Seeders\\": "database/seeders/"
}
},
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"scripts": {
"setup": [
"composer install",
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\"",
"@php artisan key:generate",
"@php artisan migrate --force",
"npm install --ignore-scripts",
"npm run build"
],
"dev": [
"Composer\\Config::disableProcessTimeout",
"npx concurrently -c \"#93c5fd,#c4b5fd,#fb7185,#fdba74\" \"php artisan serve\" \"php artisan queue:listen --tries=1 --timeout=0\" \"php artisan pail --timeout=0\" \"npm run dev\" --names=server,queue,logs,vite --kill-others"
],
"test": [
"@php artisan config:clear --ansi @no_additional_args",
"@php artisan test"
],
"post-autoload-dump": [
"Illuminate\\Foundation\\ComposerScripts::postAutoloadDump",
"@php artisan package:discover --ansi"
],
"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force"
],
"post-root-package-install": [
"@php -r \"file_exists('.env') || copy('.env.example', '.env');\""
],
"post-create-project-cmd": [
"@php artisan key:generate --ansi",
"@php -r \"file_exists('database/database.sqlite') || touch('database/database.sqlite');\"",
"@php artisan migrate --graceful --ansi"
],
"pre-package-uninstall": [
"Illuminate\\Foundation\\ComposerScripts::prePackageUninstall"
]
},
"extra": {
"laravel": {
"dont-discover": []
}
},
"config": {
"optimize-autoloader": true,
"preferred-install": "dist",
"sort-packages": true,
"allow-plugins": {
"pestphp/pest-plugin": true,
"php-http/discovery": true
}
},
"minimum-stability": "stable",
"prefer-stable": true
}
+8556
View File
File diff suppressed because it is too large Load Diff
+126
View File
@@ -0,0 +1,126 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Application Name
|--------------------------------------------------------------------------
|
| This value is the name of your application, which will be used when the
| framework needs to place the application's name in a notification or
| other UI elements where an application name needs to be displayed.
|
*/
'name' => env('APP_NAME', 'Laravel'),
/*
|--------------------------------------------------------------------------
| Application Environment
|--------------------------------------------------------------------------
|
| This value determines the "environment" your application is currently
| running in. This may determine how you prefer to configure various
| services the application utilizes. Set this in your ".env" file.
|
*/
'env' => env('APP_ENV', 'production'),
/*
|--------------------------------------------------------------------------
| Application Debug Mode
|--------------------------------------------------------------------------
|
| When your application is in debug mode, detailed error messages with
| stack traces will be shown on every error that occurs within your
| application. If disabled, a simple generic error page is shown.
|
*/
'debug' => (bool) env('APP_DEBUG', false),
/*
|--------------------------------------------------------------------------
| Application URL
|--------------------------------------------------------------------------
|
| This URL is used by the console to properly generate URLs when using
| the Artisan command line tool. You should set this to the root of
| the application so that it's available within Artisan commands.
|
*/
'url' => env('APP_URL', 'http://localhost'),
/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. The timezone
| is set to "UTC" by default as it is suitable for most use cases.
|
*/
'timezone' => 'UTC',
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
|--------------------------------------------------------------------------
|
| The application locale determines the default locale that will be used
| by Laravel's translation / localization methods. This option can be
| set to any locale for which you plan to have translation strings.
|
*/
'locale' => env('APP_LOCALE', 'en'),
'fallback_locale' => env('APP_FALLBACK_LOCALE', 'en'),
'faker_locale' => env('APP_FAKER_LOCALE', 'en_US'),
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| This key is utilized by Laravel's encryption services and should be set
| to a random, 32 character string to ensure that all encrypted values
| are secure. You should do this prior to deploying the application.
|
*/
'cipher' => 'AES-256-CBC',
'key' => env('APP_KEY'),
'previous_keys' => [
...array_filter(
explode(',', (string) env('APP_PREVIOUS_KEYS', ''))
),
],
/*
|--------------------------------------------------------------------------
| Maintenance Mode Driver
|--------------------------------------------------------------------------
|
| These configuration options determine the driver used to determine and
| manage Laravel's "maintenance mode" status. The "cache" driver will
| allow maintenance mode to be controlled across multiple machines.
|
| Supported drivers: "file", "cache"
|
*/
'maintenance' => [
'driver' => env('APP_MAINTENANCE_DRIVER', 'file'),
'store' => env('APP_MAINTENANCE_STORE', 'database'),
],
];
+117
View File
@@ -0,0 +1,117 @@
<?php
use App\Models\User;
return [
/*
|--------------------------------------------------------------------------
| Authentication Defaults
|--------------------------------------------------------------------------
|
| This option defines the default authentication "guard" and password
| reset "broker" for your application. You may change these values
| as required, but they're a perfect start for most applications.
|
*/
'defaults' => [
'guard' => env('AUTH_GUARD', 'web'),
'passwords' => env('AUTH_PASSWORD_BROKER', 'users'),
],
/*
|--------------------------------------------------------------------------
| Authentication Guards
|--------------------------------------------------------------------------
|
| Next, you may define every authentication guard for your application.
| Of course, a great default configuration has been defined for you
| which utilizes session storage plus the Eloquent user provider.
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| Supported: "session"
|
*/
'guards' => [
'web' => [
'driver' => 'session',
'provider' => 'users',
],
],
/*
|--------------------------------------------------------------------------
| User Providers
|--------------------------------------------------------------------------
|
| All authentication guards have a user provider, which defines how the
| users are actually retrieved out of your database or other storage
| system used by the application. Typically, Eloquent is utilized.
|
| If you have multiple user tables or models you may configure multiple
| providers to represent the model / table. These providers may then
| be assigned to any extra authentication guards you have defined.
|
| Supported: "database", "eloquent"
|
*/
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => env('AUTH_MODEL', User::class),
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
/*
|--------------------------------------------------------------------------
| Resetting Passwords
|--------------------------------------------------------------------------
|
| These configuration options specify the behavior of Laravel's password
| reset functionality, including the table utilized for token storage
| and the user provider that is invoked to actually retrieve users.
|
| The expiry time is the number of minutes that each reset token will be
| considered valid. This security feature keeps tokens short-lived so
| they have less time to be guessed. You may change this as needed.
|
| The throttle setting is the number of seconds a user must wait before
| generating more password reset tokens. This prevents the user from
| quickly generating a very large amount of password reset tokens.
|
*/
'passwords' => [
'users' => [
'provider' => 'users',
'table' => env('AUTH_PASSWORD_RESET_TOKEN_TABLE', 'password_reset_tokens'),
'expire' => 60,
'throttle' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Password Confirmation Timeout
|--------------------------------------------------------------------------
|
| Here you may define the number of seconds before a password confirmation
| window expires and users are asked to re-enter their password via the
| confirmation screen. By default, the timeout lasts for three hours.
|
*/
'password_timeout' => env('AUTH_PASSWORD_TIMEOUT', 10800),
];
+136
View File
@@ -0,0 +1,136 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Cache Store
|--------------------------------------------------------------------------
|
| This option controls the default cache store that will be used by the
| framework. This connection is utilized if another isn't explicitly
| specified when running a cache operation inside the application.
|
*/
'default' => env('CACHE_STORE', 'database'),
/*
|--------------------------------------------------------------------------
| Cache Stores
|--------------------------------------------------------------------------
|
| Here you may define all of the cache "stores" for your application as
| well as their drivers. You may even define multiple stores for the
| same cache driver to group types of items stored in your caches.
|
| Supported drivers: "array", "database", "file", "memcached",
| "redis", "dynamodb", "storage", "octane",
| "session", "failover", "null"
|
*/
'stores' => [
'array' => [
'driver' => 'array',
'serialize' => false,
],
'database' => [
'driver' => 'database',
'connection' => env('DB_CACHE_CONNECTION'),
'table' => env('DB_CACHE_TABLE', 'cache'),
'lock_connection' => env('DB_CACHE_LOCK_CONNECTION'),
'lock_table' => env('DB_CACHE_LOCK_TABLE'),
],
'file' => [
'driver' => 'file',
'path' => storage_path('framework/cache/data'),
'lock_path' => storage_path('framework/cache/data'),
],
'storage' => [
'driver' => 'storage',
'disk' => env('CACHE_STORAGE_DISK'),
'path' => env('CACHE_STORAGE_PATH', 'framework/cache/data'),
],
'memcached' => [
'driver' => 'memcached',
'persistent_id' => env('MEMCACHED_PERSISTENT_ID'),
'sasl' => [
env('MEMCACHED_USERNAME'),
env('MEMCACHED_PASSWORD'),
],
'options' => [
// Memcached::OPT_CONNECT_TIMEOUT => 2000,
],
'servers' => [
[
'host' => env('MEMCACHED_HOST', '127.0.0.1'),
'port' => env('MEMCACHED_PORT', 11211),
'weight' => 100,
],
],
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_CACHE_CONNECTION', 'cache'),
'lock_connection' => env('REDIS_CACHE_LOCK_CONNECTION', 'default'),
],
'dynamodb' => [
'driver' => 'dynamodb',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'table' => env('DYNAMODB_CACHE_TABLE', 'cache'),
'endpoint' => env('DYNAMODB_ENDPOINT'),
],
'octane' => [
'driver' => 'octane',
],
'failover' => [
'driver' => 'failover',
'stores' => [
'database',
'array',
],
],
],
/*
|--------------------------------------------------------------------------
| Cache Key Prefix
|--------------------------------------------------------------------------
|
| When utilizing the APC, database, memcached, Redis, and DynamoDB cache
| stores, there might be other applications using the same cache. For
| that reason, you may prefix every cache key to avoid collisions.
|
*/
'prefix' => env('CACHE_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-cache-'),
/*
|--------------------------------------------------------------------------
| Serializable Classes
|--------------------------------------------------------------------------
|
| This value determines the classes that can be unserialized from cache
| storage. By default, no PHP classes will be unserialized from your
| cache to prevent gadget chain attacks if your APP_KEY is leaked.
|
*/
'serializable_classes' => false,
];
+8
View File
@@ -0,0 +1,8 @@
<?php
return [
'url' => 'http://'.env('CLICKHOUSE_HOST', 'localhost').':'.env('CLICKHOUSE_HTTP_PORT', '8123'),
'database' => env('CLICKHOUSE_DB', 'telemetry'),
'username' => env('CLICKHOUSE_USER', 'default'),
'password' => env('CLICKHOUSE_PASSWORD', ''),
];
+184
View File
@@ -0,0 +1,184 @@
<?php
use Illuminate\Support\Str;
use Pdo\Mysql;
return [
/*
|--------------------------------------------------------------------------
| Default Database Connection Name
|--------------------------------------------------------------------------
|
| Here you may specify which of the database connections below you wish
| to use as your default connection for database operations. This is
| the connection which will be utilized unless another connection
| is explicitly specified when you execute a query / statement.
|
*/
'default' => env('DB_CONNECTION', 'sqlite'),
/*
|--------------------------------------------------------------------------
| Database Connections
|--------------------------------------------------------------------------
|
| Below are all of the database connections defined for your application.
| An example configuration is provided for each database system which
| is supported by Laravel. You're free to add / remove connections.
|
*/
'connections' => [
'sqlite' => [
'driver' => 'sqlite',
'url' => env('DB_URL'),
'database' => env('DB_DATABASE', database_path('database.sqlite')),
'prefix' => '',
'foreign_key_constraints' => env('DB_FOREIGN_KEYS', true),
'busy_timeout' => null,
'journal_mode' => null,
'synchronous' => null,
'transaction_mode' => 'DEFERRED',
],
'mysql' => [
'driver' => 'mysql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'mariadb' => [
'driver' => 'mariadb',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '3306'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'unix_socket' => env('DB_SOCKET', ''),
'charset' => env('DB_CHARSET', 'utf8mb4'),
'collation' => env('DB_COLLATION', 'utf8mb4_unicode_ci'),
'prefix' => '',
'prefix_indexes' => true,
'strict' => true,
'engine' => null,
'options' => extension_loaded('pdo_mysql') ? array_filter([
Mysql::ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
]) : [],
],
'pgsql' => [
'driver' => 'pgsql',
'url' => env('DB_URL'),
'host' => env('DB_HOST', '127.0.0.1'),
'port' => env('DB_PORT', '5432'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
'search_path' => 'public',
'sslmode' => env('DB_SSLMODE', 'prefer'),
],
'sqlsrv' => [
'driver' => 'sqlsrv',
'url' => env('DB_URL'),
'host' => env('DB_HOST', 'localhost'),
'port' => env('DB_PORT', '1433'),
'database' => env('DB_DATABASE', 'laravel'),
'username' => env('DB_USERNAME', 'root'),
'password' => env('DB_PASSWORD', ''),
'charset' => env('DB_CHARSET', 'utf8'),
'prefix' => '',
'prefix_indexes' => true,
// 'encrypt' => env('DB_ENCRYPT', 'yes'),
// 'trust_server_certificate' => env('DB_TRUST_SERVER_CERTIFICATE', 'false'),
],
],
/*
|--------------------------------------------------------------------------
| Migration Repository Table
|--------------------------------------------------------------------------
|
| This table keeps track of all the migrations that have already run for
| your application. Using this information, we can determine which of
| the migrations on disk haven't actually been run on the database.
|
*/
'migrations' => [
'table' => 'migrations',
'update_date_on_publish' => true,
],
/*
|--------------------------------------------------------------------------
| Redis Databases
|--------------------------------------------------------------------------
|
| Redis is an open source, fast, and advanced key-value store that also
| provides a richer body of commands than a typical key-value system
| such as Memcached. You may define your connection settings here.
|
*/
'redis' => [
'client' => env('REDIS_CLIENT', 'phpredis'),
'options' => [
'cluster' => env('REDIS_CLUSTER', 'redis'),
'prefix' => env('REDIS_PREFIX', Str::slug((string) env('APP_NAME', 'laravel')).'-database-'),
'persistent' => env('REDIS_PERSISTENT', false),
],
'default' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_DB', '0'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
'cache' => [
'url' => env('REDIS_URL'),
'host' => env('REDIS_HOST', '127.0.0.1'),
'username' => env('REDIS_USERNAME'),
'password' => env('REDIS_PASSWORD'),
'port' => env('REDIS_PORT', '6379'),
'database' => env('REDIS_CACHE_DB', '1'),
'max_retries' => env('REDIS_MAX_RETRIES', 3),
'backoff_algorithm' => env('REDIS_BACKOFF_ALGORITHM', 'decorrelated_jitter'),
'backoff_base' => env('REDIS_BACKOFF_BASE', 100),
'backoff_cap' => env('REDIS_BACKOFF_CAP', 1000),
],
],
];
+80
View File
@@ -0,0 +1,80 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Filesystem Disk
|--------------------------------------------------------------------------
|
| Here you may specify the default filesystem disk that should be used
| by the framework. The "local" disk, as well as a variety of cloud
| based disks are available to your application for file storage.
|
*/
'default' => env('FILESYSTEM_DISK', 'local'),
/*
|--------------------------------------------------------------------------
| Filesystem Disks
|--------------------------------------------------------------------------
|
| Below you may configure as many filesystem disks as necessary, and you
| may even configure multiple disks for the same driver. Examples for
| most supported storage drivers are configured here for reference.
|
| Supported drivers: "local", "ftp", "sftp", "s3"
|
*/
'disks' => [
'local' => [
'driver' => 'local',
'root' => storage_path('app/private'),
'serve' => true,
'throw' => false,
'report' => false,
],
'public' => [
'driver' => 'local',
'root' => storage_path('app/public'),
'url' => rtrim(env('APP_URL', 'http://localhost'), '/').'/storage',
'visibility' => 'public',
'throw' => false,
'report' => false,
],
's3' => [
'driver' => 's3',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION'),
'bucket' => env('AWS_BUCKET'),
'url' => env('AWS_URL'),
'endpoint' => env('AWS_ENDPOINT'),
'use_path_style_endpoint' => env('AWS_USE_PATH_STYLE_ENDPOINT', false),
'throw' => false,
'report' => false,
],
],
/*
|--------------------------------------------------------------------------
| Symbolic Links
|--------------------------------------------------------------------------
|
| Here you may configure the symbolic links that will be created when the
| `storage:link` Artisan command is executed. The array keys should be
| the locations of the links and the values should be their targets.
|
*/
'links' => [
public_path('storage') => storage_path('app/public'),
],
];
+132
View File
@@ -0,0 +1,132 @@
<?php
use Monolog\Handler\NullHandler;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\SyslogUdpHandler;
use Monolog\Processor\PsrLogMessageProcessor;
return [
/*
|--------------------------------------------------------------------------
| Default Log Channel
|--------------------------------------------------------------------------
|
| This option defines the default log channel that is utilized to write
| messages to your logs. The value provided here should match one of
| the channels present in the list of "channels" configured below.
|
*/
'default' => env('LOG_CHANNEL', 'stack'),
/*
|--------------------------------------------------------------------------
| Deprecations Log Channel
|--------------------------------------------------------------------------
|
| This option controls the log channel that should be used to log warnings
| regarding deprecated PHP and library features. This allows you to get
| your application ready for upcoming major versions of dependencies.
|
*/
'deprecations' => [
'channel' => env('LOG_DEPRECATIONS_CHANNEL', 'null'),
'trace' => env('LOG_DEPRECATIONS_TRACE', false),
],
/*
|--------------------------------------------------------------------------
| Log Channels
|--------------------------------------------------------------------------
|
| Here you may configure the log channels for your application. Laravel
| utilizes the Monolog PHP logging library, which includes a variety
| of powerful log handlers and formatters that you're free to use.
|
| Available drivers: "single", "daily", "slack", "syslog",
| "errorlog", "monolog", "custom", "stack"
|
*/
'channels' => [
'stack' => [
'driver' => 'stack',
'channels' => explode(',', (string) env('LOG_STACK', 'single')),
'ignore_exceptions' => false,
],
'single' => [
'driver' => 'single',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'daily' => [
'driver' => 'daily',
'path' => storage_path('logs/laravel.log'),
'level' => env('LOG_LEVEL', 'debug'),
'days' => env('LOG_DAILY_DAYS', 14),
'replace_placeholders' => true,
],
'slack' => [
'driver' => 'slack',
'url' => env('LOG_SLACK_WEBHOOK_URL'),
'username' => env('LOG_SLACK_USERNAME', env('APP_NAME', 'Laravel')),
'emoji' => env('LOG_SLACK_EMOJI', ':boom:'),
'level' => env('LOG_LEVEL', 'critical'),
'replace_placeholders' => true,
],
'papertrail' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => env('LOG_PAPERTRAIL_HANDLER', SyslogUdpHandler::class),
'handler_with' => [
'host' => env('PAPERTRAIL_URL'),
'port' => env('PAPERTRAIL_PORT'),
'connectionString' => 'tls://'.env('PAPERTRAIL_URL').':'.env('PAPERTRAIL_PORT'),
],
'processors' => [PsrLogMessageProcessor::class],
],
'stderr' => [
'driver' => 'monolog',
'level' => env('LOG_LEVEL', 'debug'),
'handler' => StreamHandler::class,
'handler_with' => [
'stream' => 'php://stderr',
],
'formatter' => env('LOG_STDERR_FORMATTER'),
'processors' => [PsrLogMessageProcessor::class],
],
'syslog' => [
'driver' => 'syslog',
'level' => env('LOG_LEVEL', 'debug'),
'facility' => env('LOG_SYSLOG_FACILITY', LOG_USER),
'replace_placeholders' => true,
],
'errorlog' => [
'driver' => 'errorlog',
'level' => env('LOG_LEVEL', 'debug'),
'replace_placeholders' => true,
],
'null' => [
'driver' => 'monolog',
'handler' => NullHandler::class,
],
'emergency' => [
'path' => storage_path('logs/laravel.log'),
],
],
];
+118
View File
@@ -0,0 +1,118 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Mailer
|--------------------------------------------------------------------------
|
| This option controls the default mailer that is used to send all email
| messages unless another mailer is explicitly specified when sending
| the message. All additional mailers can be configured within the
| "mailers" array. Examples of each type of mailer are provided.
|
*/
'default' => env('MAIL_MAILER', 'log'),
/*
|--------------------------------------------------------------------------
| Mailer Configurations
|--------------------------------------------------------------------------
|
| Here you may configure all of the mailers used by your application plus
| their respective settings. Several examples have been configured for
| you and you are free to add your own as your application requires.
|
| Laravel supports a variety of mail "transport" drivers that can be used
| when delivering an email. You may specify which one you're using for
| your mailers below. You may also add additional mailers if needed.
|
| Supported: "smtp", "sendmail", "mailgun", "ses", "ses-v2",
| "postmark", "resend", "log", "array",
| "failover", "roundrobin"
|
*/
'mailers' => [
'smtp' => [
'transport' => 'smtp',
'scheme' => env('MAIL_SCHEME'),
'url' => env('MAIL_URL'),
'host' => env('MAIL_HOST', '127.0.0.1'),
'port' => env('MAIL_PORT', 2525),
'username' => env('MAIL_USERNAME'),
'password' => env('MAIL_PASSWORD'),
'timeout' => null,
'local_domain' => env('MAIL_EHLO_DOMAIN', parse_url((string) env('APP_URL', 'http://localhost'), PHP_URL_HOST)),
],
'ses' => [
'transport' => 'ses',
],
'postmark' => [
'transport' => 'postmark',
// 'message_stream_id' => env('POSTMARK_MESSAGE_STREAM_ID'),
// 'client' => [
// 'timeout' => 5,
// ],
],
'resend' => [
'transport' => 'resend',
],
'sendmail' => [
'transport' => 'sendmail',
'path' => env('MAIL_SENDMAIL_PATH', '/usr/sbin/sendmail -bs -i'),
],
'log' => [
'transport' => 'log',
'channel' => env('MAIL_LOG_CHANNEL'),
],
'array' => [
'transport' => 'array',
],
'failover' => [
'transport' => 'failover',
'mailers' => [
'smtp',
'log',
],
'retry_after' => 60,
],
'roundrobin' => [
'transport' => 'roundrobin',
'mailers' => [
'ses',
'postmark',
],
'retry_after' => 60,
],
],
/*
|--------------------------------------------------------------------------
| Global "From" Address
|--------------------------------------------------------------------------
|
| You may wish for all emails sent by your application to be sent from
| the same address. Here you may specify a name and address that is
| used globally for all emails that are sent by your application.
|
*/
'from' => [
'address' => env('MAIL_FROM_ADDRESS', 'hello@example.com'),
'name' => env('MAIL_FROM_NAME', env('APP_NAME', 'Laravel')),
],
];
+129
View File
@@ -0,0 +1,129 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Default Queue Connection Name
|--------------------------------------------------------------------------
|
| Laravel's queue supports a variety of backends via a single, unified
| API, giving you convenient access to each backend using identical
| syntax for each. The default queue connection is defined below.
|
*/
'default' => env('QUEUE_CONNECTION', 'database'),
/*
|--------------------------------------------------------------------------
| Queue Connections
|--------------------------------------------------------------------------
|
| Here you may configure the connection options for every queue backend
| used by your application. An example configuration is provided for
| each backend supported by Laravel. You're also free to add more.
|
| Drivers: "sync", "database", "beanstalkd", "sqs", "redis",
| "deferred", "background", "failover", "null"
|
*/
'connections' => [
'sync' => [
'driver' => 'sync',
],
'database' => [
'driver' => 'database',
'connection' => env('DB_QUEUE_CONNECTION'),
'table' => env('DB_QUEUE_TABLE', 'jobs'),
'queue' => env('DB_QUEUE', 'default'),
'retry_after' => (int) env('DB_QUEUE_RETRY_AFTER', 90),
'after_commit' => false,
],
'beanstalkd' => [
'driver' => 'beanstalkd',
'host' => env('BEANSTALKD_QUEUE_HOST', 'localhost'),
'queue' => env('BEANSTALKD_QUEUE', 'default'),
'retry_after' => (int) env('BEANSTALKD_QUEUE_RETRY_AFTER', 90),
'block_for' => 0,
'after_commit' => false,
],
'sqs' => [
'driver' => 'sqs',
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'prefix' => env('SQS_PREFIX', 'https://sqs.us-east-1.amazonaws.com/your-account-id'),
'queue' => env('SQS_QUEUE', 'default'),
'suffix' => env('SQS_SUFFIX'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
'after_commit' => false,
],
'redis' => [
'driver' => 'redis',
'connection' => env('REDIS_QUEUE_CONNECTION', 'default'),
'queue' => env('REDIS_QUEUE', 'default'),
'retry_after' => (int) env('REDIS_QUEUE_RETRY_AFTER', 90),
'block_for' => null,
'after_commit' => false,
],
'deferred' => [
'driver' => 'deferred',
],
'background' => [
'driver' => 'background',
],
'failover' => [
'driver' => 'failover',
'connections' => [
'database',
'deferred',
],
],
],
/*
|--------------------------------------------------------------------------
| Job Batching
|--------------------------------------------------------------------------
|
| The following options configure the database and table that store job
| batching information. These options can be updated to any database
| connection and table which has been defined by your application.
|
*/
'batching' => [
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'job_batches',
],
/*
|--------------------------------------------------------------------------
| Failed Queue Jobs
|--------------------------------------------------------------------------
|
| These options configure the behavior of failed queue job logging so you
| can control how and where failed jobs are stored. Laravel ships with
| support for storing failed jobs in a simple file or in a database.
|
| Supported drivers: "database-uuids", "dynamodb", "file", "null"
|
*/
'failed' => [
'driver' => env('QUEUE_FAILED_DRIVER', 'database-uuids'),
'database' => env('DB_CONNECTION', 'sqlite'),
'table' => 'failed_jobs',
],
];
+87
View File
@@ -0,0 +1,87 @@
<?php
use Illuminate\Cookie\Middleware\EncryptCookies;
use Illuminate\Foundation\Http\Middleware\ValidateCsrfToken;
use Laravel\Sanctum\Http\Middleware\AuthenticateSession;
use Laravel\Sanctum\Sanctum;
return [
/*
|--------------------------------------------------------------------------
| Stateful Domains
|--------------------------------------------------------------------------
|
| Requests from the following domains / hosts will receive stateful API
| authentication cookies. Typically, these should include your local
| and production domains which access your API via a frontend SPA.
|
*/
'stateful' => explode(',', env('SANCTUM_STATEFUL_DOMAINS', sprintf(
'%s%s',
'localhost,localhost:3000,127.0.0.1,127.0.0.1:8000,::1',
Sanctum::currentApplicationUrlWithPort(),
// Sanctum::currentRequestHost(),
))),
/*
|--------------------------------------------------------------------------
| Sanctum Guards
|--------------------------------------------------------------------------
|
| This array contains the authentication guards that will be checked when
| Sanctum is trying to authenticate a request. If none of these guards
| are able to authenticate the request, Sanctum will use the bearer
| token that's present on an incoming request for authentication.
|
*/
'guard' => ['web'],
/*
|--------------------------------------------------------------------------
| Expiration Minutes
|--------------------------------------------------------------------------
|
| This value controls the number of minutes until an issued token will be
| considered expired. This will override any values set in the token's
| "expires_at" attribute, but first-party sessions are not affected.
|
*/
'expiration' => null,
/*
|--------------------------------------------------------------------------
| Token Prefix
|--------------------------------------------------------------------------
|
| Sanctum can prefix new tokens in order to take advantage of numerous
| security scanning initiatives maintained by open source platforms
| that notify developers if they commit tokens into repositories.
|
| See: https://docs.github.com/en/code-security/secret-scanning/about-secret-scanning
|
*/
'token_prefix' => env('SANCTUM_TOKEN_PREFIX', ''),
/*
|--------------------------------------------------------------------------
| Sanctum Middleware
|--------------------------------------------------------------------------
|
| When authenticating your first-party SPA with Sanctum you may need to
| customize some of the middleware Sanctum uses while processing the
| request. You may change the middleware listed below as required.
|
*/
'middleware' => [
'authenticate_session' => AuthenticateSession::class,
'encrypt_cookies' => EncryptCookies::class,
'validate_csrf_token' => ValidateCsrfToken::class,
],
];
+42
View File
@@ -0,0 +1,42 @@
<?php
return [
/*
|--------------------------------------------------------------------------
| Third Party Services
|--------------------------------------------------------------------------
|
| This file is for storing the credentials for third party services such
| as Mailgun, Postmark, AWS and more. This file provides the de facto
| location for this type of information, allowing packages to have
| a conventional file to locate the various service credentials.
|
*/
'postmark' => [
'key' => env('POSTMARK_API_KEY'),
],
'resend' => [
'key' => env('RESEND_API_KEY'),
],
'ses' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY'),
'region' => env('AWS_DEFAULT_REGION', 'us-east-1'),
],
'slack' => [
'notifications' => [
'bot_user_oauth_token' => env('SLACK_BOT_USER_OAUTH_TOKEN'),
'channel' => env('SLACK_BOT_USER_DEFAULT_CHANNEL'),
],
],
'device_control' => [
'url' => env('DEVICE_CONTROL_HTTP_URL', 'http://localhost:8090'),
],
];
+233
View File
@@ -0,0 +1,233 @@
<?php
use Illuminate\Support\Str;
return [
/*
|--------------------------------------------------------------------------
| Default Session Driver
|--------------------------------------------------------------------------
|
| This option determines the default session driver that is utilized for
| incoming requests. Laravel supports a variety of storage options to
| persist session data. Database storage is a great default choice.
|
| Supported: "file", "cookie", "database", "memcached",
| "redis", "dynamodb", "array"
|
*/
'driver' => env('SESSION_DRIVER', 'database'),
/*
|--------------------------------------------------------------------------
| Session Lifetime
|--------------------------------------------------------------------------
|
| Here you may specify the number of minutes that you wish the session
| to be allowed to remain idle before it expires. If you want them
| to expire immediately when the browser is closed then you may
| indicate that via the expire_on_close configuration option.
|
*/
'lifetime' => (int) env('SESSION_LIFETIME', 120),
'expire_on_close' => env('SESSION_EXPIRE_ON_CLOSE', false),
/*
|--------------------------------------------------------------------------
| Session Encryption
|--------------------------------------------------------------------------
|
| This option allows you to easily specify that all of your session data
| should be encrypted before it's stored. All encryption is performed
| automatically by Laravel and you may use the session like normal.
|
*/
'encrypt' => env('SESSION_ENCRYPT', false),
/*
|--------------------------------------------------------------------------
| Session File Location
|--------------------------------------------------------------------------
|
| When utilizing the "file" session driver, the session files are placed
| on disk. The default storage location is defined here; however, you
| are free to provide another location where they should be stored.
|
*/
'files' => storage_path('framework/sessions'),
/*
|--------------------------------------------------------------------------
| Session Database Connection
|--------------------------------------------------------------------------
|
| When using the "database" or "redis" session drivers, you may specify a
| connection that should be used to manage these sessions. This should
| correspond to a connection in your database configuration options.
|
*/
'connection' => env('SESSION_CONNECTION'),
/*
|--------------------------------------------------------------------------
| Session Database Table
|--------------------------------------------------------------------------
|
| When using the "database" session driver, you may specify the table to
| be used to store sessions. Of course, a sensible default is defined
| for you; however, you're welcome to change this to another table.
|
*/
'table' => env('SESSION_TABLE', 'sessions'),
/*
|--------------------------------------------------------------------------
| Session Cache Store
|--------------------------------------------------------------------------
|
| When using one of the framework's cache driven session backends, you may
| define the cache store which should be used to store the session data
| between requests. This must match one of your defined cache stores.
|
| Affects: "dynamodb", "memcached", "redis"
|
*/
'store' => env('SESSION_STORE'),
/*
|--------------------------------------------------------------------------
| Session Sweeping Lottery
|--------------------------------------------------------------------------
|
| Some session drivers must manually sweep their storage location to get
| rid of old sessions from storage. Here are the chances that it will
| happen on a given request. By default, the odds are 2 out of 100.
|
*/
'lottery' => [2, 100],
/*
|--------------------------------------------------------------------------
| Session Cookie Name
|--------------------------------------------------------------------------
|
| Here you may change the name of the session cookie that is created by
| the framework. Typically, you should not need to change this value
| since doing so does not grant a meaningful security improvement.
|
*/
'cookie' => env(
'SESSION_COOKIE',
Str::slug((string) env('APP_NAME', 'laravel')).'-session'
),
/*
|--------------------------------------------------------------------------
| Session Cookie Path
|--------------------------------------------------------------------------
|
| The session cookie path determines the path for which the cookie will
| be regarded as available. Typically, this will be the root path of
| your application, but you're free to change this when necessary.
|
*/
'path' => env('SESSION_PATH', '/'),
/*
|--------------------------------------------------------------------------
| Session Cookie Domain
|--------------------------------------------------------------------------
|
| This value determines the domain and subdomains the session cookie is
| available to. By default, the cookie will be available to the root
| domain without subdomains. Typically, this shouldn't be changed.
|
*/
'domain' => env('SESSION_DOMAIN'),
/*
|--------------------------------------------------------------------------
| HTTPS Only Cookies
|--------------------------------------------------------------------------
|
| By setting this option to true, session cookies will only be sent back
| to the server if the browser has a HTTPS connection. This will keep
| the cookie from being sent to you when it can't be done securely.
|
*/
'secure' => env('SESSION_SECURE_COOKIE'),
/*
|--------------------------------------------------------------------------
| HTTP Access Only
|--------------------------------------------------------------------------
|
| Setting this value to true will prevent JavaScript from accessing the
| value of the cookie and the cookie will only be accessible through
| the HTTP protocol. It's unlikely you should disable this option.
|
*/
'http_only' => env('SESSION_HTTP_ONLY', true),
/*
|--------------------------------------------------------------------------
| Same-Site Cookies
|--------------------------------------------------------------------------
|
| This option determines how your cookies behave when cross-site requests
| take place, and can be used to mitigate CSRF attacks. By default, we
| will set this value to "lax" to permit secure cross-site requests.
|
| See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie#samesitesamesite-value
|
| Supported: "lax", "strict", "none", null
|
*/
'same_site' => env('SESSION_SAME_SITE', 'lax'),
/*
|--------------------------------------------------------------------------
| Partitioned Cookies
|--------------------------------------------------------------------------
|
| Setting this value to true will tie the cookie to the top-level site for
| a cross-site context. Partitioned cookies are accepted by the browser
| when flagged "secure" and the Same-Site attribute is set to "none".
|
*/
'partitioned' => env('SESSION_PARTITIONED_COOKIE', false),
/*
|--------------------------------------------------------------------------
| Session Serialization
|--------------------------------------------------------------------------
|
| This value controls the serialization strategy for session data, which
| is JSON by default. Setting this to "php" allows the storage of PHP
| objects in the session but can make an application vulnerable to
| "gadget chain" serialization attacks if the APP_KEY is leaked.
|
| Supported: "json", "php"
|
*/
'serialization' => 'json',
];
+1
View File
@@ -0,0 +1 @@
*.sqlite*
@@ -0,0 +1,50 @@
<?php
namespace Database\Factories;
use App\Enums\UserRole;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
/**
* @extends Factory<User>
*/
class UserFactory extends Factory
{
/**
* The current password being used by the factory.
*/
protected static ?string $password;
/**
* Define the model's default state.
*
* @return array<string, mixed>
*/
public function definition(): array
{
return [
'name' => fake()->name(),
'email' => fake()->unique()->safeEmail(),
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
// Matches the `role` column's DB default — create() doesn't
// hydrate DB-side defaults back into the in-memory model, so an
// omitted role here would leave $user->role null in-process.
'role' => UserRole::Owner,
];
}
/**
* Indicate that the model's email address should be unverified.
*/
public function unverified(): static
{
return $this->state(fn (array $attributes) => [
'email_verified_at' => null,
]);
}
}
@@ -0,0 +1,50 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->string('role')->default('owner');
$table->rememberToken();
$table->timestamps();
});
Schema::create('password_reset_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
Schema::create('sessions', function (Blueprint $table) {
$table->string('id')->primary();
$table->foreignId('user_id')->nullable()->index();
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->longText('payload');
$table->integer('last_activity')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('users');
Schema::dropIfExists('password_reset_tokens');
Schema::dropIfExists('sessions');
}
};
@@ -0,0 +1,35 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('cache', function (Blueprint $table) {
$table->string('key')->primary();
$table->mediumText('value');
$table->bigInteger('expiration')->index();
});
Schema::create('cache_locks', function (Blueprint $table) {
$table->string('key')->primary();
$table->string('owner');
$table->bigInteger('expiration')->index();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('cache');
Schema::dropIfExists('cache_locks');
}
};
@@ -0,0 +1,59 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('jobs', function (Blueprint $table) {
$table->id();
$table->string('queue')->index();
$table->longText('payload');
$table->unsignedSmallInteger('attempts');
$table->unsignedInteger('reserved_at')->nullable();
$table->unsignedInteger('available_at');
$table->unsignedInteger('created_at');
});
Schema::create('job_batches', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('name');
$table->integer('total_jobs');
$table->integer('pending_jobs');
$table->integer('failed_jobs');
$table->longText('failed_job_ids');
$table->mediumText('options')->nullable();
$table->integer('cancelled_at')->nullable();
$table->integer('created_at');
$table->integer('finished_at')->nullable();
});
Schema::create('failed_jobs', function (Blueprint $table) {
$table->id();
$table->string('uuid')->unique();
$table->string('connection');
$table->string('queue');
$table->longText('payload');
$table->longText('exception');
$table->timestamp('failed_at')->useCurrent();
$table->index(['connection', 'queue', 'failed_at']);
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('jobs');
Schema::dropIfExists('job_batches');
Schema::dropIfExists('failed_jobs');
}
};
@@ -0,0 +1,33 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::create('personal_access_tokens', function (Blueprint $table) {
$table->id();
$table->morphs('tokenable');
$table->text('name');
$table->string('token', 64)->unique();
$table->text('abilities')->nullable();
$table->timestamp('last_used_at')->nullable();
$table->timestamp('expires_at')->nullable()->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::dropIfExists('personal_access_tokens');
}
};
@@ -0,0 +1,24 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('zones', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->string('name');
$table->text('description')->nullable();
$table->timestamp('created_at')->useCurrent();
});
}
public function down(): void
{
Schema::dropIfExists('zones');
}
};
@@ -0,0 +1,23 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('device_types', function (Blueprint $table) {
$table->id();
$table->string('code')->unique(); // e.g. light, pump, fan, sensor_temp_humidity
$table->string('category'); // actuator | sensor — see App\Enums\DeviceCategory
$table->jsonb('capabilities')->default('[]'); // e.g. ["turn_on","turn_off","set_level"]
});
}
public function down(): void
{
Schema::dropIfExists('device_types');
}
};
@@ -0,0 +1,30 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('devices', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('zone_id')->constrained()->cascadeOnDelete();
$table->foreignId('device_type_id')->constrained();
$table->string('name');
$table->string('external_id')->unique(); // physical device id (ESP32 chip id, etc.) — what MQTT/Redis/gRPC key on
$table->string('protocol')->default('mqtt');
// Snapshot only — Redis (device-control-service's Device Shadow) is the
// authoritative, real-time source for online/offline.
$table->string('status')->default('offline');
$table->timestamp('created_at')->useCurrent();
});
}
public function down(): void
{
Schema::dropIfExists('devices');
}
};
@@ -0,0 +1,31 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
public function up(): void
{
Schema::create('automation_rules', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
$table->foreignId('zone_id')->constrained()->cascadeOnDelete();
$table->foreignId('target_device_id')->constrained('devices')->cascadeOnDelete();
$table->foreignId('condition_source_device_id')->constrained('devices')->cascadeOnDelete();
$table->string('condition_sensor_type');
$table->string('condition_operator'); // >, <, >=, <=, =, != — see App\Enums\ConditionOperator
$table->double('condition_value');
$table->string('action_type'); // e.g. turn_on, turn_off, set_level
$table->jsonb('action_params')->default('{}');
$table->boolean('is_active')->default(true);
$table->timestamp('created_at')->useCurrent();
});
}
public function down(): void
{
Schema::dropIfExists('automation_rules');
}
};
@@ -0,0 +1,36 @@
<?php
namespace Database\Seeders;
use App\Enums\UserRole;
use App\Models\User;
use Illuminate\Database\Console\Seeds\WithoutModelEvents;
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
use WithoutModelEvents;
/**
* Seed the application's database.
*/
public function run(): void
{
User::factory()->create([
'name' => 'Test Owner',
'email' => 'owner@example.com',
'role' => UserRole::Owner,
]);
User::factory()->create([
'name' => 'Test Viewer',
'email' => 'viewer@example.com',
'role' => UserRole::Viewer,
]);
$this->call([
DeviceTypeSeeder::class,
DemoGrowboxSeeder::class,
]);
}
}
@@ -0,0 +1,70 @@
<?php
namespace Database\Seeders;
use App\Models\AutomationRule;
use App\Models\Device;
use App\Models\DeviceType;
use App\Models\User;
use App\Models\Zone;
use Illuminate\Database\Seeder;
/**
* Demo data for the growbox zone the first zone implemented on the
* platform. Purely example content so the CRUD screens aren't empty on
* first run; nothing here is special-cased in application code.
*/
class DemoGrowboxSeeder extends Seeder
{
public function run(): void
{
$owner = User::where('email', 'owner@example.com')->firstOrFail();
$zone = Zone::query()->firstOrCreate(
['name' => 'Гроубокс'],
['user_id' => $owner->id, 'description' => 'Демо-зона для проверки платформы']
);
$sensorType = DeviceType::where('code', 'sensor_temp_humidity')->firstOrFail();
$fanType = DeviceType::where('code', 'fan')->firstOrFail();
$sensor = Device::query()->firstOrCreate(
['external_id' => 'sensor-1'],
[
'user_id' => $owner->id,
'zone_id' => $zone->id,
'device_type_id' => $sensorType->id,
'name' => 'Датчик температуры',
'protocol' => 'mqtt',
]
);
$fan = Device::query()->firstOrCreate(
['external_id' => 'fan-1'],
[
'user_id' => $owner->id,
'zone_id' => $zone->id,
'device_type_id' => $fanType->id,
'name' => 'Вентилятор',
'protocol' => 'mqtt',
]
);
AutomationRule::query()->firstOrCreate(
[
'condition_source_device_id' => $sensor->id,
'target_device_id' => $fan->id,
],
[
'user_id' => $owner->id,
'zone_id' => $zone->id,
'condition_sensor_type' => 'temperature',
'condition_operator' => '>',
'condition_value' => 28,
'action_type' => 'turn_on',
'action_params' => [],
'is_active' => true,
]
);
}
}
@@ -0,0 +1,30 @@
<?php
namespace Database\Seeders;
use App\Enums\DeviceCategory;
use App\Models\DeviceType;
use Illuminate\Database\Seeder;
/**
* Seeds the initial device_types registry. These are the growbox zone's
* device types the first zone implemented on the platform but the
* table itself is an open registry: adding a device type for another zone
* (e.g. a smart plug for "living room") is just another row, no code change.
*/
class DeviceTypeSeeder extends Seeder
{
public function run(): void
{
$types = [
['code' => 'light', 'category' => DeviceCategory::Actuator, 'capabilities' => ['turn_on', 'turn_off', 'set_level']],
['code' => 'pump', 'category' => DeviceCategory::Actuator, 'capabilities' => ['turn_on', 'turn_off']],
['code' => 'fan', 'category' => DeviceCategory::Actuator, 'capabilities' => ['turn_on', 'turn_off', 'set_level']],
['code' => 'sensor_temp_humidity', 'category' => DeviceCategory::Sensor, 'capabilities' => ['temperature', 'humidity']],
];
foreach ($types as $type) {
DeviceType::query()->firstOrCreate(['code' => $type['code']], $type);
}
}
}
+23
View File
@@ -0,0 +1,23 @@
server {
listen 80;
server_name _;
root /var/www/html/public;
index index.php;
client_max_body_size 20m;
location / {
try_files $uri $uri/ /index.php?$query_string;
}
location ~ \.php$ {
fastcgi_pass 127.0.0.1:9000;
fastcgi_index index.php;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
}
location ~ /\.(?!well-known).* {
deny all;
}
}
+20
View File
@@ -0,0 +1,20 @@
[supervisord]
nodaemon=true
[program:php-fpm]
command=php-fpm -F
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
[program:nginx]
command=nginx -g "daemon off;"
autostart=true
autorestart=true
stdout_logfile=/dev/stdout
stdout_logfile_maxbytes=0
stderr_logfile=/dev/stderr
stderr_logfile_maxbytes=0
+2932
View File
File diff suppressed because it is too large Load Diff
+24
View File
@@ -0,0 +1,24 @@
{
"$schema": "https://www.schemastore.org/package.json",
"private": true,
"type": "module",
"scripts": {
"build": "vite build",
"dev": "vite"
},
"devDependencies": {
"@tailwindcss/forms": "^0.5.2",
"@tailwindcss/vite": "^4.0.0",
"autoprefixer": "^10.4.2",
"concurrently": "^9.0.1",
"laravel-vite-plugin": "^3.1",
"postcss": "^8.4.31",
"tailwindcss": "^3.1.0",
"vite": "^8.0.0"
},
"dependencies": {
"@inertiajs/vue3": "^3.6.1",
"@vitejs/plugin-vue": "^6.0.8",
"vue": "^3.5.41"
}
}
+36
View File
@@ -0,0 +1,36 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="vendor/phpunit/phpunit/phpunit.xsd"
bootstrap="vendor/autoload.php"
colors="true"
>
<testsuites>
<testsuite name="Unit">
<directory>tests/Unit</directory>
</testsuite>
<testsuite name="Feature">
<directory>tests/Feature</directory>
</testsuite>
</testsuites>
<source>
<include>
<directory>app</directory>
</include>
</source>
<php>
<env name="APP_ENV" value="testing"/>
<env name="APP_MAINTENANCE_DRIVER" value="file"/>
<env name="BCRYPT_ROUNDS" value="4"/>
<env name="BROADCAST_CONNECTION" value="null"/>
<env name="CACHE_STORE" value="array"/>
<env name="DB_CONNECTION" value="sqlite"/>
<env name="DB_DATABASE" value=":memory:"/>
<env name="DB_URL" value=""/>
<env name="MAIL_MAILER" value="array"/>
<env name="QUEUE_CONNECTION" value="sync"/>
<env name="SESSION_DRIVER" value="array"/>
<env name="PULSE_ENABLED" value="false"/>
<env name="TELESCOPE_ENABLED" value="false"/>
<env name="NIGHTWATCH_ENABLED" value="false"/>
</php>
</phpunit>
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
+25
View File
@@ -0,0 +1,25 @@
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
Options -MultiViews -Indexes
</IfModule>
RewriteEngine On
# Handle Authorization Header
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
# Handle X-XSRF-Token Header
RewriteCond %{HTTP:x-xsrf-token} .
RewriteRule .* - [E=HTTP_X_XSRF_TOKEN:%{HTTP:X-XSRF-Token}]
# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} (.+)/$
RewriteRule ^ %1 [L,R=301]
# Send Requests To Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^ index.php [L]
</IfModule>
+20
View File
@@ -0,0 +1,20 @@
<?php
use Illuminate\Foundation\Application;
use Illuminate\Http\Request;
define('LARAVEL_START', microtime(true));
// Determine if the application is in maintenance mode...
if (file_exists($maintenance = __DIR__.'/../storage/framework/maintenance.php')) {
require $maintenance;
}
// Register the Composer autoloader...
require __DIR__.'/../vendor/autoload.php';
// Bootstrap Laravel and handle the request...
/** @var Application $app */
$app = require_once __DIR__.'/../bootstrap/app.php';
$app->handleRequest(Request::capture());
+2
View File
@@ -0,0 +1,2 @@
User-agent: *
Disallow:

Some files were not shown because too many files have changed in this diff Show More