From a60ea8d262588b02caa3e007c56f5ae8d75e3c86 Mon Sep 17 00:00:00 2001 From: HiFox Agent Date: Wed, 11 Nov 2026 20:50:40 +0800 Subject: [PATCH] fix(XZH-21): align note history to notes.version, wire inbox into unified trash, migrate history on category delete - NotesController: snapshot written under result version; history/{version} no longer falls back to current content; DBG removed - V18: legacy_versioning flag so pre-upgrade history keeps its numbering - NoteCategoriesController: migrate notes + history on category delete (includes trashed notes), snapshot at result version - InboxController/TrashService/AdminToolsController: inbox items soft delete, restore, purge; recapture revives trashed item - PlannerController batch tags scoped by kind; Dashboard taskCounts.due shares today-tasks filter - Tests: 34 passing (3 new regression cases) --- .../myspace/admin/AdminToolsController.java | 3 +- .../com/myspace/admin/PlannerController.java | 4 +- .../dashboard/DashboardController.java | 7 +- .../com/myspace/library/InboxController.java | 36 ++++-- .../com/myspace/library/TrashService.java | 10 +- .../notes/NoteCategoriesController.java | 38 ++++++- .../com/myspace/notes/NotesController.java | 55 ++++++--- .../V18__note_history_version_alignment.sql | 10 ++ .../java/com/myspace/ApiIntegrationTest.java | 106 ++++++++++++++++-- .../java/com/myspace/VerificationTest.java | 25 +++-- 10 files changed, 236 insertions(+), 58 deletions(-) create mode 100644 backend/src/main/resources/db/migration/V18__note_history_version_alignment.sql diff --git a/backend/src/main/java/com/myspace/admin/AdminToolsController.java b/backend/src/main/java/com/myspace/admin/AdminToolsController.java index 1d6e361..e078821 100644 --- a/backend/src/main/java/com/myspace/admin/AdminToolsController.java +++ b/backend/src/main/java/com/myspace/admin/AdminToolsController.java @@ -36,6 +36,7 @@ public class AdminToolsController { 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 """; public record Name(@NotBlank @Size(max=60) String name) {} @@ -63,7 +64,7 @@ public class AdminToolsController { "versions",db.queryForObject("select count(*) from note_history h join notes n on n.id=h.note_id where n.deleted_at is null",Long.class), "tags",tags().size(), "flows",db.queryForObject("select count(*) from workspace_flows where deleted_at is null",Long.class), - "inbox",db.queryForObject("select count(*) from inbox_items where processed_at is null",Long.class), + "inbox",db.queryForObject("select count(*) from inbox_items where processed_at is null and deleted_at is null",Long.class), "trashByKind",trashByKind()); } diff --git a/backend/src/main/java/com/myspace/admin/PlannerController.java b/backend/src/main/java/com/myspace/admin/PlannerController.java index 732f273..38a0b10 100644 --- a/backend/src/main/java/com/myspace/admin/PlannerController.java +++ b/backend/src/main/java/com/myspace/admin/PlannerController.java @@ -69,8 +69,8 @@ public class PlannerController { case "tags" -> { var tags=db.queryForList("select tags from planner_items where kind=? and id=? and deleted_at is null for update",String.class,kind,id) .stream().findFirst().orElseThrow(PlannerController::missing); - require(db.update("update planner_items set tags=?,updated_at=now() where id=?", - LibraryFields.tags(tags+","+(input.value()==null?"":input.value())),id)); + require(db.update("update planner_items set tags=?,updated_at=now() where kind=? and id=? and deleted_at is null", + LibraryFields.tags(tags+","+(input.value()==null?"":input.value())),kind,id)); } default -> throw new ResponseStatusException(HttpStatus.BAD_REQUEST,"操作不适用于此模块"); } diff --git a/backend/src/main/java/com/myspace/dashboard/DashboardController.java b/backend/src/main/java/com/myspace/dashboard/DashboardController.java index 5d746ea..bf9ea71 100644 --- a/backend/src/main/java/com/myspace/dashboard/DashboardController.java +++ b/backend/src/main/java/com/myspace/dashboard/DashboardController.java @@ -43,12 +43,13 @@ public class DashboardController { + " and (starts_at is null or starts_at < ?::timestamp)" + " order by (starts_at is not null) desc,(priority='high') desc,starts_at,updated_at desc,id limit 4", day + "T23:59:59"), + // due 与上方「今日待办」保持同一口径:到期的或未设日期的未完成项 "taskCounts", db.queryForMap("select count(*) filter(where not completed) as open," - + " count(*) filter(where not completed and starts_at is not null" - + " and starts_at < ?::timestamp) as due," + + " count(*) filter(where not completed" + + " and (starts_at is null or starts_at < ?::timestamp)) as due," + " count(*) filter(where completed) as done" - + " from planner_items where kind='tasks' and deleted_at is null", day), + + " from planner_items where kind='tasks' and deleted_at is null", day + "T23:59:59"), "recentRss", db.queryForList("select a.id,a.title,b.title as source from rss_articles a join rss_sources b on b.id=a.source_id" + " where a.deleted_at is null and b.deleted_at is null" diff --git a/backend/src/main/java/com/myspace/library/InboxController.java b/backend/src/main/java/com/myspace/library/InboxController.java index c2b2dc7..779d3ab 100644 --- a/backend/src/main/java/com/myspace/library/InboxController.java +++ b/backend/src/main/java/com/myspace/library/InboxController.java @@ -19,15 +19,17 @@ public class InboxController { private final NotesController notes; private final BookmarksController bookmarks; private final PlannerController planner; - public InboxController(JdbcTemplate db, NotesController notes, BookmarksController bookmarks, PlannerController planner) { - this.db=db; this.notes=notes; this.bookmarks=bookmarks; this.planner=planner; + private final TrashService trash; + public InboxController(JdbcTemplate db, NotesController notes, BookmarksController bookmarks, PlannerController planner, + TrashService trash) { + this.db=db; this.notes=notes; this.bookmarks=bookmarks; this.planner=planner; this.trash=trash; } @GetMapping public List> list( @RequestParam(defaultValue = "false") boolean processed, @RequestParam(defaultValue = "0") @Min(0) int offset) { - return db.queryForList("select * from inbox_items where (processed_at is not null)=?" + return db.queryForList("select * from inbox_items where deleted_at is null and (processed_at is not null)=?" + " order by created_at desc,id limit 100 offset ?", processed, offset); } @@ -35,7 +37,22 @@ public class InboxController { @GetMapping("/{id}") public Map get(@PathVariable UUID id) { - return db.queryForList("select * from inbox_items where id=?",id).stream() + return live(id); + } + + /** 删除收集项:与原型一致,先进全站统一回收站(可恢复)。 */ + @DeleteMapping("/{id}") + @ResponseStatus(HttpStatus.NO_CONTENT) + public void delete(@PathVariable UUID id) { + String title = db.queryForList("select title from inbox_items where id=? and deleted_at is null for update", + String.class, id).stream().findFirst().orElseThrow(InboxController::missing); + db.update("update inbox_items set deleted_at=now() where id=?", id); + trash.notifyTrashed("inbox", title); + } + + /** 读取未删除的收集项。 */ + private Map live(UUID id) { + return db.queryForList("select * from inbox_items where id=? and deleted_at is null",id).stream() .findFirst().orElseThrow(InboxController::missing); } @@ -59,6 +76,11 @@ public class InboxController { default -> throw missing(); }; var item = db.queryForList(query, source).stream().findFirst().orElseThrow(InboxController::missing); + // 同一来源在回收站里还有旧条目时,再次采集视为「重新收集」:复活该条目并刷新内容,避免 unique(source_kind,source_id) 冲突 + if (db.update("update inbox_items set deleted_at=null,title=?,content=?,processed_at=null,target_kind=null,target_id=null" + + " where source_kind=? and source_id=? and deleted_at is not null", + item.get("title"), item.get("content"), kind, source) > 0) + return db.queryForMap("select * from inbox_items where source_kind=? and source_id=?", kind, source); db.update("insert into inbox_items(id,source_kind,source_id,title,content) values(?,?,?,?,?)" + " on conflict(source_kind,source_id) do nothing", UUID.randomUUID(), kind, source, item.get("title"), item.get("content")); @@ -68,7 +90,7 @@ public class InboxController { @PostMapping("/{id}/organize/{target}") @Transactional public Map organize(@PathVariable UUID id,@PathVariable String target) { - var item=db.queryForList("select * from inbox_items where id=? for update",id).stream() + var item=db.queryForList("select * from inbox_items where id=? and deleted_at is null for update",id).stream() .findFirst().orElseThrow(InboxController::missing); if(item.get("target_id")!=null) { if(!target.equals(item.get("target_kind"))) @@ -98,8 +120,8 @@ public class InboxController { @PutMapping("/{id}/processed") @ResponseStatus(HttpStatus.NO_CONTENT) public void process(@PathVariable UUID id, @RequestBody Processed input) { - if (db.update("update inbox_items set processed_at=case when ? then coalesce(processed_at,now()) else null end where id=?", - input.processed(), id) == 0) throw missing(); + if (db.update("update inbox_items set processed_at=case when ? then coalesce(processed_at,now()) else null end" + + " where id=? and deleted_at is null", input.processed(), id) == 0) throw missing(); } public record Processed(boolean processed) {} diff --git a/backend/src/main/java/com/myspace/library/TrashService.java b/backend/src/main/java/com/myspace/library/TrashService.java index 56a5c0b..6127819 100644 --- a/backend/src/main/java/com/myspace/library/TrashService.java +++ b/backend/src/main/java/com/myspace/library/TrashService.java @@ -26,9 +26,11 @@ public class TrashService { Map.entry("snippets", new Spec("planner_items", "代码片段", "title", false)), Map.entry("rss", new Spec("rss_sources", "RSS 订阅", "title", false)), Map.entry("prompts", new Spec("ai_prompts", "AI 提示词", "title", false)), - Map.entry("flows", new Spec("workspace_flows", "自动化工作流", "title", false))); + Map.entry("flows", new Spec("workspace_flows", "自动化工作流", "title", false)), + // 收集箱没有分类列:恢复时不补分类 + Map.entry("inbox", new Spec("inbox_items", "收集项", "title", false))); public static final List KINDS = List.of("notes", "blogs", "bookmarks", "assets", - "tasks", "events", "snippets", "rss", "prompts", "flows"); + "tasks", "events", "snippets", "rss", "prompts", "flows", "inbox"); private static final Map CATEGORY_TABLES = Map.of( "notes", "note_categories", "blogs", "blog_categories", "assets", "asset_categories", "bookmarks", "bookmark_categories"); @@ -101,7 +103,9 @@ public class TrashService { Object category = rows.getFirst().get("category"); if (spec.category() && category != null) ensureCategory(kind, (String) category); notifications.notify("已恢复" + label(kind) + "「" - + WorkspaceNotifications.clip((String) rows.getFirst().get("title"), 100) + "」"); + + WorkspaceNotifications.clip((String) rows.getFirst().get("title"), 100) + "」" + // 订阅删除时文章被同事务隐藏,恢复订阅不会把旧文章带回来,这里明确告知,避免误解 + + (Objects.equals(kind, "rss") ? ";删除时隐藏的历史文章不会恢复,下次刷新只拉取新文章" : "")); } @Transactional diff --git a/backend/src/main/java/com/myspace/notes/NoteCategoriesController.java b/backend/src/main/java/com/myspace/notes/NoteCategoriesController.java index 7677a22..8aa534a 100644 --- a/backend/src/main/java/com/myspace/notes/NoteCategoriesController.java +++ b/backend/src/main/java/com/myspace/notes/NoteCategoriesController.java @@ -59,10 +59,11 @@ public class NoteCategoriesController { if (!categories.contains(name)) { throw new ResponseStatusException(HttpStatus.NOT_FOUND, "分类不存在"); } + if (replacement != null && replacement.isEmpty()) replacement = null; if (categories.size() == 1) { throw new ResponseStatusException(HttpStatus.CONFLICT, "至少需要保留一个分类"); } - if (replacement == null || replacement.isEmpty()) { + if (replacement == null) { Boolean hasNotes = db.queryForObject( "select exists(select 1 from notes where category=?)", Boolean.class, name); if (Boolean.TRUE.equals(hasNotes)) { @@ -72,12 +73,39 @@ public class NoteCategoriesController { if (name.equals(replacement) || !categories.contains(replacement)) { throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "请选择另一个已有分类"); } - db.update("update notes set category=?,version=version+1,updated_at=now() where category=?", - replacement, name); + moveCategoryNotes(name, replacement); } - // 历史快照带有 category 外键:先清掉该分类的版本记录,再删分类,否则事务会因外键报错回滚 - db.update("delete from note_history where category=?", name); + // 历史快照带有 category 外键:不清理会让「分类下只剩历史引用」的删除被外键挡住(整个事务回滚)。 + // 有迁移目标时历史一并迁移(保留可回溯性),没有迁移目标时清掉该分类的版本记录。 + if (replacement == null) db.update("delete from note_history where category=?", name); + else db.update("update note_history set category=? where category=?", replacement, name); if (db.update("delete from note_categories where name=?", name) == 0) throw new ResponseStatusException(HttpStatus.NOT_FOUND, "分类不存在"); } + + /** + * 把分类下的笔记(含回收站中的笔记)迁到目标分类,并补一条「迁移前」的版本快照。 + * 快照必须按「迁移后的版本号」写入,否则迁移后的 history/{version} 会缺失。 + * 顺序:先迁笔记拿到新版本号;再给仍缺快照的笔记补一条,内容取自已迁到目标分类的最早快照; + * 否则迁移这个分类的历史(原分类的快照优先,保持可回溯性)。 + */ + private void moveCategoryNotes(String name, String replacement) { + db.execute("lock table notes in share row exclusive mode"); + List> moved = db.queryForList("update notes set category=?,version=version+1,updated_at=now()" + + " where category=? returning id,version", replacement, name); + for (var note : moved) { + long version = ((Number) note.get("version")).longValue(); + db.update("insert into note_history(note_id,version,title,body,category,folder,tags,star)" + + " select n.id,?,n.title,n.body,n.category,n.folder,n.tags,n.star from notes n" + + " where n.id=? and not exists(select 1 from note_history h where h.note_id=n.id and h.version=?)", + version, note.get("id"), version); + db.update("insert into note_history(note_id,version,title,body,category,folder,tags,star)" + + " select h.note_id,?,h.title,h.body,h.category,h.folder,h.tags,h.star from note_history h" + + " where h.note_id=? and h.category=?" + + " and not exists(select 1 from note_history x where x.note_id=h.note_id and x.version=?)" + + " order by h.saved_at,h.version limit 1", + version, note.get("id"), name, version); + } + db.update("update note_history set category=? where category=?", replacement, name); + } } diff --git a/backend/src/main/java/com/myspace/notes/NotesController.java b/backend/src/main/java/com/myspace/notes/NotesController.java index c3c4bfa..627a2ea 100644 --- a/backend/src/main/java/com/myspace/notes/NotesController.java +++ b/backend/src/main/java/com/myspace/notes/NotesController.java @@ -125,8 +125,9 @@ public class NotesController { && Objects.equals(current.get("tags"), tags) && Objects.equals(current.get("star"), n.star())) return current; // 原型 P0-4:每次保存前自动记录快照。提交的版本已过期时不再报冲突,也不覆盖库内较新内容 // (覆盖会把已迁移的分类、新内容回滚),本次编辑以库内最新状态为基准合并后保存。 + // 快照按「保存后的版本」编号,与 notes.version 一一对应:当前 version=N 的内容随时可通过 history/N 取回。 + long resultVersion = ((Number) current.get("version")).longValue() + 1; if (((Number) current.get("version")).longValue() != n.version()) { - snapshot(current); Map merged = new HashMap<>(current); String currentTag = (String) current.get("tag"); merged.put("title", n.title().strip()); @@ -137,12 +138,13 @@ public class NotesController { merged.put("tag", LibraryFields.firstTag((String) merged.get("tags"))); merged.put("folder", folder); merged.put("star", n.star()); + snapshot(current, resultVersion); db.update("update notes set title=?,body=?,category=?,tag=?,star=?,folder=?,tags=?,version=version+1,updated_at=now() where id=?", merged.get("title"), merged.get("body"), merged.get("category"), merged.get("tag"), merged.get("star"), merged.get("folder"), merged.get("tags"), id); return get(id); } - snapshot(current); + snapshot(current, resultVersion); db.update("update notes set title=?,body=?,category=?,tag=?,star=?,folder=?,tags=?,version=version+1,updated_at=now() where id=?", n.title().strip(), n.body(), n.category(), LibraryFields.firstTag(tags), n.star(), folder, tags, id); return get(id); @@ -153,19 +155,37 @@ public class NotesController { db.update("insert into note_categories(name) values(?) on conflict (name) do nothing", name); } + /** + * 版本列表。版本号即 notes.version 的取值,语义沿用既有约定:「version=N 的这一行是第 N 版的内容」。 + * 新口径下保存前的快照以「保存后的版本号」落库,因此当前 version 这一行就是当前内容的保存前快照, + * 历史编号与笔记版本号连续、无空洞;旧口径(V18 之前写入的行)只在没有新快照占用该号时返回,历史不会被重排。 + * 唯一随口径变化的是「第 0 版」:新口径下第一次保存前的内容记在第 1 版,因此不再出现 version=0。 + */ @GetMapping("/{id}/history") public List> history(@PathVariable UUID id, @RequestParam(defaultValue = "0") @Min(0) int offset) { get(id); - return db.queryForList("select version,title,saved_at,length(body) as characters from note_history" - + " where note_id=? order by version desc limit 50 offset ?", id, offset); + // 同一版本号可能同时有旧口径行与新快照:只保留新口径行 + return db.queryForList("select h.version,h.title,h.saved_at,length(h.body) as characters from note_history h" + + " where h.note_id=? and (not h.legacy_versioning or not exists(select 1 from note_history n" + + " where n.note_id=h.note_id and n.version=h.version and not n.legacy_versioning))" + + " order by h.version desc limit 50 offset ?", id, offset); } @GetMapping("/{id}/history/{version}") public Map version(@PathVariable UUID id, @PathVariable long version) { - get(id); - return db.queryForList("select * from note_history where note_id=? and version=?", id, version) - .stream().findFirst().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "版本不存在")); + return contentAt(get(id), version); + } + + /** + * 取历史 version 的内容。保存前快照以「保存后的版本号」写入,因此 history/N 永远是「第 N 版保存前的内容」, + * 编号与 notes.version 连续、无空洞。旧口径(V18 之前写入的行)与新快照同号时以新快照为准。 + */ + private Map contentAt(Map 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, "版本不存在")); } public record Restore(@Min(0) Long currentVersion) {} @@ -177,11 +197,14 @@ public class NotesController { var current = lock(id); // 版本号可选:旧调用方仍传 currentVersion 做并发校验;新调用方不传,就以库内最新内容为准 if (input != null && input.currentVersion() != null) checkVersion(current, input.currentVersion()); - var old = version(id, version); + // 恢复必须基于真实的历史行,不能落到「当前内容」兜底 + 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, "版本不存在")); 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"); - snapshot(current); // 原型:恢复前先把当前内容记录为快照 + snapshot(current, ((Number) current.get("version")).longValue() + 1); // 原型:恢复前先把当前内容记录为快照 db.update("update notes set title=?,body=?,category=?,folder=?,tags=?,tag=?,star=?,version=version+1,updated_at=now() where id=?", old.get("title"), old.get("body"), category, old.get("folder"), tags, LibraryFields.firstTag(tags), old.get("star"), id); return get(id); @@ -205,15 +228,13 @@ public class NotesController { } /** - * 以笔记当前版本号写入快照。同一版本号内先保存的是「更早的内容」,后保存的是最新内容: - * 并发或过期保存时重算后的内容会覆盖同版本快照,保证历史里始终能找到保存前的原文。 + * 以「保存后的版本号」写入快照(即本次保存的「保存前内容」)。此后该版本被再次保存或恢复时, + * 先读取 contentAt 取回内容,再写入新版本的快照,因此不会出现历史被覆盖或版本错位。 */ - private void snapshot(Map note) { - int r = db.update("insert into note_history(note_id,version,title,body,category,folder,tags,star)" - + " values(?,?,?,?,?,?,?,?) on conflict (note_id,version) do update set title=excluded.title," - + "body=excluded.body,category=excluded.category,folder=excluded.folder,tags=excluded.tags," - + "star=excluded.star,saved_at=now()", - note.get("id"), ((Number) note.get("version")).longValue(), WorkspaceNotifications.clip((String) note.get("title"), 120), + private void snapshot(Map note, long version) { + db.update("insert into note_history(note_id,version,title,body,category,folder,tags,star)" + + " values(?,?,?,?,?,?,?,?) on conflict (note_id,version) do nothing", + note.get("id"), version, WorkspaceNotifications.clip((String) note.get("title"), 120), note.get("body"), note.get("category"), note.get("folder"), note.get("tags"), note.get("star")); } diff --git a/backend/src/main/resources/db/migration/V18__note_history_version_alignment.sql b/backend/src/main/resources/db/migration/V18__note_history_version_alignment.sql new file mode 100644 index 0000000..1bf0f22 --- /dev/null +++ b/backend/src/main/resources/db/migration/V18__note_history_version_alignment.sql @@ -0,0 +1,10 @@ +-- 版本历史与 notes.version 对齐。 +-- 旧口径:note_history.version 存的是「来源版本」(保存前笔记的版本号), +-- 因此有 N 条历史的笔记,历史里缺了「与当前 version 对应的那一版」,回退永远差一位。 +-- 新口径:note_history.version 存「本次保存后的版本号」,notes.version 这一版的内容总能在历史里取到。 +-- +-- 旧数据无法整体平移(平移后与当前版本同号,会撞主键),所以用一列标记写入口径: +-- 迁移前已存在的行置为 true,业务层按旧口径解析(version=N 即「保存前的 N 版」);新写入的行默认 false。 +alter table note_history add column if not exists legacy_versioning boolean not null default false; +-- 只标记迁移前已存在的行;本脚本只执行一次,不会误标后续新写入的快照 +update note_history set legacy_versioning = true where not legacy_versioning; diff --git a/backend/src/test/java/com/myspace/ApiIntegrationTest.java b/backend/src/test/java/com/myspace/ApiIntegrationTest.java index 1ece415..a402841 100644 --- a/backend/src/test/java/com/myspace/ApiIntegrationTest.java +++ b/backend/src/test/java/com/myspace/ApiIntegrationTest.java @@ -160,10 +160,16 @@ class ApiIntegrationTest { .andExpect(status().isOk()) .andExpect(jsonPath("$.version").value(2)) .andExpect(jsonPath("$.category").value("设计灵感")); - // 保存前的内容进入版本历史;历史里的分类是迁移后的值,不会把旧分类带回来 + // 保存前的内容进入版本历史;历史里的分类是迁移后的值,不会把旧分类带回来。 + // 快照以「保存后的版本号」写入,因此 history/{当前 version} 恒为当前内容的保存前快照 + mvc.perform(get(noteUrl).session(session)) + .andExpect(jsonPath("$.version").value(2)); mvc.perform(get(noteUrl + "/history/1").session(session)) .andExpect(jsonPath("$.category").value("设计灵感")) .andExpect(jsonPath("$.body").value("保留正文")); + // 原分类下的快照随笔记一起迁入新分类(可回溯),因此第 2 版同样可查 + mvc.perform(get(noteUrl + "/history/2").session(session)) + .andExpect(jsonPath("$.category").value("设计灵感")); mvc.perform(get(noteUrl).session(session)).andExpect(jsonPath("$.body").value("改稿")); // 分类删除在同一事务内完成迁移与删除,不因快照写入失败而回滚(回归防护) mvc.perform(get(path).session(session)) @@ -210,7 +216,7 @@ class ApiIntegrationTest { .content(body)) .andExpect(status().isOk()) .andExpect(jsonPath("$.version").value(2)); - mvc.perform(get("/api/v1/notes/" + id + "/history/1").session(session)) + mvc.perform(get("/api/v1/notes/" + id + "/history/2").session(session)) .andExpect(jsonPath("$.body").value("# updated")); mvc.perform(get("/api/v1/dashboard").session(session)) .andExpect(jsonPath("$.notes").value(1)) @@ -630,19 +636,22 @@ class ApiIntegrationTest { input.put("body", "改稿"); mvc.perform(put(note).session(session).with(csrf()).contentType("application/json").content(json.writeValueAsBytes(input))) .andExpect(jsonPath("$.version").value(1)); - mvc.perform(get(note + "/history/0").session(session)).andExpect(jsonPath("$.body").value("初稿")); - mvc.perform(post(note + "/history/0").session(session).with(csrf()).contentType("application/json").content(json.writeValueAsBytes(Map.of("currentVersion", 1)))) + // 快照按保存后的版本号写入:「第 1 版」是 v1 保存前的内容 + mvc.perform(get(note + "/history/1").session(session)).andExpect(jsonPath("$.body").value("初稿")); + mvc.perform(post(note + "/history/1").session(session).with(csrf()).contentType("application/json").content(json.writeValueAsBytes(Map.of("currentVersion", 1)))) .andExpect(jsonPath("$.body").value("初稿")).andExpect(jsonPath("$.version").value(2)); - mvc.perform(get(note + "/history/1").session(session)).andExpect(jsonPath("$.body").value("改稿")); + // 恢复前先快照当前内容(同样记在第 2 版) + mvc.perform(get(note + "/history/2").session(session)).andExpect(jsonPath("$.body").value("改稿")); mvc.perform(post("/api/v1/library/notes/batch").session(session).with(csrf()).contentType("application/json") .content(json.writeValueAsBytes(Map.of("ids", List.of(id), "action", "trash")))) .andExpect(status().isNoContent()); mvc.perform(get(note).session(session)).andExpect(status().isNotFound()); mvc.perform(get("/api/v1/library/notes/trash").session(session)).andExpect(jsonPath("$[0].id").value(id)); mvc.perform(post("/api/v1/library/notes/trash/" + id).session(session).with(csrf())).andExpect(status().isNoContent()); - // 恢复前先快照当前内容(见「过期保存」用例),再回到历史版本 - mvc.perform(get(note + "/history/1").session(session)).andExpect(jsonPath("$.body").value("改稿")); - mvc.perform(get(note + "/history/2").session(session)).andExpect(status().isNotFound()); + // 恢复前先快照当前内容(见「过期保存」用例),再回到历史版本;历史编号与 notes.version 连续 + mvc.perform(get(note + "/history/2").session(session)).andExpect(jsonPath("$.body").value("改稿")); + mvc.perform(get(note).session(session)).andExpect(jsonPath("$.version").value(3)); + mvc.perform(get(note + "/history/3").session(session)).andExpect(status().isNotFound()); mvc.perform(get(note).session(session)).andExpect(jsonPath("$.folder").value(folder)); } @@ -808,4 +817,85 @@ class ApiIntegrationTest { assertTrue(emptied.get("purged").asInt()>=1); mvc.perform(post("/api/v1/admin-tools/trash/flows/"+flow).session(session).with(csrf())).andExpect(status().isNotFound()); } + + /** XZH-21 回归:收集箱删除进统一回收站,可恢复;回收站中的旧条目再被采集时复活而不是撞唯一键。 */ + @Test + void inboxTrashRestoreAndRecapture() throws Exception { + var session = login(); + String url = "https://example.org/inbox-" + System.nanoTime(); + String bookmark = json.readTree(mvc.perform(post("/api/v1/bookmarks").session(session).with(csrf()) + .contentType("application/json").content(json.writeValueAsBytes(Map.of( + "title", "收集箱书签", "url", url, "description", "说明", "category", "设计工具")))) + .andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText(); + String item = json.readTree(mvc.perform(post("/api/v1/inbox/bookmarks/" + bookmark).session(session).with(csrf())) + .andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray()).get("id").asText(); + mvc.perform(delete("/api/v1/inbox/" + item).session(session).with(csrf())).andExpect(status().isNoContent()); + mvc.perform(get("/api/v1/inbox").session(session)).andExpect(jsonPath("$[?(@.id=='" + item + "')]").isEmpty()); + mvc.perform(get("/api/v1/inbox/" + item).session(session)).andExpect(status().isNotFound()); + mvc.perform(get("/api/v1/admin-tools/trash").session(session).param("kind", "inbox")) + .andExpect(jsonPath("$[0].id").value(item)); + // 回收站中存在同来源条目时再次采集:复活旧条目,不因 unique(source_kind,source_id) 失败 + mvc.perform(post("/api/v1/inbox/bookmarks/" + bookmark).session(session).with(csrf())) + .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(item)) + .andExpect(jsonPath("$.deleted_at").doesNotExist()); + mvc.perform(delete("/api/v1/inbox/" + item).session(session).with(csrf())).andExpect(status().isNoContent()); + mvc.perform(post("/api/v1/admin-tools/trash/inbox/" + item).session(session).with(csrf())).andExpect(status().isNoContent()); + mvc.perform(get("/api/v1/inbox/" + item).session(session)).andExpect(jsonPath("$.id").value(item)); + mvc.perform(get("/api/v1/admin-tools/trash").session(session).param("kind", "inbox")) + .andExpect(jsonPath("$[?(@.id=='" + item + "')]").isEmpty()); + } + + /** XZH-21 回归:历史编号与 notes.version 对齐,history/{当前版本} 恒可取到「保存前」内容。 */ + @Test + void historyIndexMatchesNoteVersion() throws Exception { + var session = login(); + var input = new java.util.HashMap(Map.of( + "title", "版本对齐", "body", "v0", "category", "技术笔记", "tag", "", "version", 0)); + String id = json.readTree(mvc.perform(post("/api/v1/notes").session(session).with(csrf()) + .contentType("application/json").content(json.writeValueAsBytes(input))) + .andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText(); + String note = "/api/v1/notes/" + id; + for (String next : new String[]{"v1", "v2"}) { + input.put("body", next); + int version = mvc.perform(put(note).session(session).with(csrf()) + .contentType("application/json").content(json.writeValueAsBytes(input))) + .andExpect(status().isOk()).andReturn().getResponse().getStatus(); + assertEquals(200, version); + int current = json.readTree(mvc.perform(get(note).session(session)).andReturn().getResponse() + .getContentAsByteArray()).get("version").asInt(); + // history/{current} 是本次保存前的内容(v0 / v1) + mvc.perform(get(note + "/history/" + current).session(session)) + .andExpect(jsonPath("$.body").value(next.equals("v1") ? "v0" : "v1")); + } + // 列表从当前版本号连续向下 + mvc.perform(get(note + "/history").session(session)) + .andExpect(jsonPath("$[0].version").value(2)) + .andExpect(jsonPath("$[1].version").value(1)) + .andExpect(jsonPath("$.length()").value(2)); + mvc.perform(get(note + "/history/3").session(session)).andExpect(status().isNotFound()); + } + + /** XZH-21 回归:分类删除时迁移该分类下的历史快照,不再被 note_history 外键挡住。 */ + @Test + void categoryDeletionMigratesNoteHistory() throws Exception { + var session = login(); + String cat = "历史分类-" + java.util.UUID.randomUUID(); + mvc.perform(post("/api/v1/notes/categories").session(session).with(csrf()).contentType("application/json") + .content(json.writeValueAsBytes(Map.of("name", cat)))).andExpect(status().isCreated()); + var input = new java.util.HashMap(Map.of( + "title", "历史分类笔记", "body", "a", "category", cat, "tag", "", "version", 0)); + String id = json.readTree(mvc.perform(post("/api/v1/notes").session(session).with(csrf()) + .contentType("application/json").content(json.writeValueAsBytes(input))) + .andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText(); + input.put("body", "b"); + mvc.perform(put("/api/v1/notes/" + id).session(session).with(csrf()) + .contentType("application/json").content(json.writeValueAsBytes(input))).andExpect(status().isOk()); + mvc.perform(delete("/api/v1/notes/categories").session(session).with(csrf()) + .param("name", cat).param("replacement", "设计灵感")).andExpect(status().isNoContent()); + mvc.perform(get("/api/v1/notes/" + id).session(session)).andExpect(jsonPath("$.category").value("设计灵感")); + // 历史随分类迁移,外键不再引用已删除分类 + assertEquals(0, db.queryForObject("select count(*) from note_history where category=?", Integer.class, cat)); + mvc.perform(get("/api/v1/notes/" + id + "/history/2").session(session)) + .andExpect(jsonPath("$.category").value("设计灵感")); + } } diff --git a/backend/src/test/java/com/myspace/VerificationTest.java b/backend/src/test/java/com/myspace/VerificationTest.java index 6153740..3ea11dd 100644 --- a/backend/src/test/java/com/myspace/VerificationTest.java +++ b/backend/src/test/java/com/myspace/VerificationTest.java @@ -83,11 +83,12 @@ class VerificationTest { String id = createNote(s, body); body.put("body", "已保存正文-乙"); assertEquals(200, putNote(s, id, body)); - assertEquals(200, historyStatus(s, id, 0L), "version 0 应保存「保存前」的原始内容"); - mvc.perform(get("/api/v1/notes/" + id + "/history/0").session(s)).andExpect(jsonPath("$.body").value("原始正文-甲")); + // 快照以保存后的版本号写入:第一次保存后 history/1 就是保存前的原始正文 + assertEquals(200, historyStatus(s, id, 1L), "history/1 应保存「保存前」的原始内容"); + mvc.perform(get("/api/v1/notes/" + id + "/history/1").session(s)).andExpect(jsonPath("$.body").value("原始正文-甲")); } - /** 结论:版本号是「来源版本」而非「结果版本」——历史索引与落库版本错位 1。 */ + /** 历史编号与 notes.version 对齐:history/{当前版本} 恒为当前内容的保存前快照,无错位、无空洞。 */ @Test void historyVersionIndexIsOffByOne() throws Exception { var s = login(); @@ -95,14 +96,14 @@ class VerificationTest { "title", "索引笔记", "body", "v0", "category", "技术笔记", "tag", "", "version", 0)); String id = createNote(s, body); body.put("body", "v1"); - putNote(s, id, body); // 成功保存 → 版本变 1,快照 0 = v0 + putNote(s, id, body); // 保存后 version=1,history/1 = v0 body.put("body", "v2"); - putNote(s, id, body); // 成功保存 → 版本变 2,快照 1 = v1 + putNote(s, id, body); // 保存后 version=2,history/2 = v1 mvc.perform(get("/api/v1/notes/" + id).session(s)).andExpect(jsonPath("$.version").value(2)); - assertEquals(200, historyStatus(s, id, 0L)); - assertEquals(200, historyStatus(s, id, 1L)); - // 与 UI 直觉对照:笔记标称 version=2(即「第 3 个版本」),但不存在 2 号历史 - assertEquals(404, historyStatus(s, id, 2L), "当前版本 2 在历史里缺失,无「保存前」可回退"); + mvc.perform(get("/api/v1/notes/" + id + "/history/1").session(s)).andExpect(jsonPath("$.body").value("v0")); + mvc.perform(get("/api/v1/notes/" + id + "/history/2").session(s)).andExpect(jsonPath("$.body").value("v1")); + // 历史列表最高一条与 notes.version 连续 + mvc.perform(get("/api/v1/notes/" + id + "/history").session(s)).andExpect(jsonPath("$[0].version").value(2)); } /** 开发说明:过期保存由 409 改为 200,且不把笔记改回旧分类。 */ @@ -131,11 +132,11 @@ class VerificationTest { String id = createNote(s, body); body.put("body", "v1"); putNote(s, id, body); - mvc.perform(post("/api/v1/notes/" + id + "/history/0").session(s).with(csrf()) + mvc.perform(post("/api/v1/notes/" + id + "/history/1").session(s).with(csrf()) .contentType("application/json").content("{}")) .andExpect(status().isOk()).andExpect(jsonPath("$.body").value("v0")).andExpect(jsonPath("$.version").value(2)); - // 恢复前的 v1 应可在历史中找到 - mvc.perform(get("/api/v1/notes/" + id + "/history/1").session(s)).andExpect(jsonPath("$.body").value("v1")); + // 恢复前的 v1 应可在历史中找到(恢复前的快照记在第 2 版) + mvc.perform(get("/api/v1/notes/" + id + "/history/2").session(s)).andExpect(jsonPath("$.body").value("v1")); } /** 标签:重命名对回收站中的笔记生效,恢复后是新标签(开发说明)。 */