This commit is contained in:
gr
2026-11-11 14:22:02 +08:00
parent 245618dcdc
commit a62311a8da
64878 changed files with 3747172 additions and 66 deletions
@@ -0,0 +1,386 @@
/**
* views/knowledge/:center.vue、runs-panel.vue、review-all.vue、wash-options.vue、run-dialog.vue、
* run-format.ts、batch-dialog.vue、batch.ts、settings-dialog.vue。
* 「整理」(聊天记录 → 知识)统一译作 processing。
*/
export default {
// ── 知识中心(center.vue) ──────────────────────────────────────────
'知识中心': 'Knowledge',
'本人 ZYT 账号暂无可用客户端。': 'Your ZYT account has no available client accounts.',
'当前仅显示本人 ZYT 账号名下的知识,包含管理员代为清洗的数据;操作仍按角色权限': 'Only knowledge under your ZYT account is shown, including data processed by an administrator on your behalf; actions still follow your role permissions.',
'把历史聊天整理成可追溯的知识,审核发布后供客服回答时参考。': 'Turn chat history into traceable knowledge. Once reviewed and published, it is used as a reference when answering customers.',
'点「整理聊天记录」可一次整理全部账号的聊天;点知识标题可直接查看、审核和发布。': 'Click "Process chat history" to process the chats of all accounts at once; click a knowledge title to view, review and publish it.',
'当前账号尚无聊天归档,请先上传归档或更换账号。': 'This account has no chat archive yet. Upload an archive first or switch accounts.',
'点「整理聊天记录」生成草稿,再逐条核对来源和适用条件。': 'Click "Process chat history" to generate drafts, then check the source and conditions of each one.',
'草稿补全适用条件后审核,通过后发布;也可以勾选列表中的多条知识集中处理。': 'Fill in the conditions of a draft, review it, and publish it once approved. You can also select several items in the list and handle them together.',
'已发布知识可在检索测试中验证;确认结果后开启客服使用知识。': 'Verify published knowledge in Search test; once satisfied, turn on "Use knowledge in replies".',
'整理聊天记录': 'Process chat history',
'生成草稿': 'Generate drafts',
'审核知识': 'Review knowledge',
'发布并测试使用': 'Publish and test',
'支持语义与关键词检索': 'Semantic and keyword search available',
'关键词检索已就绪': 'Keyword search ready',
'客服使用知识': 'Use knowledge in replies',
'整理设置': 'Processing settings',
'导出已发布知识': 'Export published knowledge',
'当前汇总全部授权账号:整理聊天、查看和审核知识都可以直接进行;检索测试、导出和「客服使用知识」开关需选择具体账号。': 'Showing all authorized accounts: you can process chats and view and review knowledge directly. Search test, export and the "Use knowledge in replies" switch need a specific account.',
'知识与审核': 'Knowledge & review',
'搜索标题或问题': 'Search title or question',
'一键审核此账号全部草稿': 'Review all drafts of this account',
'一键审核全部授权账号': 'Review all authorized accounts',
'审核任务与结果': 'Review jobs and results',
'后台审核进行中': 'Background review in progress',
'已选 {count} 条(当前页)': '{count} selected (this page)',
'批量审核': 'Batch review',
'发布选中': 'Publish selected',
'驳回选中': 'Reject selected',
'停用选中': 'Disable selected',
'删除已驳回': 'Delete rejected',
'清空选择': 'Clear selection',
'问题 / 标题': 'Question / title',
'账号': 'Account',
'分类': 'Category',
'版本': 'Version',
'没有符合筛选条件的知识,可调整筛选后重试。': 'No knowledge matches the filters. Adjust them and try again.',
'还没有知识,先从历史聊天整理出待审草稿。': 'No knowledge yet. Start by processing chat history into drafts for review.',
'整理任务': 'Processing jobs',
'新聊天自动整理': 'Auto-process new chats',
'检索测试': 'Search test',
'测试只检索已发布知识,不发送客服消息。相关度是排序参考,不代表事实正确率。': 'The test only searches published knowledge and sends no messages to customers. Relevance is a ranking hint, not a measure of factual accuracy.',
'当前账号暂无已发布知识,请先审核并发布知识后再测试检索。': 'This account has no published knowledge yet. Review and publish knowledge before testing search.',
'输入一个真实业务问题(2–2000 个字符)': 'Enter a real business question (2–2000 characters)',
'检索': 'Search',
'{count} 条命中': '{count} hits',
'当前账号没有已发布知识,审核通过后还需发布才能检索。': 'This account has no published knowledge. Approved knowledge must also be published before it can be searched.',
'没有可靠命中。请补充问题信息,或发布相应知识。': 'No reliable hits. Add more detail to the question, or publish the relevant knowledge.',
'查看来源': 'View source',
'适用条件:{conditions}': 'Conditions: {conditions}',
'版本 {revision}': 'Version {revision}',
'相关度 {score}': 'Relevance {score}',
'引用记录': 'Citation log',
'时间': 'Time',
'问题': 'Question',
'知识来源': 'Knowledge sources',
'检索方式': 'Search mode',
'耗时 ms': 'Time (ms)',
'无命中': 'No hits',
'知识审核与来源': 'Knowledge review and sources',
'账号:{account}': 'Account: {account}',
'来源对话(已自动脱敏)': 'Source conversation (auto-redacted)',
'暂无可查看的来源,请检查正文查看权限': 'No viewable sources. Check your permission to view message content',
'客服': 'Agent',
'客户': 'Customer',
'标题': 'Title',
'类型': 'Type',
'完整问题': 'Full question',
'标准答案 / 步骤': 'Standard answer / steps',
'适用条件(必填)': 'Conditions (required)',
'有效期截止日期(可选)': 'Valid until (optional)',
'修改尚未保存。请先保存草稿,再审核或发布。': 'Changes are not saved. Save the draft before reviewing or publishing.',
'已核对客服身份、事实、适用条件和脱敏;内容可作为通用经验。涉及医疗内容已完成专业审核。': 'I have checked the agent identity, facts, conditions and redaction, and the content is usable as general guidance. Any medical content has passed professional review.',
'保存草稿': 'Save draft',
'审核通过': 'Approve',
'驳回': 'Reject',
'发布到知识库': 'Publish to knowledge base',
'删除已驳回知识': 'Delete rejected knowledge',
'停用': 'Disable',
'版本与操作记录': 'Versions and activity',
'恢复为草稿': 'Restore as draft',
// 知识状态、检索方式、类型
'待审核': 'Pending review',
'待发布': 'Ready to publish',
'已发布': 'Published',
'已驳回': 'Rejected',
'来源已变化': 'Source changed',
'等待处理': 'Waiting',
'处理中': 'Processing',
'已暂停': 'Paused',
'已完成': 'Completed',
'失败': 'Failed',
'已取消': 'Cancelled',
'关键词检索': 'Keyword search',
'关键词与语义检索': 'Keyword and semantic search',
'语义服务暂不可用,已使用关键词': 'Semantic service unavailable; keyword search used',
'检索暂不可用': 'Search temporarily unavailable',
'全部状态': 'All statuses',
'标准问答': 'Standard Q&A',
'业务流程': 'Business procedure',
'对话案例': 'Conversation example',
// 提示与确认
'已保存为草稿,需要重新审核后发布': 'Saved as a draft; it must be reviewed again before publishing',
'已恢复为草稿,请审核后重新发布': 'Restored as a draft; review it and publish it again',
'删除这条已驳回知识?': 'Delete this rejected knowledge item?',
'将删除知识及其来源快照和版本记录,原始聊天归档保留。删除后无法恢复。': 'The knowledge item, its source snapshots and version history will be deleted; the original chat archive is kept. This cannot be undone.',
'确认删除': 'Delete',
'请先选择具体账号': 'Select a specific account first',
'请输入至少 2 个字符的检索问题': 'Enter a search question of at least 2 characters',
'检索问题不能超过 2000 个字符': 'The search question cannot exceed 2000 characters',
'检索失败,请稍后重试': 'Search failed. Please try again later',
// ── 后端原样返回、页面上用 t(值) 翻译的固定文案 ─────────────────────
'旧版未归属数据': 'Legacy unassigned data',
'待分类': 'Uncategorized',
'全部账号': 'All accounts',
'全部授权账号': 'All authorized accounts',
'{count} 个账号': '{count} accounts',
'全部客服来源({count} 个)': 'All agent sources ({count})',
'模型清洗': 'Model cleaning',
'规则提取': 'Rule extraction',
'历史任务': 'Earlier job',
'模型整理': 'Model processing',
'规则整理': 'Rule processing',
// 草稿上的提醒(knowledge_processing.py、knowledge_model_output.py)
'待核实客服身份、适用条件和事实;自动脱敏后仍须人工检查': 'Agent identity, conditions and facts need verifying; check by hand even after auto-redaction',
'对话含图片、语音等非文字内容(已用占位符标出),请核对答案是否完整': 'The conversation contains images, voice or other non-text content (marked with placeholders); check that the answer is complete',
'包含健康或个体医疗信息,仅经专业审核通用化后可发布': 'Contains health or individual medical information; publish only after professional review and generalization',
'模型未提供有效标题,已从问题生成标题,请核对': 'The model gave no valid title; a title was generated from the question. Please check it',
'模型标题过长,已缩短标题;问题与答案未截断': 'The model title was too long and has been shortened; the question and answer are not truncated',
'模型分类缺失或无效,请人工分类': 'The model category is missing or invalid; categorize it by hand',
'模型未提供有效适用条件,请核对来源并补充后再审核': 'The model gave no valid conditions; check the source and add them before review',
'模型知识类型无效,暂按问答保留,请核对': 'The model knowledge type is invalid; kept as Q&A for now. Please check it',
'模型整理草稿,须逐项核对来源,不能直接作为正确答案': 'Model-processed draft: check every point against the source; do not treat it as a correct answer as is',
// 一键审核的原因(knowledge_review.py REASONS)
'符合校验条件': 'Passes the checks',
'缺少适用条件,需编辑补充': 'Missing conditions; edit to add them',
'知识字段不完整、过长或类型无效': 'Fields are incomplete, too long or of an invalid type',
'已超过有效期': 'Expired',
'缺少来源记录': 'Missing source records',
'来源已变化,请重新整理': 'Source changed; process it again',
'预览后知识版本或状态已变化': 'Version or status changed after the preview',
'知识已删除': 'Knowledge deleted',
'该账号已不在当前授权范围': 'This account is no longer within your authorized scope',
'搜索索引写入失败;草稿保留,请排查后重新预览': 'Search indexing failed; the draft is preserved. Resolve the issue and preview again',
'发布校验失败;草稿保留,请编辑后重新预览': 'Publication checks failed; the draft is preserved. Edit it and preview again',
// ── 整理任务(runs-panel.vue、run-format.ts) ───────────────────────
'已取消,已生成的草稿保留': 'Cancelled; drafts already generated are kept',
'已暂停,进度已保存': 'Paused; progress saved',
'已继续': 'Resumed',
'取消这个整理批次?': 'Cancel this processing run?',
'已经生成的草稿保留,剩下的聊天不再整理;正在进行的模型请求可能仍会计费。': 'Drafts already generated are kept and the remaining chats will not be processed. Model requests in progress may still be billed.',
'取消整理': 'Cancel run',
'不取消': 'Keep running',
'已按新配置继续;已生成的草稿保留,新配置只用于剩下的部分': 'Resumed with the new settings; drafts already generated are kept and the new settings apply only to the rest',
'整理批次': 'Processing run',
'进度': 'Progress',
'模型用量': 'Model usage',
'已读消息': 'Messages read',
'结果': 'Result',
'新聊天自动整理已对 {sources} 个客服来源开启:最近 24 小时整理了 {jobs} 个会话,新增草稿 {created} 条': 'Auto-processing of new chats is on for {sources} agent sources: {jobs} conversations processed in the last 24 hours, {created} new drafts',
',{count} 个会话等对话静默后整理': ', {count} conversations waiting for the chat to go quiet',
',{count} 个失败': ', {count} failed',
'。': '.',
'新聊天自动整理还没开启:新建整理时勾选「整理完以后,新聊天也自动整理」即可开启。': 'Auto-processing of new chats is off. To turn it on, tick "also auto-process new chats" when starting a processing run.',
'还没有整理过聊天记录': 'No chat history processed yet',
'{count} 路并发': '{count} concurrent',
'每次 {count} 段': '{count} per request',
'{from} 至 {to}': '{from} to {to}',
'最早': 'earliest',
'现在': 'now',
'旧版单账号任务': 'Legacy single-account job',
'已读 {processed} / {total} 条消息': 'Read {processed} / {total} messages',
'已读 {processed} 条消息': 'Read {processed} messages',
'待整理问答 {count}': '{count} Q&A pairs waiting',
'每分钟约 {perMinute} 条消息,按目前平均速度还要 {remaining}': 'About {perMinute} messages per minute; {remaining} left at the current average speed',
'旧版任务没有分原因统计': 'Legacy jobs have no breakdown by reason',
'跳过 {count} 条(系统提示、撤回等)': 'Skipped {count} (system notices, recalls, etc.)',
'{count} 次': '{count} calls',
'上限 {limit}': 'limit {limit}',
'输入 {input} / 输出 {output} 字': 'Input {input} / output {output} chars',
'不调用模型': 'No model calls',
'暂停': 'Pause',
'继续': 'Resume',
'继续出错的账号': 'Resume failed accounts',
'换模型 / 调整': 'Change model / adjust',
'调整后继续整理': 'Adjust and resume',
'保存并继续': 'Save and resume',
'已整理出 {drafts} 条草稿、调用模型 {calls} 次;这些都保留,新配置只用于剩下的部分。': 'So far {drafts} drafts with {calls} model calls; these are kept, and the new settings apply only to the rest.',
'空消息': 'Empty message',
'已撤回或删除': 'Recalled or deleted',
'系统提示': 'System notice',
'收发方向不明': 'Unknown direction',
'出错暂停': 'Paused on error',
'排队中': 'Queued',
'整理中': 'Processing',
'新增草稿 {count}': '{count} new drafts',
'更新草稿 {count}': '{count} updated drafts',
'重复 {count}': '{count} duplicates',
'模型筛掉 {count}': '{count} filtered out by model',
'还没有产出': 'No output yet',
'模型清洗 · {model}': 'Model cleaning · {model}',
'默认模型': 'default model',
'不到 1 分钟': 'less than 1 minute',
'约 {minutes} 分钟': 'about {minutes} min',
'约 {days} 天': 'about {days} days',
'约 {hours} 小时 {minutes} 分': 'about {hours} h {minutes} min',
'约 {hours} 小时': 'about {hours} h',
// ── 全量审核(review-all.vue) ─────────────────────────────────────
'等待审核': 'Waiting for review',
'审核中': 'Reviewing',
'需处理': 'Needs attention',
'全量审核任务已提交,关闭页面后仍会继续': 'Full review job submitted; it keeps running after you close the page',
'停止剩余审核?': 'Stop the remaining review?',
'已通过的知识保留在待发布,尚未处理的草稿保持原状态。': 'Approved knowledge stays ready to publish; drafts not yet processed keep their status.',
'停止剩余审核': 'Stop remaining review',
'返回': 'Back',
'全量审核': 'Full review',
'指定范围审核': 'Review a scope',
'审核范围是已整理出的待审核知识草稿,覆盖全部页面,不受列表搜索与勾选影响。通过后进入待发布,原始聊天归档不会被修改。': 'The scope is all processed drafts pending review, across every page, regardless of list search and selection. Approved items become ready to publish; the original chat archive is not modified.',
'审核账号': 'Account to review',
'预览全部待审草稿': 'Preview all pending drafts',
'范围:': 'Scope: ',
'快照时间 {time}': 'Snapshot at {time}',
'可通过': 'Eligible',
'条': 'items',
'{reason}:{count} 条': '{reason}: {count}',
'预览固定当前草稿与版本,30 分钟内可提交。执行时会再次校验来源、版本和权限;不合格条目保持原状态并列出原因。': 'The preview pins the current drafts and versions and can be submitted within 30 minutes. Sources, versions and permissions are checked again when it runs; items that fail keep their status and are listed with the reason.',
'确认所选范围已完成必要的事实、脱敏和适用性审核;涉及医疗内容已完成专业审核。批量通过符合校验条件的草稿,之后另行发布。': 'I confirm the selected scope has had the necessary fact, redaction and applicability review, and any medical content has passed professional review. Drafts that pass the checks are approved in bulk and published separately later.',
'一键审核 {count} 条并进入待发布': 'Approve {count} items as ready to publish',
'我的审核任务': 'My review jobs',
'后台分批执行,关闭页面不影响进度。': 'Runs in batches in the background; closing the page does not affect progress.',
'刷新任务': 'Refresh jobs',
'账号范围': 'Account scope',
'状态 / 进度': 'Status / progress',
'审核结果': 'Review result',
'{processed} / {total} 条': '{processed} / {total}',
'通过 {approved} · 未通过 {skipped}': 'Approved {approved} · Not approved {skipped}',
'查看结果': 'View results',
'停止': 'Stop',
'结果清单 · {scope}': 'Results · {scope}',
'未通过': 'Not approved',
'已通过': 'Approved',
'未处理': 'Not processed',
'结果清单仅显示当前仍有权限的账号。': 'Results only include accounts you still have access to.',
'知识标题': 'Knowledge title',
'原因': 'Reason',
'查看知识': 'View knowledge',
// ── 整理方式与模型(wash-options.vue) ─────────────────────────────
'(默认)': ' (default)',
'模型清单加载失败,请刷新后重试': 'Failed to load the model list. Refresh and try again',
'整理方式': 'Processing method',
'模型清洗(推荐)': 'Model cleaning (recommended)',
'规则提取(不调用模型)': 'Rule extraction (no model calls)',
'先按规则切出问答,再交给模型改写成标准知识,并筛掉寒暄、查物流等没有通用价值的对话。按调用次数计费。': 'Rules first split out Q&A pairs, then the model rewrites them as standard knowledge and filters out conversations with no general value, such as small talk or shipping queries. Billed per call.',
'只按规则切出问答、保留原话,不花模型费用;需要人工逐条整理措辞和适用条件。': 'Rules only split out Q&A pairs and keep the original wording, at no model cost; wording and conditions must be edited by hand, one by one.',
'整理模型': 'Processing model',
'选择一个已启用的文本模型': 'Select an enabled text model',
'测试': 'Test',
'还没有可用的文本模型,请先在「AI 模型 → 模型清单」启用一个,或改用规则提取。': 'No text model is available. Enable one under "AI Models → Model List" first, or use rule extraction.',
'原来选的模型已停用,请重新选择。': 'The previously selected model has been disabled. Select another one.',
'「{model}」可以正常整理(用时 {seconds} 秒)': '"{model}" works for processing ({seconds} s)',
'用一段虚构对话试整理的结果:': 'Result of a trial run on a made-up conversation:',
'问题:{question}': 'Question: {question}',
'答案:{answer}': 'Answer: {answer}',
'(模型未给出)': '(not given by the model)',
'高级设置': 'Advanced settings',
'同时调用': 'Concurrent calls',
'路': 'at once',
'每次请求合并': 'Merge per request',
'段问答': 'Q&A pairs',
'单次等待': 'Timeout per call',
'秒': 'seconds',
'调用总上限(0 = 不限)': 'Total call limit (0 = unlimited)',
'次': 'calls',
'让模型筛掉没有通用价值的问答(寒暄、催单查物流、只针对某位患者的处置)': 'Let the model filter out Q&A with no general value (small talk, order chasing and shipping queries, advice for one specific patient)',
'大部分聊天会被判为没有价值,合并请求能省下大部分调用(1 = 一段一请求)。并发越高越快,但会和客服实时回复共用同一个模型额度;': 'Most chats are judged to have no value, so merging requests saves most calls (1 = one pair per request). Higher concurrency is faster but shares the same model quota as live customer replies;',
'超时或限流会自动退避重试,频繁出现时调低并发或合并段数。整理时会自动关闭模型的深度思考(服务商支持时)。': 'timeouts and rate limits are retried automatically with backoff; if they happen often, lower the concurrency or the pairs per request. Deep thinking is turned off automatically during processing (where the provider supports it).',
// ── 新建整理(run-dialog.vue) ─────────────────────────────────────
'请选择要整理的账号': 'Select the accounts to process',
'结束日期不能早于开始日期': 'The end date cannot be earlier than the start date',
'正在统计范围…': 'Counting the scope…',
'所选范围内没有单聊消息': 'No one-to-one messages in the selected scope',
'请选择整理模型': 'Select a processing model',
'已开始整理:{count} 个账号,在「整理任务」里看进度': 'Processing started for {count} accounts; follow the progress under "Processing jobs"',
'整理哪些账号': 'Accounts to process',
'指定账号': 'Selected accounts',
'选择一个或多个客户端账号': 'Select one or more client accounts',
'时间范围(留空 = 全部聊天)': 'Date range (empty = all chats)',
'至': 'to',
'清空': 'Clear',
'整理完以后,这些账号的新聊天也自动整理(对话静默 30 分钟后)': 'After processing, also auto-process new chats of these accounts (after 30 minutes of silence)',
'{scope}:': '{scope}: ',
'个账号有聊天,': 'accounts with chats.',
'单聊消息': 'One-to-one messages',
'条(文字 {text} 条),会话 {conversations} 个': '({text} text), {conversations} conversations',
';另有 {count} 个账号在这个范围内没有聊天,会跳过': '; {count} more accounts have no chats in this range and will be skipped',
'模型只处理切出来的问答段(通常只占消息的百分之几),每次请求合并 {batch} 段;开始后在「整理任务」里看实时速度和预计剩余时间。': 'The model only handles the Q&A pairs split out (usually a few percent of the messages), {batch} per request. After starting, see the live speed and time left under "Processing jobs".',
'第一次整理全部聊天,建议在高级设置里先设一个调用上限。': 'When processing all chats for the first time, set a call limit in Advanced settings first.',
'文字消息': 'Text messages',
'会话': 'Conversations',
'开始即确认:这些聊天由客服账号产生,允许用于知识整理。整理结果都是待审草稿,不会自动发布;同一段对话已有的草稿不会重复生成。': 'Starting confirms that these chats come from agent accounts and may be used for knowledge processing. Results are drafts pending review and are never published automatically; a conversation that already has a draft will not get a duplicate.',
'开始整理': 'Start processing',
// ── 批量操作(batch-dialog.vue、batch.ts) ─────────────────────────
'批量删除 · {count} 条': 'Batch delete · {count} items',
'批量审核通过 · {count} 条': 'Batch approve · {count} items',
'批量发布 · {count} 条': 'Batch publish · {count} items',
'批量驳回 · {count} 条': 'Batch reject · {count} items',
'批量停用 · {count} 条': 'Batch disable · {count} items',
'确认删除 {count} 条': 'Delete {count} items',
'确认审核通过 {count} 条': 'Approve {count} items',
'确认发布 {count} 条': 'Publish {count} items',
'确认驳回 {count} 条': 'Reject {count} items',
'确认停用 {count} 条': 'Disable {count} items',
'版本已更新,请关闭后重新选择,避免审核旧内容': 'The version has changed. Close and select again to avoid reviewing outdated content',
'请逐条展开,核对来源、事实、脱敏和适用条件,再勾选确认。通过审核后仍需发布才可检索。': 'Expand each item, check its source, facts, redaction and conditions, then tick to confirm. Approved items must still be published before they can be searched.',
'每条知识分别校验版本和当前状态。操作结果逐条显示,失败条目不会自动重试。': 'Each item is checked for its version and current status. Results are shown per item; failed items are not retried automatically.',
'仅删除已驳回知识及其来源快照和版本记录;原始聊天归档保留。删除后无法恢复,请确认所选条目。': 'Only rejected knowledge and its source snapshots and version history are deleted; the original chat archive is kept. This cannot be undone, so check the selected items.',
'可操作 {ready} 条 · 需先处理 {blocked} 条': '{ready} ready · {blocked} need attention first',
'成功 {success} · 失败 {failed} · 未执行 {pending}': 'Succeeded {success} · Failed {failed} · Not run {pending}',
'成功': 'Succeeded',
'未执行': 'Not run',
'尚未填写': 'Not filled in',
'有效期:{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',
'当前操作完成后停止': 'Stopping after the current item',
'停止后续操作': 'Stop the rest',
'完成': 'Done',
'当前状态不支持此操作,请刷新或重新选择': 'This action is not available in the current status. Refresh or select again',
'请先编辑并补充适用条件': 'Edit the item and add conditions first',
'请求未完成,请刷新确认状态后再操作': 'The request did not complete. Refresh to check the status before trying again',
// ── 整理设置(settings-dialog.vue) ────────────────────────────────
'整理设置已保存': 'Processing settings saved',
'新建整理时默认用这里的方式和模型(每次仍可临时改)。': 'New processing runs use this method and model by default (you can still change them each time).',
'新聊天自动整理用': 'Auto-processing of new chats uses',
'规则提取(不花模型费用)': 'Rule extraction (no model cost)',
'模型清洗(用上面的默认模型,每段新对话调用一次)': 'Model cleaning (the default model above, one call per new conversation)',
// Review actions and scope confirmation.
'批量审核并发布 · {count} 条': 'Batch review and publish · {count} items',
'确认审核并发布 {count} 条': 'Confirm review and publish {count} items',
'请核对所选知识的来源、事实、脱敏和适用条件。点击下方确认按钮后执行,可展开查看详情;不符合条件的条目会跳过。': 'Check the sources, facts, redaction and conditions of the selected knowledge. Use the confirmation button below to proceed. Expand an item for details; ineligible items will be skipped.',
'审核通过后进入待发布,发布后才可检索。': 'Approved items move to Awaiting publication. They become searchable after publication.',
'等待进行中的操作完成后停止': 'Waiting for in-flight actions before stopping',
'保存并审核发布': 'Save, review and publish',
'保存并审核通过': 'Save and approve',
'审核并发布': 'Review and publish',
'审核通过,已进入待发布': 'Approved and awaiting publication',
'已审核并发布': 'Reviewed and published',
'审核全部草稿': 'Review all drafts',
'审核并发布选中': 'Review and publish selected',
'审核选中': 'Review selected',
'更多操作': 'More actions',
'审核操作会先保存修改,再按保存后的版本执行;失败时不会自动重试。': 'The review action saves your changes first, then uses the saved revision. Failed actions are not retried automatically.',
'请核对来源、事实、脱敏与适用条件,点击审核按钮即确认当前内容。': 'Check the sources, facts, redaction and conditions. Clicking the review button confirms the current content.',
'正在统计所选范围的待审草稿…': 'Counting pending drafts in the selected scope…',
'重新统计范围': 'Recount scope',
'请确认以上账号范围和数量,并核对事实、脱敏与适用条件。点击下方按钮后,符合条件的草稿将进入待发布。': 'Confirm the account scope and count above, and check the facts, redaction and conditions. The button below moves eligible drafts to Awaiting publication.',
'确认审核 {count} 条并进入待发布': 'Confirm review of {count} items and mark ready for publication',
'上一项操作仍在完成,请稍候。': 'The previous action is still finishing. Please wait.',
'审核并发布全部草稿': 'Review and publish all drafts',
'全量审核并发布': 'Full review and publication',
'当前范围包含已整理出的全部待审核知识草稿,覆盖所有页面,不受列表搜索与勾选影响。符合条件的草稿将审核并发布,可供客服检索使用。': 'The current scope includes all processed drafts pending review, across every page, regardless of list search and selection. Eligible drafts will be reviewed and published for customer service retrieval.',
'当前预览范围:': 'Current preview scope: ',
'审核通过后进入待发布': 'Approve as ready for publication',
'可审核并发布': 'Ready to review and publish',
'请核对以上账号范围、数量及知识内容。点击下方按钮后执行审核并发布;全部成功后自动关闭此弹窗并刷新知识列表,需处理的条目会保留结果。': 'Check the account scope, count and knowledge content above. The button below reviews and publishes the drafts. When all succeed, this dialog closes and the knowledge list refreshes. Results stay visible for items that need attention.',
'一键审核并发布 {count} 条': 'Review and publish {count} items',
'已审核并发布 {count} 条': 'Reviewed and published {count} items',
'已发布 {published} · 已审核 {approved} · 需处理 {skipped}': 'Published {published} · Reviewed {approved} · Need attention {skipped}',
'已发布的知识保留发布状态,尚未处理的草稿保持原状态。': 'Published knowledge stays published. Unprocessed drafts keep their current status.',
} as Record<string, string>;
@@ -0,0 +1,111 @@
import type { KnowledgeItem } from '#/api/knowledge';
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() }));
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?.()]) });
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,
};
});
import KnowledgeBatchDialog from './batch-dialog.vue';
const item = (id: string): KnowledgeItem => ({ id, title: id, question: 'question', answer: 'answer', conditions: 'condition',
tenant_id: 'tenant', category: '', kind: 'qa', status: 'draft', revision: 1, valid_until: '', updated_at: '',
vector_status: '', flags: [], sources: [], history: [] });
const settle = async () => { for (let index = 0; index < 10; index++) { await Promise.resolve(); await nextTick(); } };
function deferred<T>() {
let resolve!: (value: T) => void;
const promise = new Promise<T>((done) => { resolve = done; });
return { promise, resolve };
}
let cleanup: (() => void) | undefined;
function mount(entries: KnowledgeItem[]) {
const open = ref(true); const visible = ref(true); const selection = ref(entries); const child = ref();
const finished = vi.fn(); const closed = 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,
}) }));
app.mount(host); cleanup = () => { app.unmount(); host.remove(); };
return { open, visible, selection, child, finished, closed, host };
}
describe('knowledge batch dialog lifecycle', () => {
beforeEach(() => {
vi.resetAllMocks();
api.fetchKnowledgeItem.mockImplementation(async (_account, id) => item(id));
api.knowledgeItemAction.mockImplementation(async (_account, entry) => ({ ...entry, status: 'approved', revision: 2 }));
});
afterEach(() => { cleanup?.(); cleanup = undefined; });
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();
const state = ui.child.value.$.setupState;
expect(api.fetchKnowledgeItem).toHaveBeenCalledTimes(4); expect(state.ready).toHaveLength(4);
const gates = [deferred<KnowledgeItem>(), deferred<KnowledgeItem>(), deferred<KnowledgeItem>()];
let sent = 0;
api.knowledgeItemAction.mockImplementationOnce(() => gates[sent++]!.promise)
.mockImplementationOnce(() => gates[sent++]!.promise).mockImplementationOnce(() => gates[sent++]!.promise);
const oldRun = state.start(); await settle();
expect(state.running).toBe(true); expect(api.knowledgeItemAction).toHaveBeenCalledTimes(3);
ui.visible.value = false; await settle();
expect(ui.closed).toHaveBeenCalledWith(false); expect(ui.open.value).toBe(false);
expect(state.running).toBe(false); expect(state.executionActive).toBe(true); expect(state.results).toBeNull();
ui.selection.value = [item('fresh')]; ui.visible.value = true; ui.open.value = true; await settle();
expect(ui.child.value.$.setupState).toBe(state); expect(state.ready).toEqual([]);
expect(ui.host.textContent).toContain('等待进行中的操作完成后停止');
await state.start(); expect(api.knowledgeItemAction).toHaveBeenCalledTimes(3);
gates[0]!.resolve({ ...item('a'), status: 'approved', revision: 2 }); await settle();
expect(state.executionActive).toBe(true); expect(state.results).toBeNull(); expect(ui.finished).not.toHaveBeenCalled();
expect(api.fetchKnowledgeItem).toHaveBeenCalledTimes(4);
gates[1]!.resolve({ ...item('b'), status: 'approved', revision: 2 });
gates[2]!.resolve({ ...item('c'), status: 'approved', revision: 2 }); await oldRun; await settle();
expect(state.executionActive).toBe(false); expect(state.running).toBe(false);
expect(state.results).toBeNull(); expect(state.ready.map((entry: KnowledgeItem) => entry.id)).toEqual(['fresh']);
expect(ui.finished).not.toHaveBeenCalled(); expect(api.knowledgeItemAction).toHaveBeenCalledTimes(3);
await state.start(); await settle();
expect(api.knowledgeItemAction).toHaveBeenCalledTimes(4);
expect(api.knowledgeItemAction.mock.calls[3]).toMatchObject([-1, { id: 'fresh', revision: 1 }, 'approve', true]);
expect(state.results).toMatchObject([{ id: 'fresh', status: 'success' }]);
expect(state.running).toBe(false); expect(state.executionActive).toBe(false); expect(ui.finished).toHaveBeenCalledTimes(1);
});
it('reloads details after activation even when the cached open prop never toggled', async () => {
const old = deferred<KnowledgeItem>(); const current = deferred<KnowledgeItem>();
api.fetchKnowledgeItem.mockImplementationOnce(() => old.promise).mockImplementationOnce(() => current.promise);
const ui = mount([item('a')]); await settle(); const state = ui.child.value.$.setupState;
expect(state.loading).toBe(true); ui.visible.value = false; await settle(); expect(ui.open.value).toBe(false);
ui.visible.value = true; ui.open.value = true; await settle(); expect(state.loading).toBe(true);
old.resolve(item('old')); await settle(); expect(state.loading).toBe(true); expect(state.details).toEqual([]);
current.resolve(item('a')); await settle(); expect(state.loading).toBe(false); expect(state.ready[0].id).toBe('a');
await state.start(); expect(state.results).toMatchObject([{ id: 'a', status: 'success' }]);
expect(ui.finished).toHaveBeenCalledTimes(1);
});
it('does not reload hidden state when a mutation settles before the cached component is activated', async () => {
const ui = mount([item('a')]); await settle(); const state = ui.child.value.$.setupState;
const gate = deferred<KnowledgeItem>(); api.knowledgeItemAction.mockImplementationOnce(() => gate.promise);
const pending = state.start(); await settle(); ui.visible.value = false; await settle();
const reads = api.fetchKnowledgeItem.mock.calls.length;
gate.resolve({ ...item('a'), status: 'approved', revision: 2 }); await pending; await settle();
expect(state.executionActive).toBe(false); expect(state.results).toBeNull(); expect(state.details).toEqual([]);
expect(api.fetchKnowledgeItem).toHaveBeenCalledTimes(reads); expect(ui.finished).not.toHaveBeenCalled();
await state.start(); expect(api.knowledgeItemAction).toHaveBeenCalledTimes(1);
ui.visible.value = true; ui.open.value = true; await settle();
expect(api.fetchKnowledgeItem).toHaveBeenCalledTimes(reads + 1); expect(state.ready[0].id).toBe('a');
});
});
@@ -0,0 +1,118 @@
<script setup lang="ts">
import type { KnowledgeItem } from '#/api/knowledge';
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 { 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] }>();
const details = ref<KnowledgeItem[]>([]);
const problems = ref<Record<string, string>>({});
const loading = ref(false);
const running = ref(false);
// This lock survives dialog invalidation until every already-sent mutation settles.
const executionActive = ref(false);
let executionToken = 0;
const stopRequested = ref(false);
const results = ref<BatchResult[] | null>(null);
let generation = 0;
let viewActive = true;
function stop() {
stopRequested.value = true; generation++;
running.value = false; loading.value = false; results.value = null;
details.value = []; problems.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 completed = computed(() => results.value?.filter((row) => row.status !== 'pending').length || 0);
// 标题和确认按钮按操作分别写整句,英文语序才自然
const title = computed(() => {
const count = uniqueKnowledgeItems(props.entries).length;
return {
delete: t('批量删除 · {count} 条', { count }), approve: t('批量审核通过 · {count} 条', { count }), approve_publish: t('批量审核并发布 · {count} 条', { count }),
publish: t('批量发布 · {count} 条', { count }), reject: t('批量驳回 · {count} 条', { count }),
disable: t('批量停用 · {count} 条', { count }),
}[props.action];
});
const confirmText = computed(() => {
const count = ready.value.length;
return {
delete: t('确认删除 {count} 条', { count }), approve: t('确认审核通过 {count} 条', { count }), approve_publish: t('确认审核并发布 {count} 条', { count }),
publish: t('确认发布 {count} 条', { count }), reject: t('确认驳回 {count} 条', { count }),
disable: t('确认停用 {count} 条', { count }),
}[props.action];
});
async function loadDetails() {
stop();
const current = generation;
if (!viewActive || !props.open || executionActive.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;
}
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();
});
async function start() {
if (!viewActive || !props.open || loading.value || executionActive.value || !props.canExecute || !ready.value.length) return;
const current = generation;
const token = ++executionToken;
const account = props.accountId;
const action = props.action;
const work = uniqueKnowledgeItems(ready.value).map((item) => ({ ...item }));
executionActive.value = true; running.value = true; stopRequested.value = false;
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)),
(value) => { if (current === generation) results.value = value; }, () => stopRequested.value || current !== generation || !props.canExecute);
if (current === generation) results.value = finished;
} finally {
if (token === executionToken) executionActive.value = false;
if (current === generation) { running.value = false; emit('finished'); }
}
}
</script>
<template>
<Modal :open="open" :title="title" width="960px" :closable="!running" :keyboard="!running" :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 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>
<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>
<div v-for="row in results" :key="row.id" class="mb-2"><Tag :color="row.status === 'success' ? 'green' : row.status === 'failed' ? 'red' : 'default'">{{ row.status === 'success' ? t('成功') : row.status === 'failed' ? t('失败') : t('未执行') }}</Tag>{{ row.title }}<p v-if="row.error" class="text-red-500">{{ row.error }}</p></div>
</div>
<Collapse>
<Collapse.Panel v-for="item in details" :key="item.id">
<template #header><span>{{ item.title }} · v{{ item.revision }}</span><Tag v-if="problems[item.id]" color="orange" class="ml-2">{{ problems[item.id] }}</Tag></template>
<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>
<Button 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>
</Space></template>
</Modal>
</template>
@@ -0,0 +1,80 @@
import type { KnowledgeItem } from '#/api/knowledge';
import { t } from '#/locales/t';
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 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('请先编辑并补充适用条件');
return '';
}
export function failureText(error: unknown): string {
const detail = (error as { response?: { data?: { detail?: unknown } } })?.response?.data?.detail;
return typeof detail === 'string' ? detail : t('请求未完成,请刷新确认状态后再操作');
}
/** Keep the first selected revision when repeated IDs arrive from a caller. */
export function uniqueKnowledgeItems(items: KnowledgeItem[]): KnowledgeItem[] {
const seen = new Set<string>();
return items.filter((item) => {
if (seen.has(item.id)) return false;
seen.add(item.id); return true;
});
}
/** Fetch at most four details at a time and keep the selected revision as the action gate. */
export async function prepareKnowledgeBatch(
entries: KnowledgeItem[], action: BatchAction, fetch: (item: KnowledgeItem) => Promise<KnowledgeItem>,
stopped: () => boolean,
) {
const selected = uniqueKnowledgeItems(entries);
const details = [...selected];
const problems: Record<string, string> = {};
let next = 0;
await Promise.all(Array.from({ length: Math.min(4, selected.length) }, async () => {
while (!stopped() && next < selected.length) {
const index = next++;
const entry = selected[index]!;
try {
const item = await fetch(entry);
if (stopped()) return;
details[index] = item;
const problem = item.revision !== entry.revision
? t('版本已更新,请关闭后重新选择,避免审核旧内容') : actionProblem(item, action);
if (problem) problems[entry.id] = problem;
} catch (error) {
if (stopped()) return;
problems[entry.id] = failureText(error);
}
}
}));
return { details, problems };
}
/** At most three requests are in flight. Stop leaves unscheduled rows pending; mutations never retry. */
export async function runKnowledgeBatch(
items: KnowledgeItem[], execute: (item: KnowledgeItem) => Promise<unknown>,
update: (results: BatchResult[]) => void, stopped: () => boolean,
) {
const work = uniqueKnowledgeItems(items);
const results: BatchResult[] = work.map(({ id, title }) => ({ id, title, status: 'pending', error: '' }));
let next = 0;
await Promise.all(Array.from({ length: Math.min(3, work.length) }, async () => {
while (!stopped() && next < work.length) {
const index = next++;
const item = work[index]!;
try {
await execute(item);
results[index] = { id: item.id, title: item.title, status: 'success', error: '' };
} catch (error) {
results[index] = { id: item.id, title: item.title, status: 'failed', error: failureText(error) };
}
update(results.map((row) => ({ ...row })));
}
}));
return results;
}
@@ -0,0 +1,464 @@
<script setup lang="ts">
import type { KnowledgeAutoSummary, KnowledgeItem, KnowledgeReviewJob, KnowledgeOverview, KnowledgeRun, KnowledgeSearch, KnowledgeTrace } from '#/api/knowledge';
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 { ALL_ACCOUNTS } from '#/api/console';
import { requestErrorMessage } from '#/api/error-message';
import { exportKnowledge, fetchKnowledgeReviewJobs, fetchKnowledgeItem, fetchKnowledgeItems, fetchKnowledgeOverview, fetchKnowledgeRuns, fetchKnowledgeTraces, knowledgeItemAction, saveKnowledgeItem, searchKnowledge, setKnowledgeEnabled, setKnowledgeWatch } from '#/api/knowledge';
import ArchiveAccountSelector from '#/components/archive-account-selector.vue';
import { t } from '#/locales/t';
import KnowledgeRunDialog from './run-dialog.vue';
import KnowledgeRunsPanel from './runs-panel.vue';
import KnowledgeSettingsDialog from './settings-dialog.vue';
import KnowledgeBatchDialog from './batch-dialog.vue';
import KnowledgeReviewAll from './review-all.vue';
import type { BatchAction } from './batch';
import { actionProblem, failureText } from './batch';
import { shortTime } from './run-format';
import { useArchiveLoad } from '#/views/archive/use-archive-load';
const { hasAccessByCodes } = useAccess();
const hasAll = (codes: string[]) => codes.every((code) => hasAccessByCodes([code]));
// 每个按钮一个权限码;碰到聊天原文(来源证据)的操作还要能看正文,和后端判法一致
const withContent = (code: string) => computed(() => hasAll([code, 'im:content:read']));
const canRun = withContent('knowledge:run');
const canControl = withContent('knowledge:run:control');
const canSettings = computed(() => hasAccessByCodes(['knowledge:settings']));
const canWatch = withContent('knowledge:watch');
const canEdit = withContent('knowledge:write');
const canRestore = withContent('knowledge:restore');
const canDelete = withContent('knowledge:delete');
const canReview = withContent('knowledge:review');
const canReject = withContent('knowledge:reject');
const canAutoReview = computed(() => hasAll(['knowledge:read', 'knowledge:review:auto', 'im:content:read']));
const canPublish = withContent('knowledge:publish');
const canDisable = withContent('knowledge:disable');
const canEnable = computed(() => hasAccessByCodes(['knowledge:enable']));
const canSearch = computed(() => hasAccessByCodes(['knowledge:search']));
const canExport = computed(() => hasAccessByCodes(['knowledge:export']));
const canTrace = computed(() => hasAccessByCodes(['stats:read']));
const ownScopeFlag = computed(() => hasAccessByCodes(['knowledge:scope:own']));
const knowledgeScope = ref<KnowledgeOverview['knowledge_scope'] | null>(null);
const scopeSignature = (scope: KnowledgeOverview['knowledge_scope']) =>
JSON.stringify([scope.mode, [...new Set(scope.account_ids)].sort((left, right) => left - right)]);
const ownScope = computed(() => knowledgeScope.value?.mode === 'zyt_account'
|| (ownScopeFlag.value && !knowledgeScope.value));
const allowedAccountIds = computed(() => ownScope.value ? knowledgeScope.value?.account_ids || [] : undefined);
const scopeVersion = ref(0);
const canBatch = computed(() => canReview.value || canReject.value || canPublish.value || canDisable.value || canDelete.value);
const accountId = ref(ALL_ACCOUNTS);
const single = computed(() => accountId.value !== ALL_ACCOUNTS);
const tab = ref('items');
const overview = ref<KnowledgeOverview | null>(null);
const items = ref<KnowledgeItem[]>([]);
const runs = ref<KnowledgeRun[]>([]);
const autoSummary = ref<KnowledgeAutoSummary | null>(null);
const reviewJobs = ref<KnowledgeReviewJob[]>([]);
const reviewOpen = ref(false);
const reviewTab = ref('new');
function openFullReview(view: string) { reviewTab.value = view; reviewOpen.value = true; }
async function inspectReviewed(itemId: string, targetAccount: number) {
reviewOpen.value = false; accountId.value = targetAccount;
await accountChanged();
if (accountId.value === targetAccount) await inspect(itemId);
}
const traces = ref<KnowledgeTrace[]>([]);
const total = ref(0);
const page = ref(1);
const filter = ref('');
const query = ref('');
const testQuery = ref('');
const searchError = ref('');
const result = ref<KnowledgeSearch | null>(null);
const selected = ref<KnowledgeItem | null>(null);
const savedContent = ref('');
const contentSignature = (item: KnowledgeItem) => JSON.stringify([item.title, item.question, item.answer, item.conditions, item.category, item.kind, item.valid_until]);
const dirty = computed(() => !!selected.value && contentSignature(selected.value) !== savedContent.value);
const editorError = ref('');
const canApprovePublish = computed(() => canReview.value && canPublish.value);
const reviewAction = computed<BatchAction>(() => canApprovePublish.value ? 'approve_publish' : 'approve');
const reviewText = computed(() => dirty.value
? canApprovePublish.value ? t('保存并审核发布') : t('保存并审核通过')
: canApprovePublish.value ? t('审核并发布') : t('审核通过'));
const editorOpen = ref(false);
const createOpen = ref(false);
const settingsOpen = ref(false);
const selectedKeys = ref<string[]>([]);
const batchOpen = ref(false);
const batchAction = ref<BatchAction>('approve');
const batchEntries = ref<KnowledgeItem[]>([]);
const selectedRows = computed(() => items.value.filter((item) => selectedKeys.value.includes(item.id)));
const rowSelection = computed(() => canBatch.value ? {
selectedRowKeys: selectedKeys.value,
onChange: (keys: (number | string)[]) => { selectedKeys.value = keys.map(String); },
} : undefined);
const guideStep = computed(() => !single.value ? 0 : (overview.value?.counts.published || 0) > 0 ? 3
: (overview.value?.counts.draft || 0) + (overview.value?.counts.approved || 0) > 0 ? 2 : 1);
const guideText = computed(() => !single.value ? t('点「整理聊天记录」可一次整理全部账号的聊天;点知识标题可直接查看、审核和发布。')
: !overview.value?.source_accounts.length ? t('当前账号尚无聊天归档,请先上传归档或更换账号。')
: guideStep.value === 1 ? t('点「整理聊天记录」生成草稿,再逐条核对来源和适用条件。')
: guideStep.value === 2 ? t('草稿补全适用条件后审核,通过后发布;也可以勾选列表中的多条知识集中处理。')
: t('已发布知识可在检索测试中验证;确认结果后开启客服使用知识。'));
function actionPermission(action: BatchAction) {
return { approve: canReview.value, approve_publish: canApprovePublish.value, publish: canPublish.value,
reject: canReject.value, disable: canDisable.value, delete: canDelete.value }[action];
}
const batchPermission = computed(() => actionPermission(batchAction.value));
function batchAllowed(action: BatchAction) {
return actionPermission(action) && selectedRows.value.some((item) => !actionProblem(item, action));
}
function openBatch(action: BatchAction) {
if (!batchAllowed(action) || busy.value) return;
batchAction.value = action;
batchEntries.value = selectedRows.value.map((item) => ({ ...item }));
batchOpen.value = true;
}
function batchFinished() { selectedKeys.value = []; void load(); }
function startCreate() { createOpen.value = true; }
function created() { tab.value = 'jobs'; void load(); }
function listChanged() { selectedKeys.value = []; void load(); }
const busy = ref(false);
const request = useArchiveLoad();
const { loading } = request;
let active = true;
let timer: ReturnType<typeof setTimeout> | undefined;
let detailGeneration = 0;
let scopeReloadPending = false;
// /me polling updates access codes in place. Clear the previous scope before
// rendering, and invalidate requests and dialogs that still carry old items.
function clearScopeData() {
if (timer) clearTimeout(timer);
detailGeneration++; scopeVersion.value++;
selected.value = null; savedContent.value = ''; editorOpen.value = false; editorError.value = '';
items.value = []; overview.value = null; runs.value = []; autoSummary.value = null;
reviewJobs.value = []; traces.value = []; result.value = null; searchError.value = '';
selectedKeys.value = []; batchEntries.value = []; batchOpen.value = false; reviewOpen.value = false;
createOpen.value = false;
total.value = 0; page.value = 1;
}
watch(ownScopeFlag, () => {
request.cancel();
clearScopeData(); knowledgeScope.value = null;
scopeReloadPending = !active;
if (active) void load();
}, { flush: 'sync' });
// 文案随语言切换:包成 computed(模板里自动解包)
const labels = computed<Record<string, string>>(() => ({ draft: t('待审核'), approved: t('待发布'), published: t('已发布'), rejected: t('已驳回'), disabled: t('已停用'), stale: t('来源已变化'), queued: t('等待处理'), running: t('处理中'), paused: t('已暂停'), completed: t('已完成'), failed: t('失败'), cancelled: t('已取消') }));
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() {
await request.run(async (signal) => {
// Resolve the trusted knowledge scope before using a remembered archive account.
const allSummary = await fetchKnowledgeOverview(ALL_ACCOUNTS, signal);
if (signal.aborted) throw new DOMException('Aborted', 'AbortError');
if (knowledgeScope.value && scopeSignature(knowledgeScope.value) !== scopeSignature(allSummary.knowledge_scope)) clearScopeData();
knowledgeScope.value = allSummary.knowledge_scope;
if (signal.aborted) throw new DOMException('Aborted', 'AbortError');
if (knowledgeScope.value?.mode === 'zyt_account' && accountId.value !== ALL_ACCOUNTS
&& !knowledgeScope.value.account_ids.includes(accountId.value)) {
clearScopeData(); accountId.value = ALL_ACCOUNTS;
}
const id = accountId.value;
const [summary, entries, tasks, logs, reviews] = await Promise.all([
id === ALL_ACCOUNTS ? Promise.resolve(allSummary) : fetchKnowledgeOverview(id, signal), fetchKnowledgeItems(id, filter.value, query.value, page.value, signal),
fetchKnowledgeRuns(signal), canTrace.value ? fetchKnowledgeTraces(id, signal) : Promise.resolve({ items: [] }),
canAutoReview.value ? fetchKnowledgeReviewJobs(signal) : Promise.resolve({ items: [] }),
]);
return { summary, entries, tasks, logs, reviews };
}, (data) => {
overview.value = data.summary; items.value = data.entries.items; total.value = data.entries.total;
runs.value = data.tasks.items; autoSummary.value = data.tasks.auto; reviewJobs.value = data.reviews.items; traces.value = data.logs.items;
});
schedule();
}
function schedule() {
if (timer) clearTimeout(timer);
if (!active || ![...runs.value, ...reviewJobs.value].some((j) => ['queued', 'running'].includes(j.status))) return;
timer = setTimeout(() => { if (document.visibilityState === 'visible' && !busy.value) void load(); else schedule(); }, 5000);
}
async function accountChanged() {
const currentAccount = accountId.value;
detailGeneration++; selected.value = null; editorOpen.value = false;
items.value = []; traces.value = []; result.value = null; searchError.value = ''; overview.value = null;
selectedKeys.value = []; batchOpen.value = false; batchEntries.value = []; page.value = 1;
await load();
if (currentAccount !== accountId.value) return;
}
// 「全部账号」下也能直接打开:后端按知识自己的账号处理,并检查在授权范围内
async function inspect(id: string) {
const generation = ++detailGeneration;
const entry = await fetchKnowledgeItem(accountId.value, id);
if (generation !== detailGeneration) return;
selected.value = entry; savedContent.value = contentSignature(entry); editorError.value = ''; editorOpen.value = true;
}
async function mutate(action: () => Promise<unknown>) {
if (busy.value) return;
busy.value = true;
try { await action(); await load(); } finally { busy.value = false; }
}
async function save() {
const item = selected.value;
if (!item) return;
const id = accountId.value;
const generation = detailGeneration;
await mutate(async () => {
const saved = await saveKnowledgeItem(id, item);
if (generation === detailGeneration) { selected.value = { ...saved, account_id: item.account_id, account_label: item.account_label }; savedContent.value = contentSignature(saved); }
message.success(t('已保存为草稿,需要重新审核后发布'));
});
}
// This button is the explicit review confirmation. Save first, then act on the returned revision once.
async function review() {
if (!selected.value || !canReview.value || busy.value || !selected.value.conditions.trim()) return;
const original = { ...selected.value };
const edited = dirty.value;
if (edited && !canEdit.value) return;
const id = accountId.value; const generation = detailGeneration;
const action = reviewAction.value;
if (!actionPermission(action)) return;
editorError.value = '';
let succeeded = false;
try {
await mutate(async () => {
let item = original;
if (edited) {
const saved = await saveKnowledgeItem(id, original);
if (generation !== detailGeneration || !active) return;
item = { ...saved, account_id: original.account_id, account_label: original.account_label };
selected.value = item; savedContent.value = contentSignature(item);
}
if (generation !== detailGeneration || !active || !actionPermission(action)) return;
const changed = await knowledgeItemAction(id, item, action, true);
if (generation !== detailGeneration) return;
selected.value = { ...changed, account_id: original.account_id, account_label: original.account_label };
savedContent.value = contentSignature(changed); succeeded = true;
message.success(action === 'approve_publish' ? t('已审核并发布') : t('审核通过,已进入待发布'));
});
if (succeeded && generation === detailGeneration && editorOpen.value) {
const next = items.value.find((item) => item.status === 'draft' && item.id !== original.id);
if (next) await inspect(next.id);
}
} catch (error) { if (generation === detailGeneration) editorError.value = failureText(error); }
}
async function act(action: string, restoreRevision = 0) {
const item = selected.value;
if (!item) return;
const id = accountId.value;
const generation = detailGeneration;
await mutate(async () => {
const changed = await knowledgeItemAction(id, item, action, false, restoreRevision);
if (generation === detailGeneration) { selected.value = { ...changed, account_id: item.account_id, account_label: item.account_label }; savedContent.value = contentSignature(changed); }
message.success(action === 'restore' ? t('已恢复为草稿,请审核后重新发布') : t('操作成功'));
});
}
function deleteSelected() {
if (!selected.value) return;
const item = { ...selected.value }; const id = accountId.value; const generation = detailGeneration;
Modal.confirm({ title: t('删除这条已驳回知识?'), content: t('将删除知识及其来源快照和版本记录,原始聊天归档保留。删除后无法恢复。'),
okText: t('确认删除'), okType: 'danger', cancelText: t('取消'), onOk: () => mutate(async () => {
await knowledgeItemAction(id, item, 'delete', true);
if (generation === detailGeneration) { editorOpen.value = false; selected.value = null; }
selectedKeys.value = selectedKeys.value.filter((key) => key !== item.id);
message.success(t('已删除'));
}) });
}
async function toggleEnabled(enabled: boolean) {
const id = accountId.value;
await mutate(() => setKnowledgeEnabled(id, enabled));
}
async function test() {
if (busy.value) return;
result.value = null; searchError.value = '';
if (!single.value) { searchError.value = t('请先选择具体账号'); return; }
const text = testQuery.value.trim();
const length = Array.from(text).length;
if (length < 2) { searchError.value = t('请输入至少 2 个字符的检索问题'); return; }
if (length > 2000) { searchError.value = t('检索问题不能超过 2000 个字符'); return; }
testQuery.value = text;
const id = accountId.value;
const generation = detailGeneration;
busy.value = true;
try {
const found = await searchKnowledge(id, text);
if (generation === detailGeneration) result.value = found;
} catch (error) {
if (generation === detailGeneration) searchError.value = requestErrorMessage(error, t('检索失败,请稍后重试'));
} finally { busy.value = false; }
}
async function download() {
const id = accountId.value;
await mutate(async () => { const blob = await exportKnowledge(id); downloadFileFromBlob({ fileName: 'knowledge.jsonl', source: blob }); });
}
function stop() { active = false; detailGeneration++; request.cancel(); if (timer) clearTimeout(timer); }
onActivated(() => {
active = true;
if (scopeReloadPending) { scopeReloadPending = false; void load(); }
else schedule();
});
onDeactivated(stop); onUnmounted(stop);
</script>
<template>
<div class="space-y-4 p-5">
<Card :title="t('知识中心')">
<template #extra><ArchiveAccountSelector v-model="accountId" :allowed-ids="allowedAccountIds" :disabled="busy || createOpen || batchOpen || settingsOpen || reviewOpen" @change="accountChanged" /></template>
<p class="mb-4 text-gray-500">{{ t('把历史聊天整理成可追溯的知识,审核发布后供客服回答时参考。') }}</p>
<Alert v-if="ownScope" class="mb-4" type="info" show-icon :message="t('当前仅显示本人 ZYT 账号名下的知识,包含管理员代为清洗的数据;操作仍按角色权限')" />
<Alert v-if="knowledgeScope?.mode === 'zyt_account' && !knowledgeScope.account_ids.length" class="mb-4" type="info" show-icon :message="t('本人 ZYT 账号暂无可用客户端。')" />
<div class="mb-5 rounded-lg border p-4">
<Steps size="small" :current="guideStep" :items="[{ title: t('整理聊天记录') }, { title: t('生成草稿') }, { title: t('审核知识') }, { title: t('发布并测试使用') }]" />
<p class="mb-0 mt-3 text-gray-500">{{ guideText }}</p>
</div>
<div class="mb-5 grid grid-cols-2 gap-3 md:grid-cols-4">
<div v-for="key in ['draft', 'approved', 'published', 'stale']" :key="key" class="rounded-lg border p-4">
<div class="text-gray-500">{{ labels[key] }}</div><div class="mt-2 text-2xl font-semibold">{{ overview?.counts[key] || 0 }}</div>
</div>
</div>
<Space wrap>
<Tag>{{ overview?.semantic_configured ? t('支持语义与关键词检索') : t('关键词检索已就绪') }}</Tag>
<span>{{ t('客服使用知识') }}</span>
<Switch :checked="!!overview?.settings?.enabled" :disabled="!single || !canEnable || busy || (!overview?.settings?.enabled && !overview?.counts.published)" @change="(v) => toggleEnabled(Boolean(v))" />
<Button v-if="canRun" type="primary" :disabled="busy" @click="startCreate">{{ t('整理聊天记录') }}</Button>
<Button v-if="canSettings" @click="settingsOpen = true">{{ t('整理设置') }}</Button>
<Button v-if="canExport" :disabled="!single || busy" @click="download">{{ t('导出已发布知识') }}</Button>
<Button :loading="loading" @click="load">{{ t('刷新') }}</Button>
</Space>
<Alert v-if="!single" class="mt-4" type="info" show-icon :message="t('当前汇总全部授权账号:整理聊天、查看和审核知识都可以直接进行;检索测试、导出和「客服使用知识」开关需选择具体账号。')" />
</Card>
<Card>
<Tabs v-model:active-key="tab">
<Tabs.TabPane key="items" :tab="t('知识与审核')">
<div class="mb-4 flex flex-wrap items-center justify-between gap-3">
<div class="flex min-w-0 flex-1 flex-wrap gap-3">
<Select v-model:value="filter" :options="statusOptions" style="width: 150px" @change="() => { page = 1; listChanged(); }" />
<Input.Search v-model:value="query" :placeholder="t('搜索标题或问题')" class="w-full sm:!w-72" @search="() => { page = 1; listChanged(); }" />
</div>
<Space v-if="canAutoReview" wrap>
<Button type="primary" :disabled="busy" @click="openFullReview('new')">{{ canApprovePublish ? t('审核并发布全部草稿') : t('审核全部草稿') }}</Button>
<Button @click="openFullReview('jobs')">{{ t('审核任务与结果') }}</Button>
<Tag v-if="reviewJobs.some((job) => ['queued', 'running'].includes(job.status))" color="blue">{{ t('后台审核进行中') }}</Tag>
</Space>
</div>
<div v-if="canBatch && selectedKeys.length" class="mb-4 flex flex-wrap items-center gap-2 rounded border bg-gray-50 p-3 dark:bg-gray-900">
<span class="mr-2">{{ t('已选 {count} 条(当前页)', { count: selectedKeys.length }) }}</span>
<Button v-if="canReview" type="primary" :disabled="!batchAllowed(reviewAction) || busy" @click="openBatch(reviewAction)">{{ canApprovePublish ? t('审核并发布选中') : t('审核选中') }}</Button>
<Button v-if="canPublish" :disabled="!batchAllowed('publish') || busy" @click="openBatch('publish')">{{ t('发布选中') }}</Button>
<Dropdown v-if="canReject || canDisable || canDelete">
<Button :disabled="busy">{{ t('更多操作') }}</Button>
<template #overlay><Menu>
<Menu.Item v-if="canReject" :disabled="!batchAllowed('reject')" @click="openBatch('reject')">{{ t('驳回选中') }}</Menu.Item>
<Menu.Item v-if="canDisable" :disabled="!batchAllowed('disable')" danger @click="openBatch('disable')">{{ t('停用选中') }}</Menu.Item>
<Menu.Item v-if="canDelete" :disabled="!batchAllowed('delete')" danger @click="openBatch('delete')">{{ t('删除已驳回') }}</Menu.Item>
</Menu></template>
</Dropdown>
<Button type="link" @click="selectedKeys = []">{{ t('清空选择') }}</Button>
</div>
<!-- 固定列宽 + 最小 1000px:窗口窄时整表横向滚动,标题列不会把账号、状态挤成一个字一行 -->
<Table :row-selection="rowSelection" :data-source="items" row-key="id" :loading="loading" :pagination="{ current: page, pageSize: 30, total, showSizeChanger: false }" @change="(p) => { page = p.current || 1; listChanged(); }"
:scroll="{ x: 1000 }"
:columns="[{ title: t('问题 / 标题'), dataIndex: 'title', key: 'title' }, ...(single ? [] : [{ title: t('账号'), dataIndex: 'account_label', key: 'account', width: 160 }]), { title: t('分类'), dataIndex: 'category', key: 'category', width: 120 }, { title: t('状态'), key: 'status', width: 130 }, { title: t('版本'), dataIndex: 'revision', width: 75 }, { title: t('更新时间'), key: 'updated_at', width: 150 }]">
<template #emptyText><Empty :description="query || filter ? t('没有符合筛选条件的知识,可调整筛选后重试。') : t('还没有知识,先从历史聊天整理出待审草稿。')"><Button v-if="canRun && !query && !filter" type="primary" @click="startCreate">{{ t('整理聊天记录') }}</Button></Empty></template>
<template #bodyCell="{ column, record }">
<Button v-if="column.key === 'title'" type="link" class="!h-auto whitespace-normal text-left" @click="inspect(record.id)">{{ record.title }}</Button>
<Tag v-else-if="column.key === 'status'" :color="colors[record.status]">{{ labels[record.status] }}</Tag>
<span v-else-if="column.key === 'updated_at'" class="whitespace-nowrap">{{ shortTime(record.updated_at) }}</span>
<template v-else-if="column.key === 'account'">{{ t(record.account_label) }}</template>
<template v-else-if="column.key === 'category'">{{ t(record.category) }}</template>
</template>
</Table>
</Tabs.TabPane>
<Tabs.TabPane key="jobs" :tab="t('整理任务')">
<div v-if="single && overview?.watches.length" class="mb-4 space-y-2">
<div v-for="watch in overview.watches" :key="watch.source_account_id" class="flex items-center gap-3">
<span>{{ sourceOptions.find((s) => s.value === watch.source_account_id)?.label }} · {{ t('新聊天自动整理') }}</span>
<Switch :checked="!!watch.enabled" :disabled="!canWatch || busy" @change="(value) => mutate(() => setKnowledgeWatch(accountId, watch.source_account_id, Boolean(value)))" />
</div>
</div>
<KnowledgeRunsPanel :key="scopeVersion" :runs="runs" :auto="autoSummary" :can-create="canRun" :can-control="canControl"
:can-settings="canSettings" :loading="loading"
@changed="load" @create="startCreate" @settings="settingsOpen = true" />
</Tabs.TabPane>
<Tabs.TabPane v-if="canSearch" key="test" :tab="t('检索测试')">
<p class="text-gray-500">{{ t('测试只检索已发布知识,不发送客服消息。相关度是排序参考,不代表事实正确率。') }}</p>
<Alert v-if="single && overview && !overview.counts.published" class="mb-3" type="info" show-icon :message="t('当前账号暂无已发布知识,请先审核并发布知识后再测试检索。')" />
<Input.Search v-model:value="testQuery" :placeholder="t('输入一个真实业务问题(2–2000 个字符)')" :enter-button="t('检索')" :disabled="!single" :loading="busy" @search="test" @change="searchError = ''" />
<Alert v-if="searchError" class="mt-3" type="error" show-icon :message="searchError" />
<template v-if="result">
<p class="my-4">{{ modes[result.mode] || result.mode }} · {{ result.elapsed_ms }} ms · {{ t('{count} 条命中', { count: result.hits.length }) }}</p>
<Empty v-if="!result.hits.length" :description="overview && !overview.counts.published ? t('当前账号没有已发布知识,审核通过后还需发布才能检索。') : t('没有可靠命中。请补充问题信息,或发布相应知识。')" />
<Card v-for="hit in result.hits" :key="hit.id" class="mb-3" :title="hit.title">
<template #extra><Button type="link" @click="inspect(hit.id)">{{ t('查看来源') }}</Button></template>
<p class="whitespace-pre-wrap">{{ hit.answer }}</p><p class="text-gray-500">{{ t('适用条件:{conditions}', { conditions: hit.conditions }) }}</p>
<Tag>{{ t('版本 {revision}', { revision: hit.revision }) }}</Tag><Tag>{{ t('相关度 {score}', { score: hit.score }) }}</Tag>
</Card>
</template>
</Tabs.TabPane>
<Tabs.TabPane v-if="canTrace" key="traces" :tab="t('引用记录')">
<Table :data-source="traces" row-key="id" :pagination="{ pageSize: 15 }" :columns="[{ title: t('时间'), dataIndex: 'created_at' }, { title: t('问题'), dataIndex: 'query' }, { title: t('知识来源'), key: 'hits' }, { title: t('检索方式'), key: 'mode' }, { title: t('耗时 ms'), dataIndex: 'elapsed_ms' }]">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'hits'"><span v-if="!record.hits.length">{{ t('无命中') }}</span><Button v-for="hit in record.hits" :key="hit.id" type="link" @click="inspect(hit.id)">{{ hit.id.slice(0, 8) }} · v{{ hit.revision }}</Button></template>
<span v-else-if="column.key === 'mode'">{{ modes[record.mode] || record.mode }}</span>
</template>
</Table>
</Tabs.TabPane>
</Tabs>
</Card>
<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); }" />
<Modal v-model:open="editorOpen" :title="t('知识审核与来源')" width="1100px" :footer="null" :destroy-on-close="true">
<template v-if="selected">
<Space class="mb-4"><Tag :color="colors[selected.status]">{{ labels[selected.status] }}</Tag><Tag>{{ t('版本 {revision}', { revision: selected.revision }) }}</Tag><Tag v-if="selected.account_label" color="blue">{{ t('账号:{account}', { account: t(selected.account_label) }) }}</Tag></Space>
<Alert v-for="flag in selected.flags" :key="flag" :message="t(flag)" type="warning" class="mb-2" />
<div class="mt-4 grid gap-6 md:grid-cols-2">
<div><h3 class="mb-3 font-semibold">{{ t('来源对话(已自动脱敏)') }}</h3>
<Empty v-if="!selected.sources?.length" :description="t('暂无可查看的来源,请检查正文查看权限')" />
<div v-for="source in selected.sources" :key="source.message_id" class="mb-3 rounded border p-3">
<div class="mb-1 text-xs text-gray-500">{{ source.role === 'staff' ? t('客服') : t('客户') }} · {{ source.sent_at }} · v{{ source.version_no }}</div>
<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>
</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('审核操作会先保存修改,再按保存后的版本执行;失败时不会自动重试。')" />
<p v-if="canReview && (selected.status === 'draft' || dirty)" class="my-3 text-gray-500">{{ t('请核对来源、事实、脱敏与适用条件,点击审核按钮即确认当前内容。') }}</p>
<Space wrap>
<Button v-if="canEdit" :loading="busy" :disabled="selected.status === 'stale'" @click="save">{{ t('保存草稿') }}</Button>
<Button v-if="canReview && (selected.status === 'draft' || (dirty && selected.status !== 'stale'))" type="primary" :loading="busy" :disabled="busy || !selected.conditions.trim() || (dirty && !canEdit)" @click="review">{{ reviewText }}</Button>
<Button v-if="canReject && ['draft', 'approved'].includes(selected.status)" danger :disabled="busy" @click="act('reject')">{{ t('驳回') }}</Button>
<Button v-if="canPublish && selected.status === 'approved' && !dirty" type="primary" :loading="busy" :disabled="dirty" @click="act('publish')">{{ t('发布到知识库') }}</Button>
<Button v-if="canDelete && selected.status === 'rejected'" danger :disabled="busy" @click="deleteSelected">{{ t('删除已驳回知识') }}</Button>
<Button v-if="canDisable && selected.status === 'published'" danger :disabled="busy" @click="act('disable')">{{ t('停用') }}</Button>
</Space>
<div class="mt-5 border-t pt-3"><h3 class="font-semibold">{{ t('版本与操作记录') }}</h3>
<div v-for="(history, index) in selected.history" :key="index" class="flex items-center justify-between py-1 text-sm">
<span>v{{ history.revision }} · {{ history.action }} · {{ history.created_at }}</span>
<Button v-if="canRestore && history.revision < selected.revision" type="link" :disabled="busy" @click="act('restore', history.revision)">{{ t('恢复为草稿') }}</Button>
</div>
</div>
</template>
</Modal>
</div>
</template>
@@ -0,0 +1,367 @@
import { createApp, defineComponent, h, nextTick, onMounted, ref } from 'vue';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const api = vi.hoisted(() => ({
fetchKnowledgeOverview: vi.fn(), fetchKnowledgeItems: vi.fn(), fetchKnowledgeRuns: vi.fn(),
fetchKnowledgeTraces: vi.fn(), fetchKnowledgeReviewJobs: vi.fn(), fetchKnowledgeItem: vi.fn(),
fetchKnowledgeReviewResults: vi.fn(), previewKnowledgeReview: vi.fn(), knowledgeReviewAction: vi.fn(),
exportKnowledge: vi.fn(), knowledgeItemAction: vi.fn(), saveKnowledgeItem: vi.fn(), searchKnowledge: vi.fn(),
setKnowledgeEnabled: vi.fn(), setKnowledgeWatch: vi.fn(),
}));
const accessCodes = ref<string[]>([]);
vi.mock('@vben/access', () => ({ useAccess: () => ({
hasAccessByCodes: (codes: string[]) => codes.some((code) => accessCodes.value.includes(code)),
}) }));
vi.mock('@vben/utils', () => ({ downloadFileFromBlob: vi.fn() }));
vi.mock('#/api/knowledge', () => api);
vi.mock('#/api/console', () => ({ ALL_ACCOUNTS: -1,
fetchDesktopAccounts: async () => ({ accounts: [], can_view_legacy: false }),
}));
vi.mock('#/api/error-message', () => ({ requestErrorMessage: () => 'error' }));
vi.mock('#/locales/t', () => ({ t: (value: string) => value }));
vi.mock('#/components/archive-account-selector.vue', () => ({ default: defineComponent({
emits: ['change'], setup(_props, { emit }) { onMounted(() => emit('change', -1)); return () => h('div'); },
}) }));
vi.mock('./run-dialog.vue', () => ({ default: defineComponent({ setup: () => () => null }) }));
vi.mock('./runs-panel.vue', () => ({ default: defineComponent({ setup: () => () => null }) }));
vi.mock('./settings-dialog.vue', () => ({ default: defineComponent({ setup: () => () => null }) }));
vi.mock('./batch-dialog.vue', () => ({ default: defineComponent({ setup: () => () => null }) }));
vi.mock('ant-design-vue', async () => {
const { defineComponent, h } = await import('vue');
const plain = defineComponent({ setup: (_props, { slots }) => () => h('div', [slots.extra?.(), slots.default?.()]) });
const input = Object.assign({}, plain, { Search: plain, TextArea: plain });
return {
Alert: defineComponent({ props: ['message'], setup: (props) => () => h('p', props.message) }),
Modal: Object.assign(defineComponent({ props: ['open'], setup: (props, { slots }) =>
() => props.open ? h('section', slots.default?.()) : null }), { confirm: vi.fn() }),
Table: defineComponent({ props: ['dataSource'], setup: (props) => () =>
h('div', (props.dataSource || []).map((row: { title?: string }) => h('span', row.title))) }),
Form: Object.assign({}, plain, { Item: plain }), Tabs: Object.assign({}, plain, { TabPane: plain }),
Input: input, Button: plain, Card: plain, Dropdown: plain, Menu: Object.assign({}, plain, { Item: plain }), Empty: plain, Select: plain, Space: plain,
Steps: plain, Switch: plain, Tag: plain, Progress: plain, message: { success: vi.fn() },
};
});
import KnowledgeCenter from './center.vue';
let cleanup: (() => void) | undefined;
const item = (id: string) => ({ id, title: id, question: 'question', answer: 'answer', conditions: 'condition',
category: '', kind: 'qa', status: 'draft', revision: 1, flags: [], sources: [], history: [] });
async function settle() { for (let index = 0; index < 12; index++) { await Promise.resolve(); await nextTick(); } }
function mount() {
const host = document.createElement('div'); document.body.append(host);
const app = createApp(KnowledgeCenter); const vm = app.mount(host);
cleanup = () => { app.unmount(); host.remove(); };
return { host, state: (vm.$ as unknown as { setupState: Record<string, any> }).setupState, instance: vm.$ };
}
function findReview(node: any): any {
if (node?.component?.type.__file?.endsWith('review-all.vue')) return node.component;
const nested = node?.component && findReview(node.component.subTree);
return nested || (Array.isArray(node?.children) && node.children.map(findReview).find(Boolean));
}
describe('knowledge own scope updates', () => {
beforeEach(() => {
vi.clearAllMocks();
accessCodes.value = ['knowledge:read', 'knowledge:review', 'knowledge:review:auto', 'im:content:read'];
api.fetchKnowledgeOverview.mockImplementation(async () => ({ counts: { draft: 1 }, source_accounts: [], watches: [], settings: null,
knowledge_scope: accessCodes.value.includes('knowledge:scope:own')
? { mode: 'zyt_account', account_ids: [1] } : { mode: 'existing', account_ids: [] } }));
api.fetchKnowledgeItems.mockResolvedValue({ items: [item('other-knowledge')], total: 1 });
api.fetchKnowledgeRuns.mockResolvedValue({ items: [], auto: null });
api.fetchKnowledgeTraces.mockResolvedValue({ items: [] });
api.fetchKnowledgeReviewJobs.mockResolvedValue({ items: [] });
api.fetchKnowledgeReviewResults.mockResolvedValue({ items: [], total: 0 });
api.fetchKnowledgeItem.mockResolvedValue(item('other-knowledge'));
api.previewKnowledgeReview.mockResolvedValue({ id: 'preview', account_id: -1, scope_label: 'scope', total: 1,
mode: 'approve', published: 0, preview: { snapshot_at: '', eligible: 1, blocked: 0, accounts: [], reasons: [] } });
});
afterEach(() => { cleanup?.(); cleanup = undefined; });
it('clears old rows, detail, selections and review preview immediately, then reloads both scope changes', async () => {
const { host, state, instance } = mount(); await settle();
expect(host.textContent).toContain('other-knowledge');
await state.inspect('other-knowledge');
state.selectedKeys = ['other-knowledge']; state.batchEntries = [item('other-knowledge')];
state.batchOpen = true; state.reviewOpen = true; await settle();
const oldReview = findReview(instance.subTree);
expect(oldReview).toBeTruthy();
oldReview.setupState.preview = { scope_label: 'previous-preview', total: 1,
mode: 'approve', published: 0, preview: { snapshot_at: '', eligible: 1, blocked: 0, accounts: [], reasons: [] } };
const version = state.scopeVersion;
let resolveRows!: (value: unknown) => void;
api.fetchKnowledgeItems.mockImplementationOnce(() => new Promise((resolve) => { resolveRows = resolve; }));
accessCodes.value = [...accessCodes.value, 'knowledge:scope:own'];
expect(state.items).toEqual([]); expect(state.selected).toBeNull();
expect(state.selectedKeys).toEqual([]); expect(state.batchEntries).toEqual([]);
expect(state.editorOpen).toBe(false); expect(state.batchOpen).toBe(false); expect(state.reviewOpen).toBe(false);
expect(state.scopeVersion).toBe(version + 1);
await settle();
const currentReview = findReview(instance.subTree);
expect(currentReview.uid).not.toBe(oldReview.uid); expect(oldReview.isUnmounted).toBe(true);
expect(currentReview.setupState.preview).toBeNull();
expect(host.textContent).toContain('当前仅显示本人 ZYT 账号名下的知识,包含管理员代为清洗的数据;操作仍按角色权限');
expect(host.textContent).not.toContain('other-knowledge');
resolveRows({ items: [item('own-knowledge')], total: 1 }); await settle();
expect(host.textContent).toContain('own-knowledge');
api.fetchKnowledgeItems.mockResolvedValue({ items: [item('all-knowledge')], total: 1 });
accessCodes.value = accessCodes.value.filter((code) => code !== 'knowledge:scope:own'); await settle();
expect(host.textContent).toContain('all-knowledge');
expect(host.textContent).not.toContain('当前仅显示本人 ZYT 账号名下的知识,包含管理员代为清洗的数据;操作仍按角色权限');
});
it('ignores in-flight list, detail and search results from the previous scope', async () => {
const { host, state } = mount(); await settle();
let resolveRows!: (value: unknown) => void;
let resolveDetail!: (value: unknown) => void;
let resolveSearch!: (value: unknown) => void;
api.fetchKnowledgeItems.mockImplementationOnce(() => new Promise((resolve) => { resolveRows = resolve; }));
api.fetchKnowledgeItem.mockImplementationOnce(() => new Promise((resolve) => { resolveDetail = resolve; }));
api.searchKnowledge.mockImplementationOnce(() => new Promise((resolve) => { resolveSearch = resolve; }));
const oldLoad = state.load(); const oldInspect = state.inspect('old-detail');
state.accountId = 1; state.testQuery = 'query'; const oldSearch = state.test();
await settle();
api.fetchKnowledgeItems.mockResolvedValue({ items: [item('own-knowledge')], total: 1 });
accessCodes.value = [...accessCodes.value, 'knowledge:scope:own']; await settle();
resolveRows({ items: [item('old-list')], total: 1 });
resolveDetail(item('old-detail')); resolveSearch({ hits: [item('old-search')] });
await Promise.all([oldLoad, oldInspect, oldSearch]); await settle();
expect(host.textContent).toContain('own-knowledge');
expect(host.textContent).not.toMatch(/old-list|old-detail|old-search/);
expect(state.selected).toBeNull(); expect(state.result).toBeNull(); expect(state.editorOpen).toBe(false);
});
it('cannot restore a previous review preview from an in-flight response after scope narrowing', async () => {
const { host, state, instance } = mount(); await settle();
state.reviewOpen = true; await settle();
const previous = findReview(instance.subTree);
let resolvePreview!: (value: unknown) => void;
api.previewKnowledgeReview.mockImplementationOnce(() => new Promise((resolve) => { resolvePreview = resolve; }));
const pending = previous.setupState.inspectScope();
await settle();
accessCodes.value = [...accessCodes.value, 'knowledge:scope:own']; await settle();
resolvePreview({ scope_label: 'old-review-preview', total: 1,
mode: 'approve', published: 0, preview: { snapshot_at: '', eligible: 1, blocked: 0, accounts: [], reasons: [] } });
await pending; await settle();
expect(previous.isUnmounted).toBe(true); expect(findReview(instance.subTree).setupState.preview).toBeNull();
expect(host.textContent).not.toContain('old-review-preview'); expect(state.reviewOpen).toBe(false);
});
it('does not grant review or source access when only the scope flag is held', async () => {
accessCodes.value = ['knowledge:read', 'knowledge:scope:own'];
const { host, state } = mount(); await settle();
expect(state.canReview).toBe(false); expect(state.canAutoReview).toBe(false); expect(state.canEdit).toBe(false);
expect(host.textContent).toContain('当前仅显示本人 ZYT 账号名下的知识,包含管理员代为清洗的数据;操作仍按角色权限');
expect(host.textContent).not.toContain('批量审核');
});
it('limits account choices from the trusted overview and resets an inaccessible selected account before loading its data', async () => {
accessCodes.value.push('knowledge:scope:own');
const { state, instance } = mount(); await settle();
expect(state.allowedAccountIds).toEqual([1]);
const review = findReview(instance.subTree);
review.setupState.accountList = { can_view_legacy: true, accounts: [
{ id: 1, nickname: 'own client', zyt_sn: 'own' }, { id: 2, nickname: 'other client', zyt_sn: 'other' },
] };
expect(review.setupState.accounts.map((entry: { value: number }) => entry.value)).toEqual([-1, 1]);
await state.inspect('old-detail'); state.selectedKeys = ['old-detail'];
state.accountId = 2;
api.fetchKnowledgeItems.mockClear(); api.fetchKnowledgeOverview.mockClear();
await state.load(); await settle();
expect(state.accountId).toBe(-1); expect(state.selected).toBeNull(); expect(state.selectedKeys).toEqual([]);
expect(api.fetchKnowledgeOverview.mock.calls.every(([id]) => id === -1)).toBe(true);
expect(api.fetchKnowledgeItems.mock.calls.every(([id]) => id === -1)).toBe(true);
});
it('keeps choices empty before scope resolves and for an account with no eligible client', async () => {
accessCodes.value.push('knowledge:scope:own');
let resolveScope!: (value: unknown) => void;
api.fetchKnowledgeOverview.mockImplementationOnce(() => new Promise((resolve) => { resolveScope = resolve; }));
const { host, state } = mount(); await settle();
expect(state.allowedAccountIds).toEqual([]); expect(api.fetchKnowledgeItems).not.toHaveBeenCalled();
resolveScope({ counts: {}, source_accounts: [], watches: [], settings: null,
knowledge_scope: { mode: 'zyt_account', account_ids: [] } });
await settle();
expect(state.allowedAccountIds).toEqual([]); expect(host.textContent).toContain('本人 ZYT 账号暂无可用客户端。');
});
it('uses the backend existing scope for administrators even when the scope code is present', async () => {
accessCodes.value.push('knowledge:scope:own');
api.fetchKnowledgeOverview.mockResolvedValue({ counts: {}, source_accounts: [], watches: [], settings: null,
knowledge_scope: { mode: 'existing', account_ids: [] } });
const { host, state } = mount(); await settle();
expect(state.ownScope).toBe(false); expect(state.allowedAccountIds).toBeUndefined();
expect(host.textContent).not.toContain('当前仅显示本人 ZYT 账号名下的知识');
});
it('ignores an old overview response after permissions narrow', async () => {
const { state } = mount(); await settle();
let resolveScope!: (value: unknown) => void;
api.fetchKnowledgeOverview.mockImplementationOnce(() => new Promise((resolve) => { resolveScope = resolve; }));
const pending = state.load();
accessCodes.value.push('knowledge:scope:own'); await settle();
resolveScope({ knowledge_scope: { mode: 'existing', account_ids: [] } }); await pending; await settle();
expect(state.ownScope).toBe(true); expect(state.allowedAccountIds).toEqual([1]);
});
it('clears all-account detail, selections and fixed review preview when eligible clients disappear without a flag change', async () => {
accessCodes.value.push('knowledge:scope:own');
const { state, instance } = mount(); await settle();
await state.inspect('previous-detail'); state.selectedKeys = ['previous-detail'];
state.batchEntries = [item('previous-detail')]; state.reviewOpen = true; await settle();
const oldReview = findReview(instance.subTree);
oldReview.setupState.preview = { scope_label: 'old-preview', total: 1,
mode: 'approve', published: 0, preview: { snapshot_at: '', eligible: 1, blocked: 0, accounts: [], reasons: [] } };
let resolveDetail!: (value: unknown) => void;
api.fetchKnowledgeItem.mockImplementationOnce(() => new Promise((resolve) => { resolveDetail = resolve; }));
const oldDetail = state.inspect('in-flight-detail');
api.fetchKnowledgeOverview.mockResolvedValue({ counts: {}, source_accounts: [], watches: [], settings: null,
knowledge_scope: { mode: 'zyt_account', account_ids: [] } });
api.fetchKnowledgeItems.mockResolvedValue({ items: [], total: 0 });
await state.load(); await settle();
resolveDetail(item('in-flight-detail')); await oldDetail; await settle();
expect(state.accountId).toBe(-1); expect(state.ownScopeFlag).toBe(true); expect(state.selected).toBeNull();
expect(state.selectedKeys).toEqual([]); expect(state.batchEntries).toEqual([]); expect(state.reviewOpen).toBe(false);
expect(oldReview.isUnmounted).toBe(true); expect(findReview(instance.subTree).setupState.preview).toBeNull();
});
it('does not discard an open detail for an equivalent reordered account set', async () => {
accessCodes.value.push('knowledge:scope:own');
api.fetchKnowledgeOverview.mockResolvedValue({ counts: {}, source_accounts: [], watches: [], settings: null,
knowledge_scope: { mode: 'zyt_account', account_ids: [1, 2] } });
const { state } = mount(); await settle();
api.fetchKnowledgeItem.mockResolvedValueOnce(item('still-visible')); await state.inspect('still-visible');
const version = state.scopeVersion;
api.fetchKnowledgeOverview.mockResolvedValue({ counts: {}, source_accounts: [], watches: [], settings: null,
knowledge_scope: { mode: 'zyt_account', account_ids: [2, 1, 2] } });
await state.load(); await settle();
expect(state.scopeVersion).toBe(version); expect(state.selected.id).toBe('still-visible');
});
it('reviews only after an explicit action and uses the saved revision for edited content', async () => {
accessCodes.value.push('knowledge:publish', 'knowledge:write');
const { state } = mount(); await settle(); await state.inspect('other-knowledge');
expect(api.knowledgeItemAction).not.toHaveBeenCalled();
state.selected.answer = 'edited answer';
api.saveKnowledgeItem.mockImplementationOnce(async (_account, entry) => ({ ...entry, revision: 2, status: 'draft' }));
api.knowledgeItemAction.mockImplementationOnce(async (_account, entry) => ({ ...entry, revision: 3, status: 'published' }));
await state.review();
expect(api.saveKnowledgeItem).toHaveBeenCalledTimes(1);
expect(api.knowledgeItemAction).toHaveBeenCalledTimes(1);
expect(api.knowledgeItemAction.mock.calls[0]).toMatchObject([-1, { revision: 2, answer: 'edited answer' }, 'approve_publish', true]);
});
it('keeps review-only permission as approve and does not permit a combined batch action', async () => {
const { state } = mount(); await settle(); await state.inspect('other-knowledge');
expect(state.canApprovePublish).toBe(false); expect(state.reviewAction).toBe('approve');
state.selectedKeys = ['other-knowledge']; state.openBatch('approve_publish'); expect(state.batchOpen).toBe(false);
api.knowledgeItemAction.mockImplementationOnce(async (_account, entry) => ({ ...entry, revision: 2, status: 'approved' }));
await state.review();
expect(api.knowledgeItemAction.mock.calls[0]?.slice(2)).toEqual(['approve', true]);
});
it('requires content access for combined review and allows eligible rows in mixed selections', async () => {
accessCodes.value.push('knowledge:publish');
const { state } = mount(); await settle();
state.items = [item('draft'), { ...item('approved'), status: 'approved' }];
state.selectedKeys = ['draft', 'approved'];
expect(state.batchAllowed('approve_publish')).toBe(true); expect(state.batchAllowed('publish')).toBe(true);
accessCodes.value = accessCodes.value.filter((code) => code !== 'im:content:read');
expect(state.canApprovePublish).toBe(false); expect(state.batchAllowed('approve_publish')).toBe(false);
});
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';
api.saveKnowledgeItem.mockImplementationOnce(async (_account, entry) => ({ ...entry, revision: 2, status: 'draft' }));
api.knowledgeItemAction.mockRejectedValueOnce({ response: { data: { detail: '版本冲突' } } });
await state.review();
expect(state.selected.revision).toBe(2); expect(state.dirty).toBe(false); expect(state.editorError).toBe('版本冲突');
expect(api.saveKnowledgeItem).toHaveBeenCalledTimes(1); expect(api.knowledgeItemAction).toHaveBeenCalledTimes(1);
});
it('does not act after a failed save or after the scope changes during save', async () => {
accessCodes.value.push('knowledge:publish', 'knowledge:write');
const { state } = mount(); await settle(); await state.inspect('other-knowledge'); state.selected.answer = 'edited';
api.saveKnowledgeItem.mockRejectedValueOnce(new Error('save failed')); await state.review();
expect(api.knowledgeItemAction).not.toHaveBeenCalled();
let resolveSave!: (value: unknown) => void;
api.saveKnowledgeItem.mockImplementationOnce(() => new Promise((resolve) => { resolveSave = resolve; }));
const pending = state.review(); accessCodes.value.push('knowledge:scope:own'); await settle();
resolveSave({ ...item('other-knowledge'), revision: 2 }); await pending;
expect(api.knowledgeItemAction).not.toHaveBeenCalled(); expect(state.selected).toBeNull();
});
it('opens the next visible pending item only after successful explicit review', async () => {
api.fetchKnowledgeItems.mockResolvedValue({ items: [item('next')], total: 1 });
const { state } = mount(); await settle(); await state.inspect('other-knowledge');
api.knowledgeItemAction.mockImplementationOnce(async (_account, entry) => ({ ...entry, revision: 2, status: 'approved' }));
api.fetchKnowledgeItem.mockResolvedValueOnce(item('next')); await state.review();
expect(state.selected.id).toBe('next'); expect(state.editorOpen).toBe(true);
});
it('automatically previews a changed review scope but starts only on explicit confirmation', async () => {
const { state, instance } = mount(); await settle(); state.reviewOpen = true; await settle();
const review = findReview(instance.subTree).setupState;
expect(api.previewKnowledgeReview).toHaveBeenCalledWith(-1, 'approve'); expect(api.knowledgeReviewAction).not.toHaveBeenCalled();
api.previewKnowledgeReview.mockResolvedValueOnce({ id: 'account-preview', account_id: 1, scope_label: 'account', total: 1,
mode: 'approve', published: 0, preview: { snapshot_at: '', eligible: 1, blocked: 0, accounts: [], reasons: [] } });
review.scopeId = 1; await settle(); expect(api.previewKnowledgeReview).toHaveBeenLastCalledWith(1, 'approve');
api.knowledgeReviewAction.mockResolvedValueOnce({ id: 'job', status: 'queued' });
await review.start(); expect(api.knowledgeReviewAction).toHaveBeenCalledWith('account-preview', 'start', true);
});
it('does not preview or start all-account work when an own scope has no allowed clients', async () => {
accessCodes.value.push('knowledge:scope:own');
api.fetchKnowledgeOverview.mockResolvedValue({ counts: {}, source_accounts: [], watches: [], settings: null,
knowledge_scope: { mode: 'zyt_account', account_ids: [] } });
const { state, instance } = mount(); await settle(); state.reviewOpen = true; await settle();
const review = findReview(instance.subTree).setupState;
expect(review.accounts).toEqual([]); expect(review.scopeAllowed).toBe(false);
await review.start(); expect(api.previewKnowledgeReview).not.toHaveBeenCalled(); expect(api.knowledgeReviewAction).not.toHaveBeenCalled();
});
it('rejects stale automatic preview responses after a newer scope has loaded', async () => {
const { state, instance } = mount(); await settle(); state.reviewOpen = true; await settle();
const review = findReview(instance.subTree).setupState;
let resolvePreview!: (value: unknown) => void;
api.previewKnowledgeReview.mockImplementationOnce(() => new Promise((resolve) => { resolvePreview = resolve; }));
review.scopeId = 1; await settle();
api.previewKnowledgeReview.mockResolvedValueOnce({ id: 'new', account_id: 2, scope_label: 'new', total: 1,
mode: 'approve', published: 0, preview: { snapshot_at: '', eligible: 1, blocked: 0, accounts: [], reasons: [] } });
review.scopeId = 2; await settle();
resolvePreview({ id: 'old', scope_label: 'old' }); await settle(); expect(review.preview.id).toBe('new');
});
it('closes a successful combined full-review dialog, reloads the knowledge list, and leaves the editor closed', async () => {
accessCodes.value.push('knowledge:publish');
api.previewKnowledgeReview.mockImplementation(async (account, mode) => ({ id: 'combined-preview', account_id: account, mode,
published: 0, scope_label: 'all', total: 1, preview: { eligible: 1, blocked: 0, snapshot_at: '', accounts: [], reasons: [] } }));
const { state, instance, host } = mount(); await settle();
expect(host.textContent).toContain('审核并发布全部草稿');
state.reviewOpen = true; await settle();
const review = findReview(instance.subTree).setupState;
expect(api.previewKnowledgeReview).toHaveBeenLastCalledWith(-1, 'approve_publish');
let resolveStart!: (value: unknown) => void;
api.knowledgeReviewAction.mockImplementationOnce(() => new Promise((resolve) => { resolveStart = resolve; }));
const pending = review.start(); await settle(); expect(state.reviewOpen).toBe(true);
const listReads = api.fetchKnowledgeItems.mock.calls.length;
resolveStart({ id: 'combined-job', mode: 'approve_publish', status: 'completed', total: 1, processed: 1, published: 1, approved: 1, skipped: 0, error: '' });
await pending; await settle();
expect(state.reviewOpen).toBe(false); expect(state.editorOpen).toBe(false); expect(state.selected).toBeNull();
expect(state.accountId).toBe(-1); expect(api.fetchKnowledgeItems.mock.calls.length).toBeGreaterThan(listReads);
expect(api.fetchKnowledgeItem).not.toHaveBeenCalled(); expect(api.knowledgeItemAction).not.toHaveBeenCalled();
});
it('keeps the original full-review workflow for an auto reviewer without manual review permission', async () => {
accessCodes.value = ['knowledge:read', 'knowledge:review:auto', 'im:content:read', 'knowledge:publish'];
const { state, instance } = mount(); await settle();
expect(state.canAutoReview).toBe(true); state.reviewOpen = true; await settle();
const review = findReview(instance.subTree).setupState;
expect(review.mode).toBe('approve'); expect(api.previewKnowledgeReview).toHaveBeenLastCalledWith(-1, 'approve');
api.knowledgeReviewAction.mockResolvedValueOnce({ id: 'approve-job', mode: 'approve', status: 'completed', approved: 1, published: 0, skipped: 0 });
await review.start(); await settle(); expect(state.reviewOpen).toBe(true);
expect(api.knowledgeReviewAction).toHaveBeenCalledWith('preview', 'start', true);
});
});