TT-004: complete modular frontend integration

This commit is contained in:
2026-08-09 22:57:51 +03:00
parent a819bc9807
commit 3f14532b9b
185 changed files with 1197 additions and 204824 deletions
+1 -1
View File
@@ -27,7 +27,7 @@ export default function App() {
<Route path="users" element={<Users />} />
<Route path="roles" element={<Roles />} />
<Route path="modules" element={<Modules />} />
<Route path="module/:slug" element={<ModuleView />} />
<Route path="module/:id" element={<ModuleView />} />
</Route>
</Routes>
</AuthProvider>
+1 -1
View File
@@ -47,7 +47,7 @@ export const rolesApi = {
}
export const modulesApi = {
list: () => api.get('/modules'),
list: () => api.get('/platform/modules'),
create: (data: { name: string; slug: string; url: string; description?: string; icon?: string }) => api.post('/modules', data),
update: (id: number, data: any) => api.put(`/modules/${id}`, data),
delete: (id: number) => api.delete(`/modules/${id}`),
+2 -2
View File
@@ -55,8 +55,8 @@ export default function Layout() {
{modules.length > 0 && (
<div className="flex items-center gap-1">
{modules.map(mod => (
<Link key={mod.slug} to={`/module/${mod.slug}`}
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${location.pathname === `/module/${mod.slug}` ? 'bg-blue-600 text-white font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
<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>
))}
+42 -14
View File
@@ -3,30 +3,49 @@ import { useParams } from 'react-router-dom'
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
return url || null
}
export default function ModuleView() {
const { slug } = useParams()
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) => m.slug === slug)
const found = res.data.find((m: any) => String(m.id) === String(id))
setModule(found)
}).finally(() => setLoading(false))
}, [slug])
}).catch(() => setError('Ошибка загрузки модулей'))
.finally(() => setLoading(false))
}, [id])
// Update iframe URL and send token to iframe
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 = `${module.url}?token=${encodeURIComponent(token)}`
const url = `${frontendUrl}?token=${encodeURIComponent(token)}`
setModuleUrl(url)
}
@@ -36,14 +55,13 @@ export default function ModuleView() {
if (iframe?.contentWindow) {
iframe.contentWindow.postMessage(
{ type: 'PLATFORM_TOKEN_UPDATE', token },
module.url
'*'
)
}
}
updateUrl()
// Listen for storage changes (token refresh in another tab)
const handleStorage = (e: StorageEvent) => {
if (e.key === 'platform_token') {
updateUrl()
@@ -52,7 +70,6 @@ export default function ModuleView() {
}
window.addEventListener('storage', handleStorage)
// Check periodically for token changes
let lastToken = getToken()
const interval = setInterval(() => {
const currentToken = getToken()
@@ -71,7 +88,7 @@ export default function ModuleView() {
useEffect(() => {
setIframeLoading(true)
}, [slug])
}, [id])
if (loading) return (
<div className="flex-1 flex items-center justify-center">
@@ -79,6 +96,15 @@ export default function ModuleView() {
</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>
@@ -89,10 +115,12 @@ export default function ModuleView() {
<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>
<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>
{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 && (
+215 -40
View File
@@ -1,28 +1,57 @@
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'
export default function Modules() {
const navigate = useNavigate()
const [modules, setModules] = useState<any[]>([])
const [showForm, setShowForm] = useState(false)
const [form, setForm] = useState({ name: '', slug: '', url: '', description: '', icon: 'Package' })
const [form, setForm] = useState({
name: '',
slug: '',
url: '',
description: '',
icon: 'Package',
})
const [error, setError] = useState('')
const [syncResult, setSyncResult] = useState('')
const [expandedRoles, setExpandedRoles] = useState<number | null>(null)
const [moduleRoles, setModuleRoles] = useState<any[]>([])
const fetchModules = () => { modulesApi.list().then(res => setModules(res.data)).catch(() => {}) }
useEffect(() => { fetchModules() }, [])
const fetchModules = () => {
modulesApi
.list()
.then(res => setModules(res.data))
.catch(() => {})
}
useEffect(() => {
fetchModules()
}, [])
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
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 || 'Ошибка')
}
@@ -30,8 +59,10 @@ export default function Modules() {
const handleSync = async (id: number) => {
setSyncResult('')
try {
const res = await modulesApi.syncRoles(id)
setSyncResult(`Импортировано: ${res.data.message}`)
fetchModules()
} catch (err: any) {
@@ -41,6 +72,7 @@ export default function Modules() {
const handleDelete = async (id: number) => {
if (!confirm('Отключить модуль?')) return
await modulesApi.delete(id)
fetchModules()
}
@@ -51,16 +83,34 @@ 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}`)
}
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>
@@ -69,57 +119,172 @@ 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>
<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>
</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>}
{syncResult && (
<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">{mod.url} · slug: {mod.slug} · ролей: {mod.roles_count}</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"
title="Роли"
>
<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)}
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>
<a href={mod.url} target="_blank" rel="noopener" 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" />Открыть
</a>
<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">
<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>
<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>
</div>
@@ -127,13 +292,23 @@ export default function Modules() {
{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>
)}
@@ -144,4 +319,4 @@ export default function Modules() {
</div>
</div>
)
}
}
+1 -1
View File
@@ -7,7 +7,7 @@ export default defineConfig({
server: {
port: 5173,
proxy: {
'/api': 'http://localhost:8001',
'/api': 'http://localhost:8000',
},
},
})