Files
zyt/identity-admin/.test-runtime/kf-batch-inline-20261105/frontend/frontend.patch
T
2026-11-11 14:22:02 +08:00

554 lines
35 KiB
Diff

--- 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<KnowledgeItem[]>([]);
const problems = ref<Record<string, string>>({});
+const editableIds = ref(new Set<string>());
+const draft = ref<KnowledgeItem | null>(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 @@
</script>
<template>
- <Modal :open="open" :title="title" width="960px" :closable="!running" :keyboard="!running" :mask-closable="false" @cancel="emit('update:open', false)">
+ <Modal :open="open" :title="title" width="960px" :closable="!running && !saving" :keyboard="!running && !saving" :mask-closable="false" @cancel="emit('update:open', false)">
<Alert v-if="executionActive && !running" class="mb-3" type="info" :message="t('等待进行中的操作完成后停止')" />
<Spin :spinning="loading">
- <Alert class="mb-4" show-icon type="info" :message="['approve', 'approve_publish'].includes(action) ? t('请核对所选知识的来源、事实、脱敏和适用条件。点击下方确认按钮后执行,可展开查看详情;不符合条件的条目会跳过。') : t('每条知识分别校验版本和当前状态。操作结果逐条显示,失败条目不会自动重试。')" />
+ <Alert class="mb-4" show-icon type="info" :message="reviewing ? t('请核对所选知识的来源、事实、脱敏和适用条件。点击下方确认按钮后执行,可展开查看详情;不符合条件的条目会跳过。') : t('每条知识分别校验版本和当前状态。操作结果逐条显示,失败条目不会自动重试。')" />
<Alert v-if="action === 'delete'" class="mb-4" type="warning" show-icon :message="t('仅删除已驳回知识及其来源快照和版本记录;原始聊天归档保留。删除后无法恢复,请确认所选条目。')" />
<Alert v-if="action === 'approve'" class="mb-3" type="info" :message="t('审核通过后进入待发布,发布后才可检索。')" />
<p v-if="!loading">{{ t('可操作 {ready} 条 · 需先处理 {blocked} 条', { ready: ready.length, blocked: Object.keys(problems).length }) }}</p>
+ <Alert v-if="draft" class="mb-3" type="info" :message="t('请保存草稿或取消编辑,再继续批量审核。')" />
<div v-if="results" class="mb-4 rounded border p-3">
<Progress :percent="results.length ? Math.round(completed * 100 / results.length) : 0" :status="running ? 'active' : undefined" />
<p>{{ t('成功 {success} · 失败 {failed} · 未执行 {pending}', { success: results.filter((row) => row.status === 'success').length, failed: results.filter((row) => row.status === 'failed').length, pending: results.filter((row) => row.status === 'pending').length }) }}</p>
@@ -103,16 +171,33 @@
<Alert v-if="problems[item.id]" :message="problems[item.id]" type="warning" class="mb-3" />
<div class="grid gap-4 md:grid-cols-2">
<div><h4 class="mb-2 font-semibold">{{ t('来源对话(已自动脱敏)') }}</h4><div v-for="source in item.sources" :key="source.message_id" class="mb-2 rounded border p-2"><span class="text-xs text-gray-500">{{ source.role === 'staff' ? t('客服') : t('客户') }} · {{ source.sent_at }}</span><p class="whitespace-pre-wrap break-words">{{ source.content }}</p></div></div>
- <div><p class="whitespace-pre-wrap">{{ t('问题:{question}', { question: item.question }) }}</p><p class="whitespace-pre-wrap">{{ t('答案:{answer}', { answer: item.answer }) }}</p><p class="whitespace-pre-wrap">{{ t('适用条件:{conditions}', { conditions: item.conditions || t('尚未填写') }) }}</p><Alert v-for="flag in item.flags" :key="flag" :message="t(flag)" type="warning" class="mb-2" /><p v-if="item.valid_until">{{ t('有效期:{date}', { date: item.valid_until }) }}</p></div>
+ <div>
+ <template v-if="draft && draft.id === item.id">
+ <Space class="mb-3">
+ <Button type="primary" :loading="saving" @click="saveDraft">{{ t('保存草稿') }}</Button>
+ <Button :disabled="saving" @click="cancelEdit">{{ t('取消编辑') }}</Button>
+ </Space>
+ <Alert v-if="editorError" class="mb-3" type="error" show-icon :message="editorError" />
+ <KnowledgeItemFields v-model="draft" :disabled="saving" focus-conditions />
+ </template>
+ <template v-else>
+ <Button v-if="canEditRow(item)" class="mb-2" :disabled="!!draft || saving" @click="beginEdit(item)">{{ t('编辑草稿') }}</Button>
+ <p class="whitespace-pre-wrap">{{ t('问题:{question}', { question: item.question }) }}</p>
+ <p class="whitespace-pre-wrap">{{ t('答案:{answer}', { answer: item.answer }) }}</p>
+ <p class="whitespace-pre-wrap">{{ t('适用条件:{conditions}', { conditions: item.conditions || t('尚未填写') }) }}</p>
+ <p v-if="item.valid_until">{{ t('有效期:{date}', { date: item.valid_until }) }}</p>
+ </template>
+ <Alert v-for="flag in item.flags" :key="flag" :message="t(flag)" type="warning" class="mb-2" />
+ </div>
</div>
- <Button type="link" :disabled="running" @click="emit('edit', item.id)">{{ t('打开单条审核与编辑') }}</Button>
+ <Button v-if="!reviewing" type="link" :disabled="running" @click="emit('edit', item.id)">{{ t('打开单条审核与编辑') }}</Button>
</Collapse.Panel>
</Collapse>
</Spin>
<template #footer><Space>
<Button v-if="running" :disabled="stopRequested" @click="stopRequested = true">{{ stopRequested ? t('等待进行中的操作完成后停止') : t('停止后续操作') }}</Button>
- <Button v-else @click="emit('update:open', false)">{{ results ? t('完成') : t('取消') }}</Button>
- <Button v-if="!results" :danger="action === 'delete'" type="primary" :disabled="loading || executionActive || !ready.length || !canExecute" @click="start">{{ confirmText }}</Button>
+ <Button v-else :disabled="saving" @click="emit('update:open', false)">{{ results ? t('完成') : t('取消') }}</Button>
+ <Button v-if="!results" :danger="action === 'delete'" type="primary" :disabled="!canStart" @click="start">{{ confirmText }}</Button>
</Space></template>
</Modal>
</template>
--- 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<HTMLTextAreaElement>('textarea[autofocus]')!;
+ conditions.value = 'Only for existing customers';
+ conditions.dispatchEvent(new Event('input'));
+ await state.start();
+ expect(api.knowledgeItemAction).not.toHaveBeenCalled();
+
+ const gate = deferred<KnowledgeItem>(); 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<KnowledgeItem>(); 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<string, string> = {};
+ const editableIds = new Set<string>();
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<string, string> = { draft: 'orange', approved: 'blue', published: 'green', rejected: 'red', stale: 'red', completed: 'green', failed: 'red', running: 'blue' };
const modes = computed<Record<string, string>>(() => ({ 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 @@
<KnowledgeRunDialog :key="'create-' + scopeVersion" v-model:open="createOpen" :account-id="accountId" :can-watch="canWatch" :allowed-account-ids="allowedAccountIds" @created="created" />
<KnowledgeSettingsDialog v-model:open="settingsOpen" />
<KnowledgeReviewAll :key="'review-' + scopeVersion" v-model:open="reviewOpen" :account-id="accountId" :initial-tab="reviewTab" :own-scope="ownScope" :allowed-account-ids="allowedAccountIds" @changed="load" @inspect="inspectReviewed" />
- <KnowledgeBatchDialog :key="'batch-' + scopeVersion" v-model:open="batchOpen" :account-id="accountId" :entries="batchEntries" :action="batchAction" :can-execute="batchPermission" @finished="batchFinished" @edit="(id) => { batchOpen = false; inspect(id); }" />
+ <KnowledgeBatchDialog :key="'batch-' + scopeVersion" v-model:open="batchOpen" :account-id="accountId" :entries="batchEntries" :action="batchAction" :can-execute="batchPermission" :can-edit="canEdit" @saved="load" @finished="batchFinished" @edit="(id) => { batchOpen = false; inspect(id); }" />
<Modal v-model:open="editorOpen" :title="t('知识审核与来源')" width="1100px" :footer="null" :destroy-on-close="true">
<template v-if="selected">
@@ -432,14 +434,7 @@
<p class="m-0 whitespace-pre-wrap break-words">{{ source.content }}</p>
</div>
</div>
- <Form layout="vertical">
- <Form.Item :label="t('标题')"><Input v-model:value="selected.title" :maxlength="160" :disabled="!canEdit || busy" /></Form.Item>
- <Space><Form.Item :label="t('类型')"><Select v-model:value="selected.kind" :options="kindOptions" :disabled="!canEdit || busy" style="width: 140px" /></Form.Item><Form.Item :label="t('分类')"><Input v-model:value="selected.category" :disabled="!canEdit || busy" /></Form.Item></Space>
- <Form.Item :label="t('完整问题')"><Input.TextArea v-model:value="selected.question" :rows="3" :maxlength="4000" :disabled="!canEdit || busy" /></Form.Item>
- <Form.Item :label="t('标准答案 / 步骤')"><Input.TextArea v-model:value="selected.answer" :rows="7" :maxlength="8000" :disabled="!canEdit || busy" /></Form.Item>
- <Form.Item :label="t('适用条件(必填)')"><Input.TextArea v-model:value="selected.conditions" :rows="3" :maxlength="2000" :disabled="!canEdit || busy" /></Form.Item>
- <Form.Item :label="t('有效期截止日期(可选)')"><Input v-model:value="selected.valid_until" type="date" :disabled="!canEdit || busy" /></Form.Item>
- </Form>
+ <KnowledgeItemFields v-model="selected" :disabled="!canEdit || busy" />
</div>
<Alert v-if="editorError" class="my-3" type="error" show-icon :message="editorError" />
<Alert v-if="dirty" class="my-3" type="info" :message="t('审核操作会先保存修改,再按保存后的版本执行;失败时不会自动重试。')" />
--- a/apps/web-antd/src/views/knowledge/own-scope.test.ts
+++ b/apps/web-antd/src/views/knowledge/own-scope.test.ts
@@ -270,6 +270,24 @@
expect(state.canApprovePublish).toBe(false); expect(state.batchAllowed('approve_publish')).toBe(false);
});
+ it('opens an entirely incomplete batch for editors and keeps its selection during list refresh', async () => {
+ accessCodes.value.push('knowledge:publish');
+ api.fetchKnowledgeItems.mockResolvedValue({ items: [{ ...item('draft'), conditions: '' }], total: 1 });
+ const { state } = mount(); await settle();
+ state.selectedKeys = ['draft'];
+ expect(state.batchAllowed('approve')).toBe(false);
+ expect(state.batchAllowed('approve_publish')).toBe(false);
+ accessCodes.value.push('knowledge:write');
+ expect(state.batchAllowed('approve')).toBe(true);
+ state.openBatch('approve_publish');
+ expect(state.batchOpen).toBe(true);
+ const entries = state.batchEntries;
+ api.fetchKnowledgeItems.mockResolvedValue({ items: [{ ...item('draft'), revision: 2 }], total: 1 });
+ await state.load();
+ expect(state.batchEntries).toBe(entries); expect(state.selectedKeys).toEqual(['draft']);
+ expect(state.batchOpen).toBe(true);
+ });
+
it('does not retry a failed action or resave changes already saved', async () => {
accessCodes.value.push('knowledge:publish', 'knowledge:write');
const { state } = mount(); await settle(); await state.inspect('other-knowledge'); state.selected.answer = 'edited';
--- /dev/null
+++ b/apps/web-antd/src/views/knowledge/item-fields.vue
@@ -0,0 +1,44 @@
+<script setup lang="ts">
+import type { KnowledgeItem } from '#/api/knowledge';
+
+import { computed } from 'vue';
+import { Form, Input, Select, Space } from 'ant-design-vue';
+
+import { t } from '#/locales/t';
+
+defineProps<{ disabled: boolean; focusConditions?: boolean }>();
+const item = defineModel<KnowledgeItem>({ required: true });
+const kindOptions = computed(() => [
+ { value: 'qa', label: t('标准问答') },
+ { value: 'procedure', label: t('业务流程') },
+ { value: 'case', label: t('对话案例') },
+]);
+</script>
+
+<template>
+ <Form layout="vertical">
+ <Form.Item :label="t('标题')">
+ <Input v-model:value="item.title" :maxlength="160" :disabled="disabled" />
+ </Form.Item>
+ <Space>
+ <Form.Item :label="t('类型')">
+ <Select v-model:value="item.kind" :options="kindOptions" :disabled="disabled" style="width: 140px" />
+ </Form.Item>
+ <Form.Item :label="t('分类')">
+ <Input v-model:value="item.category" :disabled="disabled" />
+ </Form.Item>
+ </Space>
+ <Form.Item :label="t('完整问题')">
+ <Input.TextArea v-model:value="item.question" :rows="3" :maxlength="4000" :disabled="disabled" />
+ </Form.Item>
+ <Form.Item :label="t('标准答案 / 步骤')">
+ <Input.TextArea v-model:value="item.answer" :rows="7" :maxlength="8000" :disabled="disabled" />
+ </Form.Item>
+ <Form.Item :label="t('适用条件(必填)')">
+ <Input.TextArea v-model:value="item.conditions" :rows="3" :maxlength="2000" :disabled="disabled" :autofocus="focusConditions" />
+ </Form.Item>
+ <Form.Item :label="t('有效期截止日期(可选)')">
+ <Input v-model:value="item.valid_until" type="date" :disabled="disabled" />
+ </Form.Item>
+ </Form>
+</template>
--- a/apps/web-antd/src/locales/en/knowledge.ts
+++ b/apps/web-antd/src/locales/en/knowledge.ts
@@ -336,6 +336,9 @@
'有效期:{date}': 'Valid until: {date}',
'已核对本条来源、事实、脱敏和适用条件;涉及医疗内容已完成专业审核。': 'I have checked the source, facts, redaction and conditions of this item; any medical content has passed professional review.',
'打开单条审核与编辑': 'Open to review and edit',
+ '编辑草稿': 'Edit draft',
+ '取消编辑': 'Cancel editing',
+ '请保存草稿或取消编辑,再继续批量审核。': 'Save the draft or cancel editing before continuing the batch review.',
'当前操作完成后停止': 'Stopping after the current item',
'停止后续操作': 'Stop the rest',
'完成': 'Done',