fix(XZH-21): 统一回收站路由与模块标签、历史旧口径对齐、升级后会话不再误判

- AdminTools.vue: 回收站恢复/永久删除统一走 /admin-tools/trash/{kind}/{id}(RSS/提示词/工作流/收集箱此前拼到 /library → 404);模块标签改由后端 /admin-tools/trash/kinds 提供;过滤下拉覆盖全部 11 个模块
- adminRoutes.ts: moduleNames 与后端 TrashService 对齐(笔记/素材…),补 prompts/flows/inbox
- AdminToolsController: TRASH 视图限定 planner kind;新增 GET /admin-tools/trash/kinds
- LibraryController: /library/{kind}/trash 接受全部 kind,与 /admin-tools/trash 行为一致;删除通知标题列改用 TrashService.titleColumn(笔记不再写成素材)
- NotesController: history/{n} 对旧口径行按「≤n 的最大旧版本号」解析,旧库升级后最高一版保存前内容可读、恢复写回正确内容
- App.vue: 401 先确认 /auth/me,避免切模块时偶发 401 清掉登录态导致白屏
This commit is contained in:
xzh committed 2026-11-11 22:41:48 +08:00
1 parent a60ea8d262
commit bd8264b8cf
6 files changed
+83 -29

No files matched your search

@@ -32,13 +32,25 @@ public class AdminToolsController {
union all select 'blogs',id,title,deleted_at,category from blogs
union all select 'bookmarks',id,title,deleted_at,category from bookmarks
union all select 'assets',id,name,deleted_at,category from assets
union all select kind,id,title,deleted_at,'' from planner_items
union all select kind,id,title,deleted_at,'' from planner_items where kind in ('tasks','events','snippets')
union all select 'rss',id,title,deleted_at,category from rss_sources
union all select 'prompts',id,title,deleted_at,category from ai_prompts
union all select 'flows',id,title,deleted_at,'' from workspace_flows
union all select 'inbox',id,title,deleted_at,'收集箱' from inbox_items
""";
/**
* 回收站每个 kind 的表与标题列。前端据此决定调用哪个回收站接口,
* 新增模块只需改 TrashService 一处,不再在前端重复维护 kind → 路由映射。
*/
@GetMapping("/trash/kinds")
public List<Map<String,Object>> trashKinds() {
List<Map<String,Object>> kinds=new ArrayList<>();
for(String kind:TrashService.KINDS) kinds.add(Map.of("kind",kind,"label",TrashService.label(kind),
"titleColumn",TrashService.titleColumn(kind),"planner",TrashService.isPlanner(kind)));
return kinds;
}
public record Name(@NotBlank @Size(max=60) String name) {}
public record Flow(@NotBlank @Size(max=60) String title,@NotBlank @Size(max=8000) String instructions) {}
public record Preferences(@NotBlank @Size(max=60) String display_name,@NotNull @Size(max=300) String bio, boolean autosave) {}
@@ -160,32 +160,37 @@ public class LibraryController {
+ " where id=? and deleted_at is null", id);
}
/** 回收站列表只覆盖知识库类模块;RSS/提示词/工作流/收集箱用 /admin-tools/trash。 */
@GetMapping("/{kind}/trash")
public List<Map<String, Object>> trashList(@PathVariable String kind,
@RequestParam(defaultValue = "0") @Min(0) int offset) {
checkKind(kind);
return db.queryForList("select id," + (kind.equals("assets") ? "name as title" : "title")
return db.queryForList("select id," + TrashService.titleColumn(kind) + " as title"
+ ",deleted_at from " + kind + " where deleted_at is not null order by deleted_at desc,id limit 100 offset ?", offset);
}
/** 回收站恢复/永久删除统一走 TrashService,分类缺失时自动补回。 */
/**
* 回收站恢复/永久删除统一走 TrashService,分类缺失时自动补回。
* 接受 TrashService 的全部 kind,与 /admin-tools/trash/{kind}/{id} 等价,避免同一记录在两套路由上行为不同。
*/
@PostMapping("/{kind}/trash/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void restore(@PathVariable String kind, @PathVariable UUID id) {
checkKind(kind);
TrashService.spec(kind);
trash.restore(kind, id);
}
@DeleteMapping("/{kind}/trash/{id}")
@ResponseStatus(HttpStatus.NO_CONTENT)
public void purge(@PathVariable String kind, @PathVariable UUID id) {
checkKind(kind);
TrashService.spec(kind);
trash.purge(kind, id);
}
@Transactional
private int trashOne(String kind, UUID id) {
String title = db.queryForList("select " + (kind.equals("assets") ? "name" : "title") + " from " + kind
// 标题列以 TrashService 为准:素材的标题列是 name,其余是 title
String title = db.queryForList("select " + TrashService.titleColumn(kind) + " from " + kind
+ " where id=? and deleted_at is null for update", String.class, id).stream().findFirst()
.orElseThrow(LibraryController::missing);
if (trash(kind, id) == 0) throw missing();
@@ -179,13 +179,28 @@ public class NotesController {
/**
* 取历史 version 的内容。保存前快照以「保存后的版本号」写入,因此 history/N 永远是「第 N 版保存前的内容」,
* 编号与 notes.version 连续、无空洞。旧口径(V18 之前写入的行)与新快照同号时以新快照为准。
* 编号与 notes.version 连续、无空洞。旧口径(V18 之前写入的行)会按 legacy 映射归到对应版本号,见 {@link #legacyAnchor}。
*/
private Map<String, Object> contentAt(Map<String, Object> note, long version) {
return db.queryForList("select title,body,category,folder,tags,star,saved_at from note_history"
+ " where note_id=? and version=? order by legacy_versioning limit 1", note.get("id"), version)
.stream().findFirst()
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "版本不存在"));
return contentAt((UUID) note.get("id"), version);
}
/**
* 某个版本号对应的「保存前内容」。新旧口径在库里的编号规则不同:
* 新口径行 version=N 就是第 N 版保存前;旧口径行 version=N 是第 N 版保存前、第 N+1 版的内容,
* 所以旧行只在「≤ N 的最大旧版本号」这一次被使用——旧库升级后最高版本的保存前内容正好在这一行。
* 旧行不会压过更新的新快照(新快照优先),新保存的快照也不会被旧行顶替。读取与恢复共用这一份映射。
*/
private Map<String, Object> contentAt(UUID noteId, long version) {
// 1) 同号行(新口径优先);2) 否则取旧口径锚点行:≤ N 的最大旧版本号,旧库没有更高版本的旧行时就是最高一版
var row = db.queryForList("select * from note_history where note_id=? and version=?"
+ " order by legacy_versioning limit 1", noteId, version).stream().findFirst();
if (row.isEmpty() && version > 0)
row = db.queryForList("select * from note_history where note_id=? and version=(select coalesce("
+ " (select max(l.version) from note_history l where l.note_id=? and l.legacy_versioning and l.version<=?),"
+ " (select n.version-1 from notes n where n.id=?))) and legacy_versioning", noteId, noteId, version, noteId)
.stream().findFirst();
return row.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "版本不存在"));
}
public record Restore(@Min(0) Long currentVersion) {}
@@ -197,10 +212,8 @@ public class NotesController {
var current = lock(id);
// 版本号可选:旧调用方仍传 currentVersion 做并发校验;新调用方不传,就以库内最新内容为准
if (input != null && input.currentVersion() != null) checkVersion(current, input.currentVersion());
// 恢复必须基于真实的历史行,不能落到「当前内容」兜底
var old = db.queryForList("select title,body,category,folder,tags,star,saved_at from note_history"
+ " where note_id=? and version=?", id, version).stream().findFirst()
.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "版本不存在"));
// 恢复必须基于真实的历史行,不能落到「当前内容」兜底;版本号解析与 GET /history/{version} 一致
var old = contentAt(id, version);
String category = db.queryForList("select name from note_categories where name=?",
String.class, old.get("category")).stream().findFirst().orElse((String) current.get("category"));
String tags = (String) old.get("tags");
+14 -7
View File
@@ -6,11 +6,12 @@ import BookmarkTransfer from "./BookmarkTransfer.vue";
import Icon from "./Icon.vue";
import NoteHistory from "./NoteHistory.vue";
import { moduleNames, toolPages } from "./adminRoutes";
import type { ModuleKind, ToolId } from "./adminRoutes";
import type { ModuleKind, PlannerKind, ToolId } from "./adminRoutes";
import type { LibraryNote } from "./library";
interface Summary { tags:number; versions:number; trash:number; flows:number; inbox:number }
interface Row { id:string; title:string; kind:ModuleKind; deleted_at:string; versions:number; folder:string; category:string }
interface TrashKind { kind:ModuleKind; label:string; titleColumn:string; planner:boolean }
interface Flow { id:string; title:string; instructions:string }
interface Run { id:string; title:string; result:string; created_at:string }
const props=defineProps<{ page:ToolId|"tools"; summary:Summary }>();
@@ -21,7 +22,11 @@ const flows=ref<Flow[]>([]);
const runs=ref<Run[]>([]);
const result=ref<Run|null>(null);
const kind=ref<ModuleKind|"">("");
const batchKind=ref<Exclude<ModuleKind,"rss">>("notes");
const trashKinds=ref<TrashKind[]>([]);
// 回收站模块标签由后端 /admin-tools/trash/kinds 给出,新增模块不用再同步前端
const kindLabels=computed<Partial<Record<ModuleKind,string>>>(() =>
Object.fromEntries(trashKinds.value.map(item=>[item.kind,item.label])));
const batchKind=ref<"notes"|"blogs"|"assets"|"bookmarks"|PlannerKind>("notes");
const categories=ref<string[]>([]);
const selected=ref<string[]>([]);
const query=ref("");
@@ -54,6 +59,7 @@ async function load() {
busy.value=true; error.value="";
try {
const params=new URLSearchParams({q:query.value,kind:kind.value,offset:String(offset.value)});
if(props.page==="trash" && !trashKinds.value.length) trashKinds.value=await api<TrashKind[]>("/admin-tools/trash/kinds");
if(props.page==="tags") {
const list=await api<typeof tags.value>("/admin-tools/tags");
if(sequence===request) tags.value=list;
@@ -98,12 +104,13 @@ async function removeTag(tag:string) {
if(await confirm("将从使用此标签的记录中移除标签。","删除标签"))
await update(()=>api("/admin-tools/tags?"+new URLSearchParams({name:tag}),{method:"DELETE"}));
}
// 统一回收站的所有模块(含 RSS/提示词/工作流/收集箱)都走 /admin-tools/trash,不再按模块拼 /library
async function trash(row:Row,remove:boolean) {
if(remove && !(await confirm("永久删除后无法恢复。","永久删除"))) return;
const path=(row.kind==="tasks" || row.kind==="events" || row.kind==="snippets"
? "/admin-tools/trash/"+row.kind : "/library/"+row.kind+"/trash")+"/"+row.id;
await update(()=>api(path,{method:remove?"DELETE":"POST"}));
await update(()=>api("/admin-tools/trash/"+row.kind+"/"+row.id,{method:remove?"DELETE":"POST"}));
}
// 回收站标签:有分类列为空的模块(待办/日程/代码片段/RSS/工作流/收集箱)显示分类,其余只显示模块名
function kindOf(row:Row) { return kindLabels.value[row.kind] || moduleNames[row.kind] || row.kind; }
async function openHistory(row:Row) {
try { historyNote.value=await api<LibraryNote>("/notes/"+row.id); historyOpen.value=true; }
catch(failure) { ElMessage.error((failure as Error).message); }
@@ -174,7 +181,7 @@ const captureBookmark = "javascript:(()=>{if(!/^https?:$/.test(location.protocol
<div class="library-actions">
<select v-if="page==='trash'" class="field library-select" v-model="kind" aria-label="回收站模块" @change="offset=0">
<option value="">全部类型</option>
<option v-for="(label,id) in moduleNames" v-show="id!=='rss'" :key="id" :value="id">{{ label }}</option>
<option v-for="item in trashKinds" :key="item.kind" :value="item.kind">{{ item.label }}</option>
</select>
<select v-if="page==='batch'" class="field library-select" v-model="batchKind" aria-label="批量模块" @change="offset=0; selected=[]">
<option v-for="id in batchKinds" :key="id" :value="id">{{ moduleNames[id] }}</option>
@@ -193,7 +200,7 @@ const captureBookmark = "javascript:(()=>{if(!/^https?:$/.test(location.protocol
<div v-for="row in rows" :key="row.id" class="card library-dialog-row admin-row">
<input v-if="page==='batch'" type="checkbox" v-model="selected" :value="row.id" :aria-label="'选择 '+row.title" />
<div class="grow"><strong>{{ row.title }}</strong><div class="small muted">
{{ page==='trash' ? moduleNames[row.kind]+' · '+new Date(row.deleted_at).toLocaleString()
{{ page==='trash' ? kindOf(row)+' · '+new Date(row.deleted_at).toLocaleString()
: page==='history' ? row.folder+' · '+row.versions+' 个版本' : row.category }}
</div></div>
<template v-if="page==='trash'">
+14 -2
View File
@@ -106,7 +106,7 @@ const searchItems=ref<SearchItem[]>([]);
const searched=ref(false);
const tool= computed(()=>toolPage(page.value));
const toolView=computed<ToolId|"tools"|null>(()=>tool.value?.id ?? (page.value==="tools"?"tools":null));
const searchNames:Record<string,string>={...moduleNames,prompts:"提示词",chat:"AI 对话",image:"AI 图片",inbox:"收集箱"};
const searchNames:Record<string,string>={...moduleNames,chat:"AI 对话",image:"AI 图片"};
const publicationLabel=computed(()=>summary.value.publication.pending?"有改动待同步"
:summary.value.publication.published_at?"已同步":"待首次同步");
const publicLinksOpen = ref(false);
@@ -1007,8 +1007,20 @@ function syncTheme(event:StorageEvent) {
dark.value=localStorage.getItem("myspace-theme")==="dark";
document.documentElement.dataset.theme=dark.value?"dark":"light";
}
function expired() {
// 401 只代表「这一次请求没通过」,不能据此清掉登录态:切到别的模块时某个接口 401 会让整站白屏。
// 这里先向后端确认会话;只有 /auth/me 也失败(会话真的失效)才要求重新登录。
let checkingSession = false;
async function expired() {
if (checkingSession) return;
checkingSession = true;
try {
await refreshCsrf();
user.value = (await api("/auth/me")).username;
} catch {
user.value = "";
} finally {
checkingSession = false;
}
}
function beforeUnload(e: BeforeUnloadEvent) {
if (dirty.value) {
+10 -5
View File
@@ -7,10 +7,15 @@ export const toolPages = [
{ id: "browser", icon: "link", title: "浏览器工具", description: "导入书签或从浏览器收集网页" },
{ id: "linkage", icon: "graph", title: "联动说明", description: "查看各业务模块的转存路径" },
] as const;
export const moduleNames = {
notes: "知识库", blogs: "博客", assets: "图床", bookmarks: "书签",
tasks: "待办", events: "日程", snippets: "代码片段", rss: "RSS",
} as const;
// 与后端 TrashService.KINDS 的标签文案一致;回收站与批量管理共用。
// 标签接口只覆盖 notes/blogs/assets/bookmarks/tasks/events/snippets,其余模块用「模块 · 动态标签」。
export type ModuleKind =
| "notes" | "blogs" | "assets" | "bookmarks" | "tasks" | "events" | "snippets"
| "rss" | "prompts" | "flows" | "inbox";
export const moduleNames: Record<ModuleKind, string> = {
notes: "笔记", blogs: "博客", assets: "素材", bookmarks: "书签",
tasks: "待办", events: "日程", snippets: "代码片段", rss: "RSS 订阅",
prompts: "AI 提示词", flows: "自动化工作流", inbox: "收集项",
};
export type PlannerKind = "tasks" | "events" | "snippets";
export type ModuleKind = keyof typeof moduleNames;
export type ToolId = typeof toolPages[number]["id"];