refactor: architecture modules indépendants — nettoyage CORE, registry enrichi, page modules dynamique

- Supprimer les modules services et logs du CORE (déplacés dans viewServices et viewLogs)
- Enrichir modules/module.go : interface Registry avec NavItemDef, RunOnTarget, StreamOnTarget
- Réécrire modules/loader.go : NewLoader accepte *db.DB, *sshpool.Pool, *crypto.Encryptor
- Ajouter migration 005 : colonnes nav_* sur la table modules + suppression services/logs DB
- Mettre à jour db.go (repairSchema) pour ajout idempotent des colonnes nav_*
- Mettre à jour settings.go : GetModules retourne les champs nav, ajout GetRegistryModules et InstallRegistryModule
- Mettre à jour main.go : NewLoader avec les bons arguments, ajout routes /api/registry/modules
- Mettre à jour modules.html : section Store avec liste des modules Forgejo
- Mettre à jour app.js : sidebar dynamique (nav_href depuis DB), modulesPage avec store
- Mettre à jour pages.css : styles pour store de modules

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
enzo 2026-03-22 03:34:17 +01:00
parent 91cf788221
commit ec7d120ef6
15 changed files with 460 additions and 997 deletions

View file

@ -319,8 +319,7 @@ document.addEventListener('alpine:init', () => {
})
// ── Composant: sidebar ──────────────────────────────────────────────────
// Items CORE : toujours visibles.
// Items modules : visibles seulement si le module est activé en DB.
// Items CORE toujours visibles (sidebar hardcodée pour le CORE)
const _coreNavItems = [
{ id: 'dashboard', iconClass: 'lnid-dashboard-square-1', iconColor: '#6c8ef4', labelKey: 'nav.dashboard', href: '/dashboard.html' },
{ id: 'proxmox', iconClass: 'lnid-server-1', iconColor: '#22c55e', labelKey: 'nav.proxmox', href: '/proxmox.html' },
@ -328,36 +327,38 @@ document.addEventListener('alpine:init', () => {
{ id: 'settings', iconClass: 'lnid-gear-1', iconColor: '#94a3b8', labelKey: 'nav.settings', href: '/settings.html' },
{ id: 'modules', iconClass: 'lnid-puzzle', iconColor: '#f472b6', labelKey: 'nav.modules', href: '/modules.html' },
]
// Définition des items de navigation pour les modules optionnels.
// Un module dont l'id n'est pas ici n'aura pas d'entrée dans la sidebar.
const _moduleNavDef = {
terminal: { iconClass: 'lnid-terminal', iconColor: '#a78bfa', labelKey: 'nav.terminal', href: '/terminal.html' },
files: { iconClass: 'lnid-folder-1', iconColor: '#84cc16', labelKey: 'nav.files', href: '/files.html' },
services: { iconClass: 'lnid-gear-2', iconColor: '#fb923c', labelKey: 'nav.services', href: '/services.html' },
logs: { iconClass: 'lnid-scroll-angular-1', iconColor: '#38bdf8', labelKey: 'nav.logs', href: '/logs.html' },
}
Alpine.data('sidebar', () => ({
get collapsed() { return Alpine.store('ui').sidebarCollapsed },
get currentPage() { return Alpine.store('ui').currentPage },
// Commence avec les items CORE ; init() ajoute les modules activés
navItems: [..._coreNavItems],
async init() {
await this.refreshNav()
},
async refreshNav() {
try {
const res = await apiFetch('/api/modules')
if (!res.ok) return
const modules = await res.json() || []
const moduleItems = modules
.filter(m => m.is_enabled && !m.is_core && _moduleNavDef[m.id])
.map(m => ({ id: m.id, ..._moduleNavDef[m.id] }))
// Insérer les modules entre Updates et Settings
const insertAt = this.navItems.findIndex(i => i.id === 'settings')
const allModules = await res.json() || []
// Modules optionnels activés avec nav_href défini
const moduleItems = allModules
.filter(m => !m.is_core && m.is_enabled && m.nav_href)
.map(m => ({
id: m.id,
iconClass: m.nav_icon || 'lnid-puzzle',
iconColor: m.nav_color || '#94a3b8',
labelKey: m.nav_label_key || `nav.${m.id}`,
href: m.nav_href,
}))
// Insérer entre Updates et Settings
const insertAt = _coreNavItems.findIndex(i => i.id === 'settings')
this.navItems = [
...this.navItems.slice(0, insertAt),
..._coreNavItems.slice(0, insertAt),
...moduleItems,
...this.navItems.slice(insertAt),
..._coreNavItems.slice(insertAt),
]
} catch(e) {}
},
@ -1077,31 +1078,50 @@ document.addEventListener('alpine:init', () => {
modules: [],
loading: true,
toggling: {},
storeModules: [],
storeLoading: true,
installing: {},
rebuildRequired: false,
async init() {
await this.load()
await Promise.all([this.load(), this.loadStore()])
},
async load() {
this.loading = true
try {
const res = await apiFetch('/api/modules')
if (res.ok) {
this.modules = await res.json() || []
}
if (res.ok) this.modules = await res.json() || []
} finally {
this.loading = false
}
},
async loadStore() {
this.storeLoading = true
try {
const res = await apiFetch('/api/registry/modules')
if (res.ok) this.storeModules = await res.json() || []
} catch(e) {
this.storeModules = []
} finally {
this.storeLoading = false
}
},
async toggle(mod) {
this.toggling[mod.id] = true
try {
// Backend: is_enabled (pas enabled)
const action = mod.is_enabled ? 'disable' : 'enable'
const res = await apiFetch(`/api/modules/${mod.id}/${action}`, { method: 'POST' })
if (res.ok) {
mod.is_enabled = !mod.is_enabled
// Rafraîchir la sidebar
const sb = document.querySelector('[x-data="sidebar()"]')
if (sb && sb._x_dataStack) {
const sidebarData = Alpine.$data(sb)
if (sidebarData && sidebarData.refreshNav) await sidebarData.refreshNav()
}
}
} catch(e) {
console.error(e)
@ -1110,171 +1130,31 @@ document.addEventListener('alpine:init', () => {
}
},
t(key) { return Alpine.store('i18n').t(key) },
}))
// ── Composant: servicePage ──────────────────────────────────────────────
Alpine.data('servicePage', () => ({
services: [],
loading: false,
target: 'host',
targets: [{ value: 'host', label: 'Host Proxmox' }],
filter: '',
actioning: {},
get filtered() {
const q = this.filter.toLowerCase()
if (!q) return this.services
return this.services.filter(s =>
s.name.toLowerCase().includes(q) || (s.description || '').toLowerCase().includes(q)
)
},
async init() {
await this.loadTargets()
await this.load()
},
async loadTargets() {
async install(mod) {
this.installing[mod.id] = true
try {
const res = await apiFetch('/api/proxmox/lxc')
const res = await apiFetch(`/api/registry/modules/${mod.id}/install`, { method: 'POST' })
if (res.ok) {
const lxc = await res.json() || []
this.targets = [
{ value: 'host', label: 'Host Proxmox' },
...lxc.map(c => ({ value: `lxc:${c.vmid}`, label: `LXC ${c.vmid}${c.name || 'CT'+c.vmid}` }))
]
}
} catch(e) {}
},
async load() {
this.loading = true
try {
const res = await apiFetch(`/api/services?target=${this.target}`)
if (res.ok) this.services = await res.json() || []
} finally {
this.loading = false
}
},
async action(name, act) {
this.actioning[name] = act
try {
const res = await apiFetch(`/api/services/${name}/${act}`, {
method: 'POST',
body: JSON.stringify({ target: this.target })
})
if (res.ok) {
Alpine.store('toasts').success(`${act} ${name}`)
mod.installed = true
this.rebuildRequired = true
Alpine.store('toasts').success(`Module ${mod.id} installé — rebuild requis`)
await this.load()
} else {
const b = await res.json().catch(() => ({}))
Alpine.store('toasts').error(b.error || `Erreur ${act}`)
Alpine.store('toasts').error(b.error || 'Erreur installation')
}
} catch(e) {
Alpine.store('toasts').error(e.message)
} finally {
this.actioning[name] = false
this.installing[mod.id] = false
}
},
stateClass(svc) {
if (svc.active_state === 'active') return 'state-active'
if (svc.active_state === 'failed') return 'state-failed'
if (svc.active_state === 'inactive') return 'state-inactive'
return 'state-other'
},
t(key) { return Alpine.store('i18n').t(key) },
}))
// ── Composant: logsPage ─────────────────────────────────────────────────
Alpine.data('logsPage', () => ({
lines: [],
target: 'host',
targets: [{ value: 'host', label: 'Host Proxmox' }],
unit: '',
units: [],
linesCount: '100',
following: false,
ws: null,
async init() {
await this.loadTargets()
await this.loadUnits()
},
async loadTargets() {
try {
const res = await apiFetch('/api/proxmox/lxc')
if (res.ok) {
const lxc = await res.json() || []
this.targets = [
{ value: 'host', label: 'Host Proxmox' },
...lxc.map(c => ({ value: `lxc:${c.vmid}`, label: `LXC ${c.vmid}${c.name || 'CT'+c.vmid}` }))
]
}
} catch(e) {}
},
async loadUnits() {
try {
const res = await apiFetch(`/api/logs/units?target=${this.target}`)
if (res.ok) this.units = await res.json() || []
} catch(e) {}
},
async onTargetChange() {
this.stopFollow()
this.unit = ''
await this.loadUnits()
},
toggleFollow() {
if (this.following) {
this.stopFollow()
} else {
this.startFollow()
}
},
startFollow() {
this.lines = []
const token = encodeURIComponent(localStorage.getItem('pxp_token') || '')
const proto = location.protocol === 'https:' ? 'wss' : 'ws'
const unit = this.unit ? `&unit=${encodeURIComponent(this.unit)}` : ''
const url = `${proto}://${location.host}/ws/logs?token=${token}&target=${this.target}&lines=${this.linesCount}${unit}`
this.ws = new WebSocket(url)
this.following = true
this.ws.onmessage = (e) => {
const incoming = e.data.split('\n').filter(l => l !== '')
this.lines.push(...incoming)
if (this.lines.length > 3000) this.lines = this.lines.slice(-3000)
this.$nextTick(() => {
const el = this.$refs.logOutput
if (el) el.scrollTop = el.scrollHeight
})
}
this.ws.onclose = () => { this.following = false; this.ws = null }
this.ws.onerror = () => { this.following = false; this.ws = null }
},
stopFollow() {
if (this.ws) {
this.ws.close()
this.ws = null
}
this.following = false
},
clearLog() {
this.lines = []
},
t(key) { return Alpine.store('i18n').t(key) },
}))
// Note: servicePage et logsPage ont été déplacés dans les modules
// indépendants viewServices et viewLogs.
}) // end alpine:init