First commit to the code repository

This commit is contained in:
Liujian committed 2025-07-20 22:38:52 +08:00
1 parent 692cdee407
commit 0c0dd1cb56
323 files changed
+45712

No files matched your search

@@ -0,0 +1,169 @@
"use client";
import {
Modal,
ModalContent,
ModalHeader,
ModalBody,
ModalFooter,
Button,
Input,
} from "@nextui-org/react";
import { useEffect, useState } from "react";
import { Copy } from "lucide-react";
import toast from "react-hot-toast";
import { APIKey } from "@/shared/types/api";
import { useTranslation } from "@/shared/lib/useTranslation";
import { fetchAPI } from "@/shared/rpc/common-function";
import { copyToClipboard } from "@/shared/utils/clipboard";
interface APIKeyModalProps {
isOpen: boolean;
onClose: () => void;
onSubmitSuccess?: (keyData: APIKey) => void;
initialName?: string;
generatedKey?: string;
mode: "create" | "edit";
id?: string;
}
export const APIKeyModal = ({
isOpen,
onClose,
onSubmitSuccess,
initialName = "",
generatedKey,
mode,
id,
}: APIKeyModalProps) => {
const { t } = useTranslation();
const [name, setName] = useState(initialName);
const [isLoading, setIsLoading] = useState(false);
useEffect(() => {
setName(initialName);
}, [initialName]);
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === "Enter" && !isLoading) {
handleSubmit();
}
};
const handleSubmit = async () => {
const keyName = name.trim();
if (!keyName) return;
setIsLoading(true);
try {
if (mode === "create") {
const response = await fetchAPI<APIKey>("/api/apikey/info", {
method: "POST",
body: { name: keyName } as unknown as BodyInit,
});
if (!response.success) {
console.error("Error creating auth key:", response.error_message);
toast.error(t("Failed to create auth key"));
return;
}
if (onSubmitSuccess && response.data) {
onSubmitSuccess(response.data);
}
} else if (mode === "edit" && id) {
const response = await fetchAPI<APIKey>("/api/apikey/info", {
method: "PUT",
body: { apikey_id: id, name: keyName } as unknown as BodyInit,
});
if (!response.success) {
console.error("Error updating auth key:", response.error_message);
toast.error(t("Failed to update auth key"));
return;
}
if (onSubmitSuccess && response.data) {
onSubmitSuccess(response.data);
}
toast.success(t("Auth key updated successfully"));
onClose();
}
} catch (error) {
console.error("Error creating/updating auth key:", error);
toast.error(t("Failed to create/update auth key"));
} finally {
setIsLoading(false);
}
};
const handleCopyKey = async () => {
if (generatedKey) {
const result = await copyToClipboard(generatedKey);
if (result.success) {
toast.success(t("Copied to clipboard"));
} else {
toast.error(t("Copy failed, please copy manually"));
}
}
};
return (
<Modal isOpen={isOpen} onClose={onClose} isDismissable={false} size="2xl">
<ModalContent>
<ModalHeader>
{generatedKey
? t("Authorization Created")
: mode === "create"
? t("Create New Authorization")
: t("Edit Authorization")}
</ModalHeader>
<ModalBody>
{!generatedKey ? (
<Input
label={t("Authorization Name")}
placeholder={t("Edit authorization name")}
value={name}
onChange={(e) => setName(e.target.value)}
onKeyDown={handleKeyDown}
autoFocus
/>
) : (
<div>
<p className="text-sm text-gray-600 mb-2">
{t("Your Auth Key:")}
</p>
<div className="flex items-center gap-2 bg-gray-100 p-2 rounded relative justify-between">
<span >{generatedKey}</span>
<Button
isIconOnly
size="sm"
variant="light"
onPress={handleCopyKey}
>
<Copy className="w-4 h-4" />
</Button>
</div>
</div>
)}
</ModalBody>
<ModalFooter>
<Button color="danger" variant="light" onPress={onClose}>
{generatedKey ? t("Done") : t("Close")}
</Button>
{!generatedKey && (
<Button
color="primary"
onPress={handleSubmit}
isLoading={isLoading}
isDisabled={!name.trim() || isLoading}
>
{t("Save")}
</Button>
)}
</ModalFooter>
</ModalContent>
</Modal>
);
};
@@ -0,0 +1,258 @@
import React, { useState, useEffect, useCallback } from "react";
import { useTranslation } from "react-i18next";
import {
Card,
CardBody,
CardHeader,
Button,
Divider,
Spinner,
} from "@nextui-org/react";
import { Edit2, Trash2, Copy, RefreshCw } from "lucide-react";
import {
BarChart,
Bar,
XAxis,
YAxis,
CartesianGrid,
ResponsiveContainer,
Tooltip as RechartsTooltip,
} from "recharts";
import toast from "react-hot-toast";
import { fetchAPI } from "@/shared/rpc/common-function";
import { APIKey } from "@/shared/types/api";
import { copyToClipboard } from "@/shared/utils/clipboard";
interface AuthKeyDetailsProps {
selectedApiKey: APIKey | null;
onEditKey: (key: APIKey) => void;
onDeleteKey: (key: APIKey) => void;
}
interface ApiAnalyticsData {
stats_day: string;
call_tool_count: number;
}
// Custom cursor to highlight the hovered bar with a lighter and narrower overlay
const CustomCursor: React.FC<{
x?: number;
y?: number;
width?: number;
height?: number;
}> = ({ x = 0, y = 0, height = 0, width = 0 }) => {
const barVisualWidth = 20;
// Use the bar's visual width directly so the highlight precisely matches the bar
const overlayWidth = barVisualWidth;
// Center the overlay within the default cursor width
const offsetX = x + (width - overlayWidth) / 2;
return (
<rect
x={offsetX}
y={y}
width={overlayWidth}
height={height}
fill="rgba(0, 0, 0, 0.1)" // lighter mask color
/>
);
};
const AuthKeyDetails: React.FC<AuthKeyDetailsProps> = ({
selectedApiKey,
onEditKey,
onDeleteKey,
}) => {
const { t } = useTranslation();
const [analyticsData, setAnalyticsData] = useState<
{ name: string; value: number }[]
>([]);
const [isLoading, setIsLoading] = useState<boolean>(false);
const fetchAnalyticsData = useCallback(async () => {
if (!selectedApiKey) return;
try {
setIsLoading(true);
const response = await fetchAPI(
`/api/stats/key_call_tool_count?apikey_id=${selectedApiKey.apikey_id}`,
{
method: "GET",
}
);
if (response.success && response.data?.days) {
const formattedData = response.data.days.map(
(day: ApiAnalyticsData) => ({
name: new Date(day.stats_day).toISOString().split("T")[0],
value: day.call_tool_count,
})
);
setAnalyticsData(formattedData);
} else {
console.error("Analytics data fetch error:", response.error_message);
}
} catch (error) {
console.error("Analytics data fetch error:", error);
} finally {
setIsLoading(false);
}
}, [selectedApiKey, t]);
useEffect(() => {
if (!selectedApiKey?.apikey_id) return
fetchAnalyticsData();
}, [selectedApiKey?.apikey_id]);
const handleCopy = async (text: string) => {
const result = await copyToClipboard(text);
if (result.success) {
toast.success(t("Copied to clipboard"));
} else {
toast.error(t("Copy failed, please copy manually"));
}
};
const getEncryptedKey = (key: string) => {
return key.slice(0, 2) + "*".repeat(key.length - 7) + key.slice(-5);
};
if (!selectedApiKey) {
return <></>;
}
return (
<div className="flex-1 overflow-hidden">
{/* Selected Key Details */}
<Card shadow="none" className="h-full">
<CardHeader className="px-6 py-4">
<div className="flex justify-between items-center w-full">
<h2 className="text-xl font-semibold text-gray-900">
{selectedApiKey.name}
</h2>
<div className="flex gap-2">
<Button
isIconOnly
size="sm"
variant="bordered"
onPress={() => onEditKey(selectedApiKey)}
>
<Edit2 size={18} />
</Button>
<Button
isIconOnly
size="sm"
variant="bordered"
color="danger"
onPress={() => onDeleteKey(selectedApiKey)}
>
<Trash2 size={18} />
</Button>
</div>
</div>
</CardHeader>
<Divider />
<CardBody className="px-6 py-6">
{/* MCP Config Section */}
<div className="mb-6">
<div className="flex justify-between items-center w-full mb-4">
<h3 className="text-lg font-semibold text-gray-900">
{t("Auth Key")}
</h3>
</div>
<div className="flex items-center gap-2 bg-gray-100 p-2 rounded relative justify-between">
<span className="overflow-hidden text-ellipsis whitespace-nowrap">{getEncryptedKey(selectedApiKey.apikey)}</span>
<Button
isIconOnly
size="sm"
variant="light"
onPress={() => handleCopy(selectedApiKey.apikey)}
>
<Copy className="w-4 h-4" />
</Button>
</div>
</div>
{/* Analytics Section */}
<Card
shadow="none"
className="overflow-visible justify-between h-full"
>
<CardHeader className="px-0 py-4">
<div className="flex justify-between items-center w-full">
<h2 className="text-xl font-semibold text-gray-900">
{t("Analytics")}
</h2>
<Button
isIconOnly
size="sm"
variant="flat"
onPress={() => fetchAnalyticsData()}
>
<RefreshCw size={18} />
</Button>
</div>
</CardHeader>
<CardBody className="px-0" style={{ height: "280px" }}>
{analyticsData.length > 0 ? (
<ResponsiveContainer width="100%" height="100%">
<BarChart
data={analyticsData}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
>
<CartesianGrid strokeDasharray="3 3" stroke="#f0f0f0" />
<XAxis
dataKey="name"
axisLine={false}
tickLine={false}
tick={{ fontSize: 12, fill: "#666" }}
/>
<YAxis
axisLine={false}
tickLine={false}
tick={{ fontSize: 12, fill: "#666" }}
allowDecimals={false}
/>
<RechartsTooltip
cursor={<CustomCursor />}
formatter={(value: number) => [value, t("Times")]}
contentStyle={{
backgroundColor: "#fff",
border: "1px solid #e5e7eb",
borderRadius: "6px",
boxShadow: "0 4px 6px -1px rgba(0, 0, 0, 0.1)",
fontSize: "12px",
lineHeight: "1.5",
padding: "5px",
}}
/>
<Bar
dataKey="value"
fill="#3b82f6"
radius={[4, 4, 0, 0]}
maxBarSize={20}
/>
</BarChart>
</ResponsiveContainer>
) : (
<div className="flex items-center justify-center h-full">
{isLoading ? (
<Spinner size="lg" color="default" />
) : (
<p className="text-gray-500">
{t("No analytics data available")}
</p>
)}
</div>
)}
</CardBody>
</Card>
</CardBody>
</Card>
</div>
);
};
export default AuthKeyDetails;
@@ -0,0 +1,85 @@
import React from "react";
import { useTranslation } from "react-i18next";
import {
Card,
CardBody,
CardHeader,
Button,
Divider,
Listbox,
ListboxItem,
} from "@nextui-org/react";
import { Plus } from "lucide-react";
import { APIKey } from "@/shared/types/api";
interface AuthKeysListProps {
apiKeys: APIKey[] | null;
selectedApiKey: APIKey | null;
onNewKey: () => void;
onSelectKey: (key: APIKey) => void;
}
const AuthKeysList: React.FC<AuthKeysListProps> = ({
apiKeys,
selectedApiKey,
onNewKey,
onSelectKey,
}) => {
const { t } = useTranslation();
return (
<div className="min-w-[300px] w-[300px] bg-default-100/50 h-full">
<Card
shadow="none"
radius="none"
className="bg-transparent flex flex-col h-full"
>
<CardHeader className="flex justify-between items-center px-6 py-4">
<h2 className="text-xl font-semibold text-gray-900">
{t("Auth Key")}
</h2>
<Button
size="sm"
color="primary"
startContent={<Plus size={16} />}
onPress={onNewKey}
>
{t("New")}
</Button>
</CardHeader>
<Divider />
<CardBody className="flex-grow overflow-y-auto">
<Listbox
aria-label="Auth keys list"
items={apiKeys || []}
selectionMode="single"
selectedKeys={selectedApiKey ? [selectedApiKey.apikey_id] : []}
onSelectionChange={(keys) => {
const selectedId = Array.from(keys)[0];
const selectedKey = (apiKeys || []).find(
(k) => k.apikey_id === selectedId
);
if (selectedKey) onSelectKey(selectedKey);
}}
itemClasses={{
title: "text-md font-medium",
base: "bg-white p-6 transition-colors border-1 data-[selected=true]:focus:bg-primary-50 data-[selected=true]:data-[hover=true]:bg-primary-50 data-[selected=true]:border-primary-500 data-[selected=true]:bg-primary-50 data-[hover=true]:bg-default/50 data-[selectable=true]:focus:bg-default/50",
}}
classNames={{
list: "gap-4",
}}
hideSelectedIcon
>
{(key) => (
<ListboxItem key={key.apikey_id} textValue={key.name}>
{key.name}
</ListboxItem>
)}
</Listbox>
</CardBody>
</Card>
</div>
);
};
export default AuthKeysList;
@@ -0,0 +1,242 @@
import React, { useState, useEffect } from "react";
import {
Card,
CardBody,
CardHeader,
Button,
Divider,
Spinner,
} from "@nextui-org/react";
import { Plus, InboxIcon } from "lucide-react";
import toast from "react-hot-toast";
import { APIKey } from "@/shared/types/api";
import { fetchAPI } from "@/shared/rpc/common-function";
import AuthKeysList from "./AuthKeysList";
import AuthKeyDetails from "./AuthKeyDetails";
import { APIKeyModal } from "./APIKeyModal";
import { DeleteConfirmModal } from "@/shared/components/modal/DeleteConfirmModal";
import DashboardDemoContent from "@/shared/components/DashboardDemoContent";
import { useTranslation } from "@/shared/lib/useTranslation";
const OverviewPage: React.FC = () => {
const { t } = useTranslation();
// Auth Keys related states
const [isKeyModalOpen, setIsKeyModalOpen] = useState(false);
const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);
const [selectedApiKey, setSelectedApiKey] = useState<APIKey | null>(null);
const [generatedKey, setGeneratedKey] = useState<string | undefined>();
const [isLoading, setIsLoading] = useState(false);
const [apiKeys, setApiKeys] = useState<APIKey[] | null>(null);
const [editingApiKey, setEditingApiKey] = useState<APIKey | null>(null);
// fetch auth keys
const fetchApiKeys = async () => {
setIsLoading(true);
try {
const response = await fetchAPI("/api/apikey/list");
if (!response.success) {
return;
}
setApiKeys(response.data || []);
// if there are auth keys, select the first one as default
if (response.data && response.data.length > 0) {
setSelectedApiKey(response.data[0]);
}
} catch (error) {
console.error("Error fetching auth keys:", error);
} finally {
setIsLoading(false);
}
};
useEffect(() => {
fetchApiKeys();
}, []);
// create new auth key
const handleNewKey = () => {
openEditModal();
};
// edit auth key
const handleEditKey = (key: APIKey) => {
openEditModal(key);
};
// delete auth key
const handleDeleteKey = async () => {
if (!selectedApiKey) {
return;
}
const apikey_id = selectedApiKey.apikey_id;
const response = await fetchAPI("/api/apikey/info", {
method: "DELETE",
body: {
apikey_id,
} as unknown as BodyInit,
});
if (!response.success) {
console.error("Error deleting key:", response.error_message);
toast.error(t("Failed to delete"));
return;
}
toast.success(t("Deleted successfully"));
setIsDeleteModalOpen(false);
const updatedKeys =
apiKeys?.filter((key) => key.apikey_id !== apikey_id) || [];
setApiKeys(updatedKeys);
if (updatedKeys.length > 0) {
setSelectedApiKey(updatedKeys[0]);
} else {
setSelectedApiKey(null);
}
};
// select auth key
const handleSelectKey = (key: APIKey) => {
setSelectedApiKey(key);
};
// open edit auth key modal
const openEditModal = (keyData?: APIKey) => {
setEditingApiKey(keyData || null);
setGeneratedKey(undefined);
setIsKeyModalOpen(true);
};
// open delete auth key modal
const openDeleteModal = (keyData: APIKey) => {
setSelectedApiKey(keyData);
setIsDeleteModalOpen(true);
};
// create auth key success callback
const handleCreateKeySuccess = (keyData: APIKey) => {
const newKeys = [...(apiKeys || []), keyData];
setApiKeys(newKeys);
setGeneratedKey(keyData.apikey);
setSelectedApiKey(keyData);
};
// edit key success callback
const handleEditKeySuccess = ({ name }: APIKey) => {
if (!editingApiKey) return;
const id = editingApiKey.apikey_id;
const updatedKeys =
apiKeys?.map((key) =>
key.apikey_id === id
? {
...key,
name,
}
: key
) || [];
setApiKeys(updatedKeys);
setSelectedApiKey({ ...editingApiKey, name });
setEditingApiKey(null);
};
return (
<DashboardDemoContent title="My Dashboard" description="Manage your integration and auth key">
{/* Main Content */}
{isLoading ? (
<>
<div className="flex items-center justify-center py-12 mt-20">
<Spinner size="lg" color="default" />
</div>
</>
) : !apiKeys || apiKeys.length === 0 ? (
<>
<div className="w-full bg-default-100/50 h-full border-1 rounded-lg">
<Card
shadow="none"
radius="none"
className="bg-transparent flex flex-col h-full"
>
<CardHeader className="flex justify-between items-center px-6 py-4">
<h2 className="text-xl font-semibold text-gray-900">
{t("Auth Key")}
</h2>
<Button
size="sm"
color="primary"
startContent={<Plus size={16} />}
onPress={handleNewKey}
>
{t("New")}
</Button>
</CardHeader>
<Divider />
<CardBody className="flex items-center justify-center">
<InboxIcon size={96} className="text-gray-200" />
</CardBody>
</Card>
</div>
</>
) : (
<div className="flex border-1 border-gray-200 rounded-lg items-stretch overflow-hidden h-full">
<AuthKeysList
apiKeys={apiKeys}
selectedApiKey={selectedApiKey}
onNewKey={handleNewKey}
onSelectKey={handleSelectKey}
/>
<Divider orientation="vertical" className="h-auto" />
<AuthKeyDetails
selectedApiKey={selectedApiKey}
onEditKey={handleEditKey}
onDeleteKey={openDeleteModal}
/>
</div>
)}
{/* modal */}
<APIKeyModal
isOpen={isKeyModalOpen}
onClose={() => {
setIsKeyModalOpen(false);
if (!apiKeys?.length) {
setSelectedApiKey(null);
}
setGeneratedKey(undefined);
setEditingApiKey(null);
}}
onSubmitSuccess={
editingApiKey &&
apiKeys?.some((k) => k.apikey_id === editingApiKey.apikey_id)
? handleEditKeySuccess
: handleCreateKeySuccess
}
initialName={editingApiKey?.name}
generatedKey={generatedKey}
mode={
editingApiKey &&
apiKeys?.some((k) => k.apikey_id === editingApiKey.apikey_id)
? "edit"
: "create"
}
id={editingApiKey?.apikey_id}
/>
<DeleteConfirmModal
isOpen={isDeleteModalOpen}
onClose={() => {
setIsDeleteModalOpen(false);
}}
onConfirm={handleDeleteKey}
title={t("Delete Auth Key")}
description={t('Are you sure you want to delete the "{{keyName}}" Auth key?', {
keyName: selectedApiKey?.name || "",
})}
/>
</DashboardDemoContent>
);
};
export default OverviewPage;
+197
View File
@@ -0,0 +1,197 @@
"use client";
import React, { useEffect, useState, Suspense } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { useGlobalStore } from "@/shared/store/global";
import DashboardSidebar from "@/shared/components/DashboardSidebar";
import { SidebarItem, TabKey } from "@/shared/types/dashboard";
import { useSharedStore } from "@/shared/store/share";
import { formatCurrency } from '@/shared/utils/currency';
// Import dashboard content components
import DashboardOverview from "@/components/dashboard/DashboardOverview";
import WalletManagement from "@/components/wallet/WalletManagement";
import { Home, Wallet } from "lucide-react";
import { Avatar, Card, CardBody, Button, Divider } from "@nextui-org/react";
import { RechargeModal } from "@/shared/components/modal/RechargeModal";
import { useTranslation } from "@/shared/lib/useTranslation";
const DashboardContent: React.FC = () => {
const { t } = useTranslation();
const router = useRouter();
const searchParams = useSearchParams();
const [user_token, user] = useSharedStore((state) => [state.user_token, state.user]);
const [logOut, useGetUser] = useGlobalStore((state) => [
state.logOut,
state.useGetUser,
]);
const { data } = useGetUser();
// Recharge modal state
const [isRechargeModalOpen, setIsRechargeModalOpen] = useState(false);
const getInitialTab = (): TabKey => {
const tabFromUrl = searchParams.get("tab") as TabKey;
if (
tabFromUrl &&
[
"overview",
"wallet"
].includes(tabFromUrl)
) {
return tabFromUrl;
}
return "overview";
};
const [activeTab, setActiveTab] = useState<TabKey>(getInitialTab);
useEffect(() => {
if (!data) return;
if (data.code === "1000001") {
console.warn("user not found");
return;
}
}, [data]);
// If user is not logged in, redirect to login page
useEffect(() => {
if (!user_token) {
window.location.href = "/";
}
}, [user_token]);
const handleLogout = () => {
// use global store logout method
logOut();
window.location.href = "/";
};
// handle recharge with proper error handling and loading states
const handleRecharge = async () => {
setIsRechargeModalOpen(true);
};
const sidebarItems: SidebarItem[] = [
{
key: "overview",
icon: <Home className="w-5 h-5" />,
label: "Dashboard",
description: "Manage your integration and auth key",
},
// {
// key: "wallet",
// icon: <Wallet className="w-5 h-5" />,
// label: "My Wallet",
// description: "Manage your balance and recharge history",
// },
];
const handleTabNavigate = (tab: TabKey) => {
setActiveTab(tab);
// update url params
if (tab === "overview") {
// when switch to dashboard, clear all query params, only keep base path
router.push("/dashboard", { scroll: false });
} else {
// other tabs set corresponding tab params
const params = new URLSearchParams();
params.set("tab", tab);
router.push(`/dashboard?${params.toString()}`, { scroll: false });
}
};
return (
<div className="min-h-screen bg-background">
<div className="flex">
{/* Sidebar */}
<DashboardSidebar
activeTab={activeTab}
onTabNavigate={handleTabNavigate}
onLogout={handleLogout}
sidebarItems={sidebarItems}
userProfilePanel={
user && (
<div className="mb-6 space-y-3">
{/* User Information Card */}
<Card className="border-1 bg-default-100" shadow="none">
<CardBody className="p-4 gap-4">
<div className="flex items-center gap-3">
<Avatar
isBordered
src={user?.avatar || ""}
name={user.user_name || "User"}
/>
<div className="flex-1 min-w-0">
<p className="font-medium text-sm truncate">
{user.user_name || "Jack Liu"}
</p>
<p className="text-tiny text-default-600">
{user.user_name
? `${user.user_name.toLowerCase()}@gmail.com`
: "xpack@gmail.com"}
</p>
</div>
</div>
<Divider />
<div className="flex justify-between text-xs">
<div className="flex gap-2 items-center">
<Wallet size={16} />
<span>{t("Balance: {{amount}}", { amount: formatCurrency(user?.wallet?.balance || 0) })}</span>
</div>
<Button
variant="bordered"
onPress={handleRecharge}
aria-label="Recharge wallet"
size="sm"
>
{t("Recharge")}
</Button>
</div>
</CardBody>
</Card>
</div>
)
}
/>
{/* Main Content */}
<div className="flex-1 h-screen overflow-y-auto">
{activeTab === "overview" && <DashboardOverview />}
{activeTab === "wallet" && (
<WalletManagement onRecharge={() => setIsRechargeModalOpen(true)} />
)}
</div>
</div>
{/* recharge modal */}
<RechargeModal
isOpen={isRechargeModalOpen}
onClose={() => setIsRechargeModalOpen(false)}
/>
</div>
);
};
const DashboardMain: React.FC = () => {
return (
<Suspense
fallback={
<div className="min-h-screen bg-background flex items-center justify-center">
Loading...
</div>
}
>
<DashboardContent />
</Suspense>
);
};
export default DashboardMain;