完成 APP 建立流程和使用分析、增加主機備機的備援機制、管理者後臺增加資料庫監控
This commit is contained in:
303
components/admin/database-monitor.tsx
Normal file
303
components/admin/database-monitor.tsx
Normal file
@@ -0,0 +1,303 @@
|
||||
'use client';
|
||||
|
||||
// =====================================================
|
||||
// 資料庫監控組件
|
||||
// =====================================================
|
||||
|
||||
import React, { useState, useEffect } from 'react';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { RefreshCw, Database, Server, AlertTriangle, CheckCircle } from 'lucide-react';
|
||||
|
||||
interface DatabaseStatus {
|
||||
isEnabled: boolean;
|
||||
currentDatabase: 'master' | 'slave';
|
||||
masterHealthy: boolean;
|
||||
slaveHealthy: boolean;
|
||||
lastHealthCheck: string;
|
||||
consecutiveFailures: number;
|
||||
uptime: number;
|
||||
timestamp: string;
|
||||
}
|
||||
|
||||
interface DatabaseMonitorProps {
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function DatabaseMonitor({ className }: DatabaseMonitorProps) {
|
||||
const [status, setStatus] = useState<DatabaseStatus | null>(null);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [switching, setSwitching] = useState(false);
|
||||
|
||||
// 獲取資料庫狀態
|
||||
const fetchStatus = async () => {
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const response = await fetch('/api/admin/database-status');
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
setStatus(data.data);
|
||||
} else {
|
||||
setError(data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('無法連接到監控服務');
|
||||
console.error('獲取資料庫狀態失敗:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 切換資料庫
|
||||
const switchDatabase = async (database: 'master' | 'slave') => {
|
||||
try {
|
||||
setSwitching(true);
|
||||
|
||||
const response = await fetch('/api/admin/database-status', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action: 'switch',
|
||||
database: database
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
// 重新獲取狀態
|
||||
await fetchStatus();
|
||||
} else {
|
||||
setError(data.message);
|
||||
}
|
||||
} catch (err) {
|
||||
setError('切換資料庫失敗');
|
||||
console.error('切換資料庫失敗:', err);
|
||||
} finally {
|
||||
setSwitching(false);
|
||||
}
|
||||
};
|
||||
|
||||
// 格式化時間
|
||||
const formatTime = (timestamp: string) => {
|
||||
return new Date(timestamp).toLocaleString('zh-TW');
|
||||
};
|
||||
|
||||
// 格式化運行時間
|
||||
const formatUptime = (seconds: number) => {
|
||||
const hours = Math.floor(seconds / 3600);
|
||||
const minutes = Math.floor((seconds % 3600) / 60);
|
||||
const secs = Math.floor(seconds % 60);
|
||||
return `${hours}時${minutes}分${secs}秒`;
|
||||
};
|
||||
|
||||
// 組件掛載時獲取狀態
|
||||
useEffect(() => {
|
||||
fetchStatus();
|
||||
|
||||
// 每30秒自動刷新
|
||||
const interval = setInterval(fetchStatus, 30000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<Card className={className}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
資料庫監控
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<RefreshCw className="h-6 w-6 animate-spin" />
|
||||
<span className="ml-2">載入中...</span>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<Card className={className}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
資料庫監控
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Alert variant="destructive">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>{error}</AlertDescription>
|
||||
</Alert>
|
||||
<Button
|
||||
onClick={fetchStatus}
|
||||
variant="outline"
|
||||
className="mt-4"
|
||||
>
|
||||
<RefreshCw className="h-4 w-4 mr-2" />
|
||||
重新載入
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
if (!status) {
|
||||
return (
|
||||
<Card className={className}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
資料庫監控
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<p>無法獲取資料庫狀態</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card className={className}>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
資料庫監控
|
||||
</div>
|
||||
<Button
|
||||
onClick={fetchStatus}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={loading}
|
||||
>
|
||||
<RefreshCw className={`h-4 w-4 mr-2 ${loading ? 'animate-spin' : ''}`} />
|
||||
刷新
|
||||
</Button>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
監控主機和備機資料庫的連接狀態
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{/* 整體狀態 */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">備援狀態</span>
|
||||
<Badge variant={status.isEnabled ? "default" : "secondary"}>
|
||||
{status.isEnabled ? "啟用" : "停用"}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* 當前資料庫 */}
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm font-medium">當前資料庫</span>
|
||||
<Badge variant={status.currentDatabase === 'master' ? "default" : "secondary"}>
|
||||
{status.currentDatabase === 'master' ? "主機" : "備機"}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* 主機狀態 */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Server className="h-4 w-4" />
|
||||
<span className="text-sm font-medium">主機資料庫</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{status.masterHealthy ? (
|
||||
<CheckCircle className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<AlertTriangle className="h-4 w-4 text-red-500" />
|
||||
)}
|
||||
<Badge variant={status.masterHealthy ? "default" : "destructive"}>
|
||||
{status.masterHealthy ? "正常" : "異常"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{status.masterHealthy && (
|
||||
<Button
|
||||
onClick={() => switchDatabase('master')}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={switching || status.currentDatabase === 'master'}
|
||||
className="w-full"
|
||||
>
|
||||
切換到主機
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 備機狀態 */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Server className="h-4 w-4" />
|
||||
<span className="text-sm font-medium">備機資料庫</span>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{status.slaveHealthy ? (
|
||||
<CheckCircle className="h-4 w-4 text-green-500" />
|
||||
) : (
|
||||
<AlertTriangle className="h-4 w-4 text-red-500" />
|
||||
)}
|
||||
<Badge variant={status.slaveHealthy ? "default" : "destructive"}>
|
||||
{status.slaveHealthy ? "正常" : "異常"}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
{status.slaveHealthy && (
|
||||
<Button
|
||||
onClick={() => switchDatabase('slave')}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
disabled={switching || status.currentDatabase === 'slave'}
|
||||
className="w-full"
|
||||
>
|
||||
切換到備機
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 統計信息 */}
|
||||
<div className="pt-4 border-t space-y-2">
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span>連續失敗次數</span>
|
||||
<span className="font-mono">{status.consecutiveFailures}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span>最後檢查時間</span>
|
||||
<span className="font-mono">{formatTime(status.lastHealthCheck)}</span>
|
||||
</div>
|
||||
<div className="flex items-center justify-between text-sm">
|
||||
<span>系統運行時間</span>
|
||||
<span className="font-mono">{formatUptime(status.uptime)}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 警告信息 */}
|
||||
{status.consecutiveFailures > 0 && (
|
||||
<Alert>
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription>
|
||||
資料庫已連續失敗 {status.consecutiveFailures} 次,請檢查連接狀態
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
@@ -1,6 +1,6 @@
|
||||
"use client"
|
||||
|
||||
import { useState } from "react"
|
||||
import React, { useState } from "react"
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import { Input } from "@/components/ui/input"
|
||||
@@ -25,6 +25,11 @@ import {
|
||||
CheckCircle,
|
||||
HardDrive,
|
||||
Clock,
|
||||
Database,
|
||||
RefreshCw,
|
||||
AlertCircle,
|
||||
CheckCircle2,
|
||||
XCircle,
|
||||
Globe,
|
||||
} from "lucide-react"
|
||||
|
||||
@@ -71,6 +76,12 @@ export function SystemSettings() {
|
||||
const [activeTab, setActiveTab] = useState("general")
|
||||
const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "saved" | "error">("idle")
|
||||
const [showSmtpPassword, setShowSmtpPassword] = useState(false)
|
||||
|
||||
// 資料庫狀態
|
||||
const [databaseStatus, setDatabaseStatus] = useState<any>(null)
|
||||
const [isLoadingStatus, setIsLoadingStatus] = useState(false)
|
||||
const [syncStatus, setSyncStatus] = useState<any>(null)
|
||||
const [isLoadingSync, setIsLoadingSync] = useState(false)
|
||||
|
||||
const handleSave = async () => {
|
||||
setSaveStatus("saving")
|
||||
@@ -90,6 +101,99 @@ export function SystemSettings() {
|
||||
setSettings((prev) => ({ ...prev, [key]: value }))
|
||||
}
|
||||
|
||||
// 獲取資料庫狀態
|
||||
const fetchDatabaseStatus = async () => {
|
||||
setIsLoadingStatus(true)
|
||||
try {
|
||||
const response = await fetch('/api/admin/database-status')
|
||||
const data = await response.json()
|
||||
if (data.success) {
|
||||
setDatabaseStatus(data.data)
|
||||
} else {
|
||||
console.error('獲取資料庫狀態失敗:', data.error)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('獲取資料庫狀態失敗:', error)
|
||||
} finally {
|
||||
setIsLoadingStatus(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 切換資料庫
|
||||
const switchDatabase = async (database: 'master' | 'slave') => {
|
||||
try {
|
||||
const response = await fetch('/api/admin/database-status', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({ action: 'switch', database }),
|
||||
})
|
||||
const data = await response.json()
|
||||
if (data.success) {
|
||||
// 重新獲取狀態
|
||||
await fetchDatabaseStatus()
|
||||
alert(data.message)
|
||||
} else {
|
||||
alert(`切換失敗: ${data.message}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('切換資料庫失敗:', error)
|
||||
alert('切換資料庫失敗')
|
||||
}
|
||||
}
|
||||
|
||||
// 獲取同步狀態
|
||||
const fetchSyncStatus = async () => {
|
||||
setIsLoadingSync(true)
|
||||
try {
|
||||
const response = await fetch('/api/admin/database-sync')
|
||||
const data = await response.json()
|
||||
if (data.success) {
|
||||
setSyncStatus(data.data)
|
||||
} else {
|
||||
console.error('獲取同步狀態失敗:', data.error)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('獲取同步狀態失敗:', error)
|
||||
} finally {
|
||||
setIsLoadingSync(false)
|
||||
}
|
||||
}
|
||||
|
||||
// 同步表資料
|
||||
const syncTable = async (tableName: string) => {
|
||||
try {
|
||||
const response = await fetch('/api/admin/database-sync', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify({
|
||||
action: 'sync_table',
|
||||
tableName: tableName
|
||||
})
|
||||
})
|
||||
const data = await response.json()
|
||||
if (data.success) {
|
||||
alert(`成功同步表 ${tableName} 到備機`)
|
||||
} else {
|
||||
alert(`同步表 ${tableName} 失敗: ${data.message}`)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('同步表失敗:', error)
|
||||
alert('同步表失敗')
|
||||
}
|
||||
}
|
||||
|
||||
// 組件載入時獲取資料庫狀態
|
||||
React.useEffect(() => {
|
||||
if (activeTab === 'performance') {
|
||||
fetchDatabaseStatus()
|
||||
fetchSyncStatus()
|
||||
}
|
||||
}, [activeTab])
|
||||
|
||||
return (
|
||||
<div className="p-6 max-w-6xl mx-auto">
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
@@ -383,6 +487,243 @@ export function SystemSettings() {
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 資料庫狀態監控 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="w-5 h-5" />
|
||||
資料庫狀態監控
|
||||
</CardTitle>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={fetchDatabaseStatus}
|
||||
disabled={isLoadingStatus}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 mr-2 ${isLoadingStatus ? 'animate-spin' : ''}`} />
|
||||
重新整理
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{databaseStatus ? (
|
||||
<>
|
||||
{/* 備援狀態概覽 */}
|
||||
<div className="p-4 bg-gray-50 border rounded-lg">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="font-medium">備援系統狀態</span>
|
||||
<Badge variant={databaseStatus.isEnabled ? "default" : "secondary"}>
|
||||
{databaseStatus.isEnabled ? "已啟用" : "已停用"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-sm text-muted-foreground">
|
||||
當前使用: {databaseStatus.currentDatabase === 'master' ? '主機' : '備機'} |
|
||||
連續失敗: {databaseStatus.consecutiveFailures} 次
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
最後檢查: {new Date(databaseStatus.lastHealthCheck).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 主機資料庫 */}
|
||||
<div className="p-4 border rounded-lg">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Server className="w-5 h-5" />
|
||||
<span className="font-medium">主機資料庫</span>
|
||||
{databaseStatus.currentDatabase === 'master' && (
|
||||
<Badge variant="default" className="bg-green-100 text-green-800">
|
||||
當前使用
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{databaseStatus.masterHealthy ? (
|
||||
<CheckCircle2 className="w-5 h-5 text-green-500" />
|
||||
) : (
|
||||
<XCircle className="w-5 h-5 text-red-500" />
|
||||
)}
|
||||
<Badge variant={databaseStatus.masterHealthy ? "default" : "destructive"}>
|
||||
{databaseStatus.masterHealthy ? '正常' : '故障'}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">主機:</span>
|
||||
<span className="ml-2 font-mono">mysql.theaken.com:33306</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">資料庫:</span>
|
||||
<span className="ml-2 font-mono">db_AI_Platform</span>
|
||||
</div>
|
||||
</div>
|
||||
{databaseStatus.currentDatabase !== 'master' && databaseStatus.masterHealthy && (
|
||||
<Button
|
||||
size="sm"
|
||||
className="mt-3"
|
||||
onClick={() => switchDatabase('master')}
|
||||
>
|
||||
切換到主機
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 備機資料庫 */}
|
||||
<div className="p-4 border rounded-lg">
|
||||
<div className="flex items-center justify-between mb-3">
|
||||
<div className="flex items-center gap-2">
|
||||
<Database className="w-5 h-5" />
|
||||
<span className="font-medium">備機資料庫</span>
|
||||
{databaseStatus.currentDatabase === 'slave' && (
|
||||
<Badge variant="default" className="bg-blue-100 text-blue-800">
|
||||
當前使用
|
||||
</Badge>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{databaseStatus.slaveHealthy ? (
|
||||
<CheckCircle2 className="w-5 h-5 text-green-500" />
|
||||
) : (
|
||||
<XCircle className="w-5 h-5 text-red-500" />
|
||||
)}
|
||||
<Badge variant={databaseStatus.slaveHealthy ? "default" : "destructive"}>
|
||||
{databaseStatus.slaveHealthy ? '正常' : '故障'}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div>
|
||||
<span className="text-muted-foreground">主機:</span>
|
||||
<span className="ml-2 font-mono">122.100.99.161:43306</span>
|
||||
</div>
|
||||
<div>
|
||||
<span className="text-muted-foreground">資料庫:</span>
|
||||
<span className="ml-2 font-mono">db_AI_Platform</span>
|
||||
</div>
|
||||
</div>
|
||||
{databaseStatus.currentDatabase !== 'slave' && databaseStatus.slaveHealthy && (
|
||||
<Button
|
||||
size="sm"
|
||||
className="mt-3"
|
||||
onClick={() => switchDatabase('slave')}
|
||||
>
|
||||
切換到備機
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* 狀態說明 */}
|
||||
<div className="p-3 bg-yellow-50 border border-yellow-200 rounded-lg">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-yellow-600 mt-0.5" />
|
||||
<div className="text-sm text-yellow-800">
|
||||
<p className="font-medium">注意事項:</p>
|
||||
<ul className="mt-1 space-y-1 text-xs">
|
||||
<li>• 系統會自動在健康檢查時切換資料庫</li>
|
||||
<li>• 手動切換僅在目標資料庫健康時有效</li>
|
||||
<li>• 建議在維護時手動切換到備機</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="p-8 text-center">
|
||||
<Database className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
|
||||
<p className="text-muted-foreground">
|
||||
{isLoadingStatus ? '載入資料庫狀態中...' : '點擊重新整理按鈕載入資料庫狀態'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* 資料庫同步管理 */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Database className="w-5 h-5" />
|
||||
資料庫同步管理
|
||||
</CardTitle>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={fetchSyncStatus}
|
||||
disabled={isLoadingSync}
|
||||
>
|
||||
<RefreshCw className={`w-4 h-4 mr-2 ${isLoadingSync ? 'animate-spin' : ''}`} />
|
||||
重新整理
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
{syncStatus ? (
|
||||
<>
|
||||
{/* 同步狀態概覽 */}
|
||||
<div className="p-4 bg-gray-50 border rounded-lg">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<span className="font-medium">雙寫同步狀態</span>
|
||||
<Badge variant={syncStatus.enabled ? "default" : "secondary"}>
|
||||
{syncStatus.enabled ? "已啟用" : "未啟用"}
|
||||
</Badge>
|
||||
</div>
|
||||
<div className="text-sm text-gray-600">
|
||||
<p>主機健康: {syncStatus.masterHealthy ? "正常" : "異常"}</p>
|
||||
<p>備機健康: {syncStatus.slaveHealthy ? "正常" : "異常"}</p>
|
||||
{syncStatus.lastSyncTime && (
|
||||
<p>最後同步: {new Date(syncStatus.lastSyncTime).toLocaleString()}</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 手動同步操作 */}
|
||||
<div className="space-y-3">
|
||||
<h4 className="font-medium">手動同步表資料</h4>
|
||||
<div className="grid grid-cols-2 gap-2">
|
||||
{['users', 'apps', 'teams', 'competitions', 'proposals', 'activity_logs'].map((tableName) => (
|
||||
<Button
|
||||
key={tableName}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={() => syncTable(tableName)}
|
||||
className="justify-start"
|
||||
>
|
||||
<Database className="w-4 h-4 mr-2" />
|
||||
同步 {tableName}
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* 同步說明 */}
|
||||
<div className="p-3 bg-blue-50 border border-blue-200 rounded-lg">
|
||||
<div className="flex items-start gap-2">
|
||||
<AlertCircle className="w-4 h-4 text-blue-600 mt-0.5" />
|
||||
<div className="text-sm text-blue-800">
|
||||
<p className="font-medium">同步說明:</p>
|
||||
<ul className="mt-1 space-y-1 text-xs">
|
||||
<li>• 手動同步會將主機資料複製到備機</li>
|
||||
<li>• 建議在維護期間進行同步操作</li>
|
||||
<li>• 同步過程中請避免對資料進行修改</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
<div className="p-8 text-center">
|
||||
<Database className="w-12 h-12 mx-auto text-muted-foreground mb-4" />
|
||||
<p className="text-muted-foreground">
|
||||
{isLoadingSync ? '載入同步狀態中...' : '點擊重新整理按鈕載入同步狀態'}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
</TabsContent>
|
||||
|
||||
{/* 用戶管理 */}
|
||||
|
@@ -858,7 +858,6 @@ export function UserManagement() {
|
||||
<TableHead>狀態</TableHead>
|
||||
<TableHead>加入日期</TableHead>
|
||||
<TableHead>最後登入</TableHead>
|
||||
<TableHead>統計</TableHead>
|
||||
<TableHead>操作</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
@@ -901,12 +900,6 @@ export function UserManagement() {
|
||||
</TableCell>
|
||||
<TableCell className="text-sm text-gray-600">{user.joinDate || "-"}</TableCell>
|
||||
<TableCell className="text-sm text-gray-600">{user.lastLogin || "-"}</TableCell>
|
||||
<TableCell>
|
||||
<div className="text-sm">
|
||||
<p>{user.appCount || 0} 應用</p>
|
||||
<p className="text-gray-500">{user.reviewCount || 0} 評價</p>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
|
@@ -42,6 +42,7 @@ import {
|
||||
} from "lucide-react"
|
||||
import { FavoriteButton } from "./favorite-button"
|
||||
import { ReviewSystem } from "./reviews/review-system"
|
||||
import { PieChart, Pie, Cell, ResponsiveContainer, Tooltip, Legend } from "recharts"
|
||||
|
||||
interface AppDetailDialogProps {
|
||||
open: boolean
|
||||
@@ -93,6 +94,7 @@ export function AppDetailDialog({ open, onOpenChange, app }: AppDetailDialogProp
|
||||
}
|
||||
})
|
||||
const [isLoadingStats, setIsLoadingStats] = useState(false)
|
||||
const [selectedDepartment, setSelectedDepartment] = useState<string | null>(null)
|
||||
|
||||
// Date range for usage trends
|
||||
const [startDate, setStartDate] = useState(() => {
|
||||
@@ -104,6 +106,9 @@ export function AppDetailDialog({ open, onOpenChange, app }: AppDetailDialogProp
|
||||
return new Date().toISOString().split("T")[0]
|
||||
})
|
||||
|
||||
// 圓餅圖顏色配置
|
||||
const COLORS = ['#3b82f6', '#8b5cf6', '#06b6d4', '#10b981', '#f59e0b', '#ef4444', '#84cc16', '#f97316']
|
||||
|
||||
// 圖標映射函數
|
||||
const getIconComponent = (iconName: string) => {
|
||||
const iconMap: { [key: string]: any } = {
|
||||
@@ -152,7 +157,7 @@ export function AppDetailDialog({ open, onOpenChange, app }: AppDetailDialogProp
|
||||
}
|
||||
|
||||
// 載入應用統計數據
|
||||
const loadAppStats = useCallback(async (customStartDate?: string, customEndDate?: string) => {
|
||||
const loadAppStats = useCallback(async (customStartDate?: string, customEndDate?: string, department?: string) => {
|
||||
if (!app.id) return
|
||||
|
||||
setIsLoadingStats(true)
|
||||
@@ -161,6 +166,7 @@ export function AppDetailDialog({ open, onOpenChange, app }: AppDetailDialogProp
|
||||
const params = new URLSearchParams()
|
||||
if (customStartDate) params.append('startDate', customStartDate)
|
||||
if (customEndDate) params.append('endDate', customEndDate)
|
||||
if (department) params.append('department', department)
|
||||
|
||||
const url = `/api/apps/${app.id}/stats${params.toString() ? `?${params.toString()}` : ''}`
|
||||
const response = await fetch(url)
|
||||
@@ -189,7 +195,22 @@ export function AppDetailDialog({ open, onOpenChange, app }: AppDetailDialogProp
|
||||
// 處理日期範圍變更
|
||||
const handleDateRangeChange = useCallback(async () => {
|
||||
if (startDate && endDate) {
|
||||
await loadAppStats(startDate, endDate)
|
||||
await loadAppStats(startDate, endDate, selectedDepartment || undefined)
|
||||
}
|
||||
}, [startDate, endDate, selectedDepartment, loadAppStats])
|
||||
|
||||
// 處理日期變更時重置部門選擇
|
||||
const handleDateChange = useCallback((newStartDate: string, newEndDate: string) => {
|
||||
setStartDate(newStartDate)
|
||||
setEndDate(newEndDate)
|
||||
setSelectedDepartment(null) // 重置部門選擇
|
||||
}, [])
|
||||
|
||||
// 處理部門選擇
|
||||
const handleDepartmentSelect = useCallback(async (department: string | null) => {
|
||||
setSelectedDepartment(department)
|
||||
if (startDate && endDate) {
|
||||
await loadAppStats(startDate, endDate, department || undefined)
|
||||
}
|
||||
}, [startDate, endDate, loadAppStats])
|
||||
|
||||
@@ -543,211 +564,315 @@ export function AppDetailDialog({ open, onOpenChange, app }: AppDetailDialogProp
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Usage Trends with Date Range */}
|
||||
{/* Date Range Filter */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<CardTitle>使用趨勢</CardTitle>
|
||||
<CardDescription>查看指定時間範圍內的使用者活躍度</CardDescription>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<CardTitle>數據篩選</CardTitle>
|
||||
<CardDescription>選擇日期範圍查看部門使用分布和使用趨勢</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex flex-col sm:flex-row gap-3 items-end">
|
||||
<div className="flex flex-col sm:flex-row gap-3 flex-1">
|
||||
<div className="flex items-center space-x-2">
|
||||
<Label htmlFor="start-date" className="text-sm">
|
||||
<Label htmlFor="start-date" className="text-sm whitespace-nowrap min-w-[60px]">
|
||||
開始日期
|
||||
</Label>
|
||||
<Input
|
||||
id="start-date"
|
||||
type="date"
|
||||
value={startDate}
|
||||
onChange={(e) => setStartDate(e.target.value)}
|
||||
onChange={(e) => handleDateChange(e.target.value, endDate)}
|
||||
className="w-36"
|
||||
max={endDate}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<Label htmlFor="end-date" className="text-sm">
|
||||
<Label htmlFor="end-date" className="text-sm whitespace-nowrap min-w-[60px]">
|
||||
結束日期
|
||||
</Label>
|
||||
<Input
|
||||
id="end-date"
|
||||
type="date"
|
||||
value={endDate}
|
||||
onChange={(e) => setEndDate(e.target.value)}
|
||||
onChange={(e) => handleDateChange(startDate, e.target.value)}
|
||||
className="w-36"
|
||||
min={startDate}
|
||||
max={new Date().toISOString().split("T")[0]}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleDateRangeChange}
|
||||
disabled={isLoadingStats || !startDate || !endDate}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
>
|
||||
{isLoadingStats ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-500 mr-1"></div>
|
||||
載入中
|
||||
</>
|
||||
) : (
|
||||
'重新載入'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleDateRangeChange}
|
||||
disabled={isLoadingStats || !startDate || !endDate}
|
||||
size="sm"
|
||||
variant="outline"
|
||||
className="whitespace-nowrap"
|
||||
>
|
||||
{isLoadingStats ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-blue-500 mr-1"></div>
|
||||
載入中
|
||||
</>
|
||||
) : (
|
||||
'重新載入'
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Analytics Layout */}
|
||||
<div className="grid grid-cols-1 xl:grid-cols-2 gap-6">
|
||||
{/* Department Usage Pie Chart */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>部門使用分布</CardTitle>
|
||||
<CardDescription>點擊部門查看該部門的使用趨勢</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
{isLoadingStats ? (
|
||||
<div className="h-80 flex items-center justify-center bg-gray-50 rounded-lg">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-2"></div>
|
||||
<p className="text-gray-500">載入使用趨勢數據中...</p>
|
||||
<p className="text-gray-500">載入部門數據中...</p>
|
||||
</div>
|
||||
</div>
|
||||
) : usageStats.trendData && usageStats.trendData.length > 0 ? (
|
||||
<>
|
||||
{/* Chart Container with Horizontal Scroll */}
|
||||
<div className="w-full overflow-x-auto">
|
||||
<div
|
||||
className="h-80 relative bg-gray-50 rounded-lg p-4"
|
||||
style={{
|
||||
minWidth: `${Math.max(800, usageStats.trendData.length * 40)}px`, // Dynamic width based on data points
|
||||
}}
|
||||
>
|
||||
{/* Month/Year Section Headers */}
|
||||
<div className="absolute top-2 left-4 right-4 flex">
|
||||
{(() => {
|
||||
const sections = getDateSections(usageStats.trendData)
|
||||
const totalBars = usageStats.trendData.length
|
||||
|
||||
return Object.entries(sections).map(([key, section]) => {
|
||||
const width = ((section.endIndex - section.startIndex + 1) / totalBars) * 100
|
||||
const left = (section.startIndex / totalBars) * 100
|
||||
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className="absolute text-xs font-medium text-gray-600 bg-white/90 px-2 py-1 rounded shadow-sm border"
|
||||
style={{
|
||||
left: `${left}%`,
|
||||
width: `${width}%`,
|
||||
textAlign: "center",
|
||||
}}
|
||||
>
|
||||
{section.label}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
})()}
|
||||
</div>
|
||||
|
||||
{/* Chart Bars */}
|
||||
<div className="h-full flex items-end justify-between space-x-2" style={{ paddingTop: "40px" }}>
|
||||
{usageStats.trendData.map((day: any, index: number) => {
|
||||
const maxUsers = Math.max(...usageStats.trendData.map((d: any) => d.users))
|
||||
const minUsers = Math.min(...usageStats.trendData.map((d: any) => d.users))
|
||||
const range = maxUsers - minUsers
|
||||
const normalizedHeight = range > 0 ? ((day.users - minUsers) / range) * 70 + 15 : 40
|
||||
|
||||
const currentDate = new Date(day.date)
|
||||
const prevDate = index > 0 ? new Date((usageStats.trendData[index - 1] as any).date) : null
|
||||
|
||||
// Check if this is the start of a new month/year for divider
|
||||
const isNewMonth =
|
||||
!prevDate ||
|
||||
currentDate.getMonth() !== prevDate.getMonth() ||
|
||||
currentDate.getFullYear() !== prevDate.getFullYear()
|
||||
|
||||
return (
|
||||
<div
|
||||
key={day.date}
|
||||
className="flex-1 flex flex-col items-center group relative"
|
||||
style={{ minWidth: "32px" }}
|
||||
>
|
||||
{/* Month divider line */}
|
||||
{isNewMonth && index > 0 && (
|
||||
<div className="absolute left-0 top-0 bottom-8 w-px bg-gray-300 opacity-50" />
|
||||
)}
|
||||
|
||||
<div
|
||||
className="w-full flex flex-col items-center justify-end"
|
||||
style={{ height: "200px" }}
|
||||
>
|
||||
<div
|
||||
className="w-full bg-gradient-to-t from-blue-500 to-purple-500 rounded-t-md transition-all duration-300 hover:from-blue-600 hover:to-purple-600 cursor-pointer relative"
|
||||
style={{ height: `${normalizedHeight}%` }}
|
||||
>
|
||||
{/* Value label */}
|
||||
<div className="absolute -top-5 left-1/2 transform -translate-x-1/2 text-xs font-medium text-gray-600 bg-white/80 px-1 rounded">
|
||||
{day.users}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Consistent day-only labels */}
|
||||
<div className="text-xs text-gray-500 mt-2 text-center">{currentDate.getDate()}日</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
) : usageStats.topDepartments && usageStats.topDepartments.length > 0 ? (
|
||||
<div className="space-y-4">
|
||||
<ResponsiveContainer width="100%" height={300}>
|
||||
<PieChart>
|
||||
<Pie
|
||||
data={usageStats.topDepartments.map((dept: any, index: number) => ({
|
||||
name: dept.department || '未知部門',
|
||||
value: dept.count,
|
||||
color: COLORS[index % COLORS.length]
|
||||
}))}
|
||||
cx="50%"
|
||||
cy="50%"
|
||||
labelLine={false}
|
||||
label={({ name, percent }) => `${name} ${((percent || 0) * 100).toFixed(0)}%`}
|
||||
outerRadius={80}
|
||||
fill="#8884d8"
|
||||
dataKey="value"
|
||||
onClick={(data) => {
|
||||
const department = data.name === '未知部門' ? null : data.name
|
||||
handleDepartmentSelect(department)
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
{usageStats.topDepartments.map((dept: any, index: number) => (
|
||||
<Cell
|
||||
key={`cell-${index}`}
|
||||
fill={COLORS[index % COLORS.length]}
|
||||
className="cursor-pointer hover:opacity-80 transition-opacity"
|
||||
/>
|
||||
))}
|
||||
</Pie>
|
||||
<Tooltip formatter={(value: any) => [`${value} 人`, '使用人數']} />
|
||||
</PieChart>
|
||||
</ResponsiveContainer>
|
||||
|
||||
{/* Department Legend */}
|
||||
<div className="space-y-2">
|
||||
{usageStats.topDepartments.map((dept: any, index: number) => {
|
||||
const totalUsers = usageStats.topDepartments.reduce((sum: number, d: any) => sum + d.count, 0)
|
||||
const percentage = totalUsers > 0 ? Math.round((dept.count / totalUsers) * 100) : 0
|
||||
const isSelected = selectedDepartment === dept.department
|
||||
|
||||
return (
|
||||
<div
|
||||
key={dept.department || index}
|
||||
className={`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${
|
||||
isSelected ? 'bg-blue-50 border border-blue-200' : 'hover:bg-gray-50'
|
||||
}`}
|
||||
onClick={() => {
|
||||
const department = dept.department === '未知部門' ? null : dept.department
|
||||
handleDepartmentSelect(department)
|
||||
}}
|
||||
>
|
||||
<div className="flex items-center space-x-3">
|
||||
<div
|
||||
className="w-3 h-3 rounded-full"
|
||||
style={{ backgroundColor: COLORS[index % COLORS.length] }}
|
||||
/>
|
||||
<span className="font-medium">{dept.department || '未知部門'}</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-sm text-gray-600">{dept.count} 人</span>
|
||||
<span className="text-sm font-medium">{percentage}%</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* Scroll Hint */}
|
||||
{usageStats.trendData && usageStats.trendData.length > 20 && (
|
||||
<div className="text-xs text-gray-500 text-center">💡 提示:圖表可左右滑動查看更多數據</div>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-80 flex items-center justify-center bg-gray-50 rounded-lg">
|
||||
<div className="text-center text-gray-500">
|
||||
<TrendingUp className="w-12 h-12 mx-auto mb-2 text-gray-300" />
|
||||
<p>在選定的日期範圍內暫無使用數據</p>
|
||||
<p className="text-sm mt-1">請嘗試選擇其他日期範圍</p>
|
||||
<Building className="w-12 h-12 mx-auto mb-2 text-gray-300" />
|
||||
<p>暫無部門使用數據</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Department Usage */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>部門使用分布</CardTitle>
|
||||
<CardDescription>各部門使用者比例</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
{usageStats.topDepartments && usageStats.topDepartments.length > 0 ? (
|
||||
usageStats.topDepartments.map((dept: any, index: number) => {
|
||||
const totalUsers = usageStats.topDepartments.reduce((sum: number, d: any) => sum + d.count, 0)
|
||||
const percentage = totalUsers > 0 ? Math.round((dept.count / totalUsers) * 100) : 0
|
||||
|
||||
return (
|
||||
<div key={dept.department || index} className="flex items-center justify-between">
|
||||
<div className="flex items-center space-x-3">
|
||||
<div className="w-3 h-3 bg-gradient-to-r from-blue-500 to-purple-500 rounded-full" />
|
||||
<span className="font-medium">{dept.department || '未知部門'}</span>
|
||||
</div>
|
||||
<div className="flex items-center space-x-2">
|
||||
<span className="text-sm text-gray-600">{dept.count} 人</span>
|
||||
<span className="text-sm font-medium">{percentage}%</span>
|
||||
{/* Usage Trends */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle>使用趨勢</CardTitle>
|
||||
<CardDescription>
|
||||
{selectedDepartment ? `${selectedDepartment} 部門的使用趨勢` : '查看指定時間範圍內的使用者活躍度'}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="space-y-4">
|
||||
{isLoadingStats ? (
|
||||
<div className="h-80 flex items-center justify-center bg-gray-50 rounded-lg">
|
||||
<div className="text-center">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-500 mx-auto mb-2"></div>
|
||||
<p className="text-gray-500">載入使用趨勢數據中...</p>
|
||||
</div>
|
||||
</div>
|
||||
) : usageStats.trendData && usageStats.trendData.length > 0 ? (
|
||||
<>
|
||||
{/* Chart Container with Horizontal Scroll */}
|
||||
<div className="w-full overflow-x-auto">
|
||||
<div
|
||||
className="h-80 relative bg-gray-50 rounded-lg p-4"
|
||||
style={{
|
||||
minWidth: `${Math.max(400, usageStats.trendData.length * 80)}px`, // Dynamic width based on data points
|
||||
}}
|
||||
>
|
||||
{/* Month/Year Section Headers - Full Width */}
|
||||
<div className="absolute top-2 left-4 right-4 flex">
|
||||
{(() => {
|
||||
const sections = getDateSections(usageStats.trendData)
|
||||
const totalBars = usageStats.trendData.length
|
||||
const barWidth = 60 // 每個柱子寬度
|
||||
const barGap = 12 // 柱子間距
|
||||
const chartLeft = 20 // paddingLeft
|
||||
const totalChartWidth = totalBars * barWidth + (totalBars - 1) * barGap
|
||||
|
||||
return Object.entries(sections).map(([key, section]) => {
|
||||
// 計算該月份在柱狀圖中的實際位置
|
||||
const sectionStartBar = section.startIndex
|
||||
const sectionEndBar = section.endIndex
|
||||
const sectionBarCount = sectionEndBar - sectionStartBar + 1
|
||||
|
||||
// 計算該月份標籤的起始位置(相對於圖表區域)
|
||||
const sectionLeft = sectionStartBar * (barWidth + barGap)
|
||||
const sectionWidth = sectionBarCount * barWidth + (sectionBarCount - 1) * barGap
|
||||
|
||||
// 轉換為相對於整個容器的百分比(從左邊界開始)
|
||||
const containerWidth = chartLeft + totalChartWidth
|
||||
const leftPercent = ((sectionLeft + chartLeft) / containerWidth) * 100
|
||||
const widthPercent = (sectionWidth / containerWidth) * 100
|
||||
|
||||
return (
|
||||
<div
|
||||
key={key}
|
||||
className="absolute text-xs font-medium text-gray-700 bg-blue-50 px-3 py-1 rounded shadow-sm border border-blue-200"
|
||||
style={{
|
||||
left: `${leftPercent}%`,
|
||||
width: `${widthPercent}%`,
|
||||
textAlign: "center",
|
||||
minWidth: "60px", // 確保標籤有最小寬度
|
||||
}}
|
||||
>
|
||||
{section.label}
|
||||
</div>
|
||||
)
|
||||
})
|
||||
})()}
|
||||
</div>
|
||||
|
||||
{/* Y-axis labels and grid lines */}
|
||||
<div className="absolute left-2 top-12 bottom-8 flex flex-col justify-between text-xs text-gray-500">
|
||||
<span>{Math.max(...usageStats.trendData.map((d: any) => d.users))}</span>
|
||||
<span>{Math.round(Math.max(...usageStats.trendData.map((d: any) => d.users)) * 0.75)}</span>
|
||||
<span>{Math.round(Math.max(...usageStats.trendData.map((d: any) => d.users)) * 0.5)}</span>
|
||||
<span>{Math.round(Math.max(...usageStats.trendData.map((d: any) => d.users)) * 0.25)}</span>
|
||||
<span>0</span>
|
||||
</div>
|
||||
|
||||
{/* Grid lines */}
|
||||
<div className="absolute left-10 top-12 bottom-8 right-4 flex flex-col justify-between">
|
||||
{[0, 0.25, 0.5, 0.75, 1].map((ratio, index) => (
|
||||
<div key={index} className="w-full h-px bg-gray-200 opacity-50"></div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* Chart Bars */}
|
||||
<div className="h-full flex items-end justify-start gap-3" style={{ paddingTop: "40px", paddingLeft: "40px" }}>
|
||||
{usageStats.trendData.map((day: any, index: number) => {
|
||||
const maxUsers = Math.max(...usageStats.trendData.map((d: any) => d.users))
|
||||
const minUsers = Math.min(...usageStats.trendData.map((d: any) => d.users))
|
||||
const range = maxUsers - minUsers
|
||||
const normalizedHeight = range > 0 ? ((day.users - minUsers) / range) * 70 + 15 : 40
|
||||
|
||||
const currentDate = new Date(day.date)
|
||||
const prevDate = index > 0 ? new Date((usageStats.trendData[index - 1] as any).date) : null
|
||||
|
||||
// Check if this is the start of a new month/year for divider
|
||||
const isNewMonth =
|
||||
!prevDate ||
|
||||
currentDate.getMonth() !== prevDate.getMonth() ||
|
||||
currentDate.getFullYear() !== prevDate.getFullYear()
|
||||
|
||||
return (
|
||||
<div
|
||||
key={day.date}
|
||||
className="flex flex-col items-center group relative"
|
||||
style={{ width: "80px" }}
|
||||
>
|
||||
{/* Month divider line */}
|
||||
{isNewMonth && index > 0 && (
|
||||
<div className="absolute left-0 top-0 bottom-8 w-px bg-gray-300 opacity-50" />
|
||||
)}
|
||||
|
||||
<div
|
||||
className="w-full flex flex-col items-center justify-end"
|
||||
style={{ height: "200px" }}
|
||||
>
|
||||
<div
|
||||
className="w-8 bg-gradient-to-t from-blue-500 to-purple-500 rounded-t-md transition-all duration-300 hover:from-blue-600 hover:to-purple-600 cursor-pointer relative shadow-sm"
|
||||
style={{ height: `${normalizedHeight}%` }}
|
||||
>
|
||||
{/* Value label */}
|
||||
<div className="absolute -top-6 left-1/2 transform -translate-x-1/2 text-xs font-medium text-gray-700 bg-white/90 px-2 py-1 rounded shadow-sm border">
|
||||
{day.users}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Consistent day-only labels */}
|
||||
<div className="text-xs text-gray-500 mt-2 text-center">{currentDate.getDate()}日</div>
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
) : (
|
||||
<div className="text-center text-gray-500 py-8">
|
||||
<Building className="w-12 h-12 mx-auto mb-2 text-gray-300" />
|
||||
<p>暫無部門使用數據</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Scroll Hint */}
|
||||
{usageStats.trendData && usageStats.trendData.length > 20 && (
|
||||
<div className="text-xs text-gray-500 text-center">💡 提示:圖表可左右滑動查看更多數據</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="h-80 flex items-center justify-center bg-gray-50 rounded-lg">
|
||||
<div className="text-center text-gray-500">
|
||||
<TrendingUp className="w-12 h-12 mx-auto mb-2 text-gray-300" />
|
||||
<p>在選定的日期範圍內暫無使用數據</p>
|
||||
<p className="text-sm mt-1">請嘗試選擇其他日期範圍</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</TabsContent>
|
||||
|
||||
<TabsContent value="reviews" className="space-y-6">
|
||||
|
Reference in New Issue
Block a user