Skip to content

Open-source LLM knowledge platform: turn raw documents into a queryable RAG, an autonomous reasoning agent, and a self-maintaining Wiki.

feat(knowledge): enhance FAQ import result tracking and UI

wizardchen135033e6df89
diff --git a/frontend/src/i18n/locales/en-US.ts b/frontend/src/i18n/locales/en-US.ts
index 942f9dc18..208f5d871 100755
--- a/frontend/src/i18n/locales/en-US.ts
+++ b/frontend/src/i18n/locales/en-US.ts
@@ -6118,9 +6118,13 @@ export default {
recentResult: 'Recent Import Results',
totalData: 'Total Data',
success: 'Successful',
+ added: 'Added',
+ merged: 'Merged',
+ partialFailed: 'Partially Failed',
failed: 'Failed',
skipped: 'Skipped',
unit: 'record(s)',
+ progressHint: 'Validating and importing FAQ data...',
downloadReasons: 'Download Reasons',
appendMode: 'Append Mode',
replaceMode: 'Replace Mode',
diff --git a/frontend/src/i18n/locales/ko-KR.ts b/frontend/src/i18n/locales/ko-KR.ts
index 6808075ce..0fa8c4639 100755
--- a/frontend/src/i18n/locales/ko-KR.ts
+++ b/frontend/src/i18n/locales/ko-KR.ts
@@ -6121,9 +6121,13 @@ export default {
recentResult: '최근 가져오기 결과',
totalData: '가져오기 데이터',
success: '성공',
+ added: '신규',
+ merged: '병합 업데이트',
+ partialFailed: '부분 실패',
failed: '실패',
skipped: '건너뜀',
unit: '건',
+ progressHint: 'FAQ 데이터를 검증하고 가져오는 중...',
downloadReasons: '원인 다운로드',
appendMode: '추가 모드',
replaceMode: '교체 모드',
diff --git a/frontend/src/i18n/locales/ru-RU.ts b/frontend/src/i18n/locales/ru-RU.ts
index f20476f70..e5b930412 100755
--- a/frontend/src/i18n/locales/ru-RU.ts
+++ b/frontend/src/i18n/locales/ru-RU.ts
@@ -5620,9 +5620,13 @@ export default {
recentResult: 'Последние результаты импорта',
totalData: 'Данные импорта',
success: 'Успешно',
+ added: 'Добавлено',
+ merged: 'Объединено',
+ partialFailed: 'Частично неудачно',
failed: 'Ошибка',
skipped: 'Пропущено',
unit: 'запись(ей)',
+ progressHint: 'Проверка и импорт данных FAQ...',
downloadReasons: 'Скачать причины',
appendMode: 'Режим добавления',
replaceMode: 'Режим замены',
diff --git a/frontend/src/i18n/locales/zh-CN.ts b/frontend/src/i18n/locales/zh-CN.ts
index aea7d9d68..15e524963 100755
--- a/frontend/src/i18n/locales/zh-CN.ts
+++ b/frontend/src/i18n/locales/zh-CN.ts
@@ -6173,9 +6173,13 @@ export default {
recentResult: "最近导入结果",
totalData: "导入数据",
success: "成功",
+ added: "新增",
+ merged: "合并更新",
+ partialFailed: "部分失败",
failed: "失败",
skipped: "跳过",
unit: "条",
+ progressHint: "正在校验并导入 FAQ 数据...",
downloadReasons: "下载原因",
appendMode: "追加模式",
replaceMode: "替换模式",
diff --git a/frontend/src/views/knowledge/components/FAQEntryManager.vue b/frontend/src/views/knowledge/components/FAQEntryManager.vue
index db931aff1..475ad3cd1 100644
--- a/frontend/src/views/knowledge/components/FAQEntryManager.vue
+++ b/frontend/src/views/knowledge/components/FAQEntryManager.vue
@@ -38,8 +38,6 @@
<t-icon name="chevron-right" class="breadcrumb-separator" />
<span class="breadcrumb-current">{{ $t('knowledgeEditor.faq.title') }}</span>
</h2>
- <!-- 标题行右侧的动作锚点:与文档详情页保持一致的「信息 + 设置」两个圆形按钮。
- FAQ 类型知识库不传 supportedFileTypes,可上传格式行会自动隐藏。 -->
<div class="kb-title-actions">
<KBInfoPopover
v-if="kbInfo && !authStore.isLiteMode"
@@ -50,98 +48,51 @@
<t-icon name="setting" size="16px" />
</button>
</t-tooltip>
- </div>
- </div>
- <p class="faq-subtitle">{{ $t('knowledgeEditor.faq.subtitle') }}</p>
- </div>
- </div>
-
- <!-- 导入结果统计(持久化显示) -->
- <div v-if="importResult && importResult.display_status === 'open' && !importState.taskId"
- class="faq-import-result-card">
- <div class="import-result-content">
- <div class="import-result-header">
- <div class="header-left">
- <t-icon name="check-circle-filled" size="20px" class="result-icon" />
- <span class="result-title">{{ $t('faqManager.import.recentResult') }}</span>
- </div>
- <div class="header-right">
- <span class="result-time">{{ formatImportTime(importResult.imported_at) }}</span>
- <t-button variant="text" theme="default" size="small" class="result-close-btn" @click="closeImportResult">
- <t-icon name="close" size="16px" />
- </t-button>
- </div>
- </div>
- <div class="import-result-body">
- <div class="import-result-stats">
- <div class="stat-item">
- <span class="stat-label">{{ $t('faqManager.import.totalData') }}</span>
- <span class="stat-value">{{ importResult.total_entries }}{{ $t('faqManager.import.unit') }}</span>
- </div>
- <div class="stat-item success">
- <span class="stat-label">{{ $t('faqManager.import.success') }}</span>
- <span class="stat-value">{{ importResult.success_count }}{{ $t('faqManager.import.unit') }}</span>
- </div>
- <div v-if="importResult.failed_count > 0" class="stat-item failed">
- <span class="stat-label">{{ $t('faqManager.import.failed') }}</span>
- <span class="stat-value">{{ importResult.failed_count }}{{ $t('faqManager.import.unit') }}</span>
- <t-button v-if="importResult.failed_entries_url" variant="outline" theme="danger" size="small"
- class="download-failed-btn" @click="downloadFailedEntries">
- <t-icon name="download" size="14px" />
- {{ $t('faqManager.import.downloadReasons') }}
- </t-button>
+ <!-- 导入结果:默认仅图标,hover / 点击展开详情 -->
+ <div v-if="showImportResultBadge" class="faq-import-host"
+ :class="{ 'is-expanded': importResultExpanded }">
+ <button type="button" class="faq-import-trigger"
+ :aria-label="$t('faqManager.import.recentResult')"
+ @click.stop="importResultExpanded = !importResultExpanded">
+ <t-icon name="check-circle-filled" size="16px" />
+ </button>
+ <div class="faq-import-panel">
+ <div class="faq-import-strip faq-import-strip--result faq-import-strip--panel">
+ <span class="faq-import-strip__text">{{ importResultSummary }}</span>
+ <t-tag size="small" variant="light"
+ :theme="importResult!.import_mode === 'append' ? 'primary' : 'warning'">
+ {{ importResult!.import_mode === 'append' ? $t('faqManager.import.appendMode') :
+ $t('faqManager.import.replaceMode') }}
+ </t-tag>
+ <t-button v-if="importResult!.failed_entries_url && importResult!.failed_count > 0"
+ variant="text" theme="danger" size="small" class="faq-import-strip__link"
+ @click="downloadFailedEntries">
+ {{ $t('faqManager.import.downloadReasons') }}
+ </t-button>
+ <span class="faq-import-strip__time">{{ formatImportTime(importResult!.imported_at) }}</span>
+ <button type="button" class="faq-import-strip__close" :aria-label="$t('common.close')"
+ @click="closeImportResult">
+ <t-icon name="close" size="14px" />
+ </button>
+ </div>
+ </div>
</div>
- <div v-if="importResult.skipped_count > 0" class="stat-item skipped">
- <span class="stat-label">{{ $t('faqManager.import.skipped') }}</span>
- <span class="stat-value">{{ importResult.skipped_count }}{{ $t('faqManager.import.unit') }}</span>
+ <!-- 导入进行中 -->
+ <div v-else-if="isImportInProgress && importState.taskStatus"
+ class="faq-import-strip faq-import-strip--in-title"
+ :class="`faq-import-strip--${importState.taskStatus.status}`">
+ <t-icon :name="importProgressIcon" size="16px" class="faq-import-strip__icon"
+ :class="{ 'is-spinning': importState.taskStatus.status === 'running' }" />
+ <span class="faq-import-strip__text">{{ importProgressText }}</span>
+ <div class="faq-import-strip__bar">
+ <div class="faq-import-strip__bar-fill" :style="{ width: `${importState.taskStatus.progress}%` }" />
+ </div>
+ <span class="faq-import-strip__count">{{ importState.taskStatus.processed }}/{{
+ importState.taskStatus.total }}</span>
</div>
</div>
- <div class="import-mode-tag">
- <t-tag size="small" variant="light" theme="success">
- {{ importResult.import_mode === 'append' ? $t('faqManager.import.appendMode') :
- $t('faqManager.import.replaceMode') }}
- </t-tag>
- </div>
</div>
- </div>
- </div>
-
- <!-- 导入进度条(显示在列表页面顶部) -->
- <div v-if="importState.taskId && importState.taskStatus" class="faq-import-progress-bar">
- <div class="progress-bar-content">
- <div class="progress-bar-header">
- <div class="progress-left">
- <t-icon :name="importState.taskStatus.status === 'running' ? 'loading' :
- importState.taskStatus.status === 'success' ? 'check-circle' :
- importState.taskStatus.status === 'failed' ? 'error-circle' : 'time'" size="18px"
- class="progress-icon" :class="{
- 'icon-loading': importState.taskStatus.status === 'running',
- 'icon-success': importState.taskStatus.status === 'success',
- 'icon-error': importState.taskStatus.status === 'failed'
- }" />
- <span class="progress-title">
- {{ importState.taskStatus.status === 'running' ? $t('faqManager.import.importing') :
- importState.taskStatus.status === 'success' ? $t('faqManager.import.importDone') :
- importState.taskStatus.status === 'failed' ? $t('faqManager.import.importFailed') :
- $t('faqManager.import.waiting') }}
- </span>
- </div>
- <div class="progress-right">
- <span class="progress-count">
- {{ importState.taskStatus.processed }}/{{ importState.taskStatus.total }} {{
- $t('faqManager.import.unit') }}
- </span>
- <t-button v-if="importState.taskStatus.status === 'success' || importState.taskStatus.status === 'failed'"
- variant="text" theme="default" size="small" class="progress-close-btn" @click="handleCloseProgress">
- <t-icon name="close" size="14px" />
- </t-button>
- </div>
- </div>
- <t-progress :percentage="importState.taskStatus.progress" :status="importState.taskStatus.status === 'failed' ? 'error' :
- importState.taskStatus.status === 'success' ? 'success' : 'active'" :label="false" class="progress-bar" />
- <p v-if="importState.taskStatus.error" class="progress-error">
- {{ importState.taskStatus.error }}
- </p>
+ <p class="faq-subtitle">{{ $t('knowledgeEditor.faq.subtitle') }}</p>
</div>
</div>
@@ -1231,21 +1182,26 @@ const importState = reactive({
progress: number
total: number
processed: number
+ message?: string
error?: string
} | null,
pollingInterval: null as ReturnType<typeof setInterval> | null,
})
// FAQ导入结果状态(持久化的)
-const importResult = ref<{
+type FAQImportResultView = {
total_entries: number
success_count: number
failed_count: number
skipped_count: number
+ partial_failed_count: number
+ merged_count: number
+ added_count: number
import_mode: string
imported_at: string
task_id: string
processing_time: number
+ message?: string
failed_entries_url?: string
success_entries?: Array<{
index: number
@@ -1255,7 +1211,73 @@ const importResult = ref<{
standard_question: string
}>
display_status: string
-} | null>(null)
+}
+
+const importResult = ref<FAQImportResultView | null>(null)
+const importResultExpanded = ref(false)
+
+const showImportResultBadge = computed(() => (
+ !!importResult.value
+ && importResult.value.display_status === 'open'
+ && !importState.taskId
+))
+
+const isImportInProgress = computed(() => {
+ const status = importState.taskStatus?.status
+ return !!importState.taskId && (status === 'running' || status === 'pending')
+})
+
+const importResultSummary = computed(() => {
+ const result = importResult.value
+ if (!result) return ''
+ if (result.message?.trim()) {
+ return result.message.trim()
+ }
+ const parts: string[] = []
+ parts.push(`${t('faqManager.import.totalData')} ${result.total_entries}`)
+ if (result.merged_count > 0) {
+ if (result.added_count > 0) {
+ parts.push(`${t('faqManager.import.added')} ${result.added_count}`)
+ }
+ parts.push(`${t('faqManager.import.merged')} ${result.merged_count}`)
+ } else if (result.success_count > 0) {
+ parts.push(`${t('faqManager.import.success')} ${result.success_count}`)
+ }
+ if (result.partial_failed_count > 0) {
+ parts.push(`${t('faqManager.import.partialFailed')} ${result.partial_failed_count}`)
+ }
+ if (result.failed_count > 0) {
+ parts.push(`${t('faqManager.import.failed')} ${result.failed_count}`)
+ }
+ if (result.skipped_count > 0) {
+ parts.push(`${t('faqManager.import.skipped')} ${result.skipped_count}`)
+ }
+ return parts.join(' · ')
+})
+
+const importProgressTitle = computed(() => {
+ const status = importState.taskStatus?.status
+ if (status === 'running') return t('faqManager.import.importing')
+ if (status === 'success') return t('faqManager.import.importDone')
+ if (status === 'failed') return t('faqManager.import.importFailed')
+ return t('faqManager.import.waiting')
+})
+
+const importProgressIcon = computed(() => {
+ const status = importState.taskStatus?.status
+ if (status === 'running') return 'loading'
+ if (status === 'success') return 'check-circle-filled'
+ if (status === 'failed') return 'error-circle-filled'
+ return 'time-filled'
+})
+
+const importProgressText = computed(() => {
+ const status = importState.taskStatus
+ if (!status) return ''
+ if (status.error) return status.error
+ if (status.message?.trim()) return status.message.trim()
+ return importProgressTitle.value
+})
// Search test state
const searchDrawerVisible = ref(false)
@@ -2166,12 +2188,14 @@ const startPolling = (taskId: string) => {
const total = progressData.total || 0
const processed = progressData.processed || 0
const error = progressData.error || ''
+ const message = progressData.message || ''
importState.taskStatus = {
status: status,
progress: progress,
total: total,
processed: processed,
+ message: message,
error: error,
}
@@ -2190,7 +2214,7 @@ const startPolling = (taskId: string) => {
if (importState.taskId) {
saveLastCompletedTaskId(importState.taskId)
}
- MessagePlugin.success(t('knowledgeEditor.faqImport.importSuccess'))
+ MessagePlugin.success(progressData.message || t('knowledgeEditor.faqImport.importSuccess'))
// 清除筛选条件,确保用户能看到所有新导入的数据
selectedTagId.value = 0
entrySearchKeyword.value = ''
@@ -2304,6 +2328,7 @@ const restoreImportTask = async () => {
progress: progress,
total: total,
processed: processed,
+ message: progressData.message || '',
error: error,
}
@@ -2372,9 +2397,13 @@ const loadImportResult = async () => {
// Map progress fields to importResult format
importResult.value = {
total_entries: data.total,
- success_count: data.success_count,
- failed_count: data.failed_count,
+ success_count: data.success_count || 0,
+ failed_count: data.failed_count || 0,
skipped_count: data.skipped_count || 0,
+ partial_failed_count: data.partial_failed_count || 0,
+ merged_count: data.merged_count || 0,
+ added_count: data.added_count || 0,
+ message: data.message || '',
import_mode: data.import_mode || 'append',
imported_at: data.imported_at,
task_id: data.task_id,
@@ -2394,6 +2423,7 @@ const loadImportResult = async () => {
// 关闭导入结果统计卡片
const closeImportResult = async () => {
+ importResultExpanded.value = false
if (!props.kbId) return
try {
await updateFAQImportResultDisplayStatus(props.kbId, 'close')
@@ -2460,6 +2490,7 @@ const handleImport = async () => {
progress: 0,
total: importState.preview.length,
processed: 0,
+ message: t('faqManager.import.progressHint'),
}
// 开始轮询任务状态
startPolling(taskId)
@@ -3483,6 +3514,18 @@ watch(() => entries.value.map(e => ({
align-items: center;
gap: 8px;
flex-wrap: wrap;
+ width: 100%;
+
+ .faq-import-strip--in-title {
+ margin-bottom: 0;
+ flex: 0 1 auto;
+ min-width: 0;
+ max-width: min(420px, 40vw);
+
+ .faq-import-strip__text {
+ max-width: 220px;
+ }
+ }
}
.kb-title-actions {
@@ -3490,7 +3533,6 @@ watch(() => entries.value.map(e => ({
align-items: center;
gap: 6px;
flex-shrink: 0;
- margin-left: 4px;
}
.faq-breadcrumb {
@@ -3573,249 +3615,204 @@ watch(() => entries.value.map(e => ({
}
-// 导入进度条样式(显示在列表页面顶部)
-.faq-import-progress-bar {
- margin-bottom: 16px;
- background: var(--td-bg-color-container);
- border: 1px solid var(--td-success-color-focus);
- border-radius: 10px;
- padding: 14px 18px;
- box-shadow: 0 2px 12px rgba(0, 168, 112, 0.08);
-
- .progress-bar-content {
- display: flex;
- flex-direction: column;
- gap: 10px;
- }
+// 导入结果入口:默认仅图标,hover / 点击展开浮层
+.faq-import-host {
+ position: relative;
+ flex-shrink: 0;
- .progress-bar-header {
- display: flex;
+ .faq-import-trigger {
+ display: inline-flex;
align-items: center;
- justify-content: space-between;
- font-size: 14px;
- color: var(--td-text-color-primary);
-
- .progress-left {
- display: flex;
- align-items: center;
- gap: 10px;
- }
+ justify-content: center;
+ border: none;
+ background: transparent;
+ padding: 2px;
+ margin: 0;
+ color: var(--td-success-color);
+ cursor: pointer;
+ line-height: 1;
+ transition: opacity 0.15s ease;
- .progress-right {
- display: flex;
- align-items: center;
- gap: 16px;
+ &:hover {
+ opacity: 0.75;
}
+ }
- .progress-icon {
- flex-shrink: 0;
+ .faq-import-panel {
+ position: absolute;
+ top: calc(100% + 8px);
+ left: 0;
+ z-index: 200;
+ opacity: 0;
+ visibility: hidden;
+ pointer-events: none;
+ transform: translateY(-4px);
+ transition: opacity 0.15s ease, transform 0.15s ease, visibility 0.15s ease;
+ }
- &.icon-loading {
- animation: rotate 1s linear infinite;
- color: var(--td-success-color);
- }
+ &:hover .faq-import-panel,
+ &.is-expanded .faq-import-panel,
+ &:focus-within .faq-import-panel {
+ opacity: 1;
+ visibility: visible;
+ pointer-events: auto;
+ transform: translateY(0);
+ }
- &.icon-success {
- color: var(--td-success-color);
- }
+ .faq-import-strip--panel {
+ margin-bottom: 0;
+ padding: 8px 10px;
+ font-size: 12px;
+ white-space: nowrap;
+ box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1);
- &.icon-error {
- color: var(--td-error-color);
- }
+ .faq-import-strip__text {
+ max-width: 360px;
}
+ }
+}
- .progress-title {
- font-weight: 600;
- font-size: 14px;
- color: var(--td-text-color-primary);
- }
- .progress-count {
- color: var(--td-text-color-secondary);
- font-size: 13px;
- font-weight: 500;
- background: rgba(0, 168, 112, 0.1);
- padding: 2px 10px;
- border-radius: 12px;
- }
+// FAQ 导入提示条(紧凑单行)
+.faq-import-strip {
+ display: inline-flex;
+ align-items: center;
+ width: fit-content;
+ gap: 8px;
+ max-width: 100%;
+ margin-bottom: 10px;
+ padding: 4px 8px 4px 10px;
+ border-radius: 6px;
+ font-size: 12px;
+ line-height: 1.4;
+ color: var(--td-text-color-secondary);
+ background: var(--td-bg-color-secondarycontainer);
+ border: 1px solid var(--td-component-stroke);
- .progress-close-btn {
- flex-shrink: 0;
- padding: 4px;
- margin-left: 4px;
- border-radius: 4px;
+ &__icon {
+ flex-shrink: 0;
+ color: var(--td-text-color-placeholder);
- &:hover {
- background: rgba(0, 0, 0, 0.06);
- }
+ &.is-spinning {
+ animation: faq-import-spin 1s linear infinite;
}
}
- .progress-bar {
- margin: 0;
- width: 100%;
-
- :deep(.t-progress) {
- width: 100%;
- }
-
- :deep(.t-progress__bar) {
- width: 100%;
- height: 8px;
- border-radius: 4px;
- background: rgba(0, 168, 112, 0.15);
- }
-
- :deep(.t-progress__inner) {
- border-radius: 4px;
- }
+ &__text {
+ flex: 0 1 auto;
+ min-width: 0;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 520px;
}
- .progress-error {
- margin: 0;
- font-size: 13px;
- color: var(--td-error-color);
- line-height: 1.5;
- background: rgba(250, 81, 81, 0.08);
- padding: 8px 12px;
- border-radius: 6px;
+ &__bar {
+ flex-shrink: 0;
+ width: 72px;
+ height: 4px;
+ border-radius: 2px;
+ background: rgba(0, 0, 0, 0.08);
+ overflow: hidden;
}
-}
-@keyframes rotate {
- from {
- transform: rotate(0deg);
+ &__bar-fill {
+ height: 100%;
+ border-radius: 2px;
+ background: var(--td-brand-color);
+ transition: width 0.3s ease;
}
- to {
- transform: rotate(360deg);
+ &__count {
+ flex-shrink: 0;
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: var(--td-text-color-placeholder);
}
-}
-// 导入结果统计卡片样式
-.faq-import-result-card {
- margin-bottom: 16px;
- background: var(--td-bg-color-container);
- border: 1px solid var(--td-component-stroke);
- border-radius: 8px;
- padding: 16px 20px;
- box-shadow: 0 1px 4px rgba(0, 0, 0, 0.04);
+ &__time {
+ flex-shrink: 0;
+ font-size: 12px;
+ color: var(--td-text-color-placeholder);
+ white-space: nowrap;
+ }
- .import-result-content {
- display: flex;
- flex-direction: column;
- gap: 12px;
+ &__link {
+ flex-shrink: 0;
+ padding: 0 4px;
+ height: auto;
+ font-size: 12px;
}
- .import-result-header {
- display: flex;
+ &__close {
+ display: inline-flex;
align-items: center;
- justify-content: space-between;
-
- .header-left {
- display: flex;
- align-items: center;
- gap: 8px;
-
- .result-icon {
- color: var(--td-brand-color);
- flex-shrink: 0;
- }
+ justify-content: center;
+ flex-shrink: 0;
+ width: 20px;
+ height: 20px;
+ margin: 0;
+ padding: 0;
+ border: none;
+ border-radius: 4px;
+ background: transparent;
+ color: var(--td-text-color-placeholder);
+ cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
- .result-title {
- font-family: var(--app-font-family);
- font-weight: 600;
- font-size: 14px;
- color: var(--td-text-color-primary);
- }
+ &:hover {
+ background: rgba(0, 0, 0, 0.06);
+ color: var(--td-text-color-secondary);
}
+ }
- .header-right {
- display: flex;
- align-items: center;
- gap: 12px;
-
- .result-time {
- font-family: var(--app-font-family);
- font-size: 13px;
- color: var(--td-text-color-secondary);
- }
-
- .result-close-btn {
- padding: 4px;
- border-radius: 4px;
- color: var(--td-text-color-secondary);
- transition: all 0.2s ease;
-
- &:hover {
- background: var(--td-bg-color-secondarycontainer);
- color: var(--td-text-color-secondary);
- }
- }
+ &--result {
+ .faq-import-strip__icon {
+ color: var(--td-success-color);
}
}
- .import-result-body {
- display: flex;
- align-items: center;
- justify-content: space-between;
- flex-wrap: wrap;
- gap: 12px;
+ &--running {
+ .faq-import-strip__icon {
+ color: var(--td-brand-color);
+ }
}
- .import-result-stats {
- display: flex;
- align-items: center;
- flex-wrap: wrap;
- gap: 24px;
-
- .stat-item {
- display: flex;
- align-items: center;
- gap: 6px;
- font-family: var(--app-font-family);
- font-size: 13px;
-
- .stat-label {
- color: var(--td-text-color-secondary);
- }
-
- .stat-value {
- font-weight: 600;
- color: var(--td-text-color-primary);
- }
+ &--success {
+ .faq-import-strip__icon {
+ color: var(--td-success-color);
+ }
- &.success .stat-value {
- color: var(--td-brand-color);
- }
+ .faq-import-strip__bar-fill {
+ background: var(--td-success-color);
+ }
+ }
- &.failed .stat-value {
- color: var(--td-error-color);
- }
+ &--failed {
+ border-color: rgba(227, 77, 89, 0.3);
+ background: rgba(227, 77, 89, 0.06);
- &.skipped .stat-value {
- color: var(--td-warning-color);
- }
+ .faq-import-strip__icon {
+ color: var(--td-error-color);
+ }
- .download-failed-btn {
- margin-left: 4px;
- padding: 0 8px;
- height: 24px;
- font-size: 12px;
- border-radius: 4px;
- display: inline-flex;
- align-items: center;
- gap: 4px;
+ .faq-import-strip__text {
+ color: var(--td-error-color);
+ }
- .t-icon {
- font-size: 12px;
- }
- }
+ .faq-import-strip__bar-fill {
+ background: var(--td-error-color);
}
}
+}
- .import-mode-tag {
- flex-shrink: 0;
+@keyframes faq-import-spin {
+ from {
+ transform: rotate(0deg);
+ }
+
+ to {
+ transform: rotate(360deg);
}
}
diff --git a/internal/application/repository/chunk.go b/internal/application/repository/chunk.go
index feef3403d..8c8af637d 100644
--- a/internal/application/repository/chunk.go
+++ b/internal/application/repository/chunk.go
@@ -298,6 +298,21 @@ func (r *chunkRepository) UpdateChunk(ctx context.Context, chunk *types.Chunk) e
return r.db.WithContext(ctx).Omit("SeqID").Save(chunk).Error
}
+// SaveChunks persists full chunk objects in a single transaction using GORM Save (UPDATE).
+func (r *chunkRepository) SaveChunks(ctx context.Context, chunks []*types.Chunk) error {
+ if len(chunks) == 0 {
+ return nil
+ }
+ return r.db.WithContext(ctx).Transaction(func(tx *gorm.DB) error {
+ for _, chunk := range chunks {
+ if err := tx.Omit("SeqID").Save(chunk).Error; err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+}
+
// UpdateChunks updates chunks in batch using raw SQL for efficiency.
// Uses raw SQL to bypass GORM's default value handling for boolean fields.
//
diff --git a/internal/application/service/knowledge_faq_import.go b/internal/application/service/knowledge_faq_import.go
index fade5f7c7..7a70b06b5 100644
--- a/internal/application/service/knowledge_faq_import.go
+++ b/internal/application/service/knowledge_faq_import.go
@@ -301,27 +301,30 @@ func (s *knowledgeService) saveFAQImportResultToDatabase(ctx context.Context,
return fmt.Errorf("failed to get FAQ knowledge: %w", err)
}
- // 计算跳过的条目数(总数 - 成功 - 失败)
- skippedCount := originalTotalEntries - progress.SuccessCount - progress.FailedCount
+ // 计算跳过的条目数(总数 - 完全成功 - 部分失败 - 完全失败)
+ skippedCount := originalTotalEntries - progress.SuccessCount - progress.PartialFailedCount - progress.FailedCount
if skippedCount < 0 {
skippedCount = 0
}
// 创建导入结果统计
importResult := &types.FAQImportResult{
- TotalEntries: originalTotalEntries,
- SuccessCount: progress.SuccessCount,
- FailedCount: progress.FailedCount,
- SkippedCount: skippedCount,
- ImportMode: payload.Mode,
- ImportedAt: time.Now(),
- TaskID: payload.TaskID,
- ProcessingTime: time.Now().Unix() - progress.CreatedAt, // 处理耗时(秒)
- DisplayStatus: "open", // 新导入的结果默认显示
- }
-
- // 如果有失败条目且提供了下载URL,设置失败URL
- if progress.FailedCount > 0 && progress.FailedEntriesURL != "" {
+ TotalEntries: originalTotalEntries,
+ SuccessCount: progress.SuccessCount,
+ FailedCount: progress.FailedCount,
+ PartialFailedCount: progress.PartialFailedCount,
+ SkippedCount: skippedCount,
+ MergedCount: progress.MergedCount,
+ AddedCount: progress.AddedCount,
+ ImportMode: payload.Mode,
+ ImportedAt: time.Now(),
+ TaskID: payload.TaskID,
+ ProcessingTime: time.Now().Unix() - progress.CreatedAt, // 处理耗时(秒)
+ DisplayStatus: "open", // 新导入的结果默认显示
+ }
+
+ // 如果有失败/部分失败条目 CSV 下载 URL,则写入结果(FailedEntries 包含完全失败与部分失败)
+ if progress.FailedEntriesURL != "" {
importResult.FailedEntriesURL = progress.FailedEntriesURL
}
@@ -335,8 +338,8 @@ func (s *knowledgeService) saveFAQImportResultToDatabase(ctx context.Context,
return fmt.Errorf("failed to update knowledge with import result: %w", err)
}
- logger.Infof(ctx, "Saved FAQ import result to database: knowledge_id=%s, task_id=%s, total=%d, success=%d, failed=%d, skipped=%d",
- payload.KnowledgeID, payload.TaskID, originalTotalEntries, progress.SuccessCount, progress.FailedCount, skippedCount)
+ logger.Infof(ctx, "Saved FAQ import result to database: knowledge_id=%s, task_id=%s, total=%d, success=%d, added=%d, merged=%d, failed=%d, partial_failed=%d, skipped=%d",
+ payload.KnowledgeID, payload.TaskID, originalTotalEntries, progress.SuccessCount, progress.AddedCount, progress.MergedCount, progress.FailedCount, progress.PartialFailedCount, skippedCount)
return nil
}
@@ -364,6 +367,53 @@ func buildFAQFailedEntry(idx int, reason string, entry *types.FAQEntryPayload) t
}
}
+func buildFAQPartialFailedEntry(idx int, entry *types.FAQEntryPayload,
+ removedSimilarQuestions, removedNegativeQuestions []string,
+) types.FAQFailedEntry {
+ answerAll := false
+ if entry.AnswerStrategy != nil && *entry.AnswerStrategy == types.AnswerStrategyAll {
+ answerAll = true
+ }
+ isDisabled := false
+ if entry.IsEnabled != nil && !*entry.IsEnabled {
+ isDisabled = true
+ }
+
+ // 构建失败原因描述:汇总信息 + 详细信息
+ var summary []string
+ if len(removedSimilarQuestions) > 0 {
+ summary = append(summary, fmt.Sprintf("%d条相似问被移除", len(removedSimilarQuestions)))
+ }
+ if len(removedNegativeQuestions) > 0 {
+ summary = append(summary, fmt.Sprintf("%d条反例被移除", len(removedNegativeQuestions)))
+ }
+
+ // 完整的 reason:汇总 | 相似问详情 | 反例详情
+ var reasonParts []string
+ reasonParts = append(reasonParts, "部分成功:"+strings.Join(summary, ","))
+ if len(removedSimilarQuestions) > 0 {
+ reasonParts = append(reasonParts, strings.Join(removedSimilarQuestions, "; "))
+ }
+ if len(removedNegativeQuestions) > 0 {
+ reasonParts = append(reasonParts, strings.Join(removedNegativeQuestions, "; "))
+ }
+
+ return types.FAQFailedEntry{
+ Index: idx,
+ Reason: strings.Join(reasonParts, " | "),
+ IsPartialFailure: true,
+ TagName: entry.TagName,
+ StandardQuestion: strings.TrimSpace(entry.StandardQuestion),
+ SimilarQuestions: entry.SimilarQuestions,
+ NegativeQuestions: entry.NegativeQuestions,
+ Answers: entry.Answers,
+ AnswerAll: answerAll,
+ IsDisabled: isDisabled,
+ RemovedSimilarQuestions: removedSimilarQuestions,
+ RemovedNegativeQuestions: removedNegativeQuestions,
+ }
+}
+
// executeFAQDryRunValidation 执行 FAQ dry run 验证,返回通过验证的条目索引
func (s *knowledgeService) executeFAQDryRunValidation(ctx context.Context,
payload *types.FAQImportPayload, progress *types.FAQImportProgress,
@@ -385,101 +435,223 @@ func (s *knowledgeService) executeFAQDryRunValidation(ctx context.Context,
// validateEntriesForAppendModeWithProgress 验证 Append 模式下的条目(带进度更新)
// 注意:验证阶段不更新 Processed,只有实际导入时才更新
+// validateEntriesForAppendModeWithProgress 验证 Append 模式下的条目(带进度更新)
+// 注意:验证阶段不更新 Processed,只有实际导入时才更新
+//
+// 分四阶段校验:
+// 阶段一(预校验):
+// 1. 标准问 - 仅文件内部去重;如已有KB标准问则标记为合并候选
+// 2. 相似问 - 对比文件+知识库(合并候选排除自身已有问题) → 单条移除冲突相似问
+// 3. 反例 - 仅对比当前QA自身标准问+相似问 → 单条移除冲突反例
+//
+// 阶段二(后校验,仅合并候选):
+// 4. 对合并后的完整数据重跑反例校验 → 冲突则整条回退到合并前状态
func (s *knowledgeService) validateEntriesForAppendModeWithProgress(ctx context.Context,
tenantID uint64, kbID string, entries []types.FAQEntryPayload, progress *types.FAQImportProgress,
) []int {
- validIndices := make([]int, 0, len(entries))
+ totalEntries := len(entries)
- // 查询知识库中已有的所有FAQ chunks的metadata
+ // 查询知识库中已有的所有 FAQ chunks 的 metadata
existingChunks, err := s.chunkRepo.ListAllFAQChunksWithMetadataByKnowledgeBaseID(ctx, tenantID, kbID)
if err != nil {
logger.Warnf(ctx, "Failed to list existing FAQ chunks for dry run: %v", err)
- // 无法获取已有数据时,仅做批次内验证
}
- // 构建已存在的标准问和相似问集合
- existingQuestions := make(map[string]bool)
+ // 构建已存在的标准问 → chunk 映射(用于合并候选识别)
+ existingStdQToChunk := make(map[string]*types.Chunk)
+ // 构建已存在的所有问题 → 所属 chunkID 映射(用于相似问冲突检测)
+ existingQuestionToChunkID := make(map[string]string)
+ // 构建每个 chunk 拥有的问题集合(用于合并时排除自身)
+ existingChunkQuestions := make(map[string]map[string]bool)
+ // 构建 chunkID → 标准问 映射(用于冲突失败原因展示)
+ existingChunkIDToStdQ := make(map[string]string)
+
for _, chunk := range existingChunks {
meta, err := chunk.FAQMetadata()
if err != nil || meta == nil {
continue
}
+ qs := make(map[string]bool)
if meta.StandardQuestion != "" {
- existingQuestions[meta.StandardQuestion] = true
+ existingStdQToChunk[meta.StandardQuestion] = chunk
+ existingQuestionToChunkID[meta.StandardQuestion] = chunk.ID
+ qs[meta.StandardQuestion] = true
}
for _, q := range meta.SimilarQuestions {
if q != "" {
- existingQuestions[q] = true
+ existingQuestionToChunkID[q] = chunk.ID
+ qs[q] = true
}
}
+ existingChunkQuestions[chunk.ID] = qs
+ existingChunkIDToStdQ[chunk.ID] = meta.StandardQuestion
}
- // 构建当前批次的标准问和相似问集合(用于批次内去重)
- batchQuestions := make(map[string]int) // value 为首次出现的索引
+ // 合并候选跟踪:entry index → 目标已有 chunk
+ mergeChunkMap := make(map[int]*types.Chunk)
+
+ // ==================== 第一次迭代:基本格式验证 + 文件内标准问去重 + 合并候选识别 ====================
+ batchStandardQuestions := make(map[string]int) // value 为首次出现的索引
+ validIndicesAfterStdQ := make([]int, 0, totalEntries)
for i, entry := range entries {
- // 验证条目基本格式
if err := validateFAQEntryPayloadBasic(&entry); err != nil {
progress.FailedCount++
- progress.FailedEntries = append(progress.FailedEntries, buildFAQFailedEntry(i, err.Error(), &entry))
+ fe := buildFAQFailedEntry(i, err.Error(), &entry)
+ fe.FailureType = "pre_validation"
+ progress.FailedEntries = append(progress.FailedEntries, fe)
continue
}
standardQ := strings.TrimSpace(entry.StandardQuestion)
- // 检查标准问是否与已有知识库重复
- if existingQuestions[standardQ] {
+ // 文件内标准问去重
+ if firstIdx, exists := batchStandardQuestions[standardQ]; exists {
progress.FailedCount++
- progress.FailedEntries = append(progress.FailedEntries, buildFAQFailedEntry(i, "标准问与知识库中已有问题重复", &entry))
+ fe := buildFAQFailedEntry(i, fmt.Sprintf("标准问冲突:与批次内第 %d 条标准问重复", firstIdx+1), &entry)
+ fe.FailureType = "pre_validation"
+ progress.FailedEntries = append(progress.FailedEntries, fe)
continue
}
- // 检查标准问是否与同批次重复
- if firstIdx, exists := batchQuestions[standardQ]; exists {
+ // 判断是否为合并候选
+ if chunk, exists := existingStdQToChunk[standardQ]; exists {
+ // 标准问在 KB 中已存在 → 标记为合并候选
+ mergeChunkMap[i] = chunk
+ logger.Infof(ctx, "FAQ entry %d: standard question '%s' exists in KB, marking as merge candidate (chunk_id=%s)", i, standardQ, chunk.ID)
+ } else if conflictChunkID, hit := existingQuestionToChunkID[standardQ]; hit {
+ // 标准问未与任何已有标准问重复,但撞上了 KB 中其他条目的相似问
+ // → 前置校验失败,避免下游 calculateAppendOperations 静默丢弃导致统计失真
+ conflictStdQ := existingChunkIDToStdQ[conflictChunkID]
progress.FailedCount++
- progress.FailedEntries = append(progress.FailedEntries, buildFAQFailedEntry(i, fmt.Sprintf("标准问与批次内第 %d 条重复", firstIdx+1), &entry))
+ fe := buildFAQFailedEntry(i,
+ fmt.Sprintf(`标准问冲突:与知识库中标准问"%s"的相似问"%s"重复`, conflictStdQ, standardQ),
+ &entry)
+ fe.FailureType = "pre_validation"
+ progress.FailedEntries = append(progress.FailedEntries, fe)
+ logger.Infof(ctx,
+ "FAQ entry %d: standard question '%s' conflicts with existing similar question of chunk_id=%s (std='%s')",
+ i, standardQ, conflictChunkID, conflictStdQ)
continue
}
- // 检查相似问是否有重复
- hasDuplicate := false
+ batchStandardQuestions[standardQ] = i
+ validIndicesAfterStdQ = append(validIndicesAfterStdQ, i)
+
+ if (i+1)%100 == 0 {
+ progress.Message = fmt.Sprintf("正在验证标准问 %d/%d...", i+1, totalEntries)
+ progress.UpdatedAt = time.Now().Unix()
+ if err := s.saveFAQImportProgress(ctx, progress); err != nil {
+ logger.Warnf(ctx, "Failed to update FAQ dry run progress: %v", err)
+ }
+ }
+ }
+
+ // ==================== 第二次迭代:相似问冲突检测 ====================
+ // 构建批次内所有标准问 + 相似问的集合
+ batchAllQuestions := make(map[string]int)
+ for _, i := range validIndicesAfterStdQ {
+ standardQ := strings.TrimSpace(entries[i].StandardQuestion)
+ batchAllQuestions[standardQ] = i
+ for _, q := range entries[i].SimilarQuestions {
+ q = strings.TrimSpace(q)
+ if q != "" {
+ if _, exists := batchAllQuestions[q]; !exists {
+ batchAllQuestions[q] = i
+ }
+ }
+ }
+ }
+
+ removedSimilarQuestionsMap := make(map[int][]string)
+ removedNegativeQuestionsMap := make(map[int][]string)
+
+ for idx, i := range validIndicesAfterStdQ {
+ entry := &entries[i]
+ standardQ := strings.TrimSpace(entry.StandardQuestion)
+
+ // 合并候选:获取目标 chunk 自身的问题集合,用于排除
+ var ownChunkQuestions map[string]bool
+ if mergeChunk, isMerge := mergeChunkMap[i]; isMerge {
+ ownChunkQuestions = existingChunkQuestions[mergeChunk.ID]
+ }
+
+ validSimilarQuestions := make([]string, 0, len(entry.SimilarQuestions))
+ var removedSimilarQuestions []string
for _, q := range entry.SimilarQuestions {
q = strings.TrimSpace(q)
if q == "" {
continue
}
- if existingQuestions[q] {
- progress.FailedCount++
- progress.FailedEntries = append(progress.FailedEntries, buildFAQFailedEntry(i, fmt.Sprintf("相似问 \"%s\" 与知识库中已有问题重复", q), &entry))
- hasDuplicate = true
- break
+ // 相似问不能与自己的标准问相同
+ if q == standardQ {
+ removedSimilarQuestions = append(removedSimilarQuestions, fmt.Sprintf(`「相似问冲突」:"%s"与本条"标准问"冲突`, q))
+ continue
}
- if firstIdx, exists := batchQuestions[q]; exists {
- progress.FailedCount++
- progress.FailedEntries = append(progress.FailedEntries, buildFAQFailedEntry(i, fmt.Sprintf("相似问 \"%s\" 与批次内第 %d 条重复", q, firstIdx+1), &entry))
- hasDuplicate = true
- break
+ // 相似问校验:对比知识库已有标准问 + 相似问
+ if _, exists := existingQuestionToChunkID[q]; exists {
+ // 合并候选:如果问题属于合并目标自身的 chunk,允许(去重合并时会处理)
+ if ownChunkQuestions != nil && ownChunkQuestions[q] {
+ validSimilarQuestions = append(validSimilarQuestions, q)
+ continue
+ }
+ removedSimilarQuestions = append(removedSimilarQuestions, fmt.Sprintf(`「相似问冲突」:"%s"与知识库已有"标准问/相似问"冲突`, q))
+ continue
}
+ // 相似问校验:对比批次内标准问 + 相似问
+ if firstIdx, exists := batchAllQuestions[q]; exists && firstIdx != i {
+ removedSimilarQuestions = append(removedSimilarQuestions, fmt.Sprintf(`「相似问冲突」:"%s"与第 %d 行"标准问/相似问"冲突`, q, firstIdx+1))
+ continue
+ }
+ validSimilarQuestions = append(validSimilarQuestions, q)
}
- if hasDuplicate {
- continue
+ entries[i].SimilarQuestions = validSimilarQuestions
+
+ if len(removedSimilarQuestions) > 0 {
+ removedSimilarQuestionsMap[i] = removedSimilarQuestions
}
- // 将当前条目的标准问和相似问加入批次集合
- batchQuestions[standardQ] = i
+ if (idx+1)%100 == 0 {
+ progress.Message = fmt.Sprintf("正在验证相似问 %d/%d...", idx+1, len(validIndicesAfterStdQ))
+ progress.UpdatedAt = time.Now().Unix()
+ if err := s.saveFAQImportProgress(ctx, progress); err != nil {
+ logger.Warnf(ctx, "Failed to update FAQ dry run progress: %v", err)
+ }
+ }
+ }
+
+ // ==================== 第三次迭代:反例冲突检测(预校验,仅检查新条目自身数据) ====================
+ for idx, i := range validIndicesAfterStdQ {
+ entry := &entries[i]
+ standardQ := strings.TrimSpace(entry.StandardQuestion)
+
+ currentQAQuestions := make(map[string]bool)
+ currentQAQuestions[standardQ] = true
for _, q := range entry.SimilarQuestions {
+ currentQAQuestions[q] = true
+ }
+
+ validNegativeQuestions := make([]string, 0, len(entry.NegativeQuestions))
+ var removedNegativeQuestions []string
+ for _, q := range entry.NegativeQuestions {
q = strings.TrimSpace(q)
- if q != "" {
- batchQuestions[q] = i
+ if q == "" {
+ continue
+ }
+ if currentQAQuestions[q] {
+ removedNegativeQuestions = append(removedNegativeQuestions, fmt.Sprintf(`「反例冲突」:"%s"与本条"标准问/相似问"冲突`, q))
+ continue
}
+ validNegativeQuestions = append(validNegativeQuestions, q)
}
+ entries[i].NegativeQuestions = validNegativeQuestions
- // 记录通过验证的条目索引
- validIndices = append(validIndices, i)
+ if len(removedNegativeQuestions) > 0 {
+ removedNegativeQuestionsMap[i] = removedNegativeQuestions
+ }
- // 定期更新进度消息(验证阶段不更新 Processed)
- if (i+1)%100 == 0 {
- progress.Message = fmt.Sprintf("正在验证条目 %d/%d...", i+1, len(entries))
+ if (idx+1)%100 == 0 {
+ progress.Message = fmt.Sprintf("正在验证反例 %d/%d...", idx+1, len(validIndicesAfterStdQ))
progress.UpdatedAt = time.Now().Unix()
if err := s.saveFAQImportProgress(ctx, progress); err != nil {
logger.Warnf(ctx, "Failed to update FAQ dry run progress: %v", err)
@@ -487,18 +659,110 @@ func (s *knowledgeService) validateEntriesForAppendModeWithProgress(ctx context.
}
}
- return validIndices
+ // ==================== 第四次迭代:后校验(仅合并候选) ====================
+ // 对合并后的完整数据重跑反例校验,冲突则整条回退到合并前状态
+ postValidationFailed := make(map[int]bool)
+ mergeCount := 0
+ for _, i := range validIndicesAfterStdQ {
+ mergeChunk, isMerge := mergeChunkMap[i]
+ if !isMerge {
+ continue
+ }
+
+ existingMeta, err := mergeChunk.FAQMetadata()
+ if err != nil || existingMeta == nil {
+ logger.Warnf(ctx, "FAQ entry %d: failed to get merge target metadata, skipping post-validation", i)
+ continue
+ }
+
+ entry := &entries[i]
+
+ // 计算合并后的完整数据
+ mergedSimilar := unionStrings(existingMeta.SimilarQuestions, entry.SimilarQuestions)
+ mergedNegative := unionStrings(existingMeta.NegativeQuestions, entry.NegativeQuestions)
+
+ // 构建合并后的冲突集合(标准问 + 所有合并后的相似问)
+ mergedPositiveSet := make(map[string]bool)
+ mergedPositiveSet[existingMeta.StandardQuestion] = true
+ for _, q := range mergedSimilar {
+ mergedPositiveSet[q] = true
+ }
+
+ // 检查每个合并后的反例是否与合并后的标准问 / 相似问冲突
+ var conflictingNegatives []string
+ for _, q := range mergedNegative {
+ if mergedPositiveSet[q] {
+ conflictingNegatives = append(conflictingNegatives, q)
+ }
+ }
+
+ if len(conflictingNegatives) > 0 {
+ // 后校验失败 → 整条回退到合并前状态
+ postValidationFailed[i] = true
+ delete(mergeChunkMap, i)
+ progress.FailedCount++
+ reason := fmt.Sprintf("后校验失败:合并后反例「%s」与相似问冲突", strings.Join(conflictingNegatives, "、"))
+ fe := buildFAQFailedEntry(i, reason, entry)
+ fe.FailureType = "post_validation"
+ progress.FailedEntries = append(progress.FailedEntries, fe)
+ logger.Infof(ctx, "FAQ entry %d: post-validation failed, conflicting negatives after merge: %v", i, conflictingNegatives)
+ } else {
+ mergeCount++
+ }
+ }
+
+ // 从有效索引中移除后校验失败的条目
+ if len(postValidationFailed) > 0 {
+ filtered := make([]int, 0, len(validIndicesAfterStdQ))
+ for _, i := range validIndicesAfterStdQ {
+ if !postValidationFailed[i] {
+ filtered = append(filtered, i)
+ }
+ }
+ validIndicesAfterStdQ = filtered
+ }
+
+ // 将部分失败信息添加到 FailedEntries
+ for _, i := range validIndicesAfterStdQ {
+ removedSimilar := removedSimilarQuestionsMap[i]
+ removedNegative := removedNegativeQuestionsMap[i]
+ if len(removedSimilar) > 0 || len(removedNegative) > 0 {
+ pf := buildFAQPartialFailedEntry(i, &entries[i], removedSimilar, removedNegative)
+ progress.FailedEntries = append(progress.FailedEntries, pf)
+ progress.PartialFailedCount++
+ }
+ }
+
+ // 记录合并条目索引到 progress(用于执行阶段和重试)
+ mergeIndices := make([]int, 0, mergeCount)
+ for _, i := range validIndicesAfterStdQ {
+ if _, isMerge := mergeChunkMap[i]; isMerge {
+ mergeIndices = append(mergeIndices, i)
+ }
+ }
+ progress.MergeEntryIndices = mergeIndices
+
+ logger.Infof(ctx, "Append mode validation completed: total=%d, valid=%d, merge_candidates=%d, failed=%d, partial_failed=%d",
+ totalEntries, len(validIndicesAfterStdQ), mergeCount, progress.FailedCount, progress.PartialFailedCount)
+
+ return validIndicesAfterStdQ
}
// validateEntriesForReplaceModeWithProgress 验证 Replace 模式下的条目(带进度更新)
// 注意:验证阶段不更新 Processed,只有实际导入时才更新
+// 分三次迭代校验,确保前面过滤掉的数据不会被后面考虑:
+// 1. 标准问 - 对比所有标准问 → 整条QA失败「标准问冲突」
+// 2. 相似问 - 对比所有标准问+相似问 → 单条问法失败「相似问冲突」(仅移除冲突的相似问)
+// 3. 反例 - 对比当前QA下所有标准问+相似问 → 单条问法失败「反例冲突」(仅移除冲突的反例)
func (s *knowledgeService) validateEntriesForReplaceModeWithProgress(ctx context.Context,
entries []types.FAQEntryPayload, progress *types.FAQImportProgress,
) []int {
- validIndices := make([]int, 0, len(entries))
+ totalEntries := len(entries)
- // Replace 模式下只检查批次内重复
- batchQuestions := make(map[string]int) // value 为首次出现的索引
+ // ==================== 第一次迭代:基本格式验证 + 标准问冲突检测 ====================
+ // 标准问冲突会导致整条QA失败
+ batchStandardQuestions := make(map[string]int) // value 为首次出现的索引
+ validIndicesAfterStdQ := make([]int, 0, totalEntries)
for i, entry := range entries {
// 验证条目基本格式
@@ -510,46 +774,131 @@ func (s *knowledgeService) validateEntriesForReplaceModeWithProgress(ctx context
standardQ := strings.TrimSpace(entry.StandardQuestion)
- // 检查标准问是否与同批次重复
- if firstIdx, exists := batchQuestions[standardQ]; exists {
+ // 标准问校验:对比所有标准问 → 整条QA失败「标准问冲突」
+ if firstIdx, exists := batchStandardQuestions[standardQ]; exists {
progress.FailedCount++
- progress.FailedEntries = append(progress.FailedEntries, buildFAQFailedEntry(i, fmt.Sprintf("标准问与批次内第 %d 条重复", firstIdx+1), &entry))
+ progress.FailedEntries = append(progress.FailedEntries, buildFAQFailedEntry(i, fmt.Sprintf("标准问冲突:与批次内第 %d 条标准问重复", firstIdx+1), &entry))
continue
}
- // 检查相似问是否有重复
- hasDuplicate := false
+ // 记录标准问
+ batchStandardQuestions[standardQ] = i
+ validIndicesAfterStdQ = append(validIndicesAfterStdQ, i)
+
+ // 定期更新进度消息
+ if (i+1)%100 == 0 {
+ progress.Message = fmt.Sprintf("正在验证标准问 %d/%d...", i+1, totalEntries)
+ progress.UpdatedAt = time.Now().Unix()
+ if err := s.saveFAQImportProgress(ctx, progress); err != nil {
+ logger.Warnf(ctx, "Failed to update FAQ dry run progress: %v", err)
+ }
+ }
+ }
+
+ // ==================== 第二次迭代:相似问冲突检测 ====================
+ // 只处理通过第一次校验的条目,相似问冲突只移除冲突的相似问
+ // 构建所有标准问+相似问的集合(只包含通过第一次校验的条目)
+ batchAllQuestions := make(map[string]int) // value 为首次出现的索引
+ for _, i := range validIndicesAfterStdQ {
+ standardQ := strings.TrimSpace(entries[i].StandardQuestion)
+ batchAllQuestions[standardQ] = i
+ for _, q := range entries[i].SimilarQuestions {
+ q = strings.TrimSpace(q)
+ if q != "" {
+ // 只记录第一次出现的位置
+ if _, exists := batchAllQuestions[q]; !exists {
+ batchAllQuestions[q] = i
+ }
+ }
+ }
+ }
+
+ // 用于收集每个条目被移除的相似问和反例
+ removedSimilarQuestionsMap := make(map[int][]string) // key 为条目索引
+ removedNegativeQuestionsMap := make(map[int][]string) // key 为条目索引
+
+ // 对每个通过第一次校验的条目,过滤冲突的相似问
+ for idx, i := range validIndicesAfterStdQ {
+ entry := &entries[i]
+ standardQ := strings.TrimSpace(entry.StandardQuestion)
+
+ validSimilarQuestions := make([]string, 0, len(entry.SimilarQuestions))
+ var removedSimilarQuestions []string
for _, q := range entry.SimilarQuestions {
q = strings.TrimSpace(q)
if q == "" {
continue
}
- if firstIdx, exists := batchQuestions[q]; exists {
- progress.FailedCount++
- progress.FailedEntries = append(progress.FailedEntries, buildFAQFailedEntry(i, fmt.Sprintf("相似问 \"%s\" 与批次内第 %d 条重复", q, firstIdx+1), &entry))
- hasDuplicate = true
- break
+ // 相似问校验:对比所有标准问+相似问 → 单条问法失败「相似问冲突」
+ // 如果该相似问与其他条目的标准问或相似问冲突(且不是自己的标准问),则移除
+ if firstIdx, exists := batchAllQuestions[q]; exists && firstIdx != i {
+ logger.Infof(ctx, "FAQ entry %d: similar question '%s' conflicts with entry %d, removing", i, q, firstIdx+1)
+ removedSimilarQuestions = append(removedSimilarQuestions, fmt.Sprintf(`「相似问冲突」:"%s"与第 %d 行"标准问/相似问"冲突`, q, firstIdx+1))
+ continue
}
+ // 相似问不能与自己的标准问相同
+ if q == standardQ {
+ logger.Infof(ctx, "FAQ entry %d: similar question '%s' same as standard question, removing", i, q)
+ removedSimilarQuestions = append(removedSimilarQuestions, fmt.Sprintf(`「相似问冲突」:"%s"与本条"标准问"冲突`, q))
+ continue
+ }
+ validSimilarQuestions = append(validSimilarQuestions, q)
}
- if hasDuplicate {
- continue
+ entries[i].SimilarQuestions = validSimilarQuestions
+
+ // 记录被移除的相似问
+ if len(removedSimilarQuestions) > 0 {
+ removedSimilarQuestionsMap[i] = removedSimilarQuestions
}
- // 将当前条目的标准问和相似问加入批次集合
- batchQuestions[standardQ] = i
+ // 定期更新进度消息
+ if (idx+1)%100 == 0 {
+ progress.Message = fmt.Sprintf("正在验证相似问 %d/%d...", idx+1, len(validIndicesAfterStdQ))
+ progress.UpdatedAt = time.Now().Unix()
+ if err := s.saveFAQImportProgress(ctx, progress); err != nil {
+ logger.Warnf(ctx, "Failed to update FAQ dry run progress: %v", err)
+ }
+ }
+ }
+
+ // ==================== 第三次迭代:反例冲突检测 ====================
+ // 只处理通过前两次校验的条目,反例冲突只移除冲突的反例
+ for idx, i := range validIndicesAfterStdQ {
+ entry := &entries[i]
+ standardQ := strings.TrimSpace(entry.StandardQuestion)
+
+ // 构建当前QA的所有问题集合(标准问+通过校验的相似问)
+ currentQAQuestions := make(map[string]bool)
+ currentQAQuestions[standardQ] = true
for _, q := range entry.SimilarQuestions {
+ currentQAQuestions[q] = true
+ }
+
+ validNegativeQuestions := make([]string, 0, len(entry.NegativeQuestions))
+ var removedNegativeQuestions []string
+ for _, q := range entry.NegativeQuestions {
q = strings.TrimSpace(q)
- if q != "" {
- batchQuestions[q] = i
+ if q == "" {
+ continue
}
+ // 反例校验:对比当前QA下所有标准问+相似问 → 单条问法失败「反例冲突」
+ if currentQAQuestions[q] {
+ logger.Infof(ctx, "FAQ entry %d: negative question '%s' conflicts with current QA's questions, removing", i, q)
+ removedNegativeQuestions = append(removedNegativeQuestions, fmt.Sprintf(`「反例冲突」:"%s"与本条"标准问/相似问"冲突`, q))
+ continue
+ }
+ validNegativeQuestions = append(validNegativeQuestions, q)
}
+ entries[i].NegativeQuestions = validNegativeQuestions
- // 记录通过验证的条目索引
- validIndices = append(validIndices, i)
+ // 记录被移除的反例
+ if len(removedNegativeQuestions) > 0 {
+ removedNegativeQuestionsMap[i] = removedNegativeQuestions
+ }
- // 定期更新进度消息(验证阶段不更新 Processed)
- if (i+1)%100 == 0 {
- progress.Message = fmt.Sprintf("正在验证条目 %d/%d...", i+1, len(entries))
+ // 定期更新进度消息
+ if (idx+1)%100 == 0 {
+ progress.Message = fmt.Sprintf("正在验证反例 %d/%d...", idx+1, len(validIndicesAfterStdQ))
progress.UpdatedAt = time.Now().Unix()
if err := s.saveFAQImportProgress(ctx, progress); err != nil {
logger.Warnf(ctx, "Failed to update FAQ dry run progress: %v", err)
@@ -557,7 +906,39 @@ func (s *knowledgeService) validateEntriesForReplaceModeWithProgress(ctx context
}
}
- return validIndices
+ // 将部分失败信息添加到 FailedEntries
+ for _, i := range validIndicesAfterStdQ {
+ removedSimilar := removedSimilarQuestionsMap[i]
+ removedNegative := removedNegativeQuestionsMap[i]
+ if len(removedSimilar) > 0 || len(removedNegative) > 0 {
+ pf := buildFAQPartialFailedEntry(i, &entries[i], removedSimilar, removedNegative)
+ progress.FailedEntries = append(progress.FailedEntries, pf)
+ progress.PartialFailedCount++
+ }
+ }
+
+ return validIndicesAfterStdQ
+}
+
+// unionStrings 合并两个字符串切片并去重(完全匹配)
+func unionStrings(a, b []string) []string {
+ seen := make(map[string]bool, len(a)+len(b))
+ result := make([]string, 0, len(a)+len(b))
+ for _, s := range a {
+ s = strings.TrimSpace(s)
+ if s != "" && !seen[s] {
+ seen[s] = true
+ result = append(result, s)
+ }
+ }
+ for _, s := range b {
+ s = strings.TrimSpace(s)
+ if s != "" && !seen[s] {
+ seen[s] = true
+ result = append(result, s)
+ }
+ }
+ return result
}
// validateFAQEntryPayloadBasic 验证 FAQ 条目的基本格式
@@ -585,33 +966,45 @@ func validateFAQEntryPayloadBasic(entry *types.FAQEntryPayload) error {
return nil
}
-// calculateAppendOperations 计算Append模式下需要处理的条目,跳过已存在且内容相同的条目
-// 同时过滤掉标准问或相似问与同批次或已有知识库中重复的条目
+type faqMergeOperation struct {
+ Entry types.FAQEntryPayload
+ ExistingChunk *types.Chunk
+ OldMeta *types.FAQChunkMetadata
+ MergedMeta *types.FAQChunkMetadata
+ Detail types.FAQMergeDetail
+}
+
+// calculateAppendOperations 计算 Append 模式下的操作(支持智能合并)。
+// 如果 entry 的标准问在 KB 中已存在,则视为合并操作(相似问 / 反例并集,
+// 答案 / 策略以新条目为准);否则视为新建。无变化(hash 一致且操作位
+// 也未变)的合并目标会被 skip 掉,避免无效写库 / 重建索引。
+//
+// 内部 master 行为,对应开源版仅 "重复 = 失败" 的简化逻辑。FAQ 导入的
+// 常见使用方式是"导出修改后重新 append",需要这种合并语义才能正确叠加
+// 新的相似问而不丢历史数据。
func (s *knowledgeService) calculateAppendOperations(ctx context.Context,
tenantID uint64, kbID string, entries []types.FAQEntryPayload,
-) ([]types.FAQEntryPayload, int, error) {
+) (newEntries []types.FAQEntryPayload, mergeOps []faqMergeOperation, skippedCount int, err error) {
if len(entries) == 0 {
- return []types.FAQEntryPayload{}, 0, nil
+ return nil, nil, 0, nil
}
- // 1. 查询知识库中已有的所有FAQ chunks的metadata
existingChunks, err := s.chunkRepo.ListAllFAQChunksWithMetadataByKnowledgeBaseID(ctx, tenantID, kbID)
if err != nil {
- return nil, 0, fmt.Errorf("failed to list existing FAQ chunks: %w", err)
+ return nil, nil, 0, fmt.Errorf("failed to list existing FAQ chunks: %w", err)
}
- // 2. 构建已存在的标准问和相似问集合
+ existingStdQToChunk := make(map[string]*types.Chunk)
existingQuestions := make(map[string]bool)
for _, chunk := range existingChunks {
- meta, err := chunk.FAQMetadata()
- if err != nil || meta == nil {
+ meta, cErr := chunk.FAQMetadata()
+ if cErr != nil || meta == nil {
continue
}
- // 添加标准问
if meta.StandardQuestion != "" {
+ existingStdQToChunk[meta.StandardQuestion] = chunk
existingQuestions[meta.StandardQuestion] = true
}
- // 添加相似问
for _, q := range meta.SimilarQuestions {
if q != "" {
existingQuestions[q] = true
@@ -619,51 +1012,109 @@ func (s *knowledgeService) calculateAppendOperations(ctx context.Context,
}
}
- // 3. 构建当前批次的标准问和相似问集合(用于批次内去重)
batchQuestions := make(map[string]bool)
- entriesToProcess := make([]types.FAQEntryPayload, 0, len(entries))
- skippedCount := 0
+ newEntries = make([]types.FAQEntryPayload, 0, len(entries))
+ mergeOps = make([]faqMergeOperation, 0)
- for _, entry := range entries {
- meta, err := sanitizeFAQEntryPayload(&entry)
- if err != nil {
- // 跳过无效条目
+ for entryIdx, entry := range entries {
+ meta, sErr := sanitizeFAQEntryPayload(&entry)
+ if sErr != nil {
skippedCount++
- logger.Warnf(ctx, "Skipping invalid FAQ entry: %v", err)
+ logger.Warnf(ctx, "Skipping invalid FAQ entry: %v", sErr)
continue
}
- // 检查标准问是否重复(与已有或同批次)
- if existingQuestions[meta.StandardQuestion] || batchQuestions[meta.StandardQuestion] {
- skippedCount++
- logger.Infof(ctx, "Skipping FAQ entry with duplicate standard question: %s", meta.StandardQuestion)
- continue
- }
+ // 检查标准问是否在 KB 中作为标准问存在 → 合并候选
+ existingChunk, isMergeCandidate := existingStdQToChunk[meta.StandardQuestion]
+ if isMergeCandidate {
+ existingMeta, mErr := existingChunk.FAQMetadata()
+ if mErr != nil || existingMeta == nil {
+ isMergeCandidate = false
+ } else {
+ mergedSimilar := unionStrings(existingMeta.SimilarQuestions, meta.SimilarQuestions)
+ mergedNegative := unionStrings(existingMeta.NegativeQuestions, meta.NegativeQuestions)
+
+ mergedMeta := &types.FAQChunkMetadata{
+ StandardQuestion: existingMeta.StandardQuestion,
+ SimilarQuestions: mergedSimilar,
+ NegativeQuestions: mergedNegative,
+ Answers: meta.Answers,
+ AnswerStrategy: meta.AnswerStrategy,
+ Version: existingMeta.Version + 1,
+ Source: existingMeta.Source,
+ }
- // 检查相似问是否有重复(与已有或同批次)
- hasDuplicateSimilar := false
- for _, q := range meta.SimilarQuestions {
- if existingQuestions[q] || batchQuestions[q] {
- hasDuplicateSimilar = true
- logger.Infof(ctx, "Skipping FAQ entry with duplicate similar question: %s (standard: %s)", q, meta.StandardQuestion)
- break
+ newHash := types.CalculateFAQContentHash(mergedMeta)
+ enabledChanged := entry.IsEnabled != nil && *entry.IsEnabled != existingChunk.IsEnabled
+ recommendedChanged := entry.IsRecommended != nil &&
+ *entry.IsRecommended != existingChunk.Flags.HasFlag(types.ChunkFlagRecommended)
+ answerStrategyChanged := meta.AnswerStrategy != existingMeta.AnswerStrategy
+ if existingChunk.ContentHash == newHash && !enabledChanged && !recommendedChanged && !answerStrategyChanged {
+ skippedCount++
+ logger.Infof(ctx, "Skipping merge for unchanged FAQ entry: %s", meta.StandardQuestion)
+ continue
+ }
+
+ oldAnswerStr := strings.Join(existingMeta.Answers, "##")
+ newAnswerStr := strings.Join(meta.Answers, "##")
+ oldSimilarSet := make(map[string]bool, len(existingMeta.SimilarQuestions))
+ for _, q := range existingMeta.SimilarQuestions {
+ oldSimilarSet[q] = true
+ }
+ oldNegativeSet := make(map[string]bool, len(existingMeta.NegativeQuestions))
+ for _, q := range existingMeta.NegativeQuestions {
+ oldNegativeSet[q] = true
+ }
+ newSimilarCount := 0
+ for _, q := range mergedSimilar {
+ if !oldSimilarSet[q] {
+ newSimilarCount++
+ }
+ }
+ newNegativeCount := 0
+ for _, q := range mergedNegative {
+ if !oldNegativeSet[q] {
+ newNegativeCount++
+ }
+ }
+
+ mergeOps = append(mergeOps, faqMergeOperation{
+ Entry: entry,
+ ExistingChunk: existingChunk,
+ OldMeta: existingMeta,
+ MergedMeta: mergedMeta,
+ Detail: types.FAQMergeDetail{
+ Index: entryIdx,
+ StandardQuestion: meta.StandardQuestion,
+ AnswerChanged: oldAnswerStr != newAnswerStr,
+ NewSimilarCount: newSimilarCount,
+ NewNegativeCount: newNegativeCount,
+ },
+ })
+ continue
}
}
- if hasDuplicateSimilar {
+
+ // 走到这里说明既不是合并候选,又跟现有 KB / 当前批次的标准问 / 相似问冲突。
+ // 正常情况下这些冲突应在 executeFAQDryRunValidation 阶段就被拦截,这里
+ // 仅作为防御性兜底;用 Warn 级别打点便于排查验证层漏检。
+ if existingQuestions[meta.StandardQuestion] || batchQuestions[meta.StandardQuestion] {
skippedCount++
+ logger.Warnf(ctx,
+ "calculateAppendOperations: dropping FAQ entry with duplicate standard question %q "+
+ "(should have been filtered at validation); entry_idx=%d",
+ meta.StandardQuestion, entryIdx)
continue
}
- // 将当前条目的标准问和相似问加入批次集合
batchQuestions[meta.StandardQuestion] = true
for _, q := range meta.SimilarQuestions {
batchQuestions[q] = true
}
-
- entriesToProcess = append(entriesToProcess, entry)
+ newEntries = append(newEntries, entry)
}
- return entriesToProcess, skippedCount, nil
+ return newEntries, mergeOps, skippedCount, nil
}
// calculateReplaceOperations 计算Replace模式下需要删除、创建、更新的条目
@@ -876,32 +1327,45 @@ func (s *knowledgeService) executeFAQImport(ctx context.Context, taskID string,
logger.Infof(ctx, "FAQ import task %s: deleted %d chunks (including updates)", taskID, len(chunksToDelete))
}
} else {
- // Append模式:查询已存在的条目,跳过未变化的
- entriesToProcess, skippedCount, err = s.calculateAppendOperations(ctx, tenantID, kb.ID, payload.Entries)
+ // Append 模式(智能合并):标准问已存在的条目走 merge ops,其余作为新建。
+ var mergeOps []faqMergeOperation
+ entriesToProcess, mergeOps, skippedCount, err = s.calculateAppendOperations(ctx, tenantID, kb.ID, payload.Entries)
if err != nil {
return fmt.Errorf("failed to calculate append operations: %w", err)
}
- }
+ if len(mergeOps) > 0 {
+ mergedCount, mergeErr := s.executeFAQMergeOperations(ctx, taskID, kb, faqKnowledge, embeddingModel, indexMode, mergeOps, progress)
+ if mergeErr != nil {
+ return fmt.Errorf("failed to execute merge operations: %w", mergeErr)
+ }
+ logger.Infof(ctx, "FAQ import task %s: merged %d entries", taskID, mergedCount)
+ progress.MergedCount = mergedCount
+ for _, op := range mergeOps {
+ progress.MergeDetails = append(progress.MergeDetails, op.Detail)
+ }
+ }
+ }
logger.Infof(
ctx,
- "FAQ import task %s: total entries: %d, to process: %d, skipped: %d",
+ "FAQ import task %s: total entries: %d, new to create: %d, skipped: %d, merged: %d",
taskID,
len(payload.Entries),
len(entriesToProcess),
skippedCount,
+ progress.MergedCount,
)
// 如果没有需要处理的条目,直接返回
if len(entriesToProcess) == 0 {
- logger.Infof(ctx, "FAQ import task %s: no entries to process, all skipped", taskID)
+ logger.Infof(ctx, "FAQ import task %s: no new entries to create", taskID)
return nil
}
// 分批处理需要创建的条目
remainingEntries := len(entriesToProcess)
totalStartTime := time.Now()
- actualProcessed := skippedCount + processedCount
+ actualProcessed := skippedCount + processedCount + progress.MergedCount
logger.Infof(
ctx,
@@ -1827,7 +2291,7 @@ func (s *knowledgeService) ProcessFAQImport(ctx context.Context, t *asynq.Task)
// 任务成功完成
logger.Infof(ctx, "FAQ import task completed: %s, imported: %d, failed: %d",
- payload.TaskID, len(validEntries), progress.FailedCount)
+ payload.TaskID, len(progress.SuccessEntries), progress.FailedCount)
// 最终完成处理(生成失败条目 CSV 等)
return s.finalizeFAQValidation(ctx, &payload, progress, originalTotalEntries)
@@ -1859,6 +2323,43 @@ func (s *knowledgeService) finalizeFAQValidation(ctx context.Context, payload *t
}
}
+ // 必须在 saveFAQImportResultToDatabase 之前计算最终统计。
+ progress.Status = types.FAQImportStatusCompleted
+ progress.Progress = 100
+ progress.Processed = originalTotalEntries
+
+ if len(progress.ValidEntryIndices) > 0 {
+ progress.SuccessCount = len(progress.ValidEntryIndices) - progress.PartialFailedCount
+ } else if len(progress.SuccessEntries) > 0 {
+ progress.SuccessCount = len(progress.SuccessEntries) - progress.PartialFailedCount
+ } else {
+ progress.SuccessCount = originalTotalEntries - progress.FailedCount - progress.PartialFailedCount
+ }
+ if progress.SuccessCount < 0 {
+ progress.SuccessCount = 0
+ }
+
+ if progress.AddedCount == 0 && progress.MergedCount > 0 {
+ progress.AddedCount = progress.SuccessCount - progress.MergedCount
+ if progress.AddedCount < 0 {
+ progress.AddedCount = 0
+ }
+ } else if progress.AddedCount == 0 {
+ progress.AddedCount = progress.SuccessCount
+ }
+
+ skippedCount := originalTotalEntries - progress.SuccessCount - progress.PartialFailedCount - progress.FailedCount
+ if skippedCount < 0 {
+ skippedCount = 0
+ }
+ progress.SkippedCount = skippedCount
+
+ if payload.DryRun {
+ progress.Message = s.buildFAQImportResultMessage("验证完成", progress)
+ } else {
+ progress.Message = s.buildFAQImportResultMessage("导入完成", progress)
+ }
+
// 如果不是 dry run 模式,保存导入结果统计到数据库
if !payload.DryRun {
if err := s.saveFAQImportResultToDatabase(ctx, payload, progress, originalTotalEntries); err != nil {
@@ -1889,16 +2390,11 @@ func (s *knowledgeService) finalizeFAQValidation(ctx context.Context, payload *t
logger.Warnf(ctx, "Failed to update final FAQ import status: %v", err)
}
- logger.Infof(ctx, "FAQ task completed: %s, dry_run=%v, success: %d, failed: %d",
- payload.TaskID, payload.DryRun, progress.SuccessCount, progress.FailedCount)
+ logger.Infof(ctx, "FAQ task completed: %s, dry_run=%v, success: %d, added: %d, merged: %d, failed: %d, partial_failed: %d",
+ payload.TaskID, payload.DryRun, progress.SuccessCount, progress.AddedCount, progress.MergedCount, progress.FailedCount, progress.PartialFailedCount)
if !payload.DryRun {
- skippedCount := originalTotalEntries - progress.SuccessCount - progress.FailedCount
- if skippedCount < 0 {
- skippedCount = 0
- }
- progress.SkippedCount = skippedCount
- outcome := faqImportCompletedOutcome(progress.SuccessCount, progress.FailedCount, skippedCount)
+ outcome := faqImportCompletedOutcome(progress.SuccessCount, progress.FailedCount, progress.SkippedCount)
s.recordFAQImportKBActivity(ctx, payload, progress, originalTotalEntries,
types.AuditActionFAQImportCompleted, outcome)
}
@@ -1906,6 +2402,155 @@ func (s *knowledgeService) finalizeFAQValidation(ctx context.Context, payload *t
return nil
}
+// executeFAQMergeOperations 批量执行 append-mode 合并操作:更新已有 chunk
+// 的 metadata / content / 索引。使用 ListChunksByID 批量加载 + SaveChunks 事
+// 务批量保存,减少 DB 往返。任一批次失败立即返回,由 executeFAQImport
+// 的 defer recovery 决定是否回滚整次导入。
+//
+// 必要时这里逐条 fan-out 索引(EFPutDocument),而不是合并 chunks 批量
+// 重建:因为索引底层是按 SourceID 覆盖写入,按合并后的最终内容直接 put
+// 即可。
+func (s *knowledgeService) executeFAQMergeOperations(
+ ctx context.Context,
+ taskID string,
+ kb *types.KnowledgeBase,
+ faqKnowledge *types.Knowledge,
+ embeddingModel embedding.Embedder,
+ indexMode types.FAQIndexMode,
+ mergeOps []faqMergeOperation,
+ progress *types.FAQImportProgress,
+) (int, error) {
+ if len(mergeOps) == 0 {
+ return 0, nil
+ }
+
+ tenantID := ctx.Value(types.TenantIDContextKey).(uint64)
+ mergedCount := 0
+
+ for batchStart := 0; batchStart < len(mergeOps); batchStart += faqImportBatchSize {
+ batchEnd := batchStart + faqImportBatchSize
+ if batchEnd > len(mergeOps) {
+ batchEnd = len(mergeOps)
+ }
+ batch := mergeOps[batchStart:batchEnd]
+
+ // 1. 批量加载完整 chunk(calculateAppendOperations 中只加载了部分字段,
+ // 缺少 status/is_enabled/flags/seq_id 等,直接更新会将这些字段覆盖为零值)
+ chunkIDs := make([]string, len(batch))
+ for i, op := range batch {
+ chunkIDs[i] = op.ExistingChunk.ID
+ }
+ fullChunks, err := s.chunkRepo.ListChunksByID(ctx, tenantID, chunkIDs)
+ if err != nil {
+ logger.Errorf(ctx, "FAQ import task %s: failed to batch reload chunks for merge: %v", taskID, err)
+ return mergedCount, fmt.Errorf("failed to batch reload chunks for merge: %w", err)
+ }
+ chunkMap := make(map[string]*types.Chunk, len(fullChunks))
+ for _, c := range fullChunks {
+ chunkMap[c.ID] = c
+ }
+
+ // 2. 逐条应用合并数据
+ mergedChunks := make([]*types.Chunk, 0, len(batch))
+ for _, op := range batch {
+ fullChunk, ok := chunkMap[op.ExistingChunk.ID]
+ if !ok {
+ logger.Errorf(ctx, "FAQ import task %s: chunk %s not found during batch reload", taskID, op.ExistingChunk.ID)
+ return mergedCount, fmt.Errorf("chunk %s not found during batch reload", op.ExistingChunk.ID)
+ }
+
+ if err := fullChunk.SetFAQMetadata(op.MergedMeta); err != nil {
+ logger.Errorf(ctx, "FAQ import task %s: failed to set merged metadata for chunk %s: %v", taskID, fullChunk.ID, err)
+ return mergedCount, fmt.Errorf("failed to set merged FAQ metadata: %w", err)
+ }
+
+ fullChunk.Content = buildFAQChunkContent(op.MergedMeta, indexMode)
+ fullChunk.ContentHash = types.CalculateFAQContentHash(op.MergedMeta)
+ fullChunk.UpdatedAt = time.Now()
+
+ // 用新值覆盖运营状态
+ if op.Entry.IsEnabled != nil {
+ fullChunk.IsEnabled = *op.Entry.IsEnabled
+ }
+ if op.Entry.IsRecommended != nil {
+ if *op.Entry.IsRecommended {
+ fullChunk.Flags = fullChunk.Flags.SetFlag(types.ChunkFlagRecommended)
+ } else {
+ fullChunk.Flags = fullChunk.Flags.ClearFlag(types.ChunkFlagRecommended)
+ }
+ }
+
+ mergedChunks = append(mergedChunks, fullChunk)
+ }
+
+ // 3. 事务批量保存(GORM Save 全字段更新,确保 metadata/content_hash 持久化)
+ if err := s.chunkRepo.SaveChunks(ctx, mergedChunks); err != nil {
+ logger.Errorf(ctx, "FAQ import task %s: failed to batch save merged chunks: %v", taskID, err)
+ return mergedCount, fmt.Errorf("failed to batch save merged chunks: %w", err)
+ }
+
+ // 4. 重建索引(EFPutDocument 会自动覆盖相同 SourceID)
+ if err := s.indexFAQChunks(ctx, kb, faqKnowledge, mergedChunks, embeddingModel, false, false); err != nil {
+ return mergedCount, fmt.Errorf("failed to re-index merged chunks: %w", err)
+ }
+
+ // 5. 收集成功条目信息
+ for i, op := range batch {
+ chunk := mergedChunks[i]
+ meta := op.MergedMeta
+ var tagID int64
+ tagName := ""
+ if chunk.TagID != "" {
+ if tag, tErr := s.tagRepo.GetByID(ctx, tenantID, chunk.TagID); tErr == nil && tag != nil {
+ tagID = tag.SeqID
+ tagName = tag.Name
+ }
+ }
+ progress.SuccessEntries = append(progress.SuccessEntries, types.FAQSuccessEntry{
+ Index: op.Detail.Index,
+ SeqID: chunk.SeqID,
+ TagID: tagID,
+ TagName: tagName,
+ StandardQuestion: meta.StandardQuestion,
+ })
+ }
+
+ mergedCount += len(batch)
+
+ logger.Infof(ctx, "FAQ import task %s: merged batch %d-%d (%d chunks)", taskID, batchStart+1, batchEnd, len(mergedChunks))
+ }
+
+ return mergedCount, nil
+}
+
+// buildFAQImportResultMessage 构建 FAQ 导入 / 验证最终结果的人类可读消息。
+// 前端会把它直接展示在 toast / 任务列表里,所以保持简单清晰:
+// - 默认形态:"导入完成 / 上传 N 条 / 成功 X 条 [/ 失败 Y 条] [/ 部分失败 Z 条]"
+// - 当 MergedCount > 0 时改用拆分形态:"/ 新增 X 条 / 合并更新 Y 条",
+// 让用户在 append 模式下看到合并了多少条历史 FAQ 而不是只看到总成功数。
+//
+// 内部 master 原始实现;HEAD 版本之前没有,所有完成消息只有 "正在处理第 N/M 条"。
+func (s *knowledgeService) buildFAQImportResultMessage(prefix string, progress *types.FAQImportProgress) string {
+ parts := []string{prefix}
+ parts = append(parts, fmt.Sprintf("上传 %d 条", progress.Total))
+
+ if progress.MergedCount > 0 {
+ parts = append(parts, fmt.Sprintf("新增 %d 条", progress.AddedCount))
+ parts = append(parts, fmt.Sprintf("合并更新 %d 条", progress.MergedCount))
+ } else {
+ parts = append(parts, fmt.Sprintf("成功 %d 条", progress.SuccessCount))
+ }
+
+ if progress.FailedCount > 0 {
+ parts = append(parts, fmt.Sprintf("失败 %d 条", progress.FailedCount))
+ }
+ if progress.PartialFailedCount > 0 {
+ parts = append(parts, fmt.Sprintf("部分失败 %d 条", progress.PartialFailedCount))
+ }
+
+ return strings.Join(parts, " / ")
+}
+
const (
faqImportProgressKeyPrefix = "faq_import_progress:"
faqImportRunningKeyPrefix = "faq_import_running:"
@@ -1966,11 +2611,19 @@ func (s *knowledgeService) GetFAQImportProgress(ctx context.Context, taskID stri
knowledge, err := s.repo.GetKnowledgeByID(ctx, tenantID, progress.KnowledgeID)
if err == nil && knowledge != nil {
if result, err := knowledge.GetLastFAQImportResult(); err == nil && result != nil {
+ progress.SuccessCount = result.SuccessCount
+ progress.FailedCount = result.FailedCount
+ progress.PartialFailedCount = result.PartialFailedCount
progress.SkippedCount = result.SkippedCount
+ progress.MergedCount = result.MergedCount
+ progress.AddedCount = result.AddedCount
progress.ImportMode = result.ImportMode
progress.ImportedAt = result.ImportedAt
progress.DisplayStatus = result.DisplayStatus
progress.ProcessingTime = result.ProcessingTime
+ if result.FailedEntriesURL != "" {
+ progress.FailedEntriesURL = result.FailedEntriesURL
+ }
}
}
}
diff --git a/internal/types/faq.go b/internal/types/faq.go
index b260406e5..900466097 100644
--- a/internal/types/faq.go
+++ b/internal/types/faq.go
@@ -284,6 +284,7 @@ type FAQBatchUpsertPayload struct {
type FAQFailedEntry struct {
Index int `json:"index"` // 条目在批次中的索引(从0开始)
Reason string `json:"reason"` // 失败原因
+ FailureType string `json:"failure_type,omitempty"` // 失败类型:pre_validation / post_validation
IsPartialFailure bool `json:"is_partial_failure,omitempty"` // 是否为部分失败(相似问/反例被移除,但整条仍可导入)
TagName string `json:"tag_name,omitempty"` // 分类
StandardQuestion string `json:"standard_question"` // 标准问题
@@ -297,6 +298,15 @@ type FAQFailedEntry struct {
RemovedNegativeQuestions []string `json:"removed_negative_questions,omitempty"` // 被移除的反例及原因
}
+// FAQMergeDetail 表示一条 FAQ 在 append 模式下与已有 chunk 合并的结果摘要。
+type FAQMergeDetail struct {
+ Index int `json:"index"` // 行号(在批次中的索引)
+ StandardQuestion string `json:"standard_question"` // 标准问
+ AnswerChanged bool `json:"answer_changed"` // 答案是否变更
+ NewSimilarCount int `json:"new_similar_count"` // 新增相似问数量
+ NewNegativeCount int `json:"new_negative_count"` // 新增反例数量
+}
+
// FAQSuccessEntry 表示导入成功的条目简单信息
type FAQSuccessEntry struct {
Index int `json:"index"` // 条目在批次中的索引(从0开始)
@@ -381,6 +391,10 @@ type FAQImportProgress struct {
FailedEntriesURL string `json:"failed_entries_url,omitempty"` // 失败条目CSV下载URL(大量时返回URL)
SuccessEntries []FAQSuccessEntry `json:"success_entries,omitempty"` // 成功条目简单信息(少量时直接返回)
ValidEntryIndices []int `json:"valid_entry_indices,omitempty"` // 验证通过的条目索引(用于重试时跳过验证)
+ MergeEntryIndices []int `json:"merge_entry_indices,omitempty"` // 需要合并的条目索引(内部使用,用于重试时跳过识别)
+ MergedCount int `json:"merged_count,omitempty"` // 合并更新的条目数
+ AddedCount int `json:"added_count,omitempty"` // 新增的条目数
+ MergeDetails []FAQMergeDetail `json:"merge_details,omitempty"` // 合并详情
Message string `json:"message"` // Status message
Error string `json:"error"` // Error message if failed
CreatedAt int64 `json:"created_at"` // Task creation timestamp
@@ -411,6 +425,8 @@ type FAQImportResult struct {
FailedCount int `json:"failed_count"` // 完全失败的条目数
PartialFailedCount int `json:"partial_failed_count"` // 部分失败的条目数(相似问/反例被移除但已导入)
SkippedCount int `json:"skipped_count"` // 跳过的条目数(如重复等)
+ MergedCount int `json:"merged_count"` // 合并更新的条目数
+ AddedCount int `json:"added_count"` // 新增的条目数
// 导入模式和时间信息
ImportMode string `json:"import_mode"` // 导入模式:append 或 replace
diff --git a/internal/types/interfaces/chunk.go b/internal/types/interfaces/chunk.go
index dd0e00cd4..1e62f5e30 100644
--- a/internal/types/interfaces/chunk.go
+++ b/internal/types/interfaces/chunk.go
@@ -56,6 +56,8 @@ type ChunkRepository interface {
UpdateChunk(ctx context.Context, chunk *types.Chunk) error
// UpdateChunks updates chunks in batch
UpdateChunks(ctx context.Context, chunks []*types.Chunk) error
+ // SaveChunks persists full chunk objects in a single transaction using GORM Save (UPDATE).
+ SaveChunks(ctx context.Context, chunks []*types.Chunk) error
// DeleteChunk deletes a chunk
DeleteChunk(ctx context.Context, tenantID uint64, id string) error
// DeleteChunks deletes chunks by IDs in batch