feat: add Matrix Management

This commit is contained in:
DeathKaioken 2025-10-16 16:35:17 +02:00
parent 7625ded0e9
commit 3ee6e90128
3 changed files with 305 additions and 96 deletions

View File

@ -0,0 +1,45 @@
export type CreateMatrixResult = {
ok: boolean
status: number
body?: any
message?: string
}
export async function createMatrix(params: {
token: string
name: string
email: string
force?: boolean
baseUrl?: string
}): Promise<CreateMatrixResult> {
const { token, name, email, force = false, baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || '' } = params
if (!token) return { ok: false, status: 401, message: 'Missing token' }
const url = new URL(`${baseUrl}/api/matrix/create`)
url.searchParams.set('name', name)
url.searchParams.set('email', email)
if (force) url.searchParams.set('force', 'true')
try {
const res = await fetch(url.toString(), {
method: 'GET',
headers: {
Authorization: `Bearer ${token}`,
},
credentials: 'include',
})
let body: any = null
try { body = await res.json() } catch {}
if (!res.ok) {
return {
ok: false,
status: res.status,
body,
message: body?.message || `Create matrix failed (${res.status})`
}
}
return { ok: true, status: res.status, body }
} catch (err) {
return { ok: false, status: 0, message: 'Network error' }
}
}

View File

@ -0,0 +1,31 @@
export type GetMatrixStatsResult = {
ok: boolean
status: number
body?: any
message?: string
}
export async function getMatrixStats(params: {
token: string
baseUrl?: string
}): Promise<GetMatrixStatsResult> {
const { token, baseUrl = process.env.NEXT_PUBLIC_API_BASE_URL || '' } = params
if (!token) return { ok: false, status: 401, message: 'Missing token' }
const url = `${baseUrl}/api/matrix/stats`
try {
const res = await fetch(url, {
method: 'GET',
headers: { Authorization: `Bearer ${token}` },
credentials: 'include',
})
let body: any = null
try { body = await res.json() } catch {}
if (!res.ok) {
return { ok: false, status: res.status, body, message: body?.message || `Fetch stats failed (${res.status})` }
}
return { ok: true, status: res.status, body }
} catch {
return { ok: false, status: 0, message: 'Network error' }
}
}

View File

@ -12,6 +12,8 @@ import {
import PageLayout from '../../components/PageLayout'
import { useRouter } from 'next/navigation'
import useAuthStore from '../../store/authStore'
import { createMatrix } from './hooks/createMatrix'
import { getMatrixStats } from './hooks/getMatrixStats'
type Matrix = {
id: string
@ -23,9 +25,9 @@ type Matrix = {
}
export default function MatrixManagementPage() {
// Auth guard
const router = useRouter()
const user = useAuthStore(s => s.user)
const token = useAuthStore(s => s.accessToken)
const isAdmin =
!!user &&
(
@ -43,58 +45,83 @@ export default function MatrixManagementPage() {
}
}, [user, isAdmin, router])
const [matrices, setMatrices] = useState<Matrix[]>([
{
id: 'm1',
name: 'Gold Matrix',
status: 'active',
usersCount: 128,
createdAt: new Date(Date.now() - 5 * 24 * 3600 * 1000).toISOString(),
topNodeEmail: 'alice@example.com',
},
{
id: 'm2',
name: 'Silver Matrix',
status: 'inactive',
usersCount: 64,
createdAt: new Date(Date.now() - 15 * 24 * 3600 * 1000).toISOString(),
topNodeEmail: 'bob@example.com',
},
{
id: 'm3',
name: 'Bronze Matrix',
status: 'active',
usersCount: 42,
createdAt: new Date(Date.now() - 40 * 24 * 3600 * 1000).toISOString(),
topNodeEmail: 'charlie@example.com',
},
])
const [matrices, setMatrices] = useState<Matrix[]>([])
const [stats, setStats] = useState({ total: 0, active: 0, totalUsers: 0 })
const [statsLoading, setStatsLoading] = useState(false)
const [statsError, setStatsError] = useState<string>('')
const [createOpen, setCreateOpen] = useState(false)
const [createName, setCreateName] = useState('')
const [createEmail, setCreateEmail] = useState('')
const [formError, setFormError] = useState<string>('')
const stats = useMemo(() => {
const total = matrices.length
const active = matrices.filter(m => m.status === 'active').length
const totalUsers = matrices.reduce((acc, m) => acc + (m.usersCount || 0), 0)
return { total, active, totalUsers }
}, [matrices])
const [createLoading, setCreateLoading] = useState(false)
const [forcePrompt, setForcePrompt] = useState<{ name: string; email: string } | null>(null)
const [createSuccess, setCreateSuccess] = useState<{ name: string; email: string } | null>(null)
const loadStats = async () => {
if (!token) return
setStatsLoading(true)
setStatsError('')
try {
const res = await getMatrixStats({ token })
console.log('📊 MatrixManagement: GET /matrix/stats ->', res.status, res.body)
if (res.ok) {
const payload = res.body?.data || res.body || {}
const apiMatrices: any[] = Array.isArray(payload.matrices) ? payload.matrices : []
const mapped: Matrix[] = apiMatrices.map((m: any, idx: number) => {
const isActive = !!m?.isActive
const createdAt = m?.createdAt || m?.ego_activated_at || m?.activatedAt || new Date().toISOString()
const topNodeEmail = m?.topNodeEmail || m?.masterTopUserEmail || m?.email || ''
return {
id: String(m?.rootUserId ?? m?.id ?? `m-${idx}`),
name: String(m?.name ?? 'Unnamed Matrix'),
status: isActive ? 'active' : 'inactive',
usersCount: Number(m?.usersCount ?? 0),
createdAt: String(createdAt),
topNodeEmail: String(topNodeEmail),
}
})
setMatrices(mapped)
const activeMatrices = Number(payload.activeMatrices ?? mapped.filter(m => m.status === 'active').length)
const totalMatrices = Number(payload.totalMatrices ?? mapped.length)
const totalUsersSubscribed = Number(payload.totalUsersSubscribed ?? 0)
setStats({ total: totalMatrices, active: activeMatrices, totalUsers: totalUsersSubscribed })
console.log('✅ MatrixManagement: mapped stats:', { total: totalMatrices, active: activeMatrices, totalUsers: totalUsersSubscribed })
console.log('✅ MatrixManagement: mapped matrices sample:', mapped.slice(0, 3))
} else {
setStatsError(res.message || 'Failed to load matrix stats.')
}
} catch (e) {
console.error('❌ MatrixManagement: stats load error', e)
setStatsError('Network error while loading matrix stats.')
} finally {
setStatsLoading(false)
}
}
useEffect(() => {
loadStats()
}, [token])
const resetForm = () => {
setCreateName('')
setCreateEmail('')
setFormError('')
setForcePrompt(null)
setCreateSuccess(null)
}
const validateEmail = (email: string) =>
/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email.trim())
const handleCreate = (e: React.FormEvent) => {
const handleCreate = async (e: React.FormEvent) => {
e.preventDefault()
const name = createName.trim()
const email = createEmail.trim()
setFormError('')
setCreateSuccess(null)
setForcePrompt(null)
if (!name) {
setFormError('Please provide a matrix name.')
@ -104,18 +131,57 @@ export default function MatrixManagementPage() {
setFormError('Please provide a valid top-node email.')
return
}
const newMatrix: Matrix = {
id: `m-${Date.now()}`,
name,
status: 'active',
usersCount: 0,
createdAt: new Date().toISOString(),
topNodeEmail: email,
if (!token) {
setFormError('Not authenticated. Please log in again.')
return
}
setCreateLoading(true)
try {
const res = await createMatrix({ token, name, email })
console.log('🧱 MatrixManagement: create result ->', res.status, res.body)
if (res.ok && res.body?.success) {
const createdName = res.body?.data?.name || name
const createdEmail = res.body?.data?.masterTopUserEmail || email
setCreateSuccess({ name: createdName, email: createdEmail })
await loadStats()
setCreateName('')
setCreateEmail('')
} else if (res.status === 409) {
setForcePrompt({ name, email })
} else {
setFormError(res.message || 'Failed to create matrix.')
}
} catch (err) {
setFormError('Network error while creating the matrix.')
} finally {
setCreateLoading(false)
}
}
const confirmForce = async () => {
if (!forcePrompt || !token) return
setFormError('')
setCreateLoading(true)
try {
const res = await createMatrix({ token, name: forcePrompt.name, email: forcePrompt.email, force: true })
console.log('🧱 MatrixManagement: force-create result ->', res.status, res.body)
if (res.ok && res.body?.success) {
const createdName = res.body?.data?.name || forcePrompt.name
const createdEmail = res.body?.data?.masterTopUserEmail || forcePrompt.email
setCreateSuccess({ name: createdName, email: createdEmail })
setForcePrompt(null)
setCreateName('')
setCreateEmail('')
await loadStats()
} else {
setFormError(res.message || 'Failed to create matrix (force).')
}
} catch {
setFormError('Network error while forcing the matrix creation.')
} finally {
setCreateLoading(false)
}
setMatrices(prev => [newMatrix, ...prev])
setCreateOpen(false)
resetForm()
}
const toggleStatus = (id: string) => {
@ -180,6 +246,13 @@ export default function MatrixManagementPage() {
</button>
</div>
{/* Error banner for stats */}
{statsError && (
<div className="mb-6 rounded-md border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
{statsError}
</div>
)}
{/* Stats */}
<div className="grid grid-cols-1 gap-5 sm:grid-cols-2 lg:grid-cols-3 mb-8">
<StatCard icon={CheckCircleIcon} label="Active Matrices" value={stats.active} color="bg-green-500" />
@ -189,60 +262,76 @@ export default function MatrixManagementPage() {
{/* Matrix cards */}
<div className="grid grid-cols-1 gap-6 sm:grid-cols-2 xl:grid-cols-3">
{matrices.map(m => (
<article key={m.id} className="rounded-xl bg-white border border-gray-200 shadow-sm overflow-hidden">
<div className="p-5">
<div className="flex items-start justify-between gap-3">
<h3 className="text-lg font-semibold text-gray-900">{m.name}</h3>
<StatusBadge status={m.status} />
</div>
<div className="mt-4 grid grid-cols-1 gap-3 text-sm text-gray-700">
<div className="flex items-center gap-2">
<UsersIcon className="h-5 w-5 text-gray-500" />
<span className="font-medium">{m.usersCount}</span>
<span className="text-gray-500">users</span>
</div>
<div className="flex items-center gap-2">
<CalendarDaysIcon className="h-5 w-5 text-gray-500" />
<span className="text-gray-600">
{new Date(m.createdAt).toLocaleDateString()}
</span>
</div>
<div className="flex items-center gap-2">
<EnvelopeIcon className="h-5 w-5 text-gray-500" />
<span className="text-gray-700 truncate">{m.topNodeEmail}</span>
</div>
</div>
<div className="mt-5 flex items-center justify-between">
<button
onClick={() => toggleStatus(m.id)}
className={`rounded-md px-3 py-2 text-sm font-medium border ${
m.status === 'active'
? 'border-red-300 text-red-700 hover:bg-red-50'
: 'border-green-300 text-green-700 hover:bg-green-50'
}`}
>
{m.status === 'active' ? 'Deactivate' : 'Activate'}
</button>
<button
className="text-sm font-medium text-indigo-600 hover:text-indigo-500"
onClick={() => alert('Placeholder: open matrix details')}
>
View details
</button>
{statsLoading ? (
// Simple skeleton
Array.from({ length: 3 }).map((_, i) => (
<div key={i} className="rounded-xl bg-white border border-gray-200 shadow-sm overflow-hidden">
<div className="p-5 animate-pulse space-y-4">
<div className="h-5 w-1/2 bg-gray-200 rounded" />
<div className="h-4 w-1/3 bg-gray-200 rounded" />
<div className="h-4 w-2/3 bg-gray-200 rounded" />
<div className="h-9 w-full bg-gray-100 rounded" />
</div>
</div>
</article>
))}
))
) : matrices.length === 0 ? (
<div className="text-sm text-gray-600">No matrices found.</div>
) : (
matrices.map(m => (
<article key={m.id} className="rounded-xl bg-white border border-gray-200 shadow-sm overflow-hidden">
<div className="p-5">
<div className="flex items-start justify-between gap-3">
<h3 className="text-lg font-semibold text-gray-900">{m.name}</h3>
<StatusBadge status={m.status} />
</div>
<div className="mt-4 grid grid-cols-1 gap-3 text-sm text-gray-700">
<div className="flex items-center gap-2">
<UsersIcon className="h-5 w-5 text-gray-500" />
<span className="font-medium">{m.usersCount}</span>
<span className="text-gray-500">users</span>
</div>
<div className="flex items-center gap-2">
<CalendarDaysIcon className="h-5 w-5 text-gray-500" />
<span className="text-gray-600">
{new Date(m.createdAt).toLocaleDateString()}
</span>
</div>
<div className="flex items-center gap-2">
<EnvelopeIcon className="h-5 w-5 text-gray-500" />
<span className="text-gray-700 truncate">{m.topNodeEmail}</span>
</div>
</div>
<div className="mt-5 flex items-center justify-between">
<button
onClick={() => toggleStatus(m.id)}
className={`rounded-md px-3 py-2 text-sm font-medium border ${
m.status === 'active'
? 'border-red-300 text-red-700 hover:bg-red-50'
: 'border-green-300 text-green-700 hover:bg-green-50'
}`}
>
{m.status === 'active' ? 'Deactivate' : 'Activate'}
</button>
<button
className="text-sm font-medium text-indigo-600 hover:text-indigo-500"
onClick={() => alert(`Placeholder: open matrix details for ${m.name}`)}
>
View details
</button>
</div>
</div>
</article>
))
)}
</div>
</div>
{/* Create Matrix Modal */}
{createOpen && (
<div className="fixed inset-0 z-50">
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={() => setCreateOpen(false)} />
<div className="absolute inset-0 bg-black/40 backdrop-blur-sm" onClick={() => { setCreateOpen(false); resetForm() }} />
<div className="absolute inset-0 flex items-center justify-center p-4">
<div className="w-full max-w-md rounded-xl bg-white shadow-2xl ring-1 ring-black/10">
<div className="px-5 py-4 border-b border-gray-100 flex items-center justify-between">
@ -255,13 +344,51 @@ export default function MatrixManagementPage() {
</button>
</div>
<form onSubmit={handleCreate} className="p-5 space-y-4">
{/* Success banner */}
{createSuccess && (
<div className="rounded-md border border-green-200 bg-green-50 px-3 py-2 text-sm text-green-700">
Matrix created successfully.
<div className="mt-1 text-green-800">
<span className="font-semibold">Name:</span> {createSuccess.name}{' '}
<span className="font-semibold ml-3">Top node:</span> {createSuccess.email}
</div>
</div>
)}
{/* 409 force prompt */}
{forcePrompt && (
<div className="rounded-md border border-amber-200 bg-amber-50 px-3 py-2 text-sm text-amber-800">
A matrix configuration already exists for this selection.
<div className="mt-2 flex items-center gap-2">
<button
type="button"
onClick={confirmForce}
disabled={createLoading}
className="rounded-md bg-amber-600 hover:bg-amber-500 text-white px-3 py-1.5 text-xs font-medium disabled:opacity-50"
>
Replace (force)
</button>
<button
type="button"
onClick={() => setForcePrompt(null)}
disabled={createLoading}
className="rounded-md border border-amber-300 px-3 py-1.5 text-xs font-medium text-amber-800 hover:bg-amber-100 disabled:opacity-50"
>
Cancel
</button>
</div>
</div>
)}
{/* Form fields */}
<div>
<label className="block text-sm font-medium text-gray-800 mb-1">Matrix Name</label>
<input
type="text"
value={createName}
onChange={e => setCreateName(e.target.value)}
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
disabled={createLoading}
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent disabled:bg-gray-100"
placeholder="e.g., Platinum Matrix"
/>
</div>
@ -271,28 +398,34 @@ export default function MatrixManagementPage() {
type="email"
value={createEmail}
onChange={e => setCreateEmail(e.target.value)}
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent"
disabled={createLoading}
className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm focus:ring-2 focus:ring-indigo-500 focus:border-transparent disabled:bg-gray-100"
placeholder="owner@example.com"
/>
</div>
{formError && (
<div className="rounded-md border border-red-200 bg-red-50 px-3 py-2 text-sm text-red-700">
{formError}
</div>
)}
<div className="pt-2 flex items-center justify-end gap-2">
<button
type="button"
onClick={() => { setCreateOpen(false); resetForm() }}
className="rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50"
disabled={createLoading}
className="rounded-md border border-gray-300 px-3 py-2 text-sm text-gray-700 hover:bg-gray-50 disabled:opacity-50"
>
Cancel
</button>
<button
type="submit"
className="rounded-md bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 text-sm font-medium"
disabled={createLoading}
className="rounded-md bg-indigo-600 hover:bg-indigo-500 text-white px-4 py-2 text-sm font-medium disabled:opacity-50 inline-flex items-center gap-2"
>
Create Matrix
{createLoading && <span className="h-4 w-4 rounded-full border-2 border-white border-b-transparent animate-spin" />}
{createLoading ? 'Creating...' : 'Create Matrix'}
</button>
</div>
</form>