feat: 新增FAQ条目导出功能,支持CSV格式导出
This commit is contained in:
@@ -86,7 +86,10 @@ func (r *chunkRepository) ListPagedChunksByKnowledgeID(
|
||||
baseFilter := func(db *gorm.DB) *gorm.DB {
|
||||
db = db.Where("tenant_id = ? AND knowledge_id = ? AND chunk_type IN (?) AND status in (?)",
|
||||
tenantID, knowledgeID, chunkType, []int{int(types.ChunkStatusIndexed), int(types.ChunkStatusDefault)})
|
||||
if tagID != "" {
|
||||
if tagID == "__untagged__" {
|
||||
// Special value to filter entries without a tag
|
||||
db = db.Where("tag_id = ''")
|
||||
} else if tagID != "" {
|
||||
db = db.Where("tag_id = ?", tagID)
|
||||
}
|
||||
if keyword != "" {
|
||||
@@ -389,6 +392,48 @@ func (r *chunkRepository) ListAllFAQChunksWithMetadataByKnowledgeBaseID(
|
||||
return allChunks, nil
|
||||
}
|
||||
|
||||
// ListAllFAQChunksForExport lists all FAQ chunks for export with full metadata, tag_id, is_enabled, and flags.
|
||||
// Uses batch query to handle large datasets.
|
||||
func (r *chunkRepository) ListAllFAQChunksForExport(
|
||||
ctx context.Context,
|
||||
tenantID uint64,
|
||||
knowledgeID string,
|
||||
) ([]*types.Chunk, error) {
|
||||
const batchSize = 1000 // 每批查询1000条
|
||||
var allChunks []*types.Chunk
|
||||
offset := 0
|
||||
|
||||
for {
|
||||
var batchChunks []*types.Chunk
|
||||
if err := r.db.WithContext(ctx).
|
||||
Select("id, metadata, tag_id, is_enabled, flags").
|
||||
Where("tenant_id = ? AND knowledge_id = ? AND chunk_type = ? AND status = ?",
|
||||
tenantID, knowledgeID, types.ChunkTypeFAQ, types.ChunkStatusIndexed).
|
||||
Order("created_at ASC").
|
||||
Offset(offset).
|
||||
Limit(batchSize).
|
||||
Find(&batchChunks).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 如果没有查询到数据,说明已经查询完毕
|
||||
if len(batchChunks) == 0 {
|
||||
break
|
||||
}
|
||||
|
||||
allChunks = append(allChunks, batchChunks...)
|
||||
|
||||
// 如果返回的数据少于批次大小,说明已经是最后一批
|
||||
if len(batchChunks) < batchSize {
|
||||
break
|
||||
}
|
||||
|
||||
offset += batchSize
|
||||
}
|
||||
|
||||
return allChunks, nil
|
||||
}
|
||||
|
||||
// UpdateChunkFlagsBatch updates flags for multiple chunks in batch using SQL CASE expressions.
|
||||
// This is more efficient than updating chunks one by one.
|
||||
// setFlags: map of chunk ID to flags to set (OR operation)
|
||||
|
||||
@@ -3895,6 +3895,128 @@ func (s *knowledgeService) DeleteFAQEntries(ctx context.Context,
|
||||
return nil
|
||||
}
|
||||
|
||||
// ExportFAQEntries exports all FAQ entries for a knowledge base as CSV data.
|
||||
// The CSV format matches the import example format with 8 columns:
|
||||
// 分类(必填), 问题(必填), 相似问题(选填-多个用##分隔), 反例问题(选填-多个用##分隔),
|
||||
// 机器人回答(必填-多个用##分隔), 是否全部回复(选填-默认FALSE), 是否停用(选填-默认FALSE),
|
||||
// 是否禁止被推荐(选填-默认False 可被推荐)
|
||||
func (s *knowledgeService) ExportFAQEntries(ctx context.Context, kbID string) ([]byte, error) {
|
||||
kb, err := s.validateFAQKnowledgeBase(ctx, kbID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
|
||||
faqKnowledge, err := s.findFAQKnowledge(ctx, tenantID, kb.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if faqKnowledge == nil {
|
||||
// Return empty CSV with headers only
|
||||
return s.buildFAQCSV(nil, nil), nil
|
||||
}
|
||||
|
||||
// Get all FAQ chunks
|
||||
chunks, err := s.chunkRepo.ListAllFAQChunksForExport(ctx, tenantID, faqKnowledge.ID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to list FAQ chunks: %w", err)
|
||||
}
|
||||
|
||||
// Build tag map for tag_id -> tag_name conversion
|
||||
tagMap, err := s.buildTagMap(ctx, tenantID, kbID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to build tag map: %w", err)
|
||||
}
|
||||
|
||||
return s.buildFAQCSV(chunks, tagMap), nil
|
||||
}
|
||||
|
||||
// buildTagMap builds a map from tag_id to tag_name for the given knowledge base.
|
||||
func (s *knowledgeService) buildTagMap(ctx context.Context, tenantID uint64, kbID string) (map[string]string, error) {
|
||||
// Get all tags for this knowledge base (no pagination limit)
|
||||
page := &types.Pagination{Page: 1, PageSize: 10000}
|
||||
tags, _, err := s.tagRepo.ListByKB(ctx, tenantID, kbID, page, "")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
tagMap := make(map[string]string, len(tags))
|
||||
for _, tag := range tags {
|
||||
if tag != nil {
|
||||
tagMap[tag.ID] = tag.Name
|
||||
}
|
||||
}
|
||||
return tagMap, nil
|
||||
}
|
||||
|
||||
// buildFAQCSV builds CSV content from FAQ chunks.
|
||||
func (s *knowledgeService) buildFAQCSV(chunks []*types.Chunk, tagMap map[string]string) []byte {
|
||||
var buf strings.Builder
|
||||
|
||||
// Write CSV header (matching import example format)
|
||||
headers := []string{
|
||||
"分类(必填)",
|
||||
"问题(必填)",
|
||||
"相似问题(选填-多个用##分隔)",
|
||||
"反例问题(选填-多个用##分隔)",
|
||||
"机器人回答(必填-多个用##分隔)",
|
||||
"是否全部回复(选填-默认FALSE)",
|
||||
"是否停用(选填-默认FALSE)",
|
||||
"是否禁止被推荐(选填-默认False 可被推荐)",
|
||||
}
|
||||
buf.WriteString(strings.Join(headers, ","))
|
||||
buf.WriteString("\n")
|
||||
|
||||
// Write data rows
|
||||
for _, chunk := range chunks {
|
||||
meta, err := chunk.FAQMetadata()
|
||||
if err != nil || meta == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
// Get tag name
|
||||
tagName := ""
|
||||
if chunk.TagID != "" && tagMap != nil {
|
||||
if name, ok := tagMap[chunk.TagID]; ok {
|
||||
tagName = name
|
||||
}
|
||||
}
|
||||
|
||||
// Build row
|
||||
row := []string{
|
||||
escapeCSVField(tagName),
|
||||
escapeCSVField(meta.StandardQuestion),
|
||||
escapeCSVField(strings.Join(meta.SimilarQuestions, "##")),
|
||||
escapeCSVField(strings.Join(meta.NegativeQuestions, "##")),
|
||||
escapeCSVField(strings.Join(meta.Answers, "##")),
|
||||
boolToCSV(meta.AnswerStrategy == types.AnswerStrategyAll),
|
||||
boolToCSV(!chunk.IsEnabled), // 是否停用:取反
|
||||
boolToCSV(!chunk.Flags.HasFlag(types.ChunkFlagRecommended)), // 是否禁止被推荐:取反
|
||||
}
|
||||
buf.WriteString(strings.Join(row, ","))
|
||||
buf.WriteString("\n")
|
||||
}
|
||||
|
||||
return []byte(buf.String())
|
||||
}
|
||||
|
||||
// escapeCSVField escapes a field for CSV format.
|
||||
func escapeCSVField(field string) string {
|
||||
// If field contains comma, newline, or quote, wrap in quotes and escape internal quotes
|
||||
if strings.ContainsAny(field, ",\"\n\r") {
|
||||
return "\"" + strings.ReplaceAll(field, "\"", "\"\"") + "\""
|
||||
}
|
||||
return field
|
||||
}
|
||||
|
||||
// boolToCSV converts a boolean to CSV TRUE/FALSE string.
|
||||
func boolToCSV(b bool) string {
|
||||
if b {
|
||||
return "TRUE"
|
||||
}
|
||||
return "FALSE"
|
||||
}
|
||||
|
||||
func (s *knowledgeService) validateFAQKnowledgeBase(ctx context.Context, kbID string) (*types.KnowledgeBase, error) {
|
||||
if kbID == "" {
|
||||
return nil, werrors.NewBadRequestError("知识库 ID 不能为空")
|
||||
|
||||
@@ -221,3 +221,23 @@ func (h *FAQHandler) SearchFAQ(c *gin.Context) {
|
||||
"data": entries,
|
||||
})
|
||||
}
|
||||
|
||||
// ExportEntries exports all FAQ entries as a CSV file.
|
||||
func (h *FAQHandler) ExportEntries(c *gin.Context) {
|
||||
ctx := c.Request.Context()
|
||||
kbID := secutils.SanitizeForLog(c.Param("id"))
|
||||
|
||||
csvData, err := h.knowledgeService.ExportFAQEntries(ctx, kbID)
|
||||
if err != nil {
|
||||
logger.ErrorWithFields(ctx, err, nil)
|
||||
c.Error(err)
|
||||
return
|
||||
}
|
||||
|
||||
// Set response headers for CSV download
|
||||
c.Header("Content-Type", "text/csv; charset=utf-8")
|
||||
c.Header("Content-Disposition", "attachment; filename=faq_export.csv")
|
||||
// Add BOM for Excel compatibility with UTF-8
|
||||
bom := []byte{0xEF, 0xBB, 0xBF}
|
||||
c.Data(http.StatusOK, "text/csv; charset=utf-8", append(bom, csvData...))
|
||||
}
|
||||
|
||||
@@ -163,6 +163,7 @@ func RegisterFAQRoutes(r *gin.RouterGroup, handler *handler.FAQHandler) {
|
||||
faq := r.Group("/knowledge-bases/:id/faq")
|
||||
{
|
||||
faq.GET("/entries", handler.ListEntries)
|
||||
faq.GET("/entries/export", handler.ExportEntries)
|
||||
faq.POST("/entries", handler.UpsertEntries)
|
||||
faq.POST("/entry", handler.CreateEntry)
|
||||
faq.PUT("/entries/:entry_id", handler.UpdateEntry)
|
||||
|
||||
@@ -52,6 +52,8 @@ type ChunkRepository interface {
|
||||
// ListAllFAQChunksWithMetadataByKnowledgeBaseID lists all FAQ chunks for a knowledge base ID
|
||||
// returns ID and Metadata fields for duplicate question checking
|
||||
ListAllFAQChunksWithMetadataByKnowledgeBaseID(ctx context.Context, tenantID uint64, kbID string) ([]*types.Chunk, error)
|
||||
// ListAllFAQChunksForExport lists all FAQ chunks for export with full metadata, tag_id, is_enabled, and flags
|
||||
ListAllFAQChunksForExport(ctx context.Context, tenantID uint64, knowledgeID string) ([]*types.Chunk, error)
|
||||
// UpdateChunkFlagsBatch updates flags for multiple chunks in batch using a single SQL statement.
|
||||
// setFlags: map of chunk ID to flags to set (OR operation)
|
||||
// clearFlags: map of chunk ID to flags to clear (AND NOT operation)
|
||||
|
||||
@@ -95,6 +95,8 @@ type KnowledgeService interface {
|
||||
DeleteFAQEntries(ctx context.Context, kbID string, entryIDs []string) error
|
||||
// SearchFAQEntries searches FAQ entries using hybrid search.
|
||||
SearchFAQEntries(ctx context.Context, kbID string, req *types.FAQSearchRequest) ([]*types.FAQEntry, error)
|
||||
// ExportFAQEntries exports all FAQ entries for a knowledge base as CSV data.
|
||||
ExportFAQEntries(ctx context.Context, kbID string) ([]byte, error)
|
||||
// UpdateKnowledgeTagBatch updates tag for document knowledge items in batch.
|
||||
UpdateKnowledgeTagBatch(ctx context.Context, updates map[string]*string) error
|
||||
// UpdateFAQEntryTagBatch updates tag for FAQ entries in batch.
|
||||
|
||||
Reference in New Issue
Block a user