--- a/apps/web-antd/src/views/knowledge/batch-dialog.vue +++ b/apps/web-antd/src/views/knowledge/batch-dialog.vue @@ -3,14 +3,19 @@ import type { BatchAction, BatchResult } from './batch'; import { computed, onActivated, onBeforeUnmount, onDeactivated, ref, watch } from 'vue'; import { Alert, Button, Collapse, Modal, Progress, Space, Spin, Tag } from 'ant-design-vue'; -import { fetchKnowledgeItem, knowledgeItemAction } from '#/api/knowledge'; +import { fetchKnowledgeItem, knowledgeItemAction, saveKnowledgeItem } from '#/api/knowledge'; import { t } from '#/locales/t'; -import { prepareKnowledgeBatch, runKnowledgeBatch, uniqueKnowledgeItems } from './batch'; - -const props = defineProps<{ open: boolean; accountId: number; entries: KnowledgeItem[]; action: BatchAction; canExecute: boolean }>(); -const emit = defineEmits<{ 'update:open': [value: boolean]; finished: []; edit: [id: string] }>(); +import { actionProblem, failureText, isReviewAction, prepareKnowledgeBatch, runKnowledgeBatch, uniqueKnowledgeItems } from './batch'; +import KnowledgeItemFields from './item-fields.vue'; + +const props = defineProps<{ open: boolean; accountId: number; entries: KnowledgeItem[]; action: BatchAction; canExecute: boolean; canEdit: boolean }>(); +const emit = defineEmits<{ 'update:open': [value: boolean]; finished: []; saved: []; edit: [id: string] }>(); const details = ref([]); const problems = ref>({}); +const editableIds = ref(new Set()); +const draft = ref(null); +const editorError = ref(''); +const saving = ref(false); const loading = ref(false); const running = ref(false); // This lock survives dialog invalidation until every already-sent mutation settles. @@ -24,10 +29,15 @@ stopRequested.value = true; generation++; running.value = false; loading.value = false; results.value = null; details.value = []; problems.value = {}; + editableIds.value.clear(); draft.value = null; editorError.value = ''; } onBeforeUnmount(() => { viewActive = false; stop(); }); onDeactivated(() => { viewActive = false; stop(); emit('update:open', false); }); const ready = computed(() => details.value.filter((item) => !problems.value[item.id])); +const reviewing = computed(() => isReviewAction(props.action)); +const canEditBatch = computed(() => reviewing.value && props.canExecute && props.canEdit); +const canStart = computed(() => props.open && props.canExecute && !loading.value && !executionActive.value + && !draft.value && !saving.value && !results.value && ready.value.length > 0); const completed = computed(() => results.value?.filter((row) => row.status !== 'pending').length || 0); // 标题和确认按钮按操作分别写整句,英文语序才自然 const title = computed(() => { @@ -50,21 +60,78 @@ async function loadDetails() { stop(); const current = generation; - if (!viewActive || !props.open || executionActive.value) return; + if (!viewActive || !props.open || executionActive.value || saving.value) return; loading.value = true; const account = props.accountId; const prepared = await prepareKnowledgeBatch(props.entries.map((item) => ({ ...item })), props.action, (entry) => fetchKnowledgeItem(account, entry.id), () => current !== generation); if (current !== generation) return; - details.value = prepared.details; problems.value = prepared.problems; loading.value = false; + details.value = prepared.details; problems.value = prepared.problems; editableIds.value = prepared.editableIds; + loading.value = false; } watch(() => [props.open, props.accountId, props.action, props.entries], loadDetails, { immediate: true }); -onActivated(() => { viewActive = true; if (props.open && !loading.value && !executionActive.value && !details.value.length && !results.value) void loadDetails(); }); -watch(executionActive, (active) => { - if (!active && viewActive && props.open && !running.value && !results.value) void loadDetails(); -}); +onActivated(() => { + viewActive = true; + if (props.open && !loading.value && !executionActive.value && !saving.value && !details.value.length && !results.value) void loadDetails(); +}); +watch([executionActive, saving], ([executing, savingDraft]) => { + if (!executing && !savingDraft && viewActive && props.open && !loading.value && !details.value.length && !results.value) void loadDetails(); +}); + +function canEditRow(item: KnowledgeItem) { + return canEditBatch.value && !loading.value && !executionActive.value && !results.value + && editableIds.value.has(item.id) && item.status === 'draft'; +} +function beginEdit(item: KnowledgeItem) { + if (!viewActive || !props.open || saving.value || draft.value || !canEditRow(item)) return; + draft.value = { ...item }; +} +function cancelEdit() { + if (saving.value) return; + draft.value = null; + editorError.value = ''; +} +watch(canEditBatch, (allowed) => { + if (!allowed && draft.value) { + // Reload before any further batch action if an invalidated save may have changed a revision. + if (saving.value) void loadDetails(); + else cancelEdit(); + } +}); +async function saveDraft() { + const item = draft.value; + if (!viewActive || !props.open || saving.value || !item || !canEditRow(item)) return; + const current = generation; + const account = props.accountId; + const action = props.action; + const isCurrent = () => current === generation && viewActive && props.open && canEditBatch.value + && props.accountId === account && props.action === action && draft.value === item; + saving.value = true; + editorError.value = ''; + try { + const saved = await saveKnowledgeItem(account, { ...item }); + if (!isCurrent()) return; + if (saved.id !== item.id || saved.revision <= item.revision) { + editorError.value = failureText(null); + return; + } + details.value = details.value.map((entry) => entry.id === item.id + ? { ...saved, account_id: entry.account_id, account_label: entry.account_label } + : entry); + const problem = actionProblem(saved, action); + if (problem) problems.value[item.id] = problem; + else delete problems.value[item.id]; + draft.value = null; + emit('saved'); + } catch (error) { + if (isCurrent()) editorError.value = failureText(error); + } finally { + saving.value = false; + } +} + async function start() { - if (!viewActive || !props.open || loading.value || executionActive.value || !props.canExecute || !ready.value.length) return; + if (!viewActive || !canStart.value) return; const current = generation; const token = ++executionToken; const account = props.accountId; @@ -74,7 +141,7 @@ results.value = work.map((item) => ({ id: item.id, title: item.title, status: 'pending', error: '' })); try { const finished = await runKnowledgeBatch(work, - (item) => knowledgeItemAction(account, item, action, ['delete', 'approve', 'approve_publish'].includes(action)), + (item) => knowledgeItemAction(account, item, action, action === 'delete' || isReviewAction(action)), (value) => { if (current === generation) results.value = value; }, () => stopRequested.value || current !== generation || !props.canExecute); if (current === generation) results.value = finished; } finally { @@ -85,13 +152,14 @@ --- a/apps/web-antd/src/views/knowledge/batch-dialog.test.ts +++ b/apps/web-antd/src/views/knowledge/batch-dialog.test.ts @@ -1,19 +1,28 @@ import type { KnowledgeItem } from '#/api/knowledge'; +import type { BatchAction } from './batch'; import { createApp, defineComponent, h, KeepAlive, nextTick, ref } from 'vue'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -const api = vi.hoisted(() => ({ fetchKnowledgeItem: vi.fn(), knowledgeItemAction: vi.fn() })); +const api = vi.hoisted(() => ({ fetchKnowledgeItem: vi.fn(), knowledgeItemAction: vi.fn(), saveKnowledgeItem: vi.fn() })); vi.mock('#/api/knowledge', () => api); vi.mock('#/locales/t', () => ({ t: (value: string) => value })); vi.mock('ant-design-vue', async () => { const { defineComponent, h } = await import('vue'); const plain = defineComponent({ setup: (_props, { slots }) => () => h('div', [slots.header?.(), slots.default?.()]) }); + const textarea = defineComponent({ + props: ['value', 'autofocus', 'disabled'], + emits: ['update:value'], + setup: (props, { emit }) => () => h('textarea', { + ...props, onInput: (event: Event) => emit('update:value', (event.target as HTMLTextAreaElement).value), + }), + }); return { Alert: defineComponent({ props: ['message'], setup: (props) => () => h('p', props.message) }), Modal: defineComponent({ props: ['open'], setup: (props, { slots }) => () => props.open ? h('section', [slots.default?.(), slots.footer?.()]) : null }), Button: defineComponent({ props: ['disabled'], setup: (props, { slots }) => () => h('button', { disabled: props.disabled }, slots.default?.()) }), Collapse: Object.assign({}, plain, { Panel: plain }), Progress: plain, Space: plain, Spin: plain, Tag: plain, + Form: Object.assign({}, plain, { Item: plain }), Input: Object.assign({}, plain, { TextArea: textarea }), Select: plain, }; }); @@ -29,17 +38,23 @@ return { promise, resolve }; } let cleanup: (() => void) | undefined; -function mount(entries: KnowledgeItem[]) { +function mount(entries: KnowledgeItem[], action: BatchAction = 'approve', editAllowed = false) { const open = ref(true); const visible = ref(true); const selection = ref(entries); const child = ref(); - const finished = vi.fn(); const closed = vi.fn(); + const canEdit = ref(editAllowed); + const finished = vi.fn(); const closed = vi.fn(); const saved = vi.fn(); const host = document.createElement('div'); document.body.append(host); const app = createApp(defineComponent({ setup: () => () => h(KeepAlive, null, { default: () => visible.value ? h(KnowledgeBatchDialog, { ref: child, open: open.value, entries: selection.value, - accountId: -1, action: 'approve', canExecute: true, - 'onUpdate:open': (value: boolean) => { open.value = value; closed(value); }, onFinished: finished }) : null, + accountId: -1, action, canExecute: true, canEdit: canEdit.value, + 'onUpdate:open': (value: boolean) => { open.value = value; closed(value); }, onFinished: finished, onSaved: saved }) : null, }) })); app.mount(host); cleanup = () => { app.unmount(); host.remove(); }; - return { open, visible, selection, child, finished, closed, host }; + return { open, visible, selection, child, canEdit, finished, closed, saved, host }; +} +function button(host: HTMLElement, label: string) { + const match = [...host.querySelectorAll('button')].find((element) => element.textContent === label); + if (!match) throw new Error(`Missing button: ${label}`); + return match; } describe('knowledge batch dialog lifecycle', () => { @@ -49,6 +64,95 @@ api.knowledgeItemAction.mockImplementation(async (_account, entry) => ({ ...entry, status: 'approved', revision: 2 })); }); afterEach(() => { cleanup?.(); cleanup = undefined; }); + + it.each([ + ['approve', '确认审核通过 {count} 条'], + ['approve_publish', '确认审核并发布 {count} 条'], + ] as const)('saves inside %s and approves only the returned revision', async (action, confirmLabel) => { + const missing = { ...item('needs-conditions'), conditions: '', account_id: 10, account_label: 'Client 10', + sources: [{ message_id: 'source', role: 'staff', sent_at: '', version_no: 1, content: 'source evidence' }] }; + api.fetchKnowledgeItem.mockResolvedValueOnce(missing); + const ui = mount([missing, item('other')], action, true); await settle(); + const state = ui.child.value.$.setupState; + const untouched = state.details[1]; + expect(state.ready).toEqual([untouched]); + button(ui.host, '编辑草稿').click(); await settle(); + expect(ui.host.textContent).toContain('source evidence'); + expect(button(ui.host, confirmLabel).disabled).toBe(true); + const conditions = ui.host.querySelector('textarea[autofocus]')!; + conditions.value = 'Only for existing customers'; + conditions.dispatchEvent(new Event('input')); + await state.start(); + expect(api.knowledgeItemAction).not.toHaveBeenCalled(); + + const gate = deferred(); api.saveKnowledgeItem.mockReturnValueOnce(gate.promise); + button(ui.host, '保存草稿').click(); await settle(); + expect(api.saveKnowledgeItem).toHaveBeenCalledWith(-1, expect.objectContaining({ + id: missing.id, conditions: 'Only for existing customers', revision: 1, + })); + expect(state.details[0].conditions).toBe(''); + await state.start(); expect(api.knowledgeItemAction).not.toHaveBeenCalled(); + expect(button(ui.host, confirmLabel).disabled).toBe(true); + gate.resolve({ ...missing, title: 'Saved title', conditions: 'Redacted conditions', revision: 2, + account_id: undefined, account_label: undefined }); + await settle(); + expect(state.ready).toHaveLength(2); expect(state.details[1]).toBe(untouched); + expect(ui.host.textContent).toContain('Saved title · v2'); + expect(state.details[0]).toMatchObject({ account_id: 10, account_label: 'Client 10' }); + expect(ui.open.value).toBe(true); expect(ui.selection.value[0]?.revision).toBe(1); + expect(ui.saved).toHaveBeenCalledTimes(1); expect(api.fetchKnowledgeItem).toHaveBeenCalledTimes(2); + expect(api.knowledgeItemAction).not.toHaveBeenCalled(); + button(ui.host, confirmLabel).click(); await settle(); + expect(api.knowledgeItemAction.mock.calls).toMatchObject([ + [-1, { id: missing.id, revision: 2, conditions: 'Redacted conditions' }, action, true], + [-1, { id: 'other', revision: 1 }, action, true], + ]); + }); + + it('keeps failed draft edits local and only allows batch confirmation after canceling them', async () => { + const ui = mount([item('a')], 'approve', true); await settle(); + const state = ui.child.value.$.setupState; + button(ui.host, '编辑草稿').click(); state.draft.conditions = 'unsaved'; + api.saveKnowledgeItem.mockRejectedValueOnce({ response: { data: { detail: '保存未完成' } } }); + await state.saveDraft(); await settle(); + expect(ui.host.textContent).toContain('保存未完成'); expect(state.draft.conditions).toBe('unsaved'); + expect(state.details[0]).toMatchObject({ conditions: 'condition', revision: 1 }); + expect(ui.saved).not.toHaveBeenCalled(); + await state.start(); expect(api.knowledgeItemAction).not.toHaveBeenCalled(); + button(ui.host, '取消编辑').click(); await settle(); + expect(ui.host.textContent).not.toContain('保存未完成'); + expect(button(ui.host, '确认审核通过 {count} 条').disabled).toBe(false); + }); + + it('rejects stale, failed and non-draft rows and discards a pending save after edit permission is revoked', async () => { + let editable = item('editable'); + api.fetchKnowledgeItem.mockImplementation(async (_account, id: string) => { + if (id === 'failed') throw new Error('fetch failed'); + if (id === 'stale') return { ...item(id), revision: 2 }; + if (id === 'approved') return { ...item(id), status: 'approved' }; + return editable; + }); + const ui = mount(['stale', 'failed', 'approved', 'editable'].map(item)); await settle(); + const state = ui.child.value.$.setupState; + expect(ui.host.textContent).not.toContain('编辑草稿'); + ui.canEdit.value = true; await settle(); + for (const entry of state.details.slice(0, 3)) state.beginEdit(entry); + expect(state.draft).toBeNull(); + button(ui.host, '编辑草稿').click(); + const gate = deferred(); api.saveKnowledgeItem.mockReturnValueOnce(gate.promise); + const pending = state.saveDraft(); + ui.canEdit.value = false; await settle(); + expect(state.draft).toBeNull(); expect(state.details).toEqual([]); + ui.canEdit.value = true; await settle(); + await state.start(); expect(api.knowledgeItemAction).not.toHaveBeenCalled(); + editable = { ...editable, revision: 2, title: 'Refreshed details' }; + gate.resolve({ ...editable, title: 'stale save response' }); + await pending; await settle(); + expect(ui.saved).not.toHaveBeenCalled(); expect(api.fetchKnowledgeItem).toHaveBeenCalledTimes(8); + expect(ui.host.textContent).not.toContain('stale save response'); + expect(state.ready).toEqual([]); + expect(state.details[3]).toMatchObject({ id: 'editable', revision: 2, title: 'Refreshed details' }); + }); it('closes on deactivation, drains only in-flight mutations and reopens without stale results or finished events', async () => { const ui = mount([item('a'), item('a'), item('b'), item('c'), item('unscheduled')]); await settle(); --- a/apps/web-antd/src/views/knowledge/batch.ts +++ b/apps/web-antd/src/views/knowledge/batch.ts @@ -5,10 +5,14 @@ export type BatchAction = 'approve' | 'approve_publish' | 'delete' | 'disable' | 'publish' | 'reject'; export interface BatchResult { id: string; title: string; status: 'failed' | 'pending' | 'success'; error: string } +export function isReviewAction(action: BatchAction): boolean { + return action === 'approve' || action === 'approve_publish'; +} + export function actionProblem(item: KnowledgeItem, action: BatchAction): string { const allowed = { delete: ['rejected'], approve: ['draft'], approve_publish: ['draft'], publish: ['approved'], reject: ['draft', 'approved'], disable: ['published'] }; if (!allowed[action].includes(item.status)) return t('当前状态不支持此操作,请刷新或重新选择'); - if (['approve', 'approve_publish'].includes(action) && !item.conditions.trim()) return t('请先编辑并补充适用条件'); + if (isReviewAction(action) && !item.conditions.trim()) return t('请先编辑并补充适用条件'); return ''; } @@ -34,6 +38,7 @@ const selected = uniqueKnowledgeItems(entries); const details = [...selected]; const problems: Record = {}; + const editableIds = new Set(); let next = 0; await Promise.all(Array.from({ length: Math.min(4, selected.length) }, async () => { while (!stopped() && next < selected.length) { @@ -42,17 +47,19 @@ try { const item = await fetch(entry); if (stopped()) return; - details[index] = item; - const problem = item.revision !== entry.revision - ? t('版本已更新,请关闭后重新选择,避免审核旧内容') : actionProblem(item, action); + if (item.id === entry.id) details[index] = item; + const sameVersion = item.id === entry.id && item.revision === entry.revision; + const problem = sameVersion ? actionProblem(item, action) + : t('版本已更新,请关闭后重新选择,避免审核旧内容'); if (problem) problems[entry.id] = problem; + if (sameVersion && isReviewAction(action) && item.status === 'draft') editableIds.add(entry.id); } catch (error) { if (stopped()) return; problems[entry.id] = failureText(error); } } })); - return { details, problems }; + return { details, problems, editableIds }; } /** At most three requests are in flight. Stop leaves unscheduled rows pending; mutations never retry. */ --- a/apps/web-antd/src/views/knowledge/center.vue +++ b/apps/web-antd/src/views/knowledge/center.vue @@ -4,7 +4,7 @@ import { computed, onActivated, onDeactivated, onUnmounted, ref, watch } from 'vue'; import { useAccess } from '@vben/access'; import { downloadFileFromBlob } from '@vben/utils'; -import { Alert, Button, Card, Dropdown, Empty, Form, Input, message, Menu, Modal, Select, Space, Steps, Switch, Table, Tabs, Tag } from 'ant-design-vue'; +import { Alert, Button, Card, Dropdown, Empty, Input, message, Menu, Modal, Select, Space, Steps, Switch, Table, Tabs, Tag } from 'ant-design-vue'; import { ALL_ACCOUNTS } from '#/api/console'; import { requestErrorMessage } from '#/api/error-message'; @@ -15,9 +15,10 @@ import KnowledgeRunsPanel from './runs-panel.vue'; import KnowledgeSettingsDialog from './settings-dialog.vue'; import KnowledgeBatchDialog from './batch-dialog.vue'; +import KnowledgeItemFields from './item-fields.vue'; import KnowledgeReviewAll from './review-all.vue'; import type { BatchAction } from './batch'; -import { actionProblem, failureText } from './batch'; +import { actionProblem, failureText, isReviewAction } from './batch'; import { shortTime } from './run-format'; import { useArchiveLoad } from '#/views/archive/use-archive-load'; @@ -109,7 +110,9 @@ } const batchPermission = computed(() => actionPermission(batchAction.value)); function batchAllowed(action: BatchAction) { - return actionPermission(action) && selectedRows.value.some((item) => !actionProblem(item, action)); + const canCompleteDraft = isReviewAction(action) && canEdit.value; + return actionPermission(action) && selectedRows.value.some((item) => + (canCompleteDraft && item.status === 'draft') || !actionProblem(item, action)); } function openBatch(action: BatchAction) { if (!batchAllowed(action) || busy.value) return; @@ -153,7 +156,6 @@ const colors: Record = { draft: 'orange', approved: 'blue', published: 'green', rejected: 'red', stale: 'red', completed: 'green', failed: 'red', running: 'blue' }; const modes = computed>(() => ({ lexical: t('关键词检索'), hybrid: t('关键词与语义检索'), lexical_fallback: t('语义服务暂不可用,已使用关键词'), unavailable: t('检索暂不可用') })); const statusOptions = computed(() => [{ value: '', label: t('全部状态') }, ...['draft', 'approved', 'published', 'rejected', 'disabled', 'stale'].map((value) => ({ value, label: labels.value[value] }))]); -const kindOptions = computed(() => [{ value: 'qa', label: t('标准问答') }, { value: 'procedure', label: t('业务流程') }, { value: 'case', label: t('对话案例') }]); const sourceOptions = computed(() => (overview.value?.source_accounts || []).map((a) => ({ value: a.id, label: a.display_name || a.external_account_id }))); async function load() { @@ -418,7 +420,7 @@ - +