refactor: migrate customer and skill definition pages to use DashboardCrudPage component

- Replaced existing customer and skill definition page implementations with DashboardCrudPage for improved structure and functionality.
- Simplified state management and data fetching logic.
- Enhanced filtering and column definitions for better user experience.
- Updated translations to include new labels and processing messages.
This commit is contained in:
mlogclub
2026-05-28 09:52:47 +08:00
parent 2cb834efa3
commit 6a3c641ff9
6 changed files with 888 additions and 2009 deletions
+231 -536
View File
@@ -1,67 +1,16 @@
"use client"; "use client";
import { import { BotMessageSquareIcon, PowerIcon } from "lucide-react";
closestCenter, import { useMemo } from "react";
DndContext,
KeyboardSensor,
MouseSensor,
TouchSensor,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import {
BotMessageSquareIcon,
GripVerticalIcon,
MoreHorizontalIcon,
PlusIcon,
PowerIcon,
RefreshCwIcon,
SearchIcon,
Trash2Icon,
} from "lucide-react";
import {
useCallback,
useEffect,
useState,
type CSSProperties,
} from "react";
import { toast } from "sonner";
import { import {
DashboardPage, DashboardCrudPage,
DashboardTableShell, createDashboardStatusColumn,
DashboardTableStateRow, createDashboardStatusToggleAction,
DashboardToolbar, type DashboardCrudColumn,
} from "@/components/dashboard-page"; type DashboardCrudFilter,
import { ListPagination } from "@/components/list-pagination"; } from "@/components/dashboard/crud";
import { OptionCombobox } from "@/components/option-combobox";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { import {
createAIAgent, createAIAgent,
deleteAIAgent, deleteAIAgent,
@@ -71,13 +20,10 @@ import {
updateAIAgentStatus, updateAIAgentStatus,
type AIAgent, type AIAgent,
type CreateAIAgentPayload, type CreateAIAgentPayload,
type PageResult,
} from "@/lib/api/admin"; } from "@/lib/api/admin";
import { IMConversationServiceMode, Status } from "@/lib/generated/enums"; import { IMConversationServiceMode, Status } from "@/lib/generated/enums";
import { useI18n } from "@/i18n/provider"; import { useI18n } from "@/i18n/provider";
import { cn } from "@/lib/utils";
import { EditDialog } from "./_components/edit"; import { EditDialog } from "./_components/edit";
import { ButtonGroup } from "@/components/ui/button-group";
type TFunction = (key: string, values?: Record<string, string | number>) => string; type TFunction = (key: string, values?: Record<string, string | number>) => string;
@@ -110,488 +56,237 @@ function getServiceModeLabel(mode: number, t: TFunction) {
} }
} }
type SortableAIAgentRowProps = { function getNextStatus(item: AIAgent) {
item: AIAgent; return item.status === Status.Ok ? Status.Disabled : Status.Ok;
disabled: boolean;
actionLoadingId: number | null;
t: TFunction;
openEditDialog: (item: AIAgent) => void;
handleToggleStatus: (item: AIAgent) => void;
handleDelete: (item: AIAgent) => void;
};
function SortableAIAgentRow({
item,
disabled,
actionLoadingId,
t,
openEditDialog,
handleToggleStatus,
handleDelete,
}: SortableAIAgentRowProps) {
const knowledgeIds = item.knowledgeIds ?? [];
const knowledgeBaseNames = item.knowledgeBaseNames ?? [];
const skills = item.skills ?? [];
const directTools = item.directTools ?? [];
const directToolServerCodes = Array.from(
new Set(directTools.map((tool) => tool.serverCode).filter(Boolean)),
);
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({
id: item.id,
disabled,
});
const style: CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
};
return (
<TableRow
ref={setNodeRef}
style={style}
className={cn(
isDragging && "relative z-10 bg-muted/60 shadow-sm",
!disabled && "cursor-move",
)}
>
<TableCell className="w-14">
<Button
type="button"
variant="ghost"
size="icon"
className="size-8 cursor-grab active:cursor-grabbing"
disabled={disabled}
aria-label={t("aiAgent.dragSort", { name: item.name })}
{...attributes}
{...listeners}
>
<GripVerticalIcon className="size-4 text-muted-foreground" />
</Button>
</TableCell>
<TableCell>
<div className="flex items-center gap-3">
<div className="flex size-10 items-center justify-center rounded-2xl bg-muted">
<BotMessageSquareIcon className="size-4" />
</div>
<div>
<div className="font-medium">{item.name}</div>
</div>
</div>
</TableCell>
<TableCell>
{item.aiConfigName || "-"}
</TableCell>
<TableCell>
{getServiceModeLabel(item.serviceMode, t)}
</TableCell>
<TableCell>
<div className="flex flex-wrap gap-1">
{knowledgeIds.length === 0 ? (
<span className="text-sm text-muted-foreground">
{t("aiAgent.notConfigured")}
</span>
) : (
knowledgeBaseNames.map((name, index) => (
<Badge key={knowledgeIds[index] ?? `${item.id}-${index}`} variant="secondary">
{name}
</Badge>
))
)}
</div>
</TableCell>
<TableCell>
<div className="flex flex-wrap gap-1">
{skills.length === 0 ? (
<span className="text-sm text-muted-foreground">{t("aiAgent.ragOnly")}</span>
) : (
skills.map((skill) => (
<Badge key={skill.id} variant="outline">
{skill.name}
</Badge>
))
)}
</div>
</TableCell>
<TableCell>
<div className="space-y-2">
<div className="flex flex-wrap gap-1">
<Badge variant="secondary">{skills.length} Skills</Badge>
<Badge variant="secondary">{directTools.length} Tools</Badge>
</div>
<div className="flex flex-wrap gap-1">
{directToolServerCodes.length === 0 ? (
<span className="text-sm text-muted-foreground">
{t("aiAgent.noMcpServer")}
</span>
) : (
directToolServerCodes.map((serverCode) => (
<Badge key={serverCode} variant="outline">
{serverCode}
</Badge>
))
)}
</div>
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-3">
<Switch
checked={item.status === Status.Ok}
disabled={actionLoadingId === item.id}
onCheckedChange={() => void handleToggleStatus(item)}
aria-label={t("aiAgent.toggleStatus", { name: item.name })}
/>
<Badge
variant={item.status === Status.Ok ? "default" : "secondary"}
>
{getStatusLabel(String(item.status), t)}
</Badge>
</div>
</TableCell>
<TableCell className="text-right">
<ButtonGroup className="ml-auto">
<Button
variant="outline"
size="sm"
onClick={() => openEditDialog(item)}
>
{t("aiAgent.edit")}
</Button>
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button variant="outline" size="icon-sm" className="ml-auto" />
}
aria-label={t("aiAgent.moreActions", { name: item.name })}
>
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
disabled={actionLoadingId === item.id}
onClick={() => void handleToggleStatus(item)}
>
<PowerIcon className="size-4" />
{item.status === Status.Ok ? t("aiAgent.stop") : t("aiAgent.enabled")}
</DropdownMenuItem>
<DropdownMenuItem
className="text-destructive"
disabled={actionLoadingId === item.id}
onClick={() => void handleDelete(item)}
>
<Trash2Icon className="size-4" />
{t("aiAgent.delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
</TableCell>
</TableRow>
);
} }
export default function DashboardAIAgentsPage() { export default function DashboardAIAgentsPage() {
const t = useI18n(); const t = useI18n();
const statusOptions = getStatusOptions(t); const statusOptions = useMemo(() => getStatusOptions(t), [t]);
const [nameInput, setNameInput] = useState("");
const [statusInput, setStatusInput] = useState("all");
const [name, setName] = useState("");
const [status, setStatus] = useState("all");
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(20);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null);
const [sorting, setSorting] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [editingItemId, setEditingItemId] = useState<number | null>(null);
const [result, setResult] = useState<PageResult<AIAgent>>({
results: [],
page: { page: 1, limit: 20, total: 0 },
});
const sensors = useSensors( const filters = useMemo<DashboardCrudFilter[]>(
useSensor(MouseSensor, { () => [
activationConstraint: { distance: 8 }, {
}), name: "name",
useSensor(TouchSensor, { label: t("aiAgent.filterName"),
activationConstraint: { delay: 150, tolerance: 8 }, placeholder: t("aiAgent.filterName"),
}), defaultValue: "",
useSensor(KeyboardSensor, { trim: true,
coordinateGetter: sortableKeyboardCoordinates, className: "w-full sm:w-56",
}), },
{
name: "status",
label: t("aiAgent.allStatuses"),
type: "select",
defaultValue: "all",
allValue: "all",
options: statusOptions,
className: "w-full sm:w-52",
},
],
[statusOptions, t],
); );
const loadData = useCallback(async () => { const columns = useMemo<DashboardCrudColumn<AIAgent>[]>(
setLoading(true); () => [
try { {
const data = await fetchAIAgents({ key: "agent",
name: name.trim() || undefined, label: "Agent",
status: status === "all" ? undefined : status, render: (item) => (
page, <div className="flex items-center gap-3">
limit, <div className="flex size-10 items-center justify-center rounded-md bg-muted text-muted-foreground">
}); <BotMessageSquareIcon className="size-4" />
setResult(data); </div>
} catch (error) { <div className="font-medium">{item.name}</div>
toast.error( </div>
error instanceof Error ? error.message : t("aiAgent.loadFailed"), ),
); },
} finally { {
setLoading(false); key: "aiConfig",
} label: t("aiAgent.columnAiConfig"),
}, [limit, name, page, status, t]); render: (item) => item.aiConfigName || "-",
},
useEffect(() => { {
void loadData(); key: "serviceMode",
}, [loadData]); label: t("aiAgent.columnServiceMode"),
render: (item) => getServiceModeLabel(item.serviceMode, t),
function applyFilters() { },
setName(nameInput); {
setStatus(statusInput); key: "knowledge",
setPage(1); label: t("aiAgent.columnKnowledge"),
} render: (item) => {
const knowledgeIds = item.knowledgeIds ?? [];
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) { const knowledgeBaseNames = item.knowledgeBaseNames ?? [];
if (event.key !== "Enter") { return (
return; <div className="flex flex-wrap gap-1">
} {knowledgeIds.length === 0 ? (
event.preventDefault(); <span className="text-sm text-muted-foreground">
applyFilters(); {t("aiAgent.notConfigured")}
} </span>
) : (
function openCreateDialog() { knowledgeBaseNames.map((name, index) => (
setEditingItemId(null); <Badge
setDialogOpen(true); key={knowledgeIds[index] ?? `${item.id}-${index}`}
} variant="secondary"
>
function openEditDialog(item: AIAgent) { {name}
setEditingItemId(item.id); </Badge>
setDialogOpen(true); ))
} )}
</div>
async function handleSubmit(payload: CreateAIAgentPayload) { );
if (saving) { },
return; },
} {
setSaving(true); key: "skills",
try { label: t("aiAgent.columnSkills"),
if (editingItemId) { render: (item) => {
await updateAIAgent({ id: editingItemId, ...payload }); const skills = item.skills ?? [];
toast.success(t("aiAgent.updated", { name: payload.name })); return (
} else { <div className="flex flex-wrap gap-1">
const created = await createAIAgent(payload); {skills.length === 0 ? (
toast.success(t("aiAgent.created", { name: created.name })); <span className="text-sm text-muted-foreground">
} {t("aiAgent.ragOnly")}
setDialogOpen(false); </span>
setEditingItemId(null); ) : (
await loadData(); skills.map((skill) => (
} catch (error) { <Badge key={skill.id} variant="outline">
toast.error( {skill.name}
error instanceof Error ? error.message : t("aiAgent.saveFailed"), </Badge>
); ))
} finally { )}
setSaving(false); </div>
} );
} },
},
async function handleToggleStatus(item: AIAgent) { {
setActionLoadingId(item.id); key: "capabilities",
try { label: t("aiAgent.columnCapabilities"),
const nextStatus = render: (item) => {
item.status === Status.Ok ? Status.Disabled : Status.Ok; const skills = item.skills ?? [];
await updateAIAgentStatus(item.id, nextStatus); const directTools = item.directTools ?? [];
toast.success( const directToolServerCodes = Array.from(
t("aiAgent.statusChanged", { new Set(directTools.map((tool) => tool.serverCode).filter(Boolean)),
name: item.name, );
status: nextStatus === Status.Ok ? t("aiAgent.enabled") : t("aiAgent.stop"), return (
}), <div className="space-y-2">
); <div className="flex flex-wrap gap-1">
await loadData(); <Badge variant="secondary">{skills.length} Skills</Badge>
} catch (error) { <Badge variant="secondary">{directTools.length} Tools</Badge>
toast.error( </div>
error instanceof Error ? error.message : t("aiAgent.statusUpdateFailed"), <div className="flex flex-wrap gap-1">
); {directToolServerCodes.length === 0 ? (
} finally { <span className="text-sm text-muted-foreground">
setActionLoadingId(null); {t("aiAgent.noMcpServer")}
} </span>
} ) : (
directToolServerCodes.map((serverCode) => (
async function handleDelete(item: AIAgent) { <Badge key={serverCode} variant="outline">
setActionLoadingId(item.id); {serverCode}
try { </Badge>
await deleteAIAgent(item.id); ))
toast.success(t("aiAgent.deleted", { name: item.name })); )}
await loadData(); </div>
} catch (error) { </div>
toast.error( );
error instanceof Error ? error.message : t("aiAgent.deleteFailed"), },
); },
} finally { createDashboardStatusColumn<AIAgent, number>({
setActionLoadingId(null); label: t("aiAgent.columnStatus"),
} getStatus: (item) => item.status,
} getLabel: (status) => getStatusLabel(String(status), t),
getBadgeVariant: (status) =>
async function handleDragEnd(event: DragEndEvent) { status === Status.Ok ? "default" : "secondary",
const { active, over } = event; isEnabled: (status) => status === Status.Ok,
if (!over || active.id === over.id || sorting) { toggle: {
return; getNextStatus,
} updateStatus: (item, nextStatus) =>
updateAIAgentStatus(item.id, nextStatus),
const previousResults = result.results; successMessage: (item, nextStatus) =>
const oldIndex = previousResults.findIndex((item) => item.id === active.id); t("aiAgent.statusChanged", {
const newIndex = previousResults.findIndex((item) => item.id === over.id); name: item.name,
if (oldIndex < 0 || newIndex < 0) { status:
return; nextStatus === Status.Ok
} ? t("aiAgent.enabled")
: t("aiAgent.stop"),
const nextResults = arrayMove(previousResults, oldIndex, newIndex); }),
setResult((current) => ({ errorMessage: t("aiAgent.statusUpdateFailed"),
...current, ariaLabel: (item) => t("aiAgent.toggleStatus", { name: item.name }),
results: nextResults, },
})); }),
setSorting(true); ],
[t],
try { );
await updateAIAgentSort(nextResults.map((item) => item.id));
toast.success(t("aiAgent.sortUpdated"));
await loadData();
} catch (error) {
setResult((current) => ({
...current,
results: previousResults,
}));
toast.error(error instanceof Error ? error.message : t("aiAgent.sortUpdateFailed"));
} finally {
setSorting(false);
}
}
return ( return (
<> <DashboardCrudPage<AIAgent, CreateAIAgentPayload>
<DashboardPage> filters={filters}
<DashboardToolbar columns={columns}
actions={ fetchList={(query) =>
<> fetchAIAgents({
<Button name: typeof query.name === "string" ? query.name : undefined,
variant="outline" status: typeof query.status === "string" ? query.status : undefined,
onClick={() => void loadData()} page: Number(query.page),
disabled={loading} limit: Number(query.limit),
> })
<RefreshCwIcon className={loading ? "animate-spin" : ""} /> }
{t("aiAgent.refresh")} getItemId={(item) => item.id}
</Button> createItem={createAIAgent}
<Button onClick={openCreateDialog}> updateItem={(item, payload) => updateAIAgent({ id: item.id, ...payload })}
<PlusIcon /> deleteItem={(item) => deleteAIAgent(item.id)}
{t("aiAgent.new")} rowActions={[
</Button> createDashboardStatusToggleAction<AIAgent, number>({
</> icon: <PowerIcon />,
} label: (item) =>
> item.status === Status.Ok ? t("aiAgent.stop") : t("aiAgent.enabled"),
<Input getNextStatus,
value={nameInput} updateStatus: (item, nextStatus) =>
onChange={(event) => setNameInput(event.target.value)} updateAIAgentStatus(item.id, nextStatus),
onKeyDown={handleFilterKeyDown} successMessage: (item, nextStatus) =>
placeholder={t("aiAgent.filterName")} t("aiAgent.statusChanged", {
className="w-full sm:w-56" name: item.name,
/> status:
<div className="w-full sm:w-52"> nextStatus === Status.Ok
<OptionCombobox ? t("aiAgent.enabled")
value={statusInput} : t("aiAgent.stop"),
options={statusOptions} }),
placeholder={t("aiAgent.allStatuses")} errorMessage: t("aiAgent.statusUpdateFailed"),
searchPlaceholder={t("aiAgent.searchStatus")} }),
emptyText={t("aiAgent.emptyStatus")} ]}
onChange={setStatusInput} sort={{
/> enabled: true,
</div> onReorder: (items) => updateAIAgentSort(items.map((item) => item.id)),
<Button variant="outline" onClick={applyFilters} disabled={loading}> successMessage: t("aiAgent.sortUpdated"),
<SearchIcon /> errorMessage: t("aiAgent.sortUpdateFailed"),
{t("aiAgent.query")} handleLabel: t("aiAgent.dragSort", { name: "" }),
</Button> }}
</DashboardToolbar> renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
<EditDialog
<DashboardTableShell open={open}
pagination={ saving={saving}
<ListPagination itemId={itemId}
page={result.page.page} onOpenChange={onOpenChange}
limit={result.page.limit} onSubmit={onSubmit}
total={result.page.total} />
onPageChange={(nextPage) => setPage(nextPage)} )}
onLimitChange={(nextLimit) => { labels={{
setLimit(nextLimit); refresh: t("aiAgent.refresh"),
setPage(1); create: t("aiAgent.new"),
}} query: t("aiAgent.query"),
/> loading: t("aiAgent.loadingRows"),
} empty: t("aiAgent.emptyRows"),
> actions: t("aiAgent.columnActions"),
<DndContext edit: t("aiAgent.edit"),
sensors={sensors} delete: t("aiAgent.delete"),
collisionDetection={closestCenter} processing: t("aiAgent.processing"),
onDragEnd={handleDragEnd} moreActions: (item) => t("aiAgent.moreActions", { name: item.name }),
> loadFailed: t("aiAgent.loadFailed"),
<Table> saveFailed: t("aiAgent.saveFailed"),
<TableHeader> deleteFailed: t("aiAgent.deleteFailed"),
<TableRow> created: (payload) => t("aiAgent.created", { name: payload.name }),
<TableHead className="w-14"></TableHead> updated: (_item, payload) => t("aiAgent.updated", { name: payload.name }),
<TableHead>Agent</TableHead> deleted: (item) => t("aiAgent.deleted", { name: item.name }),
<TableHead>{t("aiAgent.columnAiConfig")}</TableHead> }}
<TableHead>{t("aiAgent.columnServiceMode")}</TableHead> />
<TableHead>{t("aiAgent.columnKnowledge")}</TableHead>
<TableHead>{t("aiAgent.columnSkills")}</TableHead>
<TableHead>{t("aiAgent.columnCapabilities")}</TableHead>
<TableHead>{t("aiAgent.columnStatus")}</TableHead>
<TableHead className="w-[88px] text-right">
{t("aiAgent.columnActions")}
</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading || result.results.length === 0 ? (
<DashboardTableStateRow
colSpan={9}
loading={loading}
loadingText={t("aiAgent.loadingRows")}
emptyText={t("aiAgent.emptyRows")}
/>
) : null}
<SortableContext
items={result.results.map((item) => item.id)}
strategy={verticalListSortingStrategy}
>
{result.results.map((item) => (
<SortableAIAgentRow
key={item.id}
item={item}
disabled={sorting}
actionLoadingId={actionLoadingId}
t={t}
openEditDialog={openEditDialog}
handleToggleStatus={handleToggleStatus}
handleDelete={handleDelete}
/>
))}
</SortableContext>
</TableBody>
</Table>
</DndContext>
</DashboardTableShell>
</DashboardPage>
<EditDialog
open={dialogOpen}
saving={saving}
itemId={editingItemId}
onOpenChange={setDialogOpen}
onSubmit={handleSubmit}
/>
</>
); );
} }
+236 -633
View File
@@ -1,68 +1,14 @@
"use client"; "use client";
import { import { useMemo } from "react";
closestCenter,
DndContext,
KeyboardSensor,
MouseSensor,
TouchSensor,
useSensor,
useSensors,
type DragEndEvent,
} from "@dnd-kit/core";
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
useSortable,
verticalListSortingStrategy,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities";
import {
GripVerticalIcon,
MoreHorizontalIcon,
PlusIcon,
RefreshCwIcon,
SearchIcon,
Trash2Icon
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState, type CSSProperties } from "react";
import { toast } from "sonner";
import { import {
DashboardPage, DashboardCrudPage,
DashboardTableShell, createDashboardStatusColumn,
DashboardTableStateRow, type DashboardCrudColumn,
DashboardToolbar, type DashboardCrudFilter,
} from "@/components/dashboard-page"; } from "@/components/dashboard/crud";
import { ListPagination } from "@/components/list-pagination";
import { Badge } from "@/components/ui/badge"; import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ButtonGroup } from "@/components/ui/button-group";
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from "@/components/ui/dialog";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { import {
createAIConfig, createAIConfig,
deleteAIConfig, deleteAIConfig,
@@ -72,17 +18,10 @@ import {
updateAIConfigStatus, updateAIConfigStatus,
type AIConfig, type AIConfig,
type CreateAIConfigPayload, type CreateAIConfigPayload,
type PageResult,
} from "@/lib/api/admin"; } from "@/lib/api/admin";
import { import { AIModelType, AIProvider, Status } from "@/lib/generated/enums";
AIModelType,
AIProvider,
Status,
} from "@/lib/generated/enums";
import { useI18n } from "@/i18n/provider"; import { useI18n } from "@/i18n/provider";
import { cn } from "@/lib/utils";
import { EditDialog } from "./_components/edit"; import { EditDialog } from "./_components/edit";
import { OptionCombobox } from "./_components/option-combobox";
type TFunction = (key: string, values?: Record<string, string | number>) => string; type TFunction = (key: string, values?: Record<string, string | number>) => string;
@@ -99,199 +38,55 @@ function getProviderOptions(t: TFunction, includeAll = true) {
const options = [ const options = [
{ value: String(AIProvider.OpenAI), label: t("aiConfig.providerOpenAI") }, { value: String(AIProvider.OpenAI), label: t("aiConfig.providerOpenAI") },
]; ];
return includeAll ? [{ value: "all", label: t("aiConfig.allProviders") }, ...options] : options; return includeAll
? [{ value: "all", label: t("aiConfig.allProviders") }, ...options]
: options;
} }
function getModelTypeOptions(t: TFunction, includeAll = true) { function getModelTypeOptions(t: TFunction, includeAll = true) {
const options = [ const options = [
{ value: String(AIModelType.LLM), label: t("aiConfig.modelTypeLlm") }, { value: String(AIModelType.LLM), label: t("aiConfig.modelTypeLlm") },
{ value: String(AIModelType.Embedding), label: t("aiConfig.modelTypeEmbedding") }, {
value: String(AIModelType.Embedding),
label: t("aiConfig.modelTypeEmbedding"),
},
{ value: String(AIModelType.Rerank), label: t("aiConfig.modelTypeRerank") }, { value: String(AIModelType.Rerank), label: t("aiConfig.modelTypeRerank") },
]; ];
return includeAll ? [{ value: "all", label: t("aiConfig.allTypes") }, ...options] : options; return includeAll
? [{ value: "all", label: t("aiConfig.allTypes") }, ...options]
: options;
} }
function getStatusLabel(value: Status, t: TFunction) { function getStatusLabel(value: Status, t: TFunction) {
return getStatusOptions(t).find((item) => item.value === String(value))?.label ?? String(value); return (
getStatusOptions(t).find((item) => item.value === String(value))?.label ??
String(value)
);
} }
function getProviderLabel(value: AIProvider, t: TFunction) { function getProviderLabel(value: AIProvider, t: TFunction) {
return getProviderOptions(t, false).find((item) => item.value === String(value))?.label ?? String(value); return (
getProviderOptions(t, false).find((item) => item.value === String(value))
?.label ?? String(value)
);
} }
function getModelTypeLabel(value: AIModelType, t: TFunction) { function getModelTypeLabel(value: AIModelType, t: TFunction) {
return getModelTypeOptions(t, false).find((item) => item.value === String(value))?.label ?? String(value); return (
getModelTypeOptions(t, false).find((item) => item.value === String(value))
?.label ?? String(value)
);
} }
function maskAPIKey(value: string) { function maskAPIKey(value: string) {
const text = value.trim(); const text = value.trim();
if (!text) { if (!text) return "-";
return "-"; if (text.length <= 8) return "****";
}
if (text.length <= 8) {
return "****";
}
return `${text.slice(0, 4)}****${text.slice(-4)}`; return `${text.slice(0, 4)}****${text.slice(-4)}`;
} }
type SortableAIConfigRowProps = { function getNextStatus(item: AIConfig) {
item: AIConfig; return item.status === Status.Ok ? Status.Disabled : Status.Ok;
disabled: boolean;
actionLoadingId: number | null;
t: TFunction;
openEditDialog: (item: AIConfig) => void;
handleToggleStatus: (item: AIConfig) => void;
handleDelete: (item: AIConfig) => void;
};
function SortableAIConfigRow({
item,
disabled,
actionLoadingId,
t,
openEditDialog,
handleToggleStatus,
handleDelete,
}: SortableAIConfigRowProps) {
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({
id: item.id,
disabled,
});
const style: CSSProperties = {
transform: CSS.Transform.toString(transform),
transition,
};
return (
<TableRow
ref={setNodeRef}
style={style}
className={cn(
isDragging && "relative z-10 bg-muted/60 shadow-sm",
!disabled && "cursor-move",
)}
>
<TableCell className="w-14">
<Button
type="button"
variant="ghost"
size="icon"
className="size-8 cursor-grab active:cursor-grabbing"
disabled={disabled}
aria-label={t("aiConfig.dragSort", { name: item.name })}
{...attributes}
{...listeners}
>
<GripVerticalIcon className="size-4 text-muted-foreground" />
</Button>
</TableCell>
<TableCell>
<div className="space-y-1 text-sm font-medium">{item.name}</div>
</TableCell>
<TableCell>
<Badge variant="outline">
{getProviderLabel(item.provider as AIProvider, t)}
</Badge>
</TableCell>
<TableCell>
<div className="space-y-1">
<Badge variant="secondary">
{getModelTypeLabel(item.modelType as AIModelType, t)}
</Badge>
<div className="text-sm">{item.modelName}</div>
{item.dimension > 0 && (
<div className="text-xs text-muted-foreground">
{t("aiConfig.dimension", { count: item.dimension })}
</div>
)}
</div>
</TableCell>
<TableCell>
<div className="space-y-1 text-sm">
<div className="line-clamp-1">{item.baseUrl}</div>
<div className="text-xs text-muted-foreground">
{t("aiConfig.apiKey", { key: maskAPIKey(item.apiKey) })}
</div>
</div>
</TableCell>
<TableCell>
<div className="space-y-1 text-xs text-muted-foreground">
<div>{t("aiConfig.contextTokens", { count: item.maxContextTokens || 0 })}</div>
<div>{t("aiConfig.outputTokens", { count: item.maxOutputTokens || 0 })}</div>
<div>
{t("aiConfig.timeoutRetry", {
timeout: item.timeoutMs,
retries: item.maxRetryCount,
})}
</div>
<div>
RPM {item.rpmLimit || 0} / TPM {item.tpmLimit || 0}
</div>
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-3">
<Switch
checked={item.status === Status.Ok}
disabled={actionLoadingId === item.id}
onCheckedChange={() => void handleToggleStatus(item)}
aria-label={t("aiConfig.toggleStatus", { name: item.name })}
/>
<Badge
variant={
item.status === Status.Ok ? "default" : "outline"
}
>
{getStatusLabel(item.status as Status, t)}
</Badge>
</div>
</TableCell>
<TableCell className="text-right">
<ButtonGroup className="ml-auto">
<Button
variant="outline"
size="sm"
onClick={() => openEditDialog(item)}
>
{t("aiConfig.edit")}
</Button>
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant="outline" size="icon-sm" />}
aria-label={t("aiConfig.moreActions", { name: item.name })}
>
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40 min-w-40">
<DropdownMenuItem
disabled={
item.status === Status.Ok ||
actionLoadingId === item.id
}
onClick={() => void handleDelete(item)}
className="text-destructive focus:text-destructive"
>
<Trash2Icon />
{item.status === Status.Ok
? t("aiConfig.deleteDisabledActive")
: actionLoadingId === item.id
? t("aiConfig.deleting")
: t("aiConfig.delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
</TableCell>
</TableRow>
);
} }
export default function DashboardAIConfigsPage() { export default function DashboardAIConfigsPage() {
@@ -299,405 +94,213 @@ export default function DashboardAIConfigsPage() {
const listStatusOptions = useMemo(() => getStatusOptions(t), [t]); const listStatusOptions = useMemo(() => getStatusOptions(t), [t]);
const providerFilterOptions = useMemo(() => getProviderOptions(t), [t]); const providerFilterOptions = useMemo(() => getProviderOptions(t), [t]);
const modelTypeFilterOptions = useMemo(() => getModelTypeOptions(t), [t]); const modelTypeFilterOptions = useMemo(() => getModelTypeOptions(t), [t]);
const [keywordInput, setKeywordInput] = useState("");
const [statusFilterInput, setStatusFilterInput] = useState("all");
const [providerFilterInput, setProviderFilterInput] = useState("all");
const [modelTypeFilterInput, setModelTypeFilterInput] = useState("all");
const [keyword, setKeyword] = useState("");
const [statusFilter, setStatusFilter] = useState("all");
const [providerFilter, setProviderFilter] = useState("all");
const [modelTypeFilter, setModelTypeFilter] = useState("all");
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(20);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null);
const [sorting, setSorting] = useState(false);
const [dialogOpen, setDialogOpen] = useState(false);
const [editingItem, setEditingItem] = useState<AIConfig | null>(null);
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
const [deletingItem, setDeletingItem] = useState<AIConfig | null>(null);
const [result, setResult] = useState<PageResult<AIConfig>>({
results: [],
page: { page: 1, limit: 20, total: 0 },
});
const sensors = useSensors( const filters = useMemo<DashboardCrudFilter[]>(
useSensor(MouseSensor, { () => [
activationConstraint: { distance: 8 }, {
}), name: "name",
useSensor(TouchSensor, { label: t("aiConfig.filterName"),
activationConstraint: { delay: 150, tolerance: 8 }, placeholder: t("aiConfig.filterName"),
}), defaultValue: "",
useSensor(KeyboardSensor, { trim: true,
coordinateGetter: sortableKeyboardCoordinates, className: "w-full sm:w-72",
}), },
{
name: "modelType",
label: t("aiConfig.allTypes"),
type: "select",
defaultValue: "all",
allValue: "all",
options: modelTypeFilterOptions,
className: "w-full sm:w-40",
},
{
name: "provider",
label: t("aiConfig.allProviders"),
type: "select",
defaultValue: "all",
allValue: "all",
options: providerFilterOptions,
className: "w-full sm:w-40",
},
{
name: "status",
label: t("aiConfig.allStatuses"),
type: "select",
defaultValue: "all",
allValue: "all",
options: listStatusOptions,
className: "w-full sm:w-32",
},
],
[listStatusOptions, modelTypeFilterOptions, providerFilterOptions, t],
); );
const loadData = useCallback(async () => { const columns = useMemo<DashboardCrudColumn<AIConfig>[]>(
setLoading(true); () => [
try { {
const data = await fetchAIConfigs({ key: "config",
name: keyword.trim() || undefined, label: t("aiConfig.columnConfig"),
status: statusFilter === "all" ? undefined : statusFilter, render: (item) => (
provider: providerFilter === "all" ? undefined : providerFilter, <div className="space-y-1 text-sm font-medium">{item.name}</div>
modelType: modelTypeFilter === "all" ? undefined : modelTypeFilter, ),
page, },
limit, {
}); key: "provider",
setResult(data); label: t("aiConfig.columnProvider"),
} catch (error) { render: (item) => (
toast.error(error instanceof Error ? error.message : t("aiConfig.loadFailed")); <Badge variant="outline">
} finally { {getProviderLabel(item.provider as AIProvider, t)}
setLoading(false); </Badge>
} ),
}, [keyword, statusFilter, providerFilter, modelTypeFilter, page, limit, t]); },
{
useEffect(() => { key: "model",
void loadData(); label: t("aiConfig.columnModel"),
}, [loadData]); render: (item) => (
<div className="space-y-1">
function applyFilters() { <Badge variant="secondary">
setKeyword(keywordInput); {getModelTypeLabel(item.modelType as AIModelType, t)}
setStatusFilter(statusFilterInput); </Badge>
setProviderFilter(providerFilterInput); <div className="text-sm">{item.modelName}</div>
setModelTypeFilter(modelTypeFilterInput); {item.dimension > 0 ? (
setPage(1); <div className="text-xs text-muted-foreground">
} {t("aiConfig.dimension", { count: item.dimension })}
</div>
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) { ) : null}
if (event.key !== "Enter") { </div>
return; ),
} },
event.preventDefault(); {
applyFilters(); key: "access",
} label: t("aiConfig.columnAccess"),
render: (item) => (
function handlePageChange(nextPage: number) { <div className="space-y-1 text-sm">
if (nextPage < 1 || nextPage === page) { <div className="line-clamp-1">{item.baseUrl}</div>
return; <div className="text-xs text-muted-foreground">
} {t("aiConfig.apiKey", { key: maskAPIKey(item.apiKey) })}
setPage(nextPage); </div>
} </div>
),
function handleLimitChange(nextLimit: number) { },
if (nextLimit <= 0 || nextLimit === limit) { {
return; key: "limits",
} label: t("aiConfig.columnLimits"),
setLimit(nextLimit); render: (item) => (
setPage(1); <div className="space-y-1 text-xs text-muted-foreground">
} <div>
{t("aiConfig.contextTokens", {
function openCreateDialog() { count: item.maxContextTokens || 0,
setEditingItem(null); })}
setDialogOpen(true); </div>
} <div>
{t("aiConfig.outputTokens", {
function openEditDialog(item: AIConfig) { count: item.maxOutputTokens || 0,
setEditingItem(item); })}
setDialogOpen(true); </div>
} <div>
{t("aiConfig.timeoutRetry", {
function handleDialogOpenChange(open: boolean) { timeout: item.timeoutMs,
if (saving) { retries: item.maxRetryCount,
return; })}
} </div>
if (!open) { <div>
setEditingItem(null); RPM {item.rpmLimit || 0} / TPM {item.tpmLimit || 0}
} </div>
setDialogOpen(open); </div>
} ),
},
async function handleSubmit(payload: CreateAIConfigPayload) { createDashboardStatusColumn<AIConfig, number>({
if (saving) { label: t("aiConfig.columnStatus"),
return; getStatus: (item) => item.status,
} getLabel: (status) => getStatusLabel(status as Status, t),
getBadgeVariant: (status) =>
setSaving(true); status === Status.Ok ? "default" : "outline",
try { isEnabled: (status) => status === Status.Ok,
if (editingItem) { toggle: {
await updateAIConfig({ id: editingItem.id, ...payload }); getNextStatus,
toast.success(t("aiConfig.updated", { name: editingItem.name })); updateStatus: (item, nextStatus) =>
} else { updateAIConfigStatus(item.id, nextStatus),
await createAIConfig(payload); successMessage: (item, nextStatus) =>
toast.success(t("aiConfig.created", { name: payload.name })); t("aiConfig.statusChanged", {
} name: item.name,
setDialogOpen(false); status:
setEditingItem(null); nextStatus === Status.Ok
await loadData(); ? t("aiConfig.enabled")
} catch (error) { : t("aiConfig.disabled"),
toast.error(error instanceof Error ? error.message : t("aiConfig.saveFailed")); }),
} finally { errorMessage: t("aiConfig.statusUpdateFailed"),
setSaving(false); ariaLabel: (item) => t("aiConfig.toggleStatus", { name: item.name }),
} },
} }),
],
async function handleToggleStatus(item: AIConfig) { [t],
setActionLoadingId(item.id); );
try {
const nextStatus =
item.status === Status.Ok
? Status.Disabled
: Status.Ok;
await updateAIConfigStatus(item.id, nextStatus);
toast.success(
t("aiConfig.statusChanged", {
name: item.name,
status: nextStatus === Status.Ok ? t("aiConfig.enabled") : t("aiConfig.disabled"),
}),
);
await loadData();
} catch (error) {
toast.error(error instanceof Error ? error.message : t("aiConfig.statusUpdateFailed"));
} finally {
setActionLoadingId(null);
}
}
async function handleDelete(item: AIConfig) {
if (item.status === Status.Ok) {
toast.error(t("aiConfig.activeDeleteBlocked"));
return;
}
setDeletingItem(item);
setDeleteDialogOpen(true);
}
async function handleConfirmDelete() {
if (!deletingItem) {
return;
}
const item = deletingItem;
setActionLoadingId(item.id);
try {
await deleteAIConfig(item.id);
toast.success(t("aiConfig.deleted", { name: item.name }));
setDeleteDialogOpen(false);
setDeletingItem(null);
await loadData();
} catch (error) {
toast.error(error instanceof Error ? error.message : t("aiConfig.deleteFailed"));
} finally {
setActionLoadingId(null);
}
}
async function handleDragEnd(event: DragEndEvent) {
const { active, over } = event;
if (!over || active.id === over.id || sorting) {
return;
}
const previousResults = result.results;
const oldIndex = previousResults.findIndex((item) => item.id === active.id);
const newIndex = previousResults.findIndex((item) => item.id === over.id);
if (oldIndex < 0 || newIndex < 0) {
return;
}
const nextResults = arrayMove(previousResults, oldIndex, newIndex);
setResult((current) => ({
...current,
results: nextResults,
}));
setSorting(true);
try {
await updateAIConfigSort(nextResults.map((item) => item.id));
toast.success(t("aiConfig.sortUpdated"));
await loadData();
} catch (error) {
setResult((current) => ({
...current,
results: previousResults,
}));
toast.error(error instanceof Error ? error.message : t("aiConfig.sortUpdateFailed"));
} finally {
setSorting(false);
}
}
return ( return (
<> <DashboardCrudPage<AIConfig, CreateAIConfigPayload>
<DashboardPage> filters={filters}
<DashboardToolbar columns={columns}
actions={ fetchList={(query) =>
<> fetchAIConfigs({
<Button name: typeof query.name === "string" ? query.name : undefined,
variant="outline" status: typeof query.status === "string" ? query.status : undefined,
onClick={() => void loadData()} provider:
disabled={loading} typeof query.provider === "string" ? query.provider : undefined,
> modelType:
<RefreshCwIcon className={loading ? "animate-spin" : ""} /> typeof query.modelType === "string" ? query.modelType : undefined,
{t("aiConfig.refresh")} page: Number(query.page),
</Button> limit: Number(query.limit),
<Button onClick={openCreateDialog}> })
<PlusIcon /> }
{t("aiConfig.new")} getItemId={(item) => item.id}
</Button> createItem={createAIConfig}
</> updateItem={(item, payload) => updateAIConfig({ id: item.id, ...payload })}
} deleteItem={(item) => deleteAIConfig(item.id)}
> canDelete={(item) => item.status !== Status.Ok}
<div className="relative w-full sm:w-72"> deleteConfirm={(item) => ({
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" /> title: t("aiConfig.confirmDeleteTitle"),
<Input description: t("aiConfig.confirmDeleteDescription", {
value={keywordInput} name: item.name,
onChange={(event) => setKeywordInput(event.target.value)} }),
onKeyDown={handleFilterKeyDown} confirmText: t("aiConfig.confirmDelete"),
placeholder={t("aiConfig.filterName")} cancelText: t("aiConfig.cancel"),
className="pl-9" variant: "destructive",
/> })}
</div> sort={{
<div className="w-full sm:w-40"> enabled: true,
<OptionCombobox onReorder: (items) => updateAIConfigSort(items.map((item) => item.id)),
value={modelTypeFilterInput} successMessage: t("aiConfig.sortUpdated"),
options={modelTypeFilterOptions} errorMessage: t("aiConfig.sortUpdateFailed"),
placeholder={t("aiConfig.allTypes")} handleLabel: t("aiConfig.dragSort", { name: "" }),
searchPlaceholder={t("aiConfig.searchModelType")} }}
emptyText={t("aiConfig.emptyModelType")} renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
onChange={setModelTypeFilterInput} <EditDialog
/> open={open}
</div> saving={saving}
<div className="w-full sm:w-40"> itemId={itemId}
<OptionCombobox onOpenChange={onOpenChange}
value={providerFilterInput} onSubmit={onSubmit}
options={providerFilterOptions} />
placeholder={t("aiConfig.allProviders")} )}
searchPlaceholder={t("aiConfig.searchProvider")} labels={{
emptyText={t("aiConfig.emptyProvider")} refresh: t("aiConfig.refresh"),
onChange={setProviderFilterInput} create: t("aiConfig.new"),
/> query: t("aiConfig.query"),
</div> loading: t("aiConfig.loadingRows"),
<div className="w-full sm:w-32"> empty: t("aiConfig.emptyRows"),
<OptionCombobox actions: t("aiConfig.columnActions"),
value={statusFilterInput} edit: t("aiConfig.edit"),
options={listStatusOptions} delete: t("aiConfig.delete"),
placeholder={t("aiConfig.allStatuses")} processing: t("aiConfig.deleting"),
searchPlaceholder={t("aiConfig.searchStatus")} moreActions: (item) => t("aiConfig.moreActions", { name: item.name }),
emptyText={t("aiConfig.emptyStatus")} loadFailed: t("aiConfig.loadFailed"),
onChange={setStatusFilterInput} saveFailed: t("aiConfig.saveFailed"),
/> deleteFailed: t("aiConfig.deleteFailed"),
</div> created: (payload) => t("aiConfig.created", { name: payload.name }),
<Button variant="outline" onClick={applyFilters} disabled={loading}> updated: (item) => t("aiConfig.updated", { name: item.name }),
<SearchIcon /> deleted: (item) => t("aiConfig.deleted", { name: item.name }),
{t("aiConfig.query")} }}
</Button> />
</DashboardToolbar>
<DashboardTableShell
pagination={
<ListPagination
page={result.page.page}
limit={result.page.limit}
total={result.page.total}
onPageChange={handlePageChange}
onLimitChange={handleLimitChange}
/>
}
>
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-14"></TableHead>
<TableHead>{t("aiConfig.columnConfig")}</TableHead>
<TableHead>{t("aiConfig.columnProvider")}</TableHead>
<TableHead>{t("aiConfig.columnModel")}</TableHead>
<TableHead>{t("aiConfig.columnAccess")}</TableHead>
<TableHead>{t("aiConfig.columnLimits")}</TableHead>
<TableHead>{t("aiConfig.columnStatus")}</TableHead>
<TableHead className="text-right">{t("aiConfig.columnActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading || result.results.length === 0 ? (
<DashboardTableStateRow
colSpan={8}
loading={loading}
loadingText={t("aiConfig.loadingRows")}
emptyText={t("aiConfig.emptyRows")}
/>
) : (
<SortableContext
items={result.results.map((item) => item.id)}
strategy={verticalListSortingStrategy}
>
{result.results.map((item) => (
<SortableAIConfigRow
key={item.id}
item={item}
disabled={sorting}
actionLoadingId={actionLoadingId}
t={t}
openEditDialog={openEditDialog}
handleToggleStatus={handleToggleStatus}
handleDelete={handleDelete}
/>
))}
</SortableContext>
)}
</TableBody>
</Table>
</DndContext>
</DashboardTableShell>
</DashboardPage>
<EditDialog
open={dialogOpen}
saving={saving}
itemId={editingItem?.id ?? null}
onOpenChange={handleDialogOpenChange}
onSubmit={handleSubmit}
/>
<Dialog
open={deleteDialogOpen}
onOpenChange={(open) => {
if (actionLoadingId) {
return;
}
setDeleteDialogOpen(open);
if (!open) {
setDeletingItem(null);
}
}}
>
<DialogContent className="max-w-md" showCloseButton={false}>
<DialogHeader>
<DialogTitle>{t("aiConfig.confirmDeleteTitle")}</DialogTitle>
<DialogDescription>
{deletingItem
? t("aiConfig.confirmDeleteDescription", { name: deletingItem.name })
: t("aiConfig.deleteIrreversible")}
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button
type="button"
variant="outline"
disabled={!!actionLoadingId}
onClick={() => {
setDeleteDialogOpen(false);
setDeletingItem(null);
}}
>
{t("aiConfig.cancel")}
</Button>
<Button
type="button"
variant="destructive"
disabled={!!actionLoadingId}
onClick={() => void handleConfirmDelete()}
>
{actionLoadingId ? t("aiConfig.deleting") : t("aiConfig.confirmDelete")}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
</>
); );
} }
+195 -379
View File
@@ -1,47 +1,17 @@
"use client"; "use client";
import { import { BanIcon, CheckCircle2Icon } from "lucide-react";
BanIcon, import { useEffect, useMemo, useState } from "react";
CheckCircle2Icon,
MoreHorizontalIcon,
PlusIcon,
SearchIcon,
Trash2Icon,
} from "lucide-react";
import { useCallback, useEffect, useMemo, useState } from "react";
import { toast } from "sonner";
import { type CustomerFormSavePayload } from "@/components/customer-form"; import { type CustomerFormSavePayload } from "@/components/customer-form";
import { import {
DashboardPage, DashboardCrudPage,
DashboardTableShell, createDashboardStatusColumn,
DashboardTableStateRow, createDashboardStatusToggleAction,
DashboardToolbar, type DashboardCrudColumn,
} from "@/components/dashboard-page"; type DashboardCrudFilter,
import { ListPagination } from "@/components/list-pagination"; } from "@/components/dashboard/crud";
import { import { type ComboboxOption } from "@/components/option-combobox";
OptionCombobox,
type ComboboxOption,
} from "@/components/option-combobox";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ButtonGroup } from "@/components/ui/button-group";
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu";
import { Input } from "@/components/ui/input";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table";
import { type PageResult } from "@/lib/api/admin";
import { fetchCompanies, type AdminCompany } from "@/lib/api/company"; import { fetchCompanies, type AdminCompany } from "@/lib/api/company";
import { import {
deleteCustomer, deleteCustomer,
@@ -54,26 +24,16 @@ import { Gender, Status } from "@/lib/generated/enums";
import { useI18n } from "@/i18n/provider"; import { useI18n } from "@/i18n/provider";
import { EditDialog } from "./_components/edit"; import { EditDialog } from "./_components/edit";
function getLabel( type TFunction = (key: string, values?: Record<string, string | number>) => string;
value: string,
options: ReadonlyArray<{ value: string; label: string }>, function getGenderText(gender: number, t: TFunction) {
fallback: string, if (gender === Gender.Male) return t("customerForm.genderMale");
) { if (gender === Gender.Female) return t("customerForm.genderFemale");
return options.find((item) => item.value === value)?.label ?? fallback; return t("customerForm.genderUnknown");
} }
export default function DashboardCustomersPage() { export default function DashboardCustomersPage() {
const t = useI18n(); const t = useI18n();
const [keywordInput, setKeywordInput] = useState("");
const [statusFilterInput, setStatusFilterInput] = useState("all");
const [genderFilterInput, setGenderFilterInput] = useState("all");
const [companyFilterInput, setCompanyFilterInput] = useState("0");
const [keyword, setKeyword] = useState("");
const [statusFilter, setStatusFilter] = useState("all");
const [genderFilter, setGenderFilter] = useState("all");
const [companyFilter, setCompanyFilter] = useState("0");
const [companyOptions, setCompanyOptions] = useState<ComboboxOption[]>([ const [companyOptions, setCompanyOptions] = useState<ComboboxOption[]>([
{ value: "0", label: t("customer.allCompanies") }, { value: "0", label: t("customer.allCompanies") },
]); ]);
@@ -81,17 +41,6 @@ export default function DashboardCustomersPage() {
{}, {},
); );
const [page, setPage] = useState(1);
const [limit, setLimit] = useState(20);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null);
const [dialogOpen, setDialogOpen] = useState(false);
const [editingItem, setEditingItem] = useState<AdminCustomer | null>(null);
const [result, setResult] = useState<PageResult<AdminCustomer>>({
results: [],
page: { page: 1, limit: 20, total: 0 },
});
const listStatusOptions = useMemo( const listStatusOptions = useMemo(
() => [ () => [
{ value: "all", label: t("status.all") }, { value: "all", label: t("status.all") },
@@ -114,337 +63,204 @@ export default function DashboardCustomersPage() {
async function loadCompanies() { async function loadCompanies() {
try { try {
const data = await fetchCompanies({ status: 0, page: 1, limit: 500 }); const data = await fetchCompanies({ status: 0, page: 1, limit: 500 });
const opts: ComboboxOption[] = [ setCompanyOptions([
{ value: "0", label: t("customer.allCompanies") }, { value: "0", label: t("customer.allCompanies") },
...data.results.map((item) => ({ ...data.results.map((item) => ({
value: String(item.id), value: String(item.id),
label: item.name, label: item.name,
})), })),
]; ]);
setCompanyOptions(opts);
const map: Record<number, string> = {}; const map: Record<number, string> = {};
data.results.forEach((item: AdminCompany) => { data.results.forEach((item: AdminCompany) => {
map[item.id] = item.name; map[item.id] = item.name;
}); });
setCompanyNameMap(map); setCompanyNameMap(map);
} catch { } catch {
// ignore // Company names are optional display enrichment for this list.
} }
} }
void loadCompanies(); void loadCompanies();
}, [t]); }, [t]);
const loadData = useCallback(async () => { const filters = useMemo<DashboardCrudFilter[]>(
setLoading(true); () => [
try { {
const data = await fetchCustomers({ name: "keyword",
keyword: keyword.trim() || undefined, label: t("customer.columnName"),
status: statusFilter === "all" ? undefined : Number(statusFilter), placeholder: t("customer.keywordPlaceholder"),
gender: genderFilter === "all" ? undefined : Number(genderFilter), defaultValue: "",
companyId: companyFilter === "0" ? undefined : Number(companyFilter), trim: true,
page, className: "w-full sm:w-72",
limit, },
}); {
setResult(data); name: "gender",
} catch (error) { label: t("customer.columnGender"),
toast.error(error instanceof Error ? error.message : t("customer.loadFailed")); type: "select",
} finally { defaultValue: "all",
setLoading(false); allValue: "all",
} valueType: "number",
}, [companyFilter, genderFilter, keyword, limit, page, statusFilter, t]); options: genderOptions,
className: "w-full sm:w-36",
},
{
name: "companyId",
label: t("customer.columnCompany"),
type: "select",
defaultValue: "0",
allValue: "0",
valueType: "number",
options: companyOptions,
className: "w-full sm:w-56",
},
{
name: "status",
label: t("customer.columnStatus"),
type: "select",
defaultValue: "all",
allValue: "all",
valueType: "number",
options: listStatusOptions,
className: "w-full sm:w-36",
},
],
[companyOptions, genderOptions, listStatusOptions, t],
);
useEffect(() => { const columns = useMemo<DashboardCrudColumn<AdminCustomer>[]>(
void loadData(); () => [
}, [loadData]); {
key: "id",
const companyFilterLabel = useMemo(() => { label: "ID",
return ( className: "w-20",
companyOptions.find((item) => item.value === companyFilterInput)?.label ?? render: (item) => item.id,
t("customer.allCompanies") },
); {
}, [companyFilterInput, companyOptions, t]); key: "name",
label: t("customer.columnName"),
function applyFilters() { render: (item) => <span className="font-medium">{item.name}</span>,
setKeyword(keywordInput); },
setStatusFilter(statusFilterInput); {
setGenderFilter(genderFilterInput); key: "gender",
setCompanyFilter(companyFilterInput); label: t("customer.columnGender"),
setPage(1); className: "w-20",
} render: (item) => (
<span className="text-muted-foreground">
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) { {getGenderText(item.gender, t)}
if (event.key !== "Enter") return; </span>
event.preventDefault(); ),
applyFilters(); },
} {
key: "company",
function handlePageChange(nextPage: number) { label: t("customer.columnCompany"),
if (nextPage < 1 || nextPage === page) return; render: (item) => (
setPage(nextPage); <span className="text-muted-foreground">
} {item.companyId > 0
? (companyNameMap[item.companyId] ?? String(item.companyId))
function openCreateDialog() { : "-"}
setEditingItem(null); </span>
setDialogOpen(true); ),
} },
{
function openEditDialog(item: AdminCustomer) { key: "mobile",
setEditingItem(item); label: t("customer.columnMobile"),
setDialogOpen(true); render: (item) => (
} <span className="text-muted-foreground">
{item.primaryMobile || "-"}
function handleDialogOpenChange(open: boolean) { </span>
if (saving) return; ),
if (!open) setEditingItem(null); },
setDialogOpen(open); {
} key: "email",
label: t("customer.columnEmail"),
async function handleSave(payload: CustomerFormSavePayload) { render: (item) => (
if (saving) return; <span className="text-muted-foreground">
setSaving(true); {item.primaryEmail || "-"}
try { </span>
await saveCustomerProfile(payload); ),
toast.success( },
editingItem createDashboardStatusColumn<AdminCustomer, number>({
? t("customer.updated", { name: editingItem.name }) label: t("customer.columnStatus"),
: t("customer.created", { name: payload.name }), className: "w-24",
); getStatus: (item) => item.status,
setDialogOpen(false); getLabel: (status) =>
setEditingItem(null); status === Status.Ok ? t("status.ok") : t("status.disabled"),
await loadData(); getBadgeVariant: (status) =>
} catch (error) { status === Status.Ok ? "default" : "secondary",
toast.error(error instanceof Error ? error.message : t("customer.saveFailed")); }),
} finally { ],
setSaving(false); [companyNameMap, t],
} );
}
async function handleToggleStatus(item: AdminCustomer) {
setActionLoadingId(item.id);
try {
const nextStatus = item.status === 0 ? 1 : 0;
await updateCustomerStatus(item.id, nextStatus);
toast.success(t(nextStatus === 0 ? "customer.enabled" : "customer.disabled", { name: item.name }));
await loadData();
} catch (error) {
toast.error(error instanceof Error ? error.message : t("customer.statusUpdateFailed"));
} finally {
setActionLoadingId(null);
}
}
async function handleDelete(item: AdminCustomer) {
setActionLoadingId(item.id);
try {
await deleteCustomer(item.id);
toast.success(t("customer.deleted", { name: item.name }));
await loadData();
} catch (error) {
toast.error(error instanceof Error ? error.message : t("customer.deleteFailed"));
} finally {
setActionLoadingId(null);
}
}
function getGenderText(gender: number) {
if (gender === Gender.Male) return t("customerForm.genderMale");
if (gender === Gender.Female) return t("customerForm.genderFemale");
return t("customerForm.genderUnknown");
}
return ( return (
<> <DashboardCrudPage<AdminCustomer, CustomerFormSavePayload>
<DashboardPage> filters={filters}
<DashboardToolbar columns={columns}
actions={ fetchList={(query) =>
<Button onClick={openCreateDialog}> fetchCustomers({
<PlusIcon /> keyword:
{t("customer.new")} typeof query.keyword === "string" ? query.keyword : undefined,
</Button> status:
} typeof query.status === "number" ? query.status : undefined,
> gender:
<div className="relative w-full sm:w-72"> typeof query.gender === "number" ? query.gender : undefined,
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" /> companyId:
<Input typeof query.companyId === "number" ? query.companyId : undefined,
value={keywordInput} page: Number(query.page),
onChange={(event) => setKeywordInput(event.target.value)} limit: Number(query.limit),
onKeyDown={handleFilterKeyDown} })
placeholder={t("customer.keywordPlaceholder")} }
className="pl-9" getItemId={(item) => item.id}
/> createItem={saveCustomerProfile}
</div> updateItem={(_item, payload) => saveCustomerProfile(payload)}
deleteItem={(item) => deleteCustomer(item.id)}
<div className="w-full sm:w-36"> canDelete={(item) => item.status !== Status.Deleted}
<OptionCombobox rowActions={[
value={genderFilterInput} createDashboardStatusToggleAction<AdminCustomer, number>({
options={genderOptions} icon: (item) =>
placeholder={getLabel(genderFilterInput, genderOptions, t("customer.select"))} item.status === Status.Ok ? <BanIcon /> : <CheckCircle2Icon />,
onChange={(v) => setGenderFilterInput(v)} label: (item) =>
/> item.status === Status.Ok
</div> ? t("customer.disable")
: t("customer.enable"),
<div className="w-full sm:w-56"> disabled: (item) => item.status === Status.Deleted,
<OptionCombobox getNextStatus: (item) =>
value={companyFilterInput} item.status === Status.Ok ? Status.Disabled : Status.Ok,
options={companyOptions} updateStatus: (item, nextStatus) =>
placeholder={companyFilterLabel} updateCustomerStatus(item.id, nextStatus),
searchPlaceholder={t("customer.searchCompany")} successMessage: (item, nextStatus) =>
onChange={(v) => setCompanyFilterInput(v)} t(nextStatus === Status.Ok ? "customer.enabled" : "customer.disabled", {
/> name: item.name,
</div> }),
errorMessage: t("customer.statusUpdateFailed"),
<div className="w-full sm:w-36"> }),
<OptionCombobox ]}
value={statusFilterInput} renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
options={listStatusOptions} <EditDialog
placeholder={getLabel(statusFilterInput, listStatusOptions, t("customer.select"))} open={open}
onChange={(v) => setStatusFilterInput(v)} saving={saving}
/> itemId={itemId}
</div> onOpenChange={onOpenChange}
onSave={onSubmit}
<Button variant="outline" onClick={applyFilters} disabled={loading}> />
<SearchIcon /> )}
{t("customer.query")} labels={{
</Button> refresh: t("customer.refresh"),
</DashboardToolbar> create: t("customer.new"),
query: t("customer.query"),
<DashboardTableShell loading: t("customer.loading"),
pagination={ empty: t("customer.empty"),
<ListPagination actions: t("customer.columnActions"),
page={result.page.page} edit: t("customer.edit"),
total={result.page.total} delete: t("customer.delete"),
limit={result.page.limit} processing: t("customer.processing"),
loading={loading} moreActions: (item) => t("customer.moreActions", { name: item.name }),
onPageChange={handlePageChange} loadFailed: t("customer.loadFailed"),
onLimitChange={(nextLimit) => { saveFailed: t("customer.saveFailed"),
setLimit(nextLimit); deleteFailed: t("customer.deleteFailed"),
setPage(1); created: (payload) => t("customer.created", { name: payload.name }),
}} updated: (item) => t("customer.updated", { name: item.name }),
/> deleted: (item) => t("customer.deleted", { name: item.name }),
} }}
> />
<Table>
<TableHeader>
<TableRow>
<TableHead className="w-20">ID</TableHead>
<TableHead>{t("customer.columnName")}</TableHead>
<TableHead className="w-20">{t("customer.columnGender")}</TableHead>
<TableHead>{t("customer.columnCompany")}</TableHead>
<TableHead>{t("customer.columnMobile")}</TableHead>
<TableHead>{t("customer.columnEmail")}</TableHead>
<TableHead className="w-24">{t("customer.columnStatus")}</TableHead>
<TableHead className="w-40">{t("customer.columnActions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading || result.results.length === 0 ? (
<DashboardTableStateRow
colSpan={8}
loading={loading}
loadingText={t("customer.loading")}
emptyText={t("customer.empty")}
/>
) : (
result.results.map((item) => {
const actionLoading = actionLoadingId === item.id;
return (
<TableRow key={item.id}>
<TableCell>{item.id}</TableCell>
<TableCell className="font-medium">{item.name}</TableCell>
<TableCell className="text-muted-foreground">
{getGenderText(item.gender)}
</TableCell>
<TableCell className="text-muted-foreground">
{item.companyId > 0
? (companyNameMap[item.companyId] ??
String(item.companyId))
: "-"}
</TableCell>
<TableCell className="text-muted-foreground">
{item.primaryMobile || "-"}
</TableCell>
<TableCell className="text-muted-foreground">
{item.primaryEmail || "-"}
</TableCell>
<TableCell>
<Badge
variant={item.status === 0 ? "default" : "secondary"}
>
{item.status === 0 ? t("status.ok") : t("status.disabled")}
</Badge>
</TableCell>
<TableCell>
<ButtonGroup className="w-full justify-end">
<Button
variant="outline"
size="sm"
onClick={() => openEditDialog(item)}
>
{t("customer.edit")}
</Button>
<DropdownMenu>
<DropdownMenuTrigger
render={
<Button
variant="outline"
size="sm"
disabled={actionLoading}
/>
}
aria-label={t("customer.moreActions", { name: item.name })}
>
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent
align="end"
className="w-40 min-w-40"
>
<DropdownMenuItem
disabled={item.status === Status.Deleted}
onClick={() => void handleToggleStatus(item)}
>
{actionLoadingId === item.id ? (
t("customer.processing")
) : item.status === 0 ? (
<>
<BanIcon />
{t("customer.disable")}
</>
) : (
<>
<CheckCircle2Icon />
{t("customer.enable")}
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
variant="destructive"
disabled={item.status === Status.Deleted}
onClick={() => void handleDelete(item)}
>
<Trash2Icon />
{t("customer.delete")}
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
</TableCell>
</TableRow>
);
})
)}
</TableBody>
</Table>
</DashboardTableShell>
</DashboardPage>
<EditDialog
open={dialogOpen}
saving={saving}
itemId={editingItem?.id ?? null}
onOpenChange={handleDialogOpenChange}
onSave={handleSave}
/>
</>
); );
} }
+220 -461
View File
@@ -1,45 +1,16 @@
"use client" "use client";
import { useCallback, useEffect, useMemo, useState } from "react" import { BrainCircuitIcon, BugIcon, RotateCcwIcon } from "lucide-react";
import { import { useMemo, useState } from "react";
BrainCircuitIcon, import { toast } from "sonner";
BugIcon,
MoreHorizontalIcon,
PlusIcon,
RefreshCwIcon,
RotateCcwIcon,
SearchIcon,
Trash2Icon,
} from "lucide-react"
import { toast } from "sonner"
import { import {
DashboardPage, DashboardCrudPage,
DashboardTableShell, createDashboardStatusColumn,
DashboardTableStateRow, type DashboardCrudColumn,
DashboardToolbar, type DashboardCrudFilter,
} from "@/components/dashboard-page" } from "@/components/dashboard/crud";
import { ListPagination } from "@/components/list-pagination" import { Badge } from "@/components/ui/badge";
import { OptionCombobox } from "@/components/option-combobox"
import { Badge } from "@/components/ui/badge"
import { Button } from "@/components/ui/button"
import { ButtonGroup } from "@/components/ui/button-group"
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Switch } from "@/components/ui/switch"
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "@/components/ui/table"
import { import {
createSkillDefinition, createSkillDefinition,
deleteSkillDefinition, deleteSkillDefinition,
@@ -48,28 +19,21 @@ import {
updateSkillDefinition, updateSkillDefinition,
updateSkillDefinitionStatus, updateSkillDefinitionStatus,
type CreateSkillDefinitionPayload, type CreateSkillDefinitionPayload,
type PageResult,
type SkillDefinition, type SkillDefinition,
} from "@/lib/api/admin" } from "@/lib/api/admin";
import { useI18n } from "@/i18n/provider" import { useI18n } from "@/i18n/provider";
import { Status } from "@/lib/generated/enums" import { Status } from "@/lib/generated/enums";
import { formatDateTime } from "@/lib/utils" import { formatDateTime } from "@/lib/utils";
import { EditDialog } from "./_components/edit" import { EditDialog } from "./_components/edit";
import { DebugDialog } from "./_components/debug-dialog" import { DebugDialog } from "./_components/debug-dialog";
type TFunction = (key: string, values?: Record<string, string | number>) => string type TFunction = (key: string, values?: Record<string, string | number>) => string;
function statusLabel(status: number, t: TFunction) { function statusLabel(status: number, t: TFunction) {
if (status === Status.Ok) { if (status === Status.Ok) return t("skillDefinition.statusOk");
return t("skillDefinition.statusOk") if (status === Status.Disabled) return t("skillDefinition.statusDisabled");
} if (status === Status.Deleted) return t("skillDefinition.statusDeleted");
if (status === Status.Disabled) { return String(status);
return t("skillDefinition.statusDisabled")
}
if (status === Status.Deleted) {
return t("skillDefinition.statusDeleted")
}
return String(status)
} }
function getStatusFilterOptions(t: TFunction) { function getStatusFilterOptions(t: TFunction) {
@@ -78,428 +42,223 @@ function getStatusFilterOptions(t: TFunction) {
{ value: String(Status.Ok), label: t("skillDefinition.statusOk") }, { value: String(Status.Ok), label: t("skillDefinition.statusOk") },
{ value: String(Status.Disabled), label: t("skillDefinition.statusDisabled") }, { value: String(Status.Disabled), label: t("skillDefinition.statusDisabled") },
{ value: String(Status.Deleted), label: t("skillDefinition.statusDeleted") }, { value: String(Status.Deleted), label: t("skillDefinition.statusDeleted") },
] ];
} }
type SkillRowProps = { function statusBadgeVariant(status: number) {
item: SkillDefinition if (status === Status.Deleted) return "destructive";
actionLoadingId: number | null if (status === Status.Ok) return "default";
openEditDialog: (item: SkillDefinition) => void return "outline";
openDebugDialog: (item: SkillDefinition) => void
handleToggleStatus: (item: SkillDefinition) => void
handleDelete: (item: SkillDefinition) => void
handleRestore: (item: SkillDefinition) => void
t: TFunction
} }
function SkillRow({ function getNextStatus(item: SkillDefinition) {
item, return item.status === Status.Ok ? Status.Disabled : Status.Ok;
actionLoadingId,
openEditDialog,
openDebugDialog,
handleToggleStatus,
handleDelete,
handleRestore,
t,
}: SkillRowProps) {
const isDeleted = item.status === Status.Deleted
const statusBadgeVariant = isDeleted
? "destructive"
: item.status === Status.Ok
? "default"
: "outline"
return (
<TableRow className={isDeleted ? "bg-destructive/5" : undefined}>
<TableCell>
<div className="flex items-start gap-3">
<div className="mt-0.5 flex size-10 items-center justify-center rounded-2xl bg-muted text-muted-foreground">
<BrainCircuitIcon className="size-4" />
</div>
<div className="min-w-0">
<div className="flex flex-wrap items-center gap-2">
<div className="font-medium">{item.name}</div>
<Badge variant="outline">{item.code}</Badge>
<Badge variant="secondary">{t("skillDefinition.whitelistCount", { count: item.toolWhitelist.length })}</Badge>
<Badge variant="secondary">{t("skillDefinition.exampleCount", { count: item.examples.length })}</Badge>
</div>
<div className="mt-2 space-y-2">
<div className="line-clamp-2 text-sm leading-6 text-muted-foreground">
{item.description || t("skillDefinition.noDescription")}
</div>
</div>
{item.toolWhitelist.length > 0 ? (
<div className="mt-2 flex flex-wrap gap-2">
{item.toolWhitelist.slice(0, 3).map((toolCode) => (
<Badge key={toolCode} variant="outline">
{toolCode}
</Badge>
))}
{item.toolWhitelist.length > 3 ? (
<Badge variant="outline">+{item.toolWhitelist.length - 3}</Badge>
) : null}
</div>
) : null}
</div>
</div>
</TableCell>
<TableCell>
<div className="flex items-center gap-3">
<Switch
checked={item.status === Status.Ok}
disabled={actionLoadingId === item.id || isDeleted}
onCheckedChange={() => void handleToggleStatus(item)}
aria-label={t("skillDefinition.toggleStatus", { name: item.name })}
/>
<Badge variant={statusBadgeVariant}>
{statusLabel(item.status, t)}
</Badge>
</div>
</TableCell>
<TableCell>
<div className="space-y-1 text-sm">
<div>{formatDateTime(item.updatedAt)}</div>
<div className="text-xs text-muted-foreground">
{item.updateUserName || "-"}
</div>
</div>
</TableCell>
<TableCell className="text-right">
<ButtonGroup className="ml-auto">
<Button variant="outline" size="sm" onClick={() => openDebugDialog(item)}>
<BugIcon />
{t("skillDefinition.debug")}
</Button>
<Button variant="outline" size="sm" onClick={() => openEditDialog(item)}>
{t("skillDefinition.edit")}
</Button>
<DropdownMenu>
<DropdownMenuTrigger
render={<Button variant="outline" size="icon-sm" />}
aria-label={t("skillDefinition.moreActions", { name: item.name })}
>
<MoreHorizontalIcon />
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-40 min-w-40">
{isDeleted ? (
<DropdownMenuItem
disabled={actionLoadingId === item.id}
onClick={() => void handleRestore(item)}
>
<RotateCcwIcon />
{actionLoadingId === item.id ? t("skillDefinition.restoring") : t("skillDefinition.restore")}
</DropdownMenuItem>
) : (
<DropdownMenuItem
disabled={actionLoadingId === item.id}
onClick={() => void handleDelete(item)}
className="text-destructive focus:text-destructive"
>
<Trash2Icon />
{actionLoadingId === item.id ? t("skillDefinition.deleting") : t("skillDefinition.delete")}
</DropdownMenuItem>
)}
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
</TableCell>
</TableRow>
)
} }
export default function DashboardSkillsPage() { export default function DashboardSkillsPage() {
const t = useI18n() const t = useI18n();
const [nameInput, setNameInput] = useState("") const [debugDialogOpen, setDebugDialogOpen] = useState(false);
const [codeInput, setCodeInput] = useState("") const [debuggingItem, setDebuggingItem] = useState<SkillDefinition | null>(
const [statusFilterInput, setStatusFilterInput] = useState("all") null,
const [name, setName] = useState("") );
const [code, setCode] = useState("") const statusFilterOptions = useMemo(() => getStatusFilterOptions(t), [t]);
const [statusFilter, setStatusFilter] = useState("all")
const [page, setPage] = useState(1)
const [limit, setLimit] = useState(20)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [actionLoadingId, setActionLoadingId] = useState<number | null>(null)
const [dialogOpen, setDialogOpen] = useState(false)
const [debugDialogOpen, setDebugDialogOpen] = useState(false)
const [editingItem, setEditingItem] = useState<SkillDefinition | null>(null)
const [debuggingItem, setDebuggingItem] = useState<SkillDefinition | null>(null)
const [result, setResult] = useState<PageResult<SkillDefinition>>({
results: [],
page: { page: 1, limit: 20, total: 0 },
})
const statusFilterOptions = useMemo(() => getStatusFilterOptions(t), [t])
const loadData = useCallback(async () => { const filters = useMemo<DashboardCrudFilter[]>(
setLoading(true) () => [
try { {
const data = await fetchSkillDefinitions({ name: "name",
name: name.trim() || undefined, label: t("skillDefinition.filterName"),
code: code.trim() || undefined, placeholder: t("skillDefinition.filterName"),
status: statusFilter === "all" ? undefined : Number(statusFilter), defaultValue: "",
page, trim: true,
limit, className: "w-full sm:w-72",
}) },
setResult(data) {
} catch (error) { name: "code",
toast.error(error instanceof Error ? error.message : t("skillDefinition.loadFailed")) label: t("skillDefinition.filterCode"),
} finally { placeholder: t("skillDefinition.filterCode"),
setLoading(false) defaultValue: "",
} trim: true,
}, [name, code, statusFilter, page, limit, t]) className: "w-full sm:w-56",
},
{
name: "status",
label: t("skillDefinition.allStatus"),
type: "select",
defaultValue: "all",
allValue: "all",
valueType: "number",
options: statusFilterOptions,
className: "w-full sm:w-36",
},
],
[statusFilterOptions, t],
);
useEffect(() => { const columns = useMemo<DashboardCrudColumn<SkillDefinition>[]>(
void loadData() () => [
}, [loadData]) {
key: "skill",
function applyFilters() { label: "Skill",
setName(nameInput) render: (item) => (
setCode(codeInput) <div className="flex items-start gap-3">
setStatusFilter(statusFilterInput) <div className="mt-0.5 flex size-10 items-center justify-center rounded-md bg-muted text-muted-foreground">
setPage(1) <BrainCircuitIcon className="size-4" />
} </div>
<div className="min-w-0">
function handleFilterKeyDown(event: React.KeyboardEvent<HTMLInputElement>) { <div className="flex flex-wrap items-center gap-2">
if (event.key !== "Enter") { <div className="font-medium">{item.name}</div>
return <Badge variant="outline">{item.code}</Badge>
} <Badge variant="secondary">
event.preventDefault() {t("skillDefinition.whitelistCount", {
applyFilters() count: item.toolWhitelist.length,
} })}
</Badge>
function handlePageChange(nextPage: number) { <Badge variant="secondary">
if (nextPage < 1 || nextPage === page) { {t("skillDefinition.exampleCount", {
return count: item.examples.length,
} })}
setPage(nextPage) </Badge>
} </div>
<div className="mt-2 line-clamp-2 text-sm leading-6 text-muted-foreground">
function openCreateDialog() { {item.description || t("skillDefinition.noDescription")}
setEditingItem(null) </div>
setDialogOpen(true) {item.toolWhitelist.length > 0 ? (
} <div className="mt-2 flex flex-wrap gap-2">
{item.toolWhitelist.slice(0, 3).map((toolCode) => (
function openEditDialog(item: SkillDefinition) { <Badge key={toolCode} variant="outline">
setEditingItem(item) {toolCode}
setDialogOpen(true) </Badge>
} ))}
{item.toolWhitelist.length > 3 ? (
function openDebugDialog(item: SkillDefinition) { <Badge variant="outline">
setDebuggingItem(item) +{item.toolWhitelist.length - 3}
setDebugDialogOpen(true) </Badge>
} ) : null}
</div>
function handleDialogOpenChange(open: boolean) { ) : null}
if (saving) { </div>
return </div>
} ),
if (!open) { },
setEditingItem(null) createDashboardStatusColumn<SkillDefinition, number>({
} label: t("skillDefinition.status"),
setDialogOpen(open) getStatus: (item) => item.status,
} getLabel: (status) => statusLabel(status, t),
getBadgeVariant: statusBadgeVariant,
function handleDebugDialogOpenChange(open: boolean) { isEnabled: (status) => status === Status.Ok,
if (!open) { toggle: {
setDebuggingItem(null) disabled: (item) => item.status === Status.Deleted,
} getNextStatus,
setDebugDialogOpen(open) updateStatus: (item, nextStatus) =>
} updateSkillDefinitionStatus(item.id, nextStatus),
successMessage: (item, nextStatus) =>
async function handleSubmit(payload: CreateSkillDefinitionPayload) { t(nextStatus === Status.Ok ? "skillDefinition.enabled" : "skillDefinition.disabled", {
if (saving) { name: item.name,
return }),
} errorMessage: t("skillDefinition.statusUpdateFailed"),
ariaLabel: (item) =>
setSaving(true) t("skillDefinition.toggleStatus", { name: item.name }),
try { },
if (editingItem) { }),
await updateSkillDefinition({ {
id: editingItem.id, key: "updatedAt",
...payload, label: t("skillDefinition.updatedAt"),
}) render: (item) => (
toast.success(t("skillDefinition.updated", { name: editingItem.name })) <div className="space-y-1 text-sm">
} else { <div>{formatDateTime(item.updatedAt)}</div>
await createSkillDefinition(payload) <div className="text-xs text-muted-foreground">
toast.success(t("skillDefinition.created", { name: payload.name })) {item.updateUserName || "-"}
} </div>
setDialogOpen(false) </div>
setEditingItem(null) ),
await loadData() },
} catch (error) { ],
toast.error(error instanceof Error ? error.message : t("skillDefinition.saveFailed")) [t],
} finally { );
setSaving(false)
}
}
async function handleToggleStatus(item: SkillDefinition) {
if (item.status === Status.Deleted) {
return
}
const nextStatus = item.status === Status.Ok ? Status.Disabled : Status.Ok
setActionLoadingId(item.id)
try {
await updateSkillDefinitionStatus(item.id, nextStatus)
toast.success(t(nextStatus === Status.Ok ? "skillDefinition.enabled" : "skillDefinition.disabled", { name: item.name }))
await loadData()
} catch (error) {
toast.error(error instanceof Error ? error.message : t("skillDefinition.statusUpdateFailed"))
} finally {
setActionLoadingId(null)
}
}
async function handleDelete(item: SkillDefinition) {
if (item.status === Status.Deleted) {
return
}
setActionLoadingId(item.id)
try {
await deleteSkillDefinition(item.id)
toast.success(t("skillDefinition.deleted", { name: item.name }))
await loadData()
} catch (error) {
toast.error(error instanceof Error ? error.message : t("skillDefinition.deleteFailed"))
} finally {
setActionLoadingId(null)
}
}
async function handleRestore(item: SkillDefinition) {
if (item.status !== Status.Deleted) {
return
}
setActionLoadingId(item.id)
try {
await restoreSkillDefinition(item.id)
toast.success(t("skillDefinition.restored", { name: item.name }))
await loadData()
} catch (error) {
toast.error(error instanceof Error ? error.message : t("skillDefinition.restoreFailed"))
} finally {
setActionLoadingId(null)
}
}
return ( return (
<> <>
<DashboardPage> <DashboardCrudPage<SkillDefinition, CreateSkillDefinitionPayload>
<DashboardToolbar filters={filters}
actions={ columns={columns}
<> fetchList={(query) =>
<Button variant="outline" onClick={() => void loadData()} disabled={loading}> fetchSkillDefinitions({
<RefreshCwIcon className={loading ? "animate-spin" : ""} /> name: typeof query.name === "string" ? query.name : undefined,
{t("skillDefinition.refresh")} code: typeof query.code === "string" ? query.code : undefined,
</Button> status: typeof query.status === "number" ? query.status : undefined,
<Button onClick={openCreateDialog}> page: Number(query.page),
<PlusIcon /> limit: Number(query.limit),
{t("skillDefinition.new")} })
</Button> }
</> getItemId={(item) => item.id}
} createItem={createSkillDefinition}
> updateItem={(item, payload) =>
<div className="relative w-full sm:w-72"> updateSkillDefinition({ id: item.id, ...payload })
<SearchIcon className="pointer-events-none absolute top-1/2 left-3 size-4 -translate-y-1/2 text-muted-foreground" /> }
<Input deleteItem={(item) => deleteSkillDefinition(item.id)}
value={nameInput} canDelete={(item) => item.status !== Status.Deleted}
onChange={(event) => setNameInput(event.target.value)} rowActions={[
onKeyDown={handleFilterKeyDown} {
placeholder={t("skillDefinition.filterName")} key: "debug",
className="pl-9" icon: <BugIcon />,
/> label: t("skillDefinition.debug"),
</div> run: ({ item }) => {
<Input setDebuggingItem(item);
value={codeInput} setDebugDialogOpen(true);
onChange={(event) => setCodeInput(event.target.value)} },
onKeyDown={handleFilterKeyDown} },
placeholder={t("skillDefinition.filterCode")} {
className="w-full sm:w-56" key: "restore",
icon: <RotateCcwIcon />,
label: t("skillDefinition.restore"),
visible: (item) => item.status === Status.Deleted,
run: async ({ item, reload }) => {
await restoreSkillDefinition(item.id);
toast.success(t("skillDefinition.restored", { name: item.name }));
await reload();
},
},
]}
renderEditDialog={({ open, saving, itemId, onOpenChange, onSubmit }) => (
<EditDialog
open={open}
saving={saving}
itemId={itemId}
onOpenChange={onOpenChange}
onSubmit={onSubmit}
/> />
<div className="w-full sm:w-36"> )}
<OptionCombobox labels={{
value={statusFilterInput} refresh: t("skillDefinition.refresh"),
options={statusFilterOptions} create: t("skillDefinition.new"),
placeholder={t("skillDefinition.allStatus")} query: t("skillDefinition.query"),
searchPlaceholder={t("skillDefinition.searchStatus")} loading: t("skillDefinition.loadingRows"),
emptyText={t("skillDefinition.emptyStatus")} empty: t("skillDefinition.emptyRows"),
onChange={setStatusFilterInput} actions: t("skillDefinition.actions"),
/> edit: t("skillDefinition.edit"),
</div> delete: t("skillDefinition.delete"),
<Button variant="outline" onClick={applyFilters} disabled={loading}> processing: t("skillDefinition.processing"),
<SearchIcon /> moreActions: (item) =>
{t("skillDefinition.query")} t("skillDefinition.moreActions", { name: item.name }),
</Button> loadFailed: t("skillDefinition.loadFailed"),
</DashboardToolbar> saveFailed: t("skillDefinition.saveFailed"),
deleteFailed: t("skillDefinition.deleteFailed"),
<DashboardTableShell created: (payload) =>
pagination={ t("skillDefinition.created", { name: payload.name }),
<ListPagination updated: (item) => t("skillDefinition.updated", { name: item.name }),
page={result.page.page} deleted: (item) => t("skillDefinition.deleted", { name: item.name }),
total={result.page.total} }}
limit={limit}
loading={loading}
onPageChange={handlePageChange}
onLimitChange={(nextLimit) => {
setLimit(nextLimit)
setPage(1)
}}
/>
}
>
<Table>
<TableHeader className="bg-muted/40">
<TableRow>
<TableHead>Skill</TableHead>
<TableHead>{t("skillDefinition.status")}</TableHead>
<TableHead>{t("skillDefinition.updatedAt")}</TableHead>
<TableHead className="w-[168px] text-right">{t("skillDefinition.actions")}</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{loading || result.results.length === 0 ? (
<DashboardTableStateRow
colSpan={4}
loading={loading}
loadingText={t("skillDefinition.loadingRows")}
emptyText={t("skillDefinition.emptyRows")}
/>
) : null}
{result.results.map((item) => (
<SkillRow
key={item.id}
item={item}
actionLoadingId={actionLoadingId}
openEditDialog={openEditDialog}
openDebugDialog={openDebugDialog}
handleToggleStatus={handleToggleStatus}
handleDelete={handleDelete}
handleRestore={handleRestore}
t={t}
/>
))}
</TableBody>
</Table>
</DashboardTableShell>
</DashboardPage>
<EditDialog
open={dialogOpen}
saving={saving}
itemId={editingItem?.id ?? null}
onOpenChange={handleDialogOpenChange}
onSubmit={handleSubmit}
/> />
<DebugDialog <DebugDialog
open={debugDialogOpen} open={debugDialogOpen}
skillCode={debuggingItem?.code ?? ""} skillCode={debuggingItem?.code ?? ""}
skillName={debuggingItem?.name ?? ""} skillName={debuggingItem?.name ?? ""}
onOpenChange={handleDebugDialogOpenChange} onOpenChange={(open) => {
if (!open) setDebuggingItem(null);
setDebugDialogOpen(open);
}}
/> />
</> </>
) );
} }
+3
View File
@@ -634,6 +634,7 @@
"deleted": "Customer deleted: {name}", "deleted": "Customer deleted: {name}",
"deleteFailed": "Could not delete the customer.", "deleteFailed": "Could not delete the customer.",
"new": "New", "new": "New",
"refresh": "Refresh",
"keywordPlaceholder": "Name, phone, email, company, or contact", "keywordPlaceholder": "Name, phone, email, company, or contact",
"searchCompany": "Search companies", "searchCompany": "Search companies",
"query": "Search", "query": "Search",
@@ -932,6 +933,7 @@
"toggleStatus": "Toggle status for {name}", "toggleStatus": "Toggle status for {name}",
"edit": "Edit", "edit": "Edit",
"moreActions": "More actions for {name}", "moreActions": "More actions for {name}",
"processing": "Working...",
"stop": "Disable", "stop": "Disable",
"delete": "Delete", "delete": "Delete",
"loadingRows": "Loading AI agents...", "loadingRows": "Loading AI agents...",
@@ -1500,6 +1502,7 @@
"restoring": "Restoring...", "restoring": "Restoring...",
"restore": "Restore", "restore": "Restore",
"deleting": "Deleting...", "deleting": "Deleting...",
"processing": "Working...",
"delete": "Delete", "delete": "Delete",
"loadFailed": "Could not load skills.", "loadFailed": "Could not load skills.",
"updated": "Skill updated: {name}", "updated": "Skill updated: {name}",
+3
View File
@@ -634,6 +634,7 @@
"deleted": "已删除客户:{name}", "deleted": "已删除客户:{name}",
"deleteFailed": "删除客户失败", "deleteFailed": "删除客户失败",
"new": "新建", "new": "新建",
"refresh": "刷新",
"keywordPlaceholder": "姓名、手机、邮箱、公司、联系方式", "keywordPlaceholder": "姓名、手机、邮箱、公司、联系方式",
"searchCompany": "搜索公司名称", "searchCompany": "搜索公司名称",
"query": "查询", "query": "查询",
@@ -932,6 +933,7 @@
"toggleStatus": "{name} 状态切换", "toggleStatus": "{name} 状态切换",
"edit": "编辑", "edit": "编辑",
"moreActions": "更多操作 {name}", "moreActions": "更多操作 {name}",
"processing": "处理中...",
"stop": "停用", "stop": "停用",
"delete": "删除", "delete": "删除",
"loadingRows": "正在加载 AI Agent...", "loadingRows": "正在加载 AI Agent...",
@@ -1500,6 +1502,7 @@
"restoring": "恢复中...", "restoring": "恢复中...",
"restore": "恢复", "restore": "恢复",
"deleting": "删除中...", "deleting": "删除中...",
"processing": "处理中...",
"delete": "删除", "delete": "删除",
"loadFailed": "加载 Skills 失败", "loadFailed": "加载 Skills 失败",
"updated": "已更新 Skill{name}", "updated": "已更新 Skill{name}",