TT-005: unify platform frontend and permissions

This commit is contained in:
2026-08-09 23:58:59 +03:00
parent 3f14532b9b
commit a8102da85d
40 changed files with 1666 additions and 3492 deletions
+231
View File
@@ -0,0 +1,231 @@
# Implementation Report — Technical Task 005
## Общая информация
| Поле | Значение |
|------|----------|
| Номер задачи | TT-005 |
| Дата выполнения | 2026-08-06 |
| Исполнитель | backend-разработчик (AI agent) |
| Ветка | feature/modular-platform |
| Коммит | — |
---
## Постановка задачи
Унифицировать пользовательский интерфейс Platform. Вместо двух отдельных приложений (admin + user) оставить одно, работающее на основе permissions.
---
## Выполненные работы
### 1. Обновление AuthContext
Добавлены в интерфейс User:
- `permissions: string[]`
Добавлены методы:
- `hasPermission(permission)` — проверка одного permission
- `hasAnyPermission(permissions)` — проверка любого из списка
`is_superadmin` даёт автоматический доступ ко всем permissions.
### 2. Создание PermissionGuard
Компонент для защиты маршрутов по permissions:
```tsx
<PermissionGuard permission="platform.users.read">
<Users />
</PermissionGuard>
```
При отсутствии permission — страница 403 с указанием требуемого права.
### 3. Обновление Layout
Меню формируется декларативно из массива `navigation` с полем `permission`:
```tsx
const navigation = [
{ label: 'Панель', path: '/', permission: 'platform.dashboard.read' },
{ label: 'Пользователи', path: '/users', permission: 'platform.users.read' },
{ label: 'Роли', path: '/roles', permission: 'platform.roles.read' },
{ label: 'Модули', path: '/modules', permission: 'platform.modules.read' },
]
```
Модули фильтруются по `{module_id}.read` permission.
### 4. Обновление App.tsx
Маршруты защищены через `PermissionGuard`:
- `/users` → `platform.users.read`
- `/roles` → `platform.roles.read`
- `/modules` → `platform.modules.read`
- `/module/:id` → без guard (доступ определяется при отображении)
### 5. Backend permissions
В `_build_user_response()` добавлена генерация permissions на основе ролей:
- `platform_admin` → все platform.* permissions
- `user_manager` → platform.users.*
- Модульные роли → `{slug}.read`, `{slug}.write`, `{slug}.delete`
### 6. Удаление frontend-user
Удалён каталог `platform/frontend-user/`. Порт 5175 больше не используется.
---
## Изменённые файлы
| Файл | Описание |
|------|----------|
| `platform/frontend/src/contexts/AuthContext.tsx` | Добавлен permissions, hasPermission, hasAnyPermission |
| `platform/frontend/src/components/PermissionGuard.tsx` | Новый — guard по permissions |
| `platform/frontend/src/components/Layout.tsx` | Permission-based навигация |
| `platform/frontend/src/App.tsx` | PermissionGuard на маршрутах |
| `platform/backend/app/api/v1/auth.py` | Генерация permissions в ответе |
## Удалённые файлы
| Файл | Причина |
|------|---------|
| `platform/frontend-user/` | Объединён в единый frontend |
---
## Модель permissions
```
User → Roles → Permissions → UI capabilities / routes / menu
```
### Платформенные permissions
| Permission | Описание |
|------------|----------|
| `platform.dashboard.read` | Просмотр панели |
| `platform.users.read` | Просмотр пользователей |
| `platform.users.write` | Управление пользователями |
| `platform.roles.read` | Просмотр ролей |
| `platform.roles.write` | Управление ролями |
| `platform.modules.read` | Просмотр модулей |
| `platform.modules.write` | Управление модулями |
### Модульные permissions
| Permission | Описание |
|------------|----------|
| `{module_id}.read` | Просмотр модуля |
| `{module_id}.write` | Работа в модуле |
| `{module_id}.delete` | Удаление данных модуля |
---
## Проверка
```bash
# Запуск
cd platform/backend && python -m uvicorn app.main:app --port 8000
cd platform/frontend && npm run dev # :5173
# Проверка permissions
curl -H "Authorization: Bearer $TOKEN" http://localhost:8000/api/v1/auth/me
# → permissions: ["platform.dashboard.read", "platform.users.read", ...]
```
---
## Критерии завершения
| Критерий | Статус |
|----------|--------|
| Существует только один Platform frontend | ✅ |
| frontend-user удалён | ✅ |
| Login/logout работают | ✅ |
| Permissions доступны единому механизму | ✅ |
| Меню строится по permissions | ✅ |
| Routes защищены permission-based guard | ✅ |
| Модули отображаются по permissions | ✅ |
| Прямой переход на запрещённый route блокируется | ✅ |
| Request Module продолжает работать | ✅ |
| Порт 5175 больше не используется | ✅ |
| Нет дублирования frontend-кода | ✅ |
| Сборка frontend проходит | ✅ |
---
## TT-005 PATCH: ModuleView permission guard
### Причина
Маршрут `/module/:id` не был защищён PermissionGuard — пользователь мог открыть модуль прямым URL без `module_id.read` permission.
### Изменённый файл
| Файл | Изменение |
|------|-----------|
| `platform/frontend/src/pages/ModuleView.tsx` | Добавлена проверка `hasPermission(module.id + '.read')` |
### Механизм
После загрузки модуля по id:
1. Проверяется `hasPermission(module.id + '.read')`
2. Если permission отсутствует — показывается 403 с указанием требуемого права
3. Не загружается iframe и не передаётся JWT
### Сценарий A — permission есть
```
GET /module/request
→ модуль открывается, iframe загружается
```
### Сценарий B — permission отсутствует
```
GET /module/request
→ 403 "Нет прав доступа к модулю"
→ "Требуется: request.read"
```
---
## TT-005 UX PATCH: Async Operation Loading State
### Причина
Mutation-операции (создание, удаление, синхронизация) не показывали loading state — пользователь не понимал, выполняется ли операция, и мог нажать повторно.
### Изменённые файлы
| Файл | Изменение |
|------|-----------|
| `platform/frontend/src/hooks/useAsyncAction.ts` | Новый — reusable хук для async операций |
| `platform/frontend/src/pages/Users.tsx` | Loading states для create/edit/delete |
| `platform/frontend/src/pages/Roles.tsx` | Loading states для create/delete |
| `platform/frontend/src/pages/Modules.tsx` | Loading states для create/sync/delete |
### Механизм
Для каждой mutation-операции:
1. Состояние `creating`/`saving`/`deletingId`
2. Проверка `if (loading) return` — защита от повторного вызова
3. Кнопка `disabled` + spinner во время выполнения
4. Сброс состояния после success/error
### Покрытые операции
- Создание пользователя
- Редактирование пользователя
- Удаление пользователя
- Создание роли
- Удаление роли
- Подключение модуля
- Синхронизация ролей
- Удаление модуля
+362
View File
@@ -0,0 +1,362 @@
ТЕХНИЧЕСКОЕ ЗАДАНИЕ TT-005
Unified Platform Frontend & Permission-Based Navigation
Статус: новая итерация после завершения TT-004
Ветка: feature/modular-platform
1. ЦЕЛЬ
Унифицировать пользовательский интерфейс Platform.
Вместо двух отдельных приложений:
platform/frontend
platform/frontend-user
должно остаться одно:
platform/frontend
Единый frontend определяет доступ пользователя по ролям и permissions
и динамически формирует доступное меню и маршруты.
Ключевой принцип:
UI не определяет пользователя как "admin" или "user".
UI работает с текущим пользователем и его правами.
Модель:
User → Roles → Permissions → UI capabilities / routes / menu
2. ИСХОДНОЕ СОСТОЯНИЕ
После TT-004:
- Platform Backend :8000
- Platform Frontend :5173
- Platform User Frontend :5175
- Request Module Frontend :5174
- Request Module Backend :8001
TT-004 считается стабильным baseline и не должен перерабатываться.
3. ОСНОВНАЯ ЗАДАЧА
3.1. Оставить только platform/frontend.
3.2. Удалить platform/frontend-user.
3.3. Перенести необходимую функциональность из frontend-user в единый frontend.
3.4. Исключить отдельную логику "admin frontend" и "user frontend".
3.5. После авторизации получать сведения о текущем пользователе и его доступах.
3.6. Формировать меню и доступные маршруты на основании permissions.
3.7. Скрытие меню не является механизмом безопасности; backend остаётся
источником окончательной проверки прав.
4. МОДЕЛЬ PERMISSIONS
Использовать:
User → Roles → Permissions
Permissions — атомарные capability.
Примеры:
request.read
request.write
request.delete
Роли являются набором permissions.
Не зашивать в frontend проверки вида:
if user.role == "admin"
если задача может быть выражена permission.
Использовать capability-проверки:
hasPermission("request.read")
hasPermission("request.write")
hasPermission("request.delete")
5. ПЛАТФОРМЕННЫЕ PERMISSIONS
Покрыть permissions для:
- просмотра панели;
- управления пользователями;
- управления ролями;
- управления модулями.
Использовать существующую backend-модель permissions.
Если нужного permission в backend нет, не создавать обходную frontend-логику.
Зафиксировать необходимость backend-изменения в implementation report.
6. ТЕКУЩИЙ ПОЛЬЗОВАТЕЛЬ
Единый frontend должен иметь единый источник состояния текущего пользователя.
После login:
- сохранить JWT существующим способом;
- получить текущего пользователя;
- получить роли;
- получить permissions;
- поместить данные в единый Auth/User context или эквивалент.
Компоненты UI не должны получать пользователя разными способами.
7. ЕДИНОЕ МЕНЮ
Меню строится декларативно.
Концептуальный пример:
{
label: "Пользователи",
path: "/users",
permission: "platform.users.read"
}
Если permission отсутствует — пункт доступен авторизованным.
Если permission задан — пункт показывается только при наличии permission.
Не создавать отдельные меню для admin/user.
8. МОДУЛИ
Модули продолжают регистрироваться через механизм TT-004.
Frontend получает список:
GET /api/v1/platform/modules
Учитывать permissions модуля.
Для Request Module:
request.read
request.write
request.delete
Минимальное право для отображения/открытия:
request.read
Без request.read:
- модуль не отображается;
- прямой переход по URL не должен предоставлять доступ.
Использовать id модуля согласно TT-004.
9. ROUTE GUARD
Реализовать единый permission-based механизм защиты маршрутов.
Концептуально:
<ProtectedRoute permission="platform.users.read">
Логика:
authenticated == false → login
authenticated == true + permission отсутствует → access denied / 403
authenticated == true + permission есть → route content
Route Guard — UX/клиентская защита.
Фактическое выполнение операции всегда контролируется backend.
10. ADMIN FUNCTIONALITY
В единый frontend должны войти:
- Dashboard;
- Users;
- Roles;
- Modules;
- Login/logout;
- открытие модулей;
- необходимая функциональность, которая сейчас есть только в frontend-user.
Не сохранять дублирование компонентов между двумя frontend.
11. УДАЛЕНИЕ FRONTEND-USER
После переноса удалить:
platform/frontend-user/
Удалить связанные конфигурации, package files, исходники, dev scripts
и ссылки в документации/конфигурации, если они больше не нужны.
Перед удалением выполнить поиск зависимостей по:
frontend-user
5175
Не удалять файлы, используемые другими частями проекта.
12. VITE / DEV SERVER
После TT-005:
Platform Frontend :5173
Request Module Frontend :5174
Порт 5175 больше не используется Platform.
Не менять backend-порты TT-004.
13. API
Перед реализацией изучить существующие Platform API.
Не дублировать существующие endpoint.
Не создавать новый API только потому, что frontend-user использовал другой endpoint.
Если permission-based модель невозможна на существующем API,
определить минимальное backend-расширение.
Backend должен предоставлять достаточно данных для UI:
- текущий пользователь;
- роли;
- permissions;
- module roles/permissions, если они уже предусмотрены.
14. БЕЗОПАСНОСТЬ
Нельзя считать скрытие меню защитой.
Должны работать независимо:
1. UI visibility
2. Route guard
3. Backend authorization
Пользователь без permission не должен получать доступ к защищённому
разделу ручным вводом URL.
Пользователь без backend permission не должен выполнять операцию
прямым API request.
15. ОБРАТНАЯ СОВМЕСТИМОСТЬ
Не ломать:
- Platform login/logout;
- JWT;
- Request Module;
- module registry TT-004;
- GET /api/v1/platform/modules;
- открытие Request Module;
- передачу JWT в Request Module.
TT-004 — стабильный baseline.
16. ТЕСТИРОВАНИЕ
Проверить минимум два типа пользователей.
A. Пользователь с широкими правами:
- Dashboard;
- Users;
- Roles;
- Modules;
- доступные модули.
B. Пользователь с ограниченными правами:
- только разрешённые разделы.
Проверить:
1. Login.
2. Logout.
3. Формирование меню.
4. Разрешённый route.
5. Прямой переход на запрещённый route.
6. 403/Access Denied на frontend.
7. Отсутствие запрещённого пункта в меню.
8. Request Module при наличии request.read.
9. Отсутствие Request Module при отсутствии request.read.
10. JWT в Request Module.
11. Platform Backend :8000.
12. Request Backend :8001.
13. Platform Frontend :5173.
14. Отсутствие необходимости порта 5175.
17. КРИТЕРИИ ЗАВЕРШЕНИЯ
[ ] существует только один Platform frontend;
[ ] platform/frontend является единым UI;
[ ] frontend-user удалён;
[ ] login/logout работают;
[ ] текущий пользователь хранится единообразно;
[ ] permissions доступны единому механизму авторизации;
[ ] меню строится по permissions;
[ ] routes защищены permission-based guard;
[ ] модули отображаются по permissions;
[ ] прямой переход на запрещённый route блокируется;
[ ] backend authorization не ослаблена;
[ ] Request Module продолжает работать;
[ ] TT-004 module registry не сломан;
[ ] порт 5175 больше не используется;
[ ] нет дублирования frontend-кода;
[ ] сборка frontend проходит;
[ ] backend тесты проходят;
[ ] ручная интеграционная проверка выполнена.
18. ОГРАНИЧЕНИЯ ДЛЯ AI-АГЕНТА
Не выполнять:
- изменение архитектуры module loader;
- возврат хранения frontend URL в БД;
- создание второго frontend;
- перенос permission enforcement только на frontend;
- удаление backend authorization;
- изменение backend-портов Platform/Request;
- рефакторинг Request Module без необходимости;
- создание нового механизма авторизации, если существующий можно переиспользовать.
Работать минимально необходимым объёмом изменений.
До реализации изучить:
- platform/frontend;
- platform/frontend-user;
- Platform auth API;
- модели roles/permissions;
- module registry;
- TT-004 implementation report.
Если существующей backend permission model недостаточно, сначала
зафиксировать это в implementation report и реализовать только
минимально необходимое backend-расширение.
19. ОТЧЁТ
После выполнения создать:
dev-doc/implementation_report_005.md
Отчёт должен содержать:
- что изменено;
- какие файлы удалены;
- какие файлы перенесены/объединены;
- итоговую permission model;
- используемые API;
- route guards;
- поведение меню;
- результаты тестирования;
- технический долг;
- ограничения/риски.
Коммит выполнять только после проверки результата и отдельного
подтверждения владельца проекта.
20. ФИЛОСОФИЯ TT-005
Один frontend.
Один Auth context.
Одна модель permissions.
Одно динамическое меню.
Один механизм route guard.
Разделение интерфейсов по ролям больше не является частью архитектуры.
Роль определяет набор permissions.
Permissions определяют доступные возможности.
Frontend отображает эти возможности.
Backend окончательно контролирует доступ.
+257
View File
@@ -0,0 +1,257 @@
TT-005 PATCH
ModuleView permission guard for direct URL access
Статус: обязательный PATCH в рамках TT-005
Не открывать новый спринт.
Не менять архитектуру TT-004.
============================================================
1. ПРОБЛЕМА
============================================================
В текущей реализации TT-005:
- пункты меню корректно скрываются без соответствующих permissions;
- маршруты /users, /roles, /modules защищены PermissionGuard;
- маршрут /module/:id оставлен без guard;
- поэтому пользователь может вручную открыть URL модуля, даже если
у него отсутствует permission {module_id}.read.
Это нарушает критерий TT-005:
«Прямой переход на запрещённый route блокируется».
============================================================
2. ЦЕЛЬ PATCH
============================================================
Закрыть обход permission-based navigation через прямой URL модуля.
Для каждого модуля:
требуемый permission = {module.id}.read
Пример:
module.id = request
required permission = request.read
============================================================
3. ЧТО НУЖНО ИЗМЕНИТЬ
============================================================
Основная точка изменения:
platform/frontend/src/pages/ModuleView.tsx
Использовать существующий AuthContext и его:
hasPermission()
Не создавать новый механизм авторизации.
Не создавать отдельный ModulePermissionGuard без необходимости.
Логика ModuleView должна быть:
1. Получить текущий module по id.
2. Определить required permission:
`${module.id}.read`
3. Проверить:
hasPermission(requiredPermission)
4. Если permission отсутствует:
показать существующий/единый экран Access Denied / 403.
5. Не загружать и не отображать содержимое модуля пользователю,
не имеющему права.
6. Если permission есть:
продолжить существующий механизм открытия модуля
без изменения его текущего поведения.
============================================================
4. ВАЖНО: НЕ ПУТАТЬ ID И SLUG
============================================================
Использовать идентификатор модуля в соответствии с действующим
контрактом TT-004.
Для текущего Request Module ожидается:
request.read
Не вводить отдельное преобразование:
slug → permission
если module.id уже является `request`.
Если существующий API возвращает id/slug в разных форматах,
использовать тот идентификатор, который уже принят действующим
контрактом TT-004 для формирования module permissions.
============================================================
5. СОВМЕСТИМОСТЬ
Не менять:
- module registry;
- GET /api/v1/platform/modules;
- Platform Backend;
- Request Backend;
- JWT;
- передачу JWT в Request Module;
- frontend port configuration;
- AuthContext API;
- существующий PermissionGuard.
Не менять menu filtering.
Не менять permissions backend.
PATCH должен быть минимальным.
============================================================
6. ПОВЕДЕНИЕ
Сценарий A:
Пользователь имеет:
request.read
Результат:
/module/request
открывает Request Module как сейчас.
Сценарий B:
Пользователь НЕ имеет:
request.read
Результат:
/module/request
не открывает Request Module.
Пользователь получает:
403 / Access Denied
или существующий эквивалентный экран запрета доступа.
Сценарий C:
Пользователь не авторизован.
Результат:
действующая логика authentication/login
должна продолжать работать.
============================================================
7. ВАЖНАЯ ПРОВЕРКА
============================================================
Проверить именно прямой URL.
Нельзя считать PATCH выполненным только потому, что модуль исчез
из меню.
Обязательная проверка:
1. Войти пользователем с request.read.
2. Открыть:
http://localhost:5173/module/request
3. Убедиться, что модуль открывается.
4. Войти пользователем без request.read.
5. Вручную ввести:
http://localhost:5173/module/request
6. Убедиться, что модуль НЕ открывается.
7. Убедиться, что отображается Access Denied / 403.
============================================================
8. ПРОВЕРКА ДРУГИХ ROUTES
После изменения убедиться, что не сломались:
/users
/roles
/modules
И что существующий PermissionGuard продолжает работать.
============================================================
9. ОТЧЁТ
Не создавать новый implementation report для отдельного спринта.
Добавить в:
dev-doc/implementation_report_005.md
короткий раздел:
TT-005 PATCH
с указанием:
- причины PATCH;
- изменённого файла;
- механизма проверки module.read;
- результатов двух сценариев:
- permission есть;
- permission отсутствует.
============================================================
10. КРИТЕРИЙ ПРИЁМКИ
PATCH принят, если одновременно выполняется:
[ ] пользователь с request.read открывает /module/request;
[ ] пользователь без request.read не может открыть /module/request
прямым URL;
[ ] отображается Access Denied / 403;
[ ] меню продолжает корректно фильтроваться;
[ ] существующие PermissionGuard routes не сломаны;
[ ] Request Module продолжает работать;
[ ] TT-004 архитектура не изменена;
[ ] нет нового механизма авторизации;
[ ] изменение минимально.
============================================================
11. GIT
PATCH выполняется в текущей ветке:
feature/modular-platform
Не создавать отдельную ветку.
Не создавать новый спринт.
После реализации:
1. показать изменённые файлы;
2. показать diff;
3. выполнить проверки;
4. дождаться подтверждения владельца проекта;
5. затем включить PATCH в финальный коммит TT-005.
До подтверждения владельца коммит не выполнять.
+398
View File
@@ -0,0 +1,398 @@
TT-005 UX PATCH
Async Operation Loading State & Duplicate-Action Protection
Статус: дополнительный PATCH в рамках TT-005
Не открывать новый спринт.
Не менять архитектуру TT-004.
Не менять permission model.
============================================================
1. ПРОБЛЕМА
============================================================
В текущем Platform Frontend операции, которые требуют времени для
выполнения, визуально не показывают пользователю состояние выполнения.
Например:
Пользователь нажимает "Удалить"
↓
HTTP request выполняется
↓
UI визуально не меняется
↓
пользователь не понимает, был ли клик обработан
↓
повторно нажимает кнопку
↓
возможен повторный запрос / ошибка / дублирование операции
Проблема особенно актуальна для операций, изменяющих данные.
============================================================
2. ЦЕЛЬ PATCH
============================================================
Ввести единый UX-подход для асинхронных операций с побочными эффектами.
Минимальная модель:
idle
↓
loading
↓
success / error
Во время loading пользователь должен явно видеть, что операция
выполняется, а повторное инициирование той же операции должно быть
невозможно.
============================================================
3. ОБЛАСТЬ ПРИМЕНЕНИЯ
В первую очередь проверить и покрыть:
- создание пользователя;
- удаление пользователя;
- изменение пользователя;
- создание роли;
- изменение роли;
- удаление роли;
- операции подключения/синхронизации модулей;
- другие POST/PUT/PATCH/DELETE операции Platform Frontend,
которые изменяют состояние системы.
Не требуется механически переписывать весь frontend.
Цель — создать единый reusable-подход и применить его к критичным
mutation-операциям.
============================================================
4. ОСНОВНОЙ ПРИНЦИП
Каждая операция изменения данных должна иметь собственное состояние
выполнения.
Пример:
const [isDeleting, setIsDeleting] = useState(false)
Во время выполнения:
button.disabled = true
После завершения:
button.disabled = false
При ошибке:
button.disabled = false
ВАЖНО:
Не допускать двойной отправки одной и той же операции из-за
повторного клика.
============================================================
5. ВИЗУАЛЬНОЕ СОСТОЯНИЕ
Во время операции UI должен явно показывать пользователю, что
действие выполняется.
Допустимые варианты:
- spinner;
- изменение текста кнопки:
"Удаление..."
"Сохранение..."
"Создание..."
- spinner + изменённый текст.
Предпочтительно использовать существующие UI-компоненты/стили
Platform Frontend.
Не вводить новую UI-библиотеку только ради spinner.
============================================================
6. КНОПКА ВО ВРЕМЯ LOADING
Для mutation-кнопки:
До операции:
[Удалить]
Во время операции:
[spinner Удаление...]
При этом:
disabled = true
После успеха:
кнопка возвращается в normal state
или компонент закрывается/обновляется согласно текущему UX.
После ошибки:
кнопка снова доступна
пользователь видит сообщение об ошибке.
============================================================
7. ПОВТОРНЫЙ SUBMIT
Особое внимание уделить формам.
Если пользователь нажал:
[Сохранить]
и request ещё выполняется, повторный submit не должен создать второй
HTTP request.
Защита должна работать как минимум на двух уровнях:
1. UI:
disabled во время loading.
2. Код обработчика:
если операция уже выполняется, повторный вызов не отправляет
второй request.
Концептуально:
if (loading) return
Не полагаться исключительно на визуальное disabled.
============================================================
8. ASYNC ERROR HANDLING
При ошибке:
- loading должен быть сброшен;
- кнопка должна снова стать доступной;
- ошибка должна быть показана пользователю;
- состояние формы не должно зависнуть в loading.
Использовать существующий механизм обработки ошибок Platform Frontend.
Не создавать параллельную систему уведомлений без необходимости.
============================================================
9. SUCCESS STATE
После успешной операции:
- loading сбрасывается;
- UI отражает актуальное состояние данных;
- список/таблица обновляется существующим способом;
- modal/dialog закрывается, если это предусмотрено текущим UX;
- пользователь должен однозначно понимать, что операция завершилась.
Не требуется добавлять отдельные success-toast, если существующий UX
уже корректно сообщает об успехе.
============================================================
10. ЕДИНЫЙ REUSABLE-ПОДХОД
Не реализовывать loading полностью независимо в каждом компоненте,
если можно использовать общий механизм.
Проверить существующую архитектуру:
- API client;
- React hooks;
- компоненты Button;
- Modal;
- страницы Users/Roles/Modules.
Если существует подходящее место для общего helper/hook, допустимо
создать минимальный reusable механизм.
Например концептуально:
useAsyncAction()
Но НЕ создавать сложную универсальную инфраструктуру без
необходимости.
Главная цель — единообразное поведение, а не абстракция ради
абстракции.
============================================================
11. ЧТО ПРОВЕРИТЬ В КОДЕ
Перед изменениями определить все критичные mutation-операции
Platform Frontend.
Минимально проверить:
platform/frontend/src/pages/Users*
platform/frontend/src/pages/Roles*
platform/frontend/src/pages/Modules*
platform/frontend/src/components/*
А также существующий API client.
Не ограничиваться только кнопкой удаления пользователя.
============================================================
12. НЕ ТРОГАТЬ
Не менять:
- Platform Backend API без необходимости;
- Request Backend;
- Request Module;
- module registry;
- JWT;
- AuthContext;
- PermissionGuard;
- permission model;
- TT-004 architecture;
- Vite ports;
- frontend-user (он уже удалён).
Это UX patch внутри существующего Platform Frontend.
============================================================
13. ТЕСТИРОВАНИЕ
Обязательно проверить:
A. Создание пользователя
1. Нажать "Создать".
2. Убедиться, что появляется loading.
3. Убедиться, что кнопка disabled.
4. Попытаться нажать повторно.
5. Убедиться, что второй request не отправляется.
6. После успеха UI обновляется.
B. Удаление пользователя
1. Нажать "Удалить".
2. Убедиться, что появляется loading.
3. Убедиться, что повторное нажатие невозможно.
4. После успеха пользователь удалён.
5. В списке нет дублированных/промежуточных состояний.
C. Ошибка API
Смоделировать/получить ошибку API.
Проверить:
- loading исчезает;
- кнопка снова активна;
- ошибка отображается;
- повторная попытка возможна.
D. Роли
Проверить создание/изменение/удаление.
E. Модули
Проверить операции подключения/синхронизации, если они доступны
в текущем UI.
============================================================
14. КРИТЕРИИ ПРИЁМКИ
[ ] mutation-операции имеют явный loading state;
[ ] пользователь видит, что операция выполняется;
[ ] кнопка блокируется во время выполнения;
[ ] повторный click не создаёт второй request;
[ ] повторный submit формы не создаёт второй request;
[ ] после success loading сбрасывается;
[ ] после error loading сбрасывается;
[ ] после error пользователь может повторить операцию;
[ ] актуальное состояние данных отображается после success;
[ ] используется единый/переиспользуемый подход там, где это разумно;
[ ] существующий UI/стили Platform сохранены;
[ ] backend и API-контракты без необходимости не изменялись.
============================================================
15. ОТЧЁТ
Добавить результаты в:
dev-doc/implementation_report_005.md
Отдельный новый implementation report не создавать.
Указать:
- какие mutation-операции были покрыты;
- какой reusable-механизм выбран;
- какие компоненты изменены;
- как предотвращается duplicate submit;
- результаты тестирования;
- известные ограничения.
============================================================
16. GIT
PATCH выполняется в текущей ветке:
feature/modular-platform
Не создавать отдельную ветку.
Не открывать TT-006.
После выполнения:
1. показать изменённые файлы;
2. показать diff;
3. выполнить тестирование;
4. предоставить результаты;
5. дождаться подтверждения владельца проекта;
6. только после подтверждения включить изменения в коммит TT-005.
============================================================
17. ГЛАВНЫЙ КРИТЕРИЙ
Пользователь никогда не должен оставаться в ситуации:
"Я нажал кнопку — что-то происходит или нет?"
После нажатия на операцию изменения данных интерфейс должен
однозначно показать:
операция принята
операция выполняется
повторное действие временно недоступно
а после завершения:
операция успешно выполнена
или:
операция завершилась ошибкой, можно повторить.
+34
View File
@@ -17,10 +17,43 @@ router = APIRouter(prefix="/auth", tags=["Auth"])
def _build_user_response(user: User, db: Session) -> dict:
global_roles = [ur.role.name for ur in user.user_roles if ur.role]
mod_roles = {}
# Collect permissions from global roles
permissions = set()
for ur in user.user_roles:
if ur.role:
# Map role names to permissions
role = ur.role
if role.name == "platform_admin":
permissions.update([
"platform.dashboard.read",
"platform.users.read",
"platform.users.write",
"platform.roles.read",
"platform.roles.write",
"platform.modules.read",
"platform.modules.write",
])
elif role.name == "user_manager":
permissions.update([
"platform.users.read",
"platform.users.write",
])
# Collect module roles
for umr in user.user_module_roles:
if umr.module_role and umr.module_role.module:
slug = umr.module_role.module.slug
mod_roles.setdefault(slug, []).append(umr.module_role.role_name)
# Add module permissions based on role
role_name = umr.module_role.role_name
if role_name == "admin":
permissions.update([f"{slug}.read", f"{slug}.write", f"{slug}.delete"])
elif role_name in ("support_agent", "manager"):
permissions.update([f"{slug}.read", f"{slug}.write"])
elif role_name == "customer":
permissions.add(f"{slug}.read")
return {
"id": user.id,
"email": user.email,
@@ -30,6 +63,7 @@ def _build_user_response(user: User, db: Session) -> dict:
"is_superadmin": user.is_superadmin,
"roles": global_roles,
"module_roles": mod_roles,
"permissions": list(permissions),
}
-24
View File
@@ -1,24 +0,0 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
node_modules
dist
dist-ssr
*.local
# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
-8
View File
@@ -1,8 +0,0 @@
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
-32
View File
@@ -1,32 +0,0 @@
# React + TypeScript + Vite
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
Currently, two official plugins are available:
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
## React Compiler
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
## Expanding the Oxlint configuration
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
```json
{
"$schema": "./node_modules/oxlint/configuration_schema.json",
"plugins": ["react", "typescript", "oxc"],
"options": {
"typeAware": true
},
"rules": {
"react/rules-of-hooks": "error",
"react/only-export-components": ["warn", { "allowConstantExport": true }]
}
}
```
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
-13
View File
@@ -1,13 +0,0 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>frontend-user</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
File diff suppressed because it is too large Load Diff
-30
View File
@@ -1,30 +0,0 @@
{
"name": "frontend-user",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "oxlint",
"preview": "vite preview"
},
"dependencies": {
"@tailwindcss/vite": "^4.3.3",
"axios": "^1.19.0",
"lucide-react": "^1.28.0",
"react": "^19.2.8",
"react-dom": "^19.2.8",
"react-router-dom": "^7.18.2",
"tailwindcss": "^4.3.3"
},
"devDependencies": {
"@types/node": "^24.13.3",
"@types/react": "^19.2.17",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.4",
"oxlint": "^1.75.0",
"typescript": "~6.0.2",
"vite": "^8.2.0"
}
}
File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 9.3 KiB

-24
View File
@@ -1,24 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg">
<symbol id="bluesky-icon" viewBox="0 0 16 17">
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
</symbol>
<symbol id="discord-icon" viewBox="0 0 20 19">
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
</symbol>
<symbol id="documentation-icon" viewBox="0 0 21 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
</symbol>
<symbol id="github-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
</symbol>
<symbol id="social-icon" viewBox="0 0 20 20">
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
</symbol>
<symbol id="x-icon" viewBox="0 0 19 19">
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
</symbol>
</svg>

Before

Width:  |  Height:  |  Size: 4.9 KiB

-184
View File
@@ -1,184 +0,0 @@
.counter {
font-size: 16px;
padding: 5px 10px;
border-radius: 5px;
color: var(--accent);
background: var(--accent-bg);
border: 2px solid transparent;
transition: border-color 0.3s;
margin-bottom: 24px;
&:hover {
border-color: var(--accent-border);
}
&:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 2px;
}
}
.hero {
position: relative;
.base,
.framework,
.vite {
inset-inline: 0;
margin: 0 auto;
}
.base {
width: 170px;
position: relative;
z-index: 0;
}
.framework,
.vite {
position: absolute;
}
.framework {
z-index: 1;
top: 34px;
height: 28px;
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
scale(1.4);
}
.vite {
z-index: 0;
top: 107px;
height: 26px;
width: auto;
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
scale(0.8);
}
}
#center {
display: flex;
flex-direction: column;
gap: 25px;
place-content: center;
place-items: center;
flex-grow: 1;
@media (max-width: 1024px) {
padding: 32px 20px 24px;
gap: 18px;
}
}
#next-steps {
display: flex;
border-top: 1px solid var(--border);
text-align: left;
& > div {
flex: 1 1 0;
padding: 32px;
@media (max-width: 1024px) {
padding: 24px 20px;
}
}
.icon {
margin-bottom: 16px;
width: 22px;
height: 22px;
}
@media (max-width: 1024px) {
flex-direction: column;
text-align: center;
}
}
#docs {
border-right: 1px solid var(--border);
@media (max-width: 1024px) {
border-right: none;
border-bottom: 1px solid var(--border);
}
}
#next-steps ul {
list-style: none;
padding: 0;
display: flex;
gap: 8px;
margin: 32px 0 0;
.logo {
height: 18px;
}
a {
color: var(--text-h);
font-size: 16px;
border-radius: 6px;
background: var(--social-bg);
display: flex;
padding: 6px 12px;
align-items: center;
gap: 8px;
text-decoration: none;
transition: box-shadow 0.3s;
&:hover {
box-shadow: var(--shadow);
}
.button-icon {
height: 18px;
width: 18px;
}
}
@media (max-width: 1024px) {
margin-top: 20px;
flex-wrap: wrap;
justify-content: center;
li {
flex: 1 1 calc(50% - 8px);
}
a {
width: 100%;
justify-content: center;
box-sizing: border-box;
}
}
}
#spacer {
height: 88px;
border-top: 1px solid var(--border);
@media (max-width: 1024px) {
height: 48px;
}
}
.ticks {
position: relative;
width: 100%;
&::before,
&::after {
content: '';
position: absolute;
top: -4.5px;
border: 5px solid transparent;
}
&::before {
left: 0;
border-left-color: var(--border);
}
&::after {
right: 0;
border-right-color: var(--border);
}
}
-29
View File
@@ -1,29 +0,0 @@
import { Routes, Route, Navigate } from 'react-router-dom'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import Layout from './components/Layout'
import Login from './pages/Login'
import Register from './pages/Register'
import Dashboard from './pages/Dashboard'
import ModuleView from './pages/ModuleView'
function ProtectedRoute({ children }: { children: React.ReactNode }) {
const { user, loading } = useAuth()
if (loading) return <div className="flex items-center justify-center h-screen">Загрузка...</div>
if (!user) return <Navigate to="/login" />
return <>{children}</>
}
export default function App() {
return (
<AuthProvider>
<Routes>
<Route path="/login" element={<Login />} />
<Route path="/register" element={<Register />} />
<Route path="/" element={<ProtectedRoute><Layout /></ProtectedRoute>}>
<Route index element={<Dashboard />} />
<Route path="module/:id" element={<ModuleView />} />
</Route>
</Routes>
</AuthProvider>
)
}
-32
View File
@@ -1,32 +0,0 @@
import axios from 'axios'
const api = axios.create({ baseURL: '/api/v1' })
api.interceptors.request.use((config) => {
const token = localStorage.getItem('platform_token')
if (token) config.headers.Authorization = `Bearer ${token}`
return config
})
api.interceptors.response.use(
(r) => r,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('platform_token')
window.location.href = '/login'
}
return Promise.reject(error)
}
)
export const authApi = {
login: (data: { email: string; password: string }) => api.post('/auth/login', data),
register: (data: { email: string; password: string; first_name: string; last_name: string }) => api.post('/auth/register', data),
me: () => api.get('/auth/me'),
}
export const modulesApi = {
list: () => api.get('/platform/modules'),
}
export default api
Binary file not shown.

Before

Width:  |  Height:  |  Size: 13 KiB

@@ -1 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>

Before

Width:  |  Height:  |  Size: 4.0 KiB

File diff suppressed because one or more lines are too long

Before

Width:  |  Height:  |  Size: 8.5 KiB

@@ -1,66 +0,0 @@
import { useState, useEffect } from 'react'
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { modulesApi } from '../api/client'
import { Package, LogOut } from 'lucide-react'
export default function Layout() {
const { logout } = useAuth()
const location = useLocation()
const navigate = useNavigate()
const [modules, setModules] = useState<any[]>([])
const isModuleView = location.pathname.startsWith('/module/')
useEffect(() => {
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
}, [])
const handleLogout = () => { logout(); navigate('/login') }
return (
<div className="flex flex-col h-screen bg-gray-100">
{/* Top header */}
<header className="bg-white shadow-sm flex-shrink-0">
<div className="flex items-center justify-between h-12 px-4">
{/* Left: logo + home */}
<div className="flex items-center gap-6">
<Link to="/" className="text-lg font-bold text-gray-800 whitespace-nowrap">Платформа</Link>
<Link to="/"
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname === '/' ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
Мои модули
</Link>
</div>
{/* Center: module tabs */}
{modules.length > 0 && (
<div className="flex items-center gap-1">
{modules.map(mod => (
<Link key={mod.id} to={`/module/${mod.id}`}
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${location.pathname === `/module/${mod.id}` ? 'bg-blue-600 text-white font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
<Package className="w-3.5 h-3.5" />{mod.name}
</Link>
))}
</div>
)}
{/* Right: logout */}
<button onClick={handleLogout} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-md">
<LogOut className="w-4 h-4" />Выход
</button>
</div>
</header>
{/* Content */}
<div className="flex-1 flex flex-col min-w-0 overflow-hidden">
{isModuleView ? (
<Outlet />
) : (
<div className="flex-1 overflow-auto p-6">
<Outlet />
</div>
)}
</div>
</div>
)
}
@@ -1,62 +0,0 @@
import { createContext, useContext, useState, useEffect } from 'react'
import type { ReactNode } from 'react'
import { authApi } from '../api/client'
interface User {
id: number
email: string
first_name: string
last_name: string
is_active: boolean
roles: string[]
module_roles: Record<string, string[]>
}
interface AuthContextType {
user: User | null
loading: boolean
login: (email: string, password: string) => Promise<void>
logout: () => void
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
export function AuthProvider({ children }: { children: ReactNode }) {
const [user, setUser] = useState<User | null>(null)
const [loading, setLoading] = useState(true)
useEffect(() => {
const token = localStorage.getItem('platform_token')
if (token) {
authApi.me()
.then(res => setUser(res.data))
.catch(() => localStorage.removeItem('platform_token'))
.finally(() => setLoading(false))
} else {
setLoading(false)
}
}, [])
const login = async (email: string, password: string) => {
const res = await authApi.login({ email, password })
localStorage.setItem('platform_token', res.data.access_token)
setUser(res.data.user)
}
const logout = () => {
localStorage.removeItem('platform_token')
setUser(null)
}
return (
<AuthContext.Provider value={{ user, loading, login, logout }}>
{children}
</AuthContext.Provider>
)
}
export function useAuth() {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error('useAuth must be inside AuthProvider')
return ctx
}
-1
View File
@@ -1 +0,0 @@
@import "tailwindcss";
-13
View File
@@ -1,13 +0,0 @@
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'
import './index.css'
createRoot(document.getElementById('root')!).render(
<StrictMode>
<BrowserRouter>
<App />
</BrowserRouter>
</StrictMode>,
)
@@ -1,58 +0,0 @@
import { useState, useEffect } from 'react'
import { Link } from 'react-router-dom'
import { modulesApi } from '../api/client'
import { useAuth } from '../contexts/AuthContext'
import { Package, ExternalLink } from 'lucide-react'
export default function Dashboard() {
const { user } = useAuth()
const [modules, setModules] = useState<any[]>([])
useEffect(() => {
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
}, [])
return (
<div>
<h1 className="text-2xl font-bold text-gray-900 mb-2">Добро пожаловать, {user?.first_name}!</h1>
<p className="text-gray-500 mb-8">Выберите модуль для работы</p>
{modules.length === 0 ? (
<div className="bg-white rounded-lg shadow p-8 text-center">
<Package className="w-12 h-12 text-gray-300 mx-auto mb-4" />
<p className="text-gray-500">Нет доступных модулей</p>
<p className="text-sm text-gray-400 mt-1">Обратитесь к администратору для подключения модулей</p>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
{modules.map(mod => {
const userRoles = user?.module_roles?.[mod.id] || []
return (
<Link key={mod.id} to={`/module/${mod.id}`}
className="bg-white rounded-lg shadow hover:shadow-md transition-shadow p-6 group">
<div className="flex items-start justify-between mb-4">
<div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
<Package className="w-6 h-6 text-blue-600" />
</div>
<ExternalLink className="w-4 h-4 text-gray-400 group-hover:text-blue-600 transition-colors" />
</div>
<h3 className="font-semibold text-lg text-gray-900 mb-1">{mod.name}</h3>
<p className="text-sm text-gray-500 mb-3">{mod.description || 'Без описания'}</p>
{userRoles.length > 0 && (
<div className="flex gap-1 flex-wrap">
{userRoles.map((r: string) => (
<span key={r} className="px-2 py-0.5 text-xs bg-green-100 text-green-800 rounded-full">{r}</span>
))}
</div>
)}
{userRoles.length === 0 && (
<span className="text-xs text-gray-400">Нет ролей в модуле</span>
)}
</Link>
)
})}
</div>
)}
</div>
)
}
@@ -1,52 +0,0 @@
import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
export default function Login() {
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const { login } = useAuth()
const navigate = useNavigate()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
await login(email, password)
navigate('/')
} catch (err: any) {
setError(err.response?.data?.detail || 'Ошибка входа')
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
<h2 className="text-lg text-gray-600 text-center mb-8">Войдите в аккаунт</h2>
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
<form onSubmit={handleSubmit} className="space-y-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
<input type="email" value={email} onChange={e => setEmail(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
<input type="password" value={password} onChange={e => setPassword(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
</div>
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
{loading ? 'Вход...' : 'Войти'}
</button>
</form>
<p className="mt-4 text-center text-sm text-gray-600">
Нет аккаунта? <Link to="/register" className="text-blue-600 hover:underline">Регистрация</Link>
</p>
</div>
</div>
)
}
@@ -1,142 +0,0 @@
import { useState, useEffect, useRef } from 'react'
import { useParams } from 'react-router-dom'
import { modulesApi } from '../api/client'
import { ExternalLink, Loader2 } from 'lucide-react'
const isDev = import.meta.env.DEV
function getModuleFrontend(module: any): string | null {
if (!module.frontend) return null
const url = isDev ? module.frontend.dev_url : module.frontend.prod_path
return url || null
}
export default function ModuleView() {
const { id } = useParams()
const [module, setModule] = useState<any>(null)
const [loading, setLoading] = useState(true)
const [iframeLoading, setIframeLoading] = useState(true)
const [moduleUrl, setModuleUrl] = useState('')
const [error, setError] = useState('')
const iframeRef = useRef<HTMLIFrameElement>(null)
useEffect(() => {
modulesApi.list().then(res => {
const found = res.data.find((m: any) => String(m.id) === String(id))
setModule(found)
}).catch(() => setError('Ошибка загрузки модулей'))
.finally(() => setLoading(false))
}, [id])
useEffect(() => {
if (!module) return
const frontendUrl = getModuleFrontend(module)
if (!frontendUrl) {
setError('Фронтенд модуля не настроен')
return
}
const getToken = () => localStorage.getItem('platform_token') || ''
const updateUrl = () => {
const token = getToken()
const url = `${frontendUrl}?token=${encodeURIComponent(token)}`
setModuleUrl(url)
}
const sendTokenToIframe = () => {
const token = getToken()
const iframe = iframeRef.current
if (iframe?.contentWindow) {
iframe.contentWindow.postMessage(
{ type: 'PLATFORM_TOKEN_UPDATE', token },
'*'
)
}
}
updateUrl()
const handleStorage = (e: StorageEvent) => {
if (e.key === 'platform_token') {
updateUrl()
sendTokenToIframe()
}
}
window.addEventListener('storage', handleStorage)
let lastToken = getToken()
const interval = setInterval(() => {
const currentToken = getToken()
if (currentToken !== lastToken) {
lastToken = currentToken
updateUrl()
sendTokenToIframe()
}
}, 10000)
return () => {
window.removeEventListener('storage', handleStorage)
clearInterval(interval)
}
}, [module])
useEffect(() => {
setIframeLoading(true)
}, [id])
if (loading) return (
<div className="flex-1 flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
</div>
)
if (error) return (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
<p className="text-red-500 mb-2">{error}</p>
<p className="text-sm text-gray-400">Модуль: {id}</p>
</div>
</div>
)
if (!module) return (
<div className="flex-1 flex items-center justify-center">
<p className="text-gray-500">Модуль не найден</p>
</div>
)
return (
<div className="flex-1 flex flex-col h-full">
<div className="flex items-center justify-between px-6 py-3 bg-white border-b flex-shrink-0">
<h1 className="text-lg font-semibold text-gray-900">{module.name}</h1>
{moduleUrl && (
<a href={moduleUrl} target="_blank" rel="noopener noreferrer"
className="flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800">
<ExternalLink className="w-4 h-4" />Открыть отдельно
</a>
)}
</div>
<div className="flex-1 relative">
{iframeLoading && (
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 z-10">
<div className="text-center">
<Loader2 className="w-8 h-8 animate-spin text-blue-500 mx-auto mb-2" />
<p className="text-sm text-gray-500">Загрузка модуля...</p>
</div>
</div>
)}
{moduleUrl && (
<iframe
ref={iframeRef}
src={moduleUrl}
className="w-full h-full border-0"
title={module.name}
onLoad={() => setIframeLoading(false)}
/>
)}
</div>
</div>
)
}
@@ -1,60 +0,0 @@
import { useState } from 'react'
import { useNavigate, Link } from 'react-router-dom'
import { authApi } from '../api/client'
export default function Register() {
const [form, setForm] = useState({ email: '', password: '', first_name: '', last_name: '' })
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const navigate = useNavigate()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
await authApi.register(form)
navigate('/login')
} catch (err: any) {
setError(err.response?.data?.detail || 'Ошибка регистрации')
} finally {
setLoading(false)
}
}
return (
<div className="min-h-screen flex items-center justify-center bg-gray-100">
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
<h2 className="text-lg text-gray-600 text-center mb-8">Регистрация</h2>
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
<form onSubmit={handleSubmit} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
<input type="text" value={form.first_name} onChange={e => setForm({...form, first_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
<input type="text" value={form.last_name} onChange={e => setForm({...form, last_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
<input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
<input type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required minLength={6} />
</div>
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
</button>
</form>
<p className="mt-4 text-center text-sm text-gray-600">
Уже есть аккаунт? <Link to="/login" className="text-blue-600 hover:underline">Войти</Link>
</p>
</div>
</div>
)
}
-26
View File
@@ -1,26 +0,0 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023", "DOM"],
"module": "esnext",
"types": ["vite/client"],
"allowArbitraryExtensions": true,
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"]
}
-7
View File
@@ -1,7 +0,0 @@
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
-23
View File
@@ -1,23 +0,0 @@
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "es2023",
"lib": ["ES2023"],
"types": ["node"],
"skipLibCheck": true,
/* Bundler mode */
"module": "nodenext",
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"noUnusedLocals": true,
"noUnusedParameters": true,
"erasableSyntaxOnly": true,
"noFallthroughCasesInSwitch": true
},
"include": ["vite.config.ts"]
}
-13
View File
@@ -1,13 +0,0 @@
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'
import tailwindcss from '@tailwindcss/vite'
export default defineConfig({
plugins: [react(), tailwindcss()],
server: {
port: 5175,
proxy: {
'/api': 'http://localhost:8000',
},
},
})
+16 -3
View File
@@ -1,6 +1,7 @@
import { Routes, Route, Navigate } from 'react-router-dom'
import { AuthProvider, useAuth } from './contexts/AuthContext'
import Layout from './components/Layout'
import PermissionGuard from './components/PermissionGuard'
import Login from './pages/Login'
import Register from './pages/Register'
import Dashboard from './pages/Dashboard'
@@ -24,9 +25,21 @@ export default function App() {
<Route path="/register" element={<Register />} />
<Route path="/" element={<ProtectedRoute><Layout /></ProtectedRoute>}>
<Route index element={<Dashboard />} />
<Route path="users" element={<Users />} />
<Route path="roles" element={<Roles />} />
<Route path="modules" element={<Modules />} />
<Route path="users" element={
<PermissionGuard permission="platform.users.read">
<Users />
</PermissionGuard>
} />
<Route path="roles" element={
<PermissionGuard permission="platform.roles.read">
<Roles />
</PermissionGuard>
} />
<Route path="modules" element={
<PermissionGuard permission="platform.modules.read">
<Modules />
</PermissionGuard>
} />
<Route path="module/:id" element={<ModuleView />} />
</Route>
</Routes>
+73 -33
View File
@@ -2,23 +2,52 @@ import { useState, useEffect } from 'react'
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { modulesApi } from '../api/client'
import { Package, LogOut } from 'lucide-react'
import { Package, LogOut, LayoutDashboard, Users, Key, Puzzle } from 'lucide-react'
interface NavItem {
label: string
path: string
icon: any
permission?: string
}
const navigation: NavItem[] = [
{ label: 'Панель', path: '/', icon: LayoutDashboard, permission: 'platform.dashboard.read' },
{ label: 'Пользователи', path: '/users', icon: Users, permission: 'platform.users.read' },
{ label: 'Роли', path: '/roles', icon: Key, permission: 'platform.roles.read' },
{ label: 'Модули', path: '/modules', icon: Puzzle, permission: 'platform.modules.read' },
]
export default function Layout() {
const { user, logout } = useAuth()
const { user, logout, hasPermission } = useAuth()
const location = useLocation()
const navigate = useNavigate()
const [modules, setModules] = useState<any[]>([])
const isAdmin = user?.is_superadmin || user?.roles?.includes('platform_admin')
const isModuleView = location.pathname.startsWith('/module/')
useEffect(() => {
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
modulesApi.list()
.then(res => {
const activeModules = res.data.filter((m: any) => m.is_active)
setModules(activeModules)
})
.catch(() => {})
}, [])
const handleLogout = () => { logout(); navigate('/login') }
// Filter navigation items based on permissions
const visibleNav = navigation.filter(item =>
!item.permission || hasPermission(item.permission)
)
// Filter modules based on permissions
const visibleModules = modules.filter(mod => {
// Check if user has at least read permission for the module
return hasPermission(`${mod.id}.read`) || user?.is_superadmin
})
return (
<div className="flex flex-col h-screen bg-gray-100">
{/* Top header */}
@@ -28,45 +57,56 @@ export default function Layout() {
<div className="flex items-center gap-6">
<Link to="/" className="text-lg font-bold text-gray-800 whitespace-nowrap">Платформа</Link>
<nav className="flex items-center gap-1">
<Link to="/"
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname === '/' ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
Панель
</Link>
{isAdmin && (
<>
<Link to="/users"
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/users') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
Пользователи
</Link>
<Link to="/roles"
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/roles') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
Роли
</Link>
<Link to="/modules"
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/modules') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
Модули
</Link>
</>
)}
{visibleNav.map(item => (
<Link
key={item.path}
to={item.path}
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${
location.pathname === item.path
? 'bg-blue-50 text-blue-700 font-medium'
: 'text-gray-600 hover:bg-gray-100'
}`}
>
<item.icon className="w-4 h-4" />
{item.label}
</Link>
))}
</nav>
</div>
{/* Center: module tabs */}
{modules.length > 0 && (
{visibleModules.length > 0 && (
<div className="flex items-center gap-1">
{modules.map(mod => (
<Link key={mod.id} to={`/module/${mod.id}`}
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${location.pathname === `/module/${mod.id}` ? 'bg-blue-600 text-white font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
<Package className="w-3.5 h-3.5" />{mod.name}
{visibleModules.map(mod => (
<Link
key={mod.id}
to={`/module/${mod.id}`}
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${
location.pathname === `/module/${mod.id}`
? 'bg-blue-600 text-white font-medium'
: 'text-gray-600 hover:bg-gray-100'
}`}
>
<Package className="w-3.5 h-3.5" />
{mod.name}
</Link>
))}
</div>
)}
{/* Right: logout */}
<button onClick={handleLogout} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-md">
<LogOut className="w-4 h-4" />Выход
</button>
{/* Right: user info + logout */}
<div className="flex items-center gap-3">
<div className="text-right">
<p className="text-sm font-medium text-gray-700">{user?.first_name} {user?.last_name}</p>
<p className="text-xs text-gray-500">{user?.email}</p>
</div>
<button
onClick={handleLogout}
className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-md"
>
<LogOut className="w-4 h-4" />Выход
</button>
</div>
</div>
</header>
@@ -0,0 +1,79 @@
import type { ReactNode } from 'react'
import { Navigate } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
interface PermissionGuardProps {
children: ReactNode
permission?: string
permissions?: string[]
requireAll?: boolean
fallback?: ReactNode
}
/**
* Guard component that checks user permissions before rendering children.
*
* Usage:
* <PermissionGuard permission="platform.users.read">
* <UsersPage />
* </PermissionGuard>
*
* <PermissionGuard permissions={["platform.users.read", "platform.users.write"]} requireAll>
* <UsersEditPage />
* </PermissionGuard>
*/
export default function PermissionGuard({
children,
permission,
permissions,
requireAll = false,
fallback,
}: PermissionGuardProps) {
const { user, loading, hasPermission, hasAnyPermission } = useAuth()
if (loading) {
return <div className="flex items-center justify-center h-screen">Загрузка...</div>
}
if (!user) {
return <Navigate to="/login" />
}
// Check single permission
if (permission && !hasPermission(permission)) {
if (fallback) return <>{fallback}</>
return (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<h2 className="text-2xl font-bold text-gray-900 mb-2">403</h2>
<p className="text-gray-500">Нет прав доступа</p>
<p className="text-sm text-gray-400 mt-1">Требуется: {permission}</p>
</div>
</div>
)
}
// Check multiple permissions
if (permissions && permissions.length > 0) {
const hasAccess = requireAll
? permissions.every(p => hasPermission(p))
: hasAnyPermission(permissions)
if (!hasAccess) {
if (fallback) return <>{fallback}</>
return (
<div className="flex items-center justify-center h-full">
<div className="text-center">
<h2 className="text-2xl font-bold text-gray-900 mb-2">403</h2>
<p className="text-gray-500">Нет прав доступа</p>
<p className="text-sm text-gray-400 mt-1">
Требуется: {permissions.join(requireAll ? ' + ' : ' или ')}
</p>
</div>
</div>
)
}
}
return <>{children}</>
}
+17 -2
View File
@@ -1,4 +1,4 @@
import { createContext, useContext, useState, useEffect } from 'react'
import { createContext, useContext, useState, useEffect, useCallback } from 'react'
import type { ReactNode } from 'react'
import { authApi } from '../api/client'
@@ -11,6 +11,7 @@ interface User {
is_superadmin: boolean
roles: string[]
module_roles: Record<string, string[]>
permissions: string[]
}
interface AuthContextType {
@@ -18,6 +19,8 @@ interface AuthContextType {
loading: boolean
login: (email: string, password: string) => Promise<void>
logout: () => void
hasPermission: (permission: string) => boolean
hasAnyPermission: (permissions: string[]) => boolean
}
const AuthContext = createContext<AuthContextType | undefined>(undefined)
@@ -49,8 +52,20 @@ export function AuthProvider({ children }: { children: ReactNode }) {
setUser(null)
}
const hasPermission = useCallback((permission: string): boolean => {
if (!user) return false
if (user.is_superadmin) return true
return user.permissions?.includes(permission) ?? false
}, [user])
const hasAnyPermission = useCallback((permissions: string[]): boolean => {
if (!user) return false
if (user.is_superadmin) return true
return permissions.some(p => user.permissions?.includes(p) ?? false)
}, [user])
return (
<AuthContext.Provider value={{ user, loading, login, logout }}>
<AuthContext.Provider value={{ user, loading, login, logout, hasPermission, hasAnyPermission }}>
{children}
</AuthContext.Provider>
)
@@ -0,0 +1,37 @@
import { useState, useCallback } from 'react'
/**
* Hook for managing async operations with loading state and duplicate-action protection.
*
* Usage:
* const { loading, execute } = useAsyncAction()
*
* const handleDelete = async () => {
* await execute(async () => {
* await usersApi.delete(userId)
* fetchUsers()
* })
* }
*
* <button onClick={handleDelete} disabled={loading}>
* {loading ? 'Удаление...' : 'Удалить'}
* </button>
*/
export function useAsyncAction() {
const [loading, setLoading] = useState(false)
const execute = useCallback(async (action: () => Promise<void>): Promise<boolean> => {
if (loading) return false
setLoading(true)
try {
await action()
return true
} catch (error) {
throw error
} finally {
setLoading(false)
}
}, [loading])
return { loading, execute }
}
+27 -13
View File
@@ -1,14 +1,11 @@
import { useState, useEffect, useRef } from 'react'
import { useParams } from 'react-router-dom'
import { useAuth } from '../contexts/AuthContext'
import { modulesApi } from '../api/client'
import { ExternalLink, Loader2 } from 'lucide-react'
const isDev = import.meta.env.DEV
/**
* Get the frontend URL for a module based on environment.
* Returns null if frontend info is not available.
*/
function getModuleFrontend(module: any): string | null {
if (!module.frontend) return null
const url = isDev ? module.frontend.dev_url : module.frontend.prod_path
@@ -17,6 +14,7 @@ function getModuleFrontend(module: any): string | null {
export default function ModuleView() {
const { id } = useParams()
const { hasPermission, loading: authLoading } = useAuth()
const [module, setModule] = useState<any>(null)
const [loading, setLoading] = useState(true)
const [iframeLoading, setIframeLoading] = useState(true)
@@ -32,8 +30,11 @@ export default function ModuleView() {
.finally(() => setLoading(false))
}, [id])
// Permission check
const hasAccess = module ? hasPermission(`${module.id}.read`) : false
useEffect(() => {
if (!module) return
if (!module || !hasAccess) return
const frontendUrl = getModuleFrontend(module)
if (!frontendUrl) {
@@ -84,18 +85,37 @@ export default function ModuleView() {
window.removeEventListener('storage', handleStorage)
clearInterval(interval)
}
}, [module])
}, [module, hasAccess])
useEffect(() => {
setIframeLoading(true)
}, [id])
if (loading) return (
if (loading || authLoading) return (
<div className="flex-1 flex items-center justify-center">
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
</div>
)
if (!module) return (
<div className="flex-1 flex items-center justify-center">
<p className="text-gray-500">Модуль не найден</p>
</div>
)
// Permission check - show 403 if no access
if (!hasAccess) {
return (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
<h2 className="text-2xl font-bold text-gray-900 mb-2">403</h2>
<p className="text-gray-500">Нет прав доступа к модулю</p>
<p className="text-sm text-gray-400 mt-1">Требуется: {module.id}.read</p>
</div>
</div>
)
}
if (error) return (
<div className="flex-1 flex items-center justify-center">
<div className="text-center">
@@ -105,12 +125,6 @@ export default function ModuleView() {
</div>
)
if (!module) return (
<div className="flex-1 flex items-center justify-center">
<p className="text-gray-500">Модуль не найден</p>
</div>
)
return (
<div className="flex-1 flex flex-col h-full">
<div className="flex items-center justify-between px-6 py-3 bg-white border-b flex-shrink-0">
+70 -199
View File
@@ -1,7 +1,7 @@
import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { modulesApi } from '../api/client'
import { Plus, RefreshCw, Trash2, ExternalLink, Key } from 'lucide-react'
import { Plus, RefreshCw, Trash2, ExternalLink, Key, Loader2 } from 'lucide-react'
export default function Modules() {
const navigate = useNavigate()
@@ -16,65 +16,64 @@ export default function Modules() {
icon: 'Package',
})
const [error, setError] = useState('')
const [creating, setCreating] = useState(false)
const [syncingId, setSyncingId] = useState<number | null>(null)
const [syncResult, setSyncResult] = useState('')
const [deletingId, setDeletingId] = useState<number | null>(null)
const [expandedRoles, setExpandedRoles] = useState<number | null>(null)
const [moduleRoles, setModuleRoles] = useState<any[]>([])
const fetchModules = () => {
modulesApi
.list()
.then(res => setModules(res.data))
.catch(() => {})
modulesApi.list().then(res => setModules(res.data)).catch(() => {})
}
useEffect(() => {
fetchModules()
}, [])
useEffect(() => { fetchModules() }, [])
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault()
if (creating) return
setError('')
setCreating(true)
try {
const res = await modulesApi.create(form)
setForm({
name: '',
slug: '',
url: '',
description: '',
icon: 'Package',
})
setForm({ name: '', slug: '', url: '', description: '', icon: 'Package' })
setShowForm(false)
fetchModules()
alert(
`Модуль создан. API Key: ${res.data.api_key}\nСохраните его — он нужен для настройки модуля.`
)
alert(`Модуль создан. API Key: ${res.data.api_key}\nСохраните его — он нужен для настройки модуля.`)
} catch (err: any) {
setError(err.response?.data?.detail || 'Ошибка')
} finally {
setCreating(false)
}
}
const handleSync = async (id: number) => {
if (syncingId) return
setSyncResult('')
setSyncingId(id)
try {
const res = await modulesApi.syncRoles(id)
setSyncResult(`Импортировано: ${res.data.message}`)
fetchModules()
} catch (err: any) {
setSyncResult(`Ошибка: ${err.response?.data?.detail || err.message}`)
} finally {
setSyncingId(null)
}
}
const handleDelete = async (id: number) => {
if (!confirm('Отключить модуль?')) return
await modulesApi.delete(id)
fetchModules()
if (deletingId) return
setDeletingId(id)
try {
await modulesApi.delete(id)
fetchModules()
} catch (err: any) {
alert(err.response?.data?.detail || 'Ошибка удаления')
} finally {
setDeletingId(null)
}
}
const toggleRoles = async (moduleId: number) => {
@@ -83,34 +82,20 @@ export default function Modules() {
setModuleRoles([])
} else {
setExpandedRoles(moduleId)
modulesApi
.getRoles(moduleId)
.then(res => setModuleRoles(res.data))
.catch(() => {})
modulesApi.getRoles(moduleId).then(res => setModuleRoles(res.data)).catch(() => {})
}
}
const handleOpenModule = (slug: string) => {
if (!slug) {
setError('У модуля отсутствует slug')
return
}
navigate(`/module/${slug}`)
const handleOpenModule = (id: string) => {
navigate(`/module/${id}`)
}
return (
<div>
<div className="flex items-center justify-between mb-6">
<h1 className="text-2xl font-bold text-gray-900">Модули</h1>
<button
onClick={() => setShowForm(!showForm)}
className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700"
>
<Plus className="w-4 h-4 mr-2" />
Подключить
<button onClick={() => setShowForm(!showForm)} className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
<Plus className="w-4 h-4 mr-2" />Подключить
</button>
</div>
@@ -119,196 +104,82 @@ export default function Modules() {
<form onSubmit={handleCreate} className="space-y-4">
<div className="grid grid-cols-2 gap-4">
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Название
</label>
<input
type="text"
value={form.name}
onChange={e =>
setForm({
...form,
name: e.target.value,
})
}
required
placeholder="Service Desk"
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<label className="block text-sm font-medium text-gray-700 mb-1">Название</label>
<input type="text" value={form.name} onChange={e => setForm({...form, name: e.target.value})} required placeholder="Service Desk"
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Slug
</label>
<input
type="text"
value={form.slug}
onChange={e =>
setForm({
...form,
slug: e.target.value,
})
}
required
placeholder="service-desk"
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<label className="block text-sm font-medium text-gray-700 mb-1">Slug</label>
<input type="text" value={form.slug} onChange={e => setForm({...form, slug: e.target.value})} required placeholder="service-desk"
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
</div>
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
URL
</label>
<input
type="text"
value={form.url}
onChange={e =>
setForm({
...form,
url: e.target.value,
})
}
required
placeholder="http://localhost:8000"
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<label className="block text-sm font-medium text-gray-700 mb-1">URL</label>
<input type="text" value={form.url} onChange={e => setForm({...form, url: e.target.value})} required placeholder="http://localhost:8000"
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
</div>
<div>
<label className="block text-sm font-medium text-gray-700 mb-1">
Описание
</label>
<input
type="text"
value={form.description}
onChange={e =>
setForm({
...form,
description: e.target.value,
})
}
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
/>
<label className="block text-sm font-medium text-gray-700 mb-1">Описание</label>
<input type="text" value={form.description} onChange={e => setForm({...form, description: e.target.value})}
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
</div>
<div className="flex gap-2">
<button
type="submit"
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700"
>
Подключить
</button>
<button
type="button"
onClick={() => setShowForm(false)}
className="px-4 py-2 border rounded-lg hover:bg-gray-100"
>
Отмена
<button type="submit" disabled={creating}
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center gap-2">
{creating && <Loader2 className="w-4 h-4 animate-spin" />}
{creating ? 'Подключение...' : 'Подключить'}
</button>
<button type="button" onClick={() => setShowForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
</div>
{error && (
<p className="text-red-500 text-sm">
{error}
</p>
)}
{error && <p className="text-red-500 text-sm">{error}</p>}
</form>
</div>
)}
{syncResult && (
<div className="bg-blue-50 text-blue-800 p-3 rounded-lg mb-4 text-sm">
{syncResult}
</div>
<div className="bg-blue-50 text-blue-800 p-3 rounded-lg mb-4 text-sm">{syncResult}</div>
)}
<div className="space-y-4">
{modules.map(mod => (
<div
key={mod.id}
className="bg-white rounded-lg shadow p-4"
>
<div key={mod.id} className="bg-white rounded-lg shadow p-4">
<div className="flex items-center justify-between">
<div>
<h3 className="font-semibold text-lg">
{mod.name}
</h3>
<p className="text-sm text-gray-500">
{mod.description}
</p>
<p className="text-xs text-gray-400 mt-1">
slug: {mod.slug}
{' · '}
ролей: {mod.roles_count ?? 0}
</p>
<h3 className="font-semibold text-lg">{mod.name}</h3>
<p className="text-sm text-gray-500">{mod.description}</p>
<p className="text-xs text-gray-400 mt-1">slug: {mod.slug} · ролей: {mod.roles_count ?? 0}</p>
</div>
<div className="flex gap-2">
<button
onClick={() => toggleRoles(mod.id)}
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50"
title="Роли"
>
<Key className="w-4 h-4" />
Роли
<button onClick={() => toggleRoles(mod.id)}
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50">
<Key className="w-4 h-4" />Роли
</button>
<button
onClick={() => handleSync(mod.id)}
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50"
title="Синхронизировать роли"
>
<RefreshCw className="w-4 h-4" />
Синхронизировать
<button onClick={() => handleSync(mod.id)} disabled={syncingId === mod.id}
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50 disabled:opacity-50">
{syncingId === mod.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <RefreshCw className="w-4 h-4" />}
{syncingId === mod.id ? 'Синхронизация...' : 'Синхронизировать'}
</button>
<button
onClick={() => handleOpenModule(mod.slug)}
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50"
title="Открыть модуль"
>
<ExternalLink className="w-4 h-4" />
Открыть
<button onClick={() => handleOpenModule(mod.id)}
className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50">
<ExternalLink className="w-4 h-4" />Открыть
</button>
<button
onClick={() => handleDelete(mod.id)}
className="flex items-center px-3 py-2 text-sm border rounded-lg hover:bg-red-50 text-red-600"
title="Отключить модуль"
>
<Trash2 className="w-4 h-4" />
<button onClick={() => handleDelete(mod.id)} disabled={deletingId === mod.id}
className="flex items-center px-3 py-2 text-sm border rounded-lg hover:bg-red-50 text-red-600 disabled:opacity-50">
{deletingId === mod.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
</button>
</div>
</div>
{expandedRoles === mod.id && (
<div className="mt-4 pt-4 border-t">
<h4 className="text-sm font-semibold mb-2">
Роли модуля
</h4>
<h4 className="text-sm font-semibold mb-2">Роли модуля</h4>
{moduleRoles.length === 0 ? (
<p className="text-sm text-gray-500">
Нет ролей. Нажмите "Синхронизировать".
</p>
<p className="text-sm text-gray-500">Нет ролей. Нажмите "Синхронизировать".</p>
) : (
<div className="flex gap-2 flex-wrap">
{moduleRoles.map(mr => (
<span
key={mr.id}
className="px-3 py-1 text-sm bg-purple-100 text-purple-800 rounded-full"
>
{mr.role_name}
</span>
<span key={mr.id} className="px-3 py-1 text-sm bg-purple-100 text-purple-800 rounded-full">{mr.role_name}</span>
))}
</div>
)}
+25 -6
View File
@@ -1,19 +1,23 @@
import { useState, useEffect } from 'react'
import { rolesApi } from '../api/client'
import { Plus, Trash2, Lock } from 'lucide-react'
import { Plus, Trash2, Lock, Loader2 } from 'lucide-react'
export default function Roles() {
const [roles, setRoles] = useState<any[]>([])
const [showForm, setShowForm] = useState(false)
const [form, setForm] = useState({ name: '', description: '' })
const [error, setError] = useState('')
const [creating, setCreating] = useState(false)
const [deletingId, setDeletingId] = useState<number | null>(null)
const fetchRoles = () => { rolesApi.list().then(res => setRoles(res.data)).catch(() => {}) }
useEffect(() => { fetchRoles() }, [])
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault()
if (creating) return
setError('')
setCreating(true)
try {
await rolesApi.create(form)
setForm({ name: '', description: '' })
@@ -21,14 +25,24 @@ export default function Roles() {
fetchRoles()
} catch (err: any) {
setError(err.response?.data?.detail || 'Ошибка')
} finally {
setCreating(false)
}
}
const handleDelete = async (id: number, isSystem: boolean) => {
if (isSystem) return
if (!confirm('Удалить роль?')) return
await rolesApi.delete(id)
fetchRoles()
if (deletingId) return
setDeletingId(id)
try {
await rolesApi.delete(id)
fetchRoles()
} catch (err: any) {
alert(err.response?.data?.detail || 'Ошибка удаления')
} finally {
setDeletingId(null)
}
}
return (
@@ -53,7 +67,11 @@ export default function Roles() {
<input type="text" value={form.description} onChange={e => setForm({...form, description: e.target.value})}
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
</div>
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Создать</button>
<button type="submit" disabled={creating}
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center gap-2">
{creating && <Loader2 className="w-4 h-4 animate-spin" />}
{creating ? 'Создание...' : 'Создать'}
</button>
</form>
{error && <p className="text-red-500 text-sm mt-2">{error}</p>}
</div>
@@ -83,8 +101,9 @@ export default function Roles() {
</td>
<td className="px-6 py-4">
{!r.is_system && (
<button onClick={() => handleDelete(r.id, r.is_system)} className="text-red-500 hover:text-red-700">
<Trash2 className="w-4 h-4" />
<button onClick={() => handleDelete(r.id, r.is_system)} disabled={deletingId === r.id}
className="text-red-500 hover:text-red-700 disabled:opacity-50">
{deletingId === r.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
</button>
)}
</td>
+39 -12
View File
@@ -1,6 +1,6 @@
import { useState, useEffect } from 'react'
import { usersApi, rolesApi, modulesApi } from '../api/client'
import { Search, Shield, Package, Plus, Edit, Trash2, X } from 'lucide-react'
import { Search, Shield, Package, Plus, Edit, Trash2, X, Loader2 } from 'lucide-react'
export default function Users() {
const [users, setUsers] = useState<any[]>([])
@@ -17,6 +17,9 @@ export default function Users() {
const [editForm, setEditForm] = useState({ first_name: '', last_name: '', email: '', password: '', is_active: true, is_superadmin: false })
const [createForm, setCreateForm] = useState({ email: '', password: '', first_name: '', last_name: '', is_superadmin: false })
const [error, setError] = useState('')
const [creating, setCreating] = useState(false)
const [saving, setSaving] = useState(false)
const [deletingId, setDeletingId] = useState<number | null>(null)
const pageSize = 20
const fetchUsers = () => {
@@ -65,7 +68,9 @@ export default function Users() {
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault()
if (creating) return
setError('')
setCreating(true)
try {
await usersApi.create(createForm)
setCreateForm({ email: '', password: '', first_name: '', last_name: '', is_superadmin: false })
@@ -73,13 +78,16 @@ export default function Users() {
fetchUsers()
} catch (err: any) {
setError(err.response?.data?.detail || 'Ошибка создания')
} finally {
setCreating(false)
}
}
const handleEdit = async (e: React.FormEvent) => {
e.preventDefault()
if (!selectedUser) return
if (!selectedUser || saving) return
setError('')
setSaving(true)
try {
const data: any = { ...editForm }
if (!data.password) delete data.password
@@ -90,15 +98,25 @@ export default function Users() {
setSelectedUser(res.data)
} catch (err: any) {
setError(err.response?.data?.detail || 'Ошибка обновления')
} finally {
setSaving(false)
}
}
const handleDelete = async (userId: number) => {
if (!confirm('Удалить пользователя? Это действие нельзя отменить.')) return
await usersApi.delete(userId)
fetchUsers()
if (selectedUser?.id === userId) {
setSelectedUser(null)
if (deletingId) return
setDeletingId(userId)
try {
await usersApi.delete(userId)
fetchUsers()
if (selectedUser?.id === userId) {
setSelectedUser(null)
}
} catch (err: any) {
alert(err.response?.data?.detail || 'Ошибка удаления')
} finally {
setDeletingId(null)
}
}
@@ -160,7 +178,11 @@ export default function Users() {
</label>
{error && <p className="text-red-500 text-sm">{error}</p>}
<div className="flex gap-2">
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Создать</button>
<button type="submit" disabled={creating}
className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700 disabled:opacity-50 flex items-center gap-2">
{creating && <Loader2 className="w-4 h-4 animate-spin" />}
{creating ? 'Создание...' : 'Создать'}
</button>
<button type="button" onClick={() => setShowCreateForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
</div>
</form>
@@ -209,7 +231,11 @@ export default function Users() {
</div>
{error && <p className="text-red-500 text-sm">{error}</p>}
<div className="flex gap-2">
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Сохранить</button>
<button type="submit" disabled={saving}
className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50 flex items-center gap-2">
{saving && <Loader2 className="w-4 h-4 animate-spin" />}
{saving ? 'Сохранение...' : 'Сохранить'}
</button>
<button type="button" onClick={() => setShowEditForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
</div>
</form>
@@ -257,12 +283,13 @@ export default function Users() {
</span>
</td>
<td className="px-4 py-3" onClick={e => e.stopPropagation()}>
<div className="flex gap-1">
<button onClick={() => { setSelectedUser(u); openEditForm(u) }} className="p-1 text-blue-500 hover:text-blue-700" title="Редактировать">
<div className="flex gap-2">
<button onClick={() => openEditForm(u)} className="p-1 text-blue-500 hover:text-blue-700">
<Edit className="w-4 h-4" />
</button>
<button onClick={() => handleDelete(u.id)} className="p-1 text-red-500 hover:text-red-700" title="Удалить">
<Trash2 className="w-4 h-4" />
<button onClick={() => handleDelete(u.id)} disabled={deletingId === u.id}
className="p-1 text-red-500 hover:text-red-700 disabled:opacity-50">
{deletingId === u.id ? <Loader2 className="w-4 h-4 animate-spin" /> : <Trash2 className="w-4 h-4" />}
</button>
</div>
</td>