feat: add knowledge directory management for documents and FAQs
- Implemented directory validation in Create and Update knowledge document services. - Added directory selection in document and FAQ edit dialogs with a new KnowledgeDirectoryPanel component. - Enhanced API to support fetching, creating, updating, and deleting knowledge directories. - Updated data models to include directory information for knowledge documents and FAQs. - Added translations for directory-related messages in English and Chinese.
This commit is contained in:
@@ -7,6 +7,7 @@ import { z } from "zod/v4"
|
||||
|
||||
import { ProjectDialog } from "@/components/project-dialog"
|
||||
import { ContentEditor } from "@/components/content-editor"
|
||||
import { OptionCombobox } from "@/components/option-combobox"
|
||||
import { Button } from "@/components/ui/button"
|
||||
import {
|
||||
Field,
|
||||
@@ -18,7 +19,9 @@ import { Input } from "@/components/ui/input"
|
||||
import {
|
||||
type KnowledgeDocument,
|
||||
type CreateKnowledgeDocumentPayload,
|
||||
type KnowledgeDirectory,
|
||||
fetchKnowledgeDocument,
|
||||
fetchKnowledgeDirectories,
|
||||
} from "@/lib/api/admin"
|
||||
import {
|
||||
KnowledgeDocumentContentType,
|
||||
@@ -30,11 +33,13 @@ type DocumentEditDialogProps = {
|
||||
saving: boolean
|
||||
itemId: number | null
|
||||
knowledgeBaseId: number | null
|
||||
initialDirectoryId?: number
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: CreateKnowledgeDocumentPayload) => Promise<void>
|
||||
}
|
||||
|
||||
const emptyForm: EditForm = {
|
||||
directoryId: "0",
|
||||
title: "",
|
||||
contentType: KnowledgeDocumentContentType.Markdown,
|
||||
content: "",
|
||||
@@ -44,6 +49,7 @@ type TFunction = (key: string, values?: Record<string, string | number>) => stri
|
||||
|
||||
function createKnowledgeDocumentFormSchema(t: TFunction) {
|
||||
return z.object({
|
||||
directoryId: z.string().trim(),
|
||||
title: z.string().trim().min(1, t("knowledge.documentTitleRequired")).max(255, t("knowledge.documentTitleMax")),
|
||||
contentType: z.string().trim().min(1, t("knowledge.contentTypeRequired")),
|
||||
content: z.string().trim().min(1, t("knowledge.contentRequired")),
|
||||
@@ -51,17 +57,28 @@ function createKnowledgeDocumentFormSchema(t: TFunction) {
|
||||
}
|
||||
|
||||
type EditForm = {
|
||||
directoryId: string
|
||||
title: string
|
||||
contentType: string
|
||||
content: string
|
||||
}
|
||||
|
||||
function buildForm(item: KnowledgeDocument | null): EditForm {
|
||||
type DirectoryOption = { value: string; label: string }
|
||||
|
||||
function flattenDirectoryOptions(items: KnowledgeDirectory[], depth = 0): DirectoryOption[] {
|
||||
return items.flatMap((item) => [
|
||||
{ value: String(item.id), label: `${depth > 0 ? " " : ""}${item.name}` },
|
||||
...flattenDirectoryOptions(item.children || [], depth + 1),
|
||||
])
|
||||
}
|
||||
|
||||
function buildForm(item: KnowledgeDocument | null, initialDirectoryId = 0): EditForm {
|
||||
if (!item) {
|
||||
return emptyForm
|
||||
return { ...emptyForm, directoryId: String(initialDirectoryId) }
|
||||
}
|
||||
|
||||
return {
|
||||
directoryId: String(item.directoryId || 0),
|
||||
title: item.title,
|
||||
contentType: item.contentType || KnowledgeDocumentContentType.Markdown,
|
||||
content: item.content || "",
|
||||
@@ -71,6 +88,7 @@ function buildForm(item: KnowledgeDocument | null): EditForm {
|
||||
function buildPayload(form: EditForm, knowledgeBaseId: number): CreateKnowledgeDocumentPayload {
|
||||
return {
|
||||
knowledgeBaseId,
|
||||
directoryId: Number(form.directoryId),
|
||||
title: form.title.trim(),
|
||||
contentType: form.contentType,
|
||||
content: form.content.trim(),
|
||||
@@ -82,6 +100,7 @@ export function DocumentEditDialog({
|
||||
saving,
|
||||
itemId,
|
||||
knowledgeBaseId,
|
||||
initialDirectoryId = 0,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: DocumentEditDialogProps) {
|
||||
@@ -94,6 +113,7 @@ export function DocumentEditDialog({
|
||||
key={itemId ? `edit-${itemId}` : "create"}
|
||||
itemId={itemId}
|
||||
knowledgeBaseId={knowledgeBaseId}
|
||||
initialDirectoryId={initialDirectoryId}
|
||||
saving={saving}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
@@ -105,6 +125,7 @@ type DocumentFormDialogBodyProps = {
|
||||
saving: boolean
|
||||
itemId: number | null
|
||||
knowledgeBaseId: number
|
||||
initialDirectoryId: number
|
||||
onOpenChange: (open: boolean) => void
|
||||
onSubmit: (payload: CreateKnowledgeDocumentPayload) => Promise<void>
|
||||
}
|
||||
@@ -113,12 +134,14 @@ function DocumentFormDialogBody({
|
||||
saving,
|
||||
itemId,
|
||||
knowledgeBaseId,
|
||||
initialDirectoryId,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: DocumentFormDialogBodyProps) {
|
||||
const t = useI18n()
|
||||
const formId = "knowledge-document-edit-form"
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [directories, setDirectories] = useState<KnowledgeDirectory[]>([])
|
||||
const knowledgeDocumentFormSchema = useMemo(() => createKnowledgeDocumentFormSchema(t), [t])
|
||||
const editFormResolver = useMemo(
|
||||
() => zodResolver(knowledgeDocumentFormSchema) as Resolver<EditForm>,
|
||||
@@ -140,11 +163,18 @@ function DocumentFormDialogBody({
|
||||
|
||||
const contentType = watch("contentType")
|
||||
const content = watch("content")
|
||||
const directoryOptions = useMemo(
|
||||
() => [
|
||||
{ value: "0", label: t("knowledge.rootContent") },
|
||||
...flattenDirectoryOptions(directories),
|
||||
],
|
||||
[directories, t],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
async function loadDetail() {
|
||||
if (!itemId) {
|
||||
reset(emptyForm)
|
||||
reset(buildForm(null, initialDirectoryId))
|
||||
return
|
||||
}
|
||||
setLoading(true)
|
||||
@@ -158,7 +188,25 @@ function DocumentFormDialogBody({
|
||||
}
|
||||
}
|
||||
void loadDetail()
|
||||
}, [itemId, reset])
|
||||
}, [itemId, initialDirectoryId, reset])
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false
|
||||
async function loadDirectories() {
|
||||
try {
|
||||
const data = await fetchKnowledgeDirectories(knowledgeBaseId)
|
||||
if (!cancelled) {
|
||||
setDirectories(data)
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load knowledge directories:", error)
|
||||
}
|
||||
}
|
||||
void loadDirectories()
|
||||
return () => {
|
||||
cancelled = true
|
||||
}
|
||||
}, [knowledgeBaseId])
|
||||
|
||||
async function onFormSubmit(values: EditForm) {
|
||||
const payload = buildPayload({ ...values, contentType, content }, knowledgeBaseId)
|
||||
@@ -194,6 +242,27 @@ function DocumentFormDialogBody({
|
||||
</div>
|
||||
) : (
|
||||
<form id={formId} onSubmit={handleSubmit(onFormSubmit)} className="space-y-4">
|
||||
<Field data-invalid={!!errors.directoryId}>
|
||||
<FieldLabel>{t("knowledge.directory")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Controller
|
||||
control={control}
|
||||
name="directoryId"
|
||||
render={({ field }) => (
|
||||
<OptionCombobox
|
||||
value={field.value}
|
||||
onChange={(value) => field.onChange(value ?? "0")}
|
||||
options={directoryOptions}
|
||||
placeholder={t("knowledge.selectDirectory")}
|
||||
searchPlaceholder={t("knowledge.searchDirectory")}
|
||||
emptyText={t("knowledge.emptyDirectory")}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<FieldError errors={[errors.directoryId]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!errors.title}>
|
||||
<FieldLabel htmlFor="doc-title">{t("knowledge.documentTitle")}</FieldLabel>
|
||||
<FieldContent>
|
||||
|
||||
@@ -55,6 +55,7 @@ import {
|
||||
} from "@/lib/generated/enums";
|
||||
import { cn, formatDateTime } from "@/lib/utils";
|
||||
import { DocumentEditDialog } from "./document-edit";
|
||||
import { KnowledgeDirectoryPanel } from "./knowledge-directory-panel";
|
||||
|
||||
type DocumentListProps = {
|
||||
knowledgeBaseId: number | null;
|
||||
@@ -140,6 +141,7 @@ const VIEW_MODE_STORAGE_KEY = "knowledge-document-view-mode";
|
||||
export function DocumentList({ knowledgeBaseId, onActionStateChange }: DocumentListProps) {
|
||||
const t = useI18n();
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [selectedDirectoryId, setSelectedDirectoryId] = useState<number | null>(null);
|
||||
const [actionLoadingMap, setActionLoadingMap] = useState<Record<number, { rebuildIndex: boolean; delete: boolean }>>({});
|
||||
const [dialogOpen, setDialogOpen] = useState(false);
|
||||
const [editingItem, setEditingItem] = useState<KnowledgeDocumentListItem | null>(
|
||||
@@ -153,6 +155,10 @@ export function DocumentList({ knowledgeBaseId, onActionStateChange }: DocumentL
|
||||
const statusOptions = useMemo(() => getStatusOptions(t), [t]);
|
||||
const indexStatusOptions = useMemo(() => getIndexStatusOptions(t), [t]);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedDirectoryId(null);
|
||||
}, [knowledgeBaseId]);
|
||||
|
||||
const filters = useMemo<DashboardPagedListFilter[]>(() => [
|
||||
{
|
||||
name: "title",
|
||||
@@ -177,10 +183,11 @@ export function DocumentList({ knowledgeBaseId, onActionStateChange }: DocumentL
|
||||
status: typeof query.status === "string" ? query.status : undefined,
|
||||
indexStatus: typeof query.indexStatus === "string" ? query.indexStatus : undefined,
|
||||
knowledgeBaseId: knowledgeBaseId ?? 0,
|
||||
directoryId: selectedDirectoryId === null ? undefined : selectedDirectoryId,
|
||||
page: typeof query.page === "number" ? query.page : Number(query.page ?? 1),
|
||||
limit: typeof query.limit === "number" ? query.limit : Number(query.limit ?? 20),
|
||||
});
|
||||
}, [knowledgeBaseId]);
|
||||
}, [knowledgeBaseId, selectedDirectoryId]);
|
||||
|
||||
const {
|
||||
draftFilters,
|
||||
@@ -196,7 +203,7 @@ export function DocumentList({ knowledgeBaseId, onActionStateChange }: DocumentL
|
||||
filters,
|
||||
fetchList,
|
||||
enabled: Boolean(knowledgeBaseId),
|
||||
reloadKey: knowledgeBaseId,
|
||||
reloadKey: `${knowledgeBaseId ?? 0}-${selectedDirectoryId ?? "all"}`,
|
||||
loadFailed: t("knowledge.loadDocumentsFailed"),
|
||||
});
|
||||
|
||||
@@ -322,7 +329,14 @@ export function DocumentList({ knowledgeBaseId, onActionStateChange }: DocumentL
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex h-full min-h-0 flex-col">
|
||||
<div className="flex h-full min-h-0">
|
||||
<KnowledgeDirectoryPanel
|
||||
knowledgeBaseId={knowledgeBaseId}
|
||||
selectedDirectoryId={selectedDirectoryId}
|
||||
onSelectDirectory={setSelectedDirectoryId}
|
||||
onChanged={() => void loadData()}
|
||||
/>
|
||||
<div className="flex min-w-0 flex-1 flex-col">
|
||||
<div className="flex flex-col gap-2 border-b bg-background px-6 py-2">
|
||||
<div className="flex gap-2">
|
||||
<div className="relative flex-1">
|
||||
@@ -528,12 +542,14 @@ export function DocumentList({ knowledgeBaseId, onActionStateChange }: DocumentL
|
||||
onLimitChange={handleLimitChange}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<DocumentEditDialog
|
||||
open={dialogOpen}
|
||||
saving={saving}
|
||||
itemId={editingItem?.id ?? null}
|
||||
knowledgeBaseId={knowledgeBaseId}
|
||||
initialDirectoryId={selectedDirectoryId ?? 0}
|
||||
onOpenChange={handleDialogOpenChange}
|
||||
onSubmit={handleSubmit}
|
||||
/>
|
||||
|
||||
@@ -6,13 +6,16 @@ import { useForm, type Resolver } from "react-hook-form";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { ProjectDialog } from "@/components/project-dialog";
|
||||
import { OptionCombobox } from "@/components/option-combobox";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Field, FieldContent, FieldError, FieldLabel } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
fetchKnowledgeFAQ,
|
||||
fetchKnowledgeDirectories,
|
||||
type CreateKnowledgeFAQPayload,
|
||||
type KnowledgeDirectory,
|
||||
type KnowledgeFAQ,
|
||||
} from "@/lib/api/admin";
|
||||
import { useI18n } from "@/i18n/provider";
|
||||
@@ -22,6 +25,7 @@ type FAQEditDialogProps = {
|
||||
saving: boolean;
|
||||
itemId: number | null;
|
||||
knowledgeBaseId: number | null;
|
||||
initialDirectoryId?: number;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSubmit: (payload: CreateKnowledgeFAQPayload) => Promise<void>;
|
||||
};
|
||||
@@ -30,6 +34,7 @@ type TFunction = (key: string, values?: Record<string, string | number>) => stri
|
||||
|
||||
function createFormSchema(t: TFunction) {
|
||||
return z.object({
|
||||
directoryId: z.string().trim(),
|
||||
question: z.string().trim().min(1, t("knowledge.faqQuestionRequired")).max(500, t("knowledge.faqQuestionMax")),
|
||||
answer: z.string().trim().min(1, t("knowledge.faqAnswerRequired")),
|
||||
similarQuestionsText: z.string(),
|
||||
@@ -38,6 +43,7 @@ function createFormSchema(t: TFunction) {
|
||||
}
|
||||
|
||||
type EditForm = {
|
||||
directoryId: string;
|
||||
question: string;
|
||||
answer: string;
|
||||
similarQuestionsText: string;
|
||||
@@ -45,17 +51,28 @@ type EditForm = {
|
||||
};
|
||||
|
||||
const emptyForm: EditForm = {
|
||||
directoryId: "0",
|
||||
question: "",
|
||||
answer: "",
|
||||
similarQuestionsText: "",
|
||||
remark: "",
|
||||
};
|
||||
|
||||
function buildForm(item: KnowledgeFAQ | null): EditForm {
|
||||
type DirectoryOption = { value: string; label: string };
|
||||
|
||||
function flattenDirectoryOptions(items: KnowledgeDirectory[], depth = 0): DirectoryOption[] {
|
||||
return items.flatMap((item) => [
|
||||
{ value: String(item.id), label: `${depth > 0 ? " " : ""}${item.name}` },
|
||||
...flattenDirectoryOptions(item.children || [], depth + 1),
|
||||
]);
|
||||
}
|
||||
|
||||
function buildForm(item: KnowledgeFAQ | null, initialDirectoryId = 0): EditForm {
|
||||
if (!item) {
|
||||
return emptyForm;
|
||||
return { ...emptyForm, directoryId: String(initialDirectoryId) };
|
||||
}
|
||||
return {
|
||||
directoryId: String(item.directoryId || 0),
|
||||
question: item.question,
|
||||
answer: item.answer,
|
||||
similarQuestionsText: (item.similarQuestions ?? []).join("\n"),
|
||||
@@ -66,6 +83,7 @@ function buildForm(item: KnowledgeFAQ | null): EditForm {
|
||||
function buildPayload(form: EditForm, knowledgeBaseId: number): CreateKnowledgeFAQPayload {
|
||||
return {
|
||||
knowledgeBaseId,
|
||||
directoryId: Number(form.directoryId),
|
||||
question: form.question.trim(),
|
||||
answer: form.answer.trim(),
|
||||
similarQuestions: form.similarQuestionsText
|
||||
@@ -81,6 +99,7 @@ export function FAQEditDialog({
|
||||
saving,
|
||||
itemId,
|
||||
knowledgeBaseId,
|
||||
initialDirectoryId = 0,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: FAQEditDialogProps) {
|
||||
@@ -94,6 +113,7 @@ export function FAQEditDialog({
|
||||
saving={saving}
|
||||
itemId={itemId}
|
||||
knowledgeBaseId={knowledgeBaseId}
|
||||
initialDirectoryId={initialDirectoryId}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
@@ -105,6 +125,7 @@ type FAQEditDialogBodyProps = {
|
||||
saving: boolean;
|
||||
itemId: number | null;
|
||||
knowledgeBaseId: number;
|
||||
initialDirectoryId: number;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSubmit: (payload: CreateKnowledgeFAQPayload) => Promise<void>;
|
||||
};
|
||||
@@ -114,11 +135,13 @@ function FAQEditDialogBody({
|
||||
saving,
|
||||
itemId,
|
||||
knowledgeBaseId,
|
||||
initialDirectoryId,
|
||||
onOpenChange,
|
||||
onSubmit,
|
||||
}: FAQEditDialogBodyProps) {
|
||||
const t = useI18n();
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [directories, setDirectories] = useState<KnowledgeDirectory[]>([]);
|
||||
const formId = "knowledge-faq-edit-form";
|
||||
const formSchema = useMemo(() => createFormSchema(t), [t]);
|
||||
const resolver = useMemo(
|
||||
@@ -135,11 +158,18 @@ function FAQEditDialogBody({
|
||||
register,
|
||||
formState: { errors },
|
||||
} = form;
|
||||
const directoryOptions = useMemo(
|
||||
() => [
|
||||
{ value: "0", label: t("knowledge.rootContent") },
|
||||
...flattenDirectoryOptions(directories),
|
||||
],
|
||||
[directories, t],
|
||||
);
|
||||
|
||||
useEffect(() => {
|
||||
async function loadDetail() {
|
||||
if (!itemId) {
|
||||
reset(emptyForm);
|
||||
reset(buildForm(null, initialDirectoryId));
|
||||
return;
|
||||
}
|
||||
setLoading(true);
|
||||
@@ -153,7 +183,28 @@ function FAQEditDialogBody({
|
||||
if (open) {
|
||||
void loadDetail();
|
||||
}
|
||||
}, [itemId, open, reset]);
|
||||
}, [itemId, initialDirectoryId, open, reset]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
return;
|
||||
}
|
||||
let cancelled = false;
|
||||
async function loadDirectories() {
|
||||
try {
|
||||
const data = await fetchKnowledgeDirectories(knowledgeBaseId);
|
||||
if (!cancelled) {
|
||||
setDirectories(data);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Failed to load knowledge directories:", error);
|
||||
}
|
||||
}
|
||||
void loadDirectories();
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [knowledgeBaseId, open]);
|
||||
|
||||
async function onFormSubmit(values: EditForm) {
|
||||
await onSubmit(buildPayload(values, knowledgeBaseId));
|
||||
@@ -181,6 +232,21 @@ function FAQEditDialogBody({
|
||||
<div className="flex items-center justify-center py-12 text-muted-foreground">{t("knowledge.loading")}</div>
|
||||
) : (
|
||||
<form id={formId} onSubmit={handleSubmit(onFormSubmit)} className="space-y-4">
|
||||
<Field data-invalid={!!errors.directoryId}>
|
||||
<FieldLabel>{t("knowledge.directory")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<OptionCombobox
|
||||
value={form.watch("directoryId")}
|
||||
onChange={(value) => form.setValue("directoryId", value ?? "0", { shouldDirty: true })}
|
||||
options={directoryOptions}
|
||||
placeholder={t("knowledge.selectDirectory")}
|
||||
searchPlaceholder={t("knowledge.searchDirectory")}
|
||||
emptyText={t("knowledge.emptyDirectory")}
|
||||
/>
|
||||
<FieldError errors={[errors.directoryId]} />
|
||||
</FieldContent>
|
||||
</Field>
|
||||
|
||||
<Field data-invalid={!!errors.question}>
|
||||
<FieldLabel htmlFor="faq-question">{t("knowledge.standardQuestion")}</FieldLabel>
|
||||
<FieldContent>
|
||||
|
||||
@@ -31,6 +31,7 @@ import { useI18n } from "@/i18n/provider";
|
||||
import { formatDateTime } from "@/lib/utils";
|
||||
import { FAQEditDialog } from "./faq-edit";
|
||||
import { FAQImportDialog } from "./faq-import-dialog";
|
||||
import { KnowledgeDirectoryPanel } from "./knowledge-directory-panel";
|
||||
|
||||
type FAQListProps = {
|
||||
knowledgeBaseId: number | null;
|
||||
@@ -121,10 +122,15 @@ export function FAQList({
|
||||
const t = useI18n();
|
||||
const [importing, setImporting] = useState(false);
|
||||
const [importDialogOpen, setImportDialogOpen] = useState(false);
|
||||
const [selectedDirectoryId, setSelectedDirectoryId] = useState<number | null>(null);
|
||||
const [crudActionState, setCrudActionState] =
|
||||
useState<DashboardCrudActionState | null>(null);
|
||||
const indexStatusOptions = useMemo(() => getIndexStatusOptions(t), [t]);
|
||||
|
||||
useEffect(() => {
|
||||
setSelectedDirectoryId(null);
|
||||
}, [knowledgeBaseId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!crudActionState) {
|
||||
return;
|
||||
@@ -206,9 +212,16 @@ export function FAQList({
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex h-full flex-col gap-4 p-4">
|
||||
<div className="flex h-full min-h-0">
|
||||
<KnowledgeDirectoryPanel
|
||||
knowledgeBaseId={knowledgeBaseId}
|
||||
selectedDirectoryId={selectedDirectoryId}
|
||||
onSelectDirectory={setSelectedDirectoryId}
|
||||
onChanged={() => crudActionState?.onRefresh()}
|
||||
/>
|
||||
<div className="min-w-0 flex-1 p-4">
|
||||
<DashboardCrudPage<KnowledgeFAQ, CreateKnowledgeFAQPayload>
|
||||
key={knowledgeBaseId}
|
||||
key={`${knowledgeBaseId}-${selectedDirectoryId ?? "all"}`}
|
||||
layout="fragment"
|
||||
showToolbarActions={false}
|
||||
filters={filters}
|
||||
@@ -216,6 +229,8 @@ export function FAQList({
|
||||
fetchList={(query) =>
|
||||
fetchKnowledgeFAQs({
|
||||
knowledgeBaseId,
|
||||
directoryId:
|
||||
selectedDirectoryId === null ? undefined : selectedDirectoryId,
|
||||
question:
|
||||
typeof query.question === "string" ? query.question : undefined,
|
||||
indexStatus:
|
||||
@@ -264,6 +279,7 @@ export function FAQList({
|
||||
saving={saving}
|
||||
itemId={itemId}
|
||||
knowledgeBaseId={knowledgeBaseId}
|
||||
initialDirectoryId={selectedDirectoryId ?? 0}
|
||||
onOpenChange={onOpenChange}
|
||||
onSubmit={onSubmit}
|
||||
/>
|
||||
@@ -289,6 +305,7 @@ export function FAQList({
|
||||
deleted: () => t("knowledge.faqDeleted"),
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<FAQImportDialog
|
||||
|
||||
@@ -0,0 +1,451 @@
|
||||
"use client";
|
||||
|
||||
import {
|
||||
ChevronDownIcon,
|
||||
ChevronRightIcon,
|
||||
FolderIcon,
|
||||
FolderPlusIcon,
|
||||
LayersIcon,
|
||||
MoreHorizontalIcon,
|
||||
PencilIcon,
|
||||
PlusIcon,
|
||||
Trash2Icon,
|
||||
} from "lucide-react";
|
||||
import type { ReactNode } from "react";
|
||||
import { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { toast } from "sonner";
|
||||
|
||||
import { OptionCombobox } from "@/components/option-combobox";
|
||||
import { ProjectDialog } from "@/components/project-dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from "@/components/ui/dropdown-menu";
|
||||
import { Field, FieldContent, FieldLabel } from "@/components/ui/field";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
createKnowledgeDirectory,
|
||||
deleteKnowledgeDirectory,
|
||||
fetchKnowledgeDirectories,
|
||||
updateKnowledgeDirectory,
|
||||
type KnowledgeDirectory,
|
||||
} from "@/lib/api/admin";
|
||||
import { useI18n } from "@/i18n/provider";
|
||||
import { cn } from "@/lib/utils";
|
||||
|
||||
type KnowledgeDirectoryPanelProps = {
|
||||
knowledgeBaseId: number;
|
||||
selectedDirectoryId: number | null;
|
||||
onSelectDirectory: (directoryId: number | null) => void;
|
||||
onChanged?: () => void;
|
||||
};
|
||||
|
||||
type DirectoryDialogState = {
|
||||
open: boolean;
|
||||
id: number | null;
|
||||
parentId: number;
|
||||
name: string;
|
||||
remark: string;
|
||||
};
|
||||
|
||||
type DirectoryOption = { value: string; label: string };
|
||||
|
||||
function rootDirectoryOptions(items: KnowledgeDirectory[]): DirectoryOption[] {
|
||||
return items.map((item) => ({ value: String(item.id), label: item.name }));
|
||||
}
|
||||
|
||||
function collectExpandedIds(items: KnowledgeDirectory[]) {
|
||||
const ids = new Set<number>();
|
||||
const walk = (nodes: KnowledgeDirectory[]) => {
|
||||
for (const node of nodes) {
|
||||
ids.add(node.id);
|
||||
walk(node.children || []);
|
||||
}
|
||||
};
|
||||
walk(items);
|
||||
return ids;
|
||||
}
|
||||
|
||||
export function KnowledgeDirectoryPanel({
|
||||
knowledgeBaseId,
|
||||
selectedDirectoryId,
|
||||
onSelectDirectory,
|
||||
onChanged,
|
||||
}: KnowledgeDirectoryPanelProps) {
|
||||
const t = useI18n();
|
||||
const [directories, setDirectories] = useState<KnowledgeDirectory[]>([]);
|
||||
const [expandedIds, setExpandedIds] = useState<Set<number>>(new Set());
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [saving, setSaving] = useState(false);
|
||||
const [dialog, setDialog] = useState<DirectoryDialogState>({
|
||||
open: false,
|
||||
id: null,
|
||||
parentId: 0,
|
||||
name: "",
|
||||
remark: "",
|
||||
});
|
||||
const parentOptions = useMemo(
|
||||
() => [
|
||||
{ value: "0", label: t("knowledge.rootDirectory") },
|
||||
...rootDirectoryOptions(directories).filter((item) => item.value !== String(dialog.id ?? "")),
|
||||
],
|
||||
[directories, dialog.id, t],
|
||||
);
|
||||
|
||||
const loadDirectories = useCallback(async () => {
|
||||
setLoading(true);
|
||||
try {
|
||||
const data = await fetchKnowledgeDirectories(knowledgeBaseId);
|
||||
setDirectories(data);
|
||||
setExpandedIds(collectExpandedIds(data));
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("knowledge.loadDirectoriesFailed"));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, [knowledgeBaseId, t]);
|
||||
|
||||
useEffect(() => {
|
||||
void loadDirectories();
|
||||
}, [loadDirectories]);
|
||||
|
||||
function toggleDirectory(id: number) {
|
||||
setExpandedIds((current) => {
|
||||
const next = new Set(current);
|
||||
if (next.has(id)) {
|
||||
next.delete(id);
|
||||
} else {
|
||||
next.add(id);
|
||||
}
|
||||
return next;
|
||||
});
|
||||
}
|
||||
|
||||
function openCreate(parentId = 0) {
|
||||
setDialog({ open: true, id: null, parentId, name: "", remark: "" });
|
||||
}
|
||||
|
||||
function openEdit(item: KnowledgeDirectory) {
|
||||
setDialog({
|
||||
open: true,
|
||||
id: item.id,
|
||||
parentId: item.parentId,
|
||||
name: item.name,
|
||||
remark: item.remark || "",
|
||||
});
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
const name = dialog.name.trim();
|
||||
if (!name) {
|
||||
toast.error(t("knowledge.directoryNameRequired"));
|
||||
return;
|
||||
}
|
||||
setSaving(true);
|
||||
try {
|
||||
if (dialog.id) {
|
||||
await updateKnowledgeDirectory({
|
||||
id: dialog.id,
|
||||
knowledgeBaseId,
|
||||
parentId: dialog.parentId,
|
||||
name,
|
||||
remark: dialog.remark.trim(),
|
||||
});
|
||||
toast.success(t("knowledge.directoryUpdated", { name }));
|
||||
} else {
|
||||
await createKnowledgeDirectory({
|
||||
knowledgeBaseId,
|
||||
parentId: dialog.parentId,
|
||||
name,
|
||||
remark: dialog.remark.trim(),
|
||||
});
|
||||
toast.success(t("knowledge.directoryCreated", { name }));
|
||||
}
|
||||
setDialog((current) => ({ ...current, open: false }));
|
||||
await loadDirectories();
|
||||
onChanged?.();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("knowledge.directorySaveFailed"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleDelete(item: KnowledgeDirectory) {
|
||||
setSaving(true);
|
||||
try {
|
||||
await deleteKnowledgeDirectory(item.id);
|
||||
if (selectedDirectoryId === item.id) {
|
||||
onSelectDirectory(null);
|
||||
}
|
||||
toast.success(t("knowledge.directoryDeleted", { name: item.name }));
|
||||
await loadDirectories();
|
||||
onChanged?.();
|
||||
} catch (error) {
|
||||
toast.error(error instanceof Error ? error.message : t("knowledge.directoryDeleteFailed"));
|
||||
} finally {
|
||||
setSaving(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex h-full min-h-0 w-56 shrink-0 flex-col border-r bg-muted/20">
|
||||
<div className="flex items-center justify-between border-b bg-background px-3 py-2">
|
||||
<div className="text-sm font-medium">{t("knowledge.directory")}</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-7"
|
||||
disabled={loading || saving}
|
||||
onClick={() => openCreate(0)}
|
||||
aria-label={t("knowledge.createDirectory")}
|
||||
>
|
||||
<FolderPlusIcon className="size-4" />
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="flex-1">
|
||||
<div className="py-1">
|
||||
<DirectoryStaticRow
|
||||
icon={<LayersIcon className="size-4 text-muted-foreground" />}
|
||||
label={t("knowledge.allContent")}
|
||||
selected={selectedDirectoryId === null}
|
||||
onClick={() => onSelectDirectory(null)}
|
||||
/>
|
||||
<DirectoryStaticRow
|
||||
icon={<FolderIcon className="size-4 text-muted-foreground" />}
|
||||
label={t("knowledge.rootContent")}
|
||||
selected={selectedDirectoryId === 0}
|
||||
onClick={() => onSelectDirectory(0)}
|
||||
/>
|
||||
{directories.map((item) => (
|
||||
<DirectoryNode
|
||||
key={item.id}
|
||||
item={item}
|
||||
depth={0}
|
||||
expandedIds={expandedIds}
|
||||
selectedDirectoryId={selectedDirectoryId}
|
||||
saving={saving}
|
||||
onToggle={toggleDirectory}
|
||||
onSelect={onSelectDirectory}
|
||||
onCreate={openCreate}
|
||||
onEdit={openEdit}
|
||||
onDelete={(directory) => void handleDelete(directory)}
|
||||
t={t}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
<ProjectDialog
|
||||
open={dialog.open}
|
||||
onOpenChange={(open) => setDialog((current) => ({ ...current, open }))}
|
||||
title={dialog.id ? t("knowledge.editDirectory") : t("knowledge.createDirectory")}
|
||||
size="sm"
|
||||
footer={
|
||||
<>
|
||||
<Button
|
||||
type="button"
|
||||
variant="outline"
|
||||
onClick={() => setDialog((current) => ({ ...current, open: false }))}
|
||||
disabled={saving}
|
||||
>
|
||||
{t("knowledge.cancel")}
|
||||
</Button>
|
||||
<Button type="button" onClick={() => void handleSubmit()} disabled={saving}>
|
||||
{saving ? t("knowledge.saving") : t("knowledge.save")}
|
||||
</Button>
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div className="space-y-4">
|
||||
<Field>
|
||||
<FieldLabel>{t("knowledge.parentDirectory")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<OptionCombobox
|
||||
value={String(dialog.parentId)}
|
||||
onChange={(value) =>
|
||||
setDialog((current) => ({ ...current, parentId: Number(value ?? 0) }))
|
||||
}
|
||||
options={parentOptions}
|
||||
placeholder={t("knowledge.selectDirectory")}
|
||||
searchPlaceholder={t("knowledge.searchDirectory")}
|
||||
emptyText={t("knowledge.emptyDirectory")}
|
||||
/>
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t("knowledge.directoryName")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Input
|
||||
value={dialog.name}
|
||||
onChange={(event) =>
|
||||
setDialog((current) => ({ ...current, name: event.target.value }))
|
||||
}
|
||||
placeholder={t("knowledge.directoryNamePlaceholder")}
|
||||
/>
|
||||
</FieldContent>
|
||||
</Field>
|
||||
<Field>
|
||||
<FieldLabel>{t("knowledge.remark")}</FieldLabel>
|
||||
<FieldContent>
|
||||
<Textarea
|
||||
value={dialog.remark}
|
||||
onChange={(event) =>
|
||||
setDialog((current) => ({ ...current, remark: event.target.value }))
|
||||
}
|
||||
rows={3}
|
||||
placeholder={t("knowledge.remarkPlaceholder")}
|
||||
/>
|
||||
</FieldContent>
|
||||
</Field>
|
||||
</div>
|
||||
</ProjectDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
type DirectoryStaticRowProps = {
|
||||
icon: ReactNode;
|
||||
label: string;
|
||||
selected: boolean;
|
||||
onClick: () => void;
|
||||
};
|
||||
|
||||
function DirectoryStaticRow({ icon, label, selected, onClick }: DirectoryStaticRowProps) {
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
className={cn(
|
||||
"flex w-full items-center gap-2 px-3 py-1.5 text-left text-sm hover:bg-accent",
|
||||
selected && "bg-accent text-accent-foreground",
|
||||
)}
|
||||
onClick={onClick}
|
||||
>
|
||||
<span className="size-5" />
|
||||
{icon}
|
||||
<span className="min-w-0 flex-1 truncate">{label}</span>
|
||||
</button>
|
||||
);
|
||||
}
|
||||
|
||||
type DirectoryNodeProps = {
|
||||
item: KnowledgeDirectory;
|
||||
depth: number;
|
||||
expandedIds: Set<number>;
|
||||
selectedDirectoryId: number | null;
|
||||
saving: boolean;
|
||||
onToggle: (id: number) => void;
|
||||
onSelect: (id: number) => void;
|
||||
onCreate: (parentId: number) => void;
|
||||
onEdit: (item: KnowledgeDirectory) => void;
|
||||
onDelete: (item: KnowledgeDirectory) => void;
|
||||
t: TFunction;
|
||||
};
|
||||
|
||||
type TFunction = (key: string, values?: Record<string, string | number>) => string;
|
||||
|
||||
function DirectoryNode({
|
||||
item,
|
||||
depth,
|
||||
expandedIds,
|
||||
selectedDirectoryId,
|
||||
saving,
|
||||
onToggle,
|
||||
onSelect,
|
||||
onCreate,
|
||||
onEdit,
|
||||
onDelete,
|
||||
t,
|
||||
}: DirectoryNodeProps) {
|
||||
const expanded = expandedIds.has(item.id);
|
||||
const hasChildren = (item.children || []).length > 0;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div
|
||||
className={cn(
|
||||
"group flex items-center gap-1 px-2 py-1.5 text-sm hover:bg-accent",
|
||||
selectedDirectoryId === item.id && "bg-accent text-accent-foreground",
|
||||
)}
|
||||
style={{ paddingLeft: 8 + depth * 16 }}
|
||||
>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-5 shrink-0"
|
||||
disabled={!hasChildren}
|
||||
onClick={() => onToggle(item.id)}
|
||||
aria-label={expanded ? t("knowledge.collapseDirectory") : t("knowledge.expandDirectory")}
|
||||
>
|
||||
{expanded ? <ChevronDownIcon className="size-3.5" /> : <ChevronRightIcon className="size-3.5" />}
|
||||
</Button>
|
||||
<FolderIcon className="size-4 shrink-0 text-muted-foreground" />
|
||||
<button
|
||||
type="button"
|
||||
className="min-w-0 flex-1 truncate text-left"
|
||||
onClick={() => onSelect(item.id)}
|
||||
>
|
||||
{item.name}
|
||||
</button>
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger
|
||||
render={
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
className="size-6 opacity-0 group-hover:opacity-100"
|
||||
disabled={saving}
|
||||
/>
|
||||
}
|
||||
aria-label={t("knowledge.moreActions", { name: item.name })}
|
||||
>
|
||||
<MoreHorizontalIcon className="size-3.5" />
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-40 min-w-40">
|
||||
{item.parentId === 0 ? (
|
||||
<DropdownMenuItem onClick={() => onCreate(item.id)}>
|
||||
<PlusIcon className="mr-2 size-3.5" />
|
||||
{t("knowledge.createSubDirectory")}
|
||||
</DropdownMenuItem>
|
||||
) : null}
|
||||
<DropdownMenuItem onClick={() => onEdit(item)}>
|
||||
<PencilIcon className="mr-2 size-3.5" />
|
||||
{t("knowledge.edit")}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => onDelete(item)}
|
||||
className="text-destructive focus:text-destructive"
|
||||
>
|
||||
<Trash2Icon className="mr-2 size-3.5" />
|
||||
{t("knowledge.delete")}
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
{expanded
|
||||
? (item.children || []).map((child) => (
|
||||
<DirectoryNode
|
||||
key={child.id}
|
||||
item={child}
|
||||
depth={depth + 1}
|
||||
expandedIds={expandedIds}
|
||||
selectedDirectoryId={selectedDirectoryId}
|
||||
saving={saving}
|
||||
onToggle={onToggle}
|
||||
onSelect={onSelect}
|
||||
onCreate={onCreate}
|
||||
onEdit={onEdit}
|
||||
onDelete={onDelete}
|
||||
t={t}
|
||||
/>
|
||||
))
|
||||
: null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user