Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3df4afab7b | ||
|
|
bd8264b8cf | ||
|
|
a60ea8d262 | ||
|
|
1bd637528d |
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,43 @@ public class LibraryController {
|
||||
+ " where id=? and deleted_at is null", id);
|
||||
}
|
||||
|
||||
/**
|
||||
* 回收站列表:接受 TrashService 的全部 kind,与 restore/purge 及 /admin-tools/trash 的 kind 集合一致,
|
||||
* 不再出现「列表 404、恢复 204」的两套口径。
|
||||
*/
|
||||
@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")
|
||||
+ ",deleted_at from " + kind + " where deleted_at is not null order by deleted_at desc,id limit 100 offset ?", offset);
|
||||
var spec = TrashService.spec(kind);
|
||||
return db.queryForList("select id," + spec.name() + " as title"
|
||||
+ ",deleted_at from " + spec.table()
|
||||
+ (TrashService.isPlanner(kind) ? " where kind=? and deleted_at is not null" : " where deleted_at is not null")
|
||||
+ " order by deleted_at desc,id limit 100 offset ?",
|
||||
TrashService.isPlanner(kind) ? new Object[]{kind, offset} : new Object[]{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,38 @@ 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 的最大旧版本号」这一点被使用,且 N 不超过当前版本号——旧库升级后
|
||||
* history/{当前版本} 落在最高旧行,即当前版本自身的保存前内容。
|
||||
* 旧行不会压过更新的新快照(新快照优先),新保存的快照也不会被旧行顶替。读取与恢复共用这一份映射。
|
||||
* 没有任何行能对应 N 时返回 404,绝不兜底到当前内容或某个固定旧行。
|
||||
* 旧行回退必须有上界:只有 N ≤ 该笔记的当前版本号(即历史能覆盖到的最大 N)时才解析,否则任意大的 N
|
||||
* 都会被 max(≤N) 映射到同一个旧行(第三轮测试阻断项 B1:history/9 → 200 返回 v1)。
|
||||
* 上界用 notes.version 而不是「最高旧版本号」:V18 前的触发器写入 0 起始的旧行,升级时用户恰好看不到
|
||||
* 当前版本的保存前内容,用最高旧版本号会把 history/{当前版本} 一刀切成 404。
|
||||
*/
|
||||
private Map<String, Object> contentAt(UUID noteId, long version) {
|
||||
// 1) 同号行(新口径优先)
|
||||
var row = db.queryForList("select * from note_history where note_id=? and version=?"
|
||||
+ " order by legacy_versioning limit 1", noteId, version).stream().findFirst();
|
||||
// 2) 旧口径锚点行:≤ N 的最大旧版本号,且 N 不得超过该笔记的当前版本号(否则一律 404)
|
||||
if (row.isEmpty() && version > 0) {
|
||||
var noteVersion = db.queryForList("select version from notes where id=?", Long.class, noteId).stream().findFirst();
|
||||
if (noteVersion.isPresent() && version <= noteVersion.get())
|
||||
row = db.queryForList("select note_id,version,title,body,category,folder,tags,star,legacy_versioning from note_history"
|
||||
+ " where note_id=?::uuid and legacy_versioning and version=(select max(version) from note_history"
|
||||
+ " where note_id=?::uuid and legacy_versioning and version<=?)::bigint", noteId, noteId, version)
|
||||
.stream().findFirst();
|
||||
}
|
||||
return row.orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "版本不存在"));
|
||||
}
|
||||
|
||||
public record Restore(@Min(0) Long currentVersion) {}
|
||||
@@ -197,10 +222,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");
|
||||
|
||||
@@ -35,6 +35,7 @@ class ApiIntegrationTest {
|
||||
@BeforeEach
|
||||
void clean() {
|
||||
db.update("delete from inbox_items");
|
||||
db.update("delete from workspace_notifications");
|
||||
db.update("delete from planner_items");
|
||||
db.update("delete from workspace_tags");
|
||||
db.update("delete from workspace_flows");
|
||||
@@ -898,4 +899,164 @@ class ApiIntegrationTest {
|
||||
mvc.perform(get("/api/v1/notes/" + id + "/history/2").session(session))
|
||||
.andExpect(jsonPath("$.category").value("设计灵感"));
|
||||
}
|
||||
|
||||
/**
|
||||
* XZH-21 回归:回收站里每个 kind 都必须两套路由等价(/admin-tools/trash 与 /library/{kind}/trash),
|
||||
* 前端不传 kind 的方法由 /admin-tools/trash/kinds 给出;列表每行只有一条记录(同 id 不重复),
|
||||
* summary.trash 与全部列表行数一致。回归第二轮测试报告的「重复行 / 恢复 404」。
|
||||
*/
|
||||
@Test
|
||||
void trashKindsCoverEveryModuleAndRoutesStayEquivalent() throws Exception {
|
||||
var session = login();
|
||||
List<Map<String, Object>> kinds = json.readValue(mvc.perform(get("/api/v1/admin-tools/trash/kinds").session(session))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray(), List.class);
|
||||
List<String> kindIds = kinds.stream().map(k -> (String) k.get("kind")).toList();
|
||||
assertEquals(List.of("notes", "blogs", "bookmarks", "assets", "tasks", "events", "snippets", "rss", "prompts", "flows", "inbox"),
|
||||
kindIds);
|
||||
for (Map<String, Object> kind : kinds) {
|
||||
boolean planner = (Boolean) kind.get("planner");
|
||||
assertEquals(planner, List.of("tasks", "events", "snippets").contains(kind.get("kind")), "planner 标记错误");
|
||||
}
|
||||
// 清理:清空回收站,让本用例的计数从 0 开始
|
||||
mvc.perform(delete("/api/v1/admin-tools/trash").session(session).with(csrf())).andExpect(status().isOk());
|
||||
|
||||
String url = "https://example.org/trash-kinds-" + 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/bookmarks/" + bookmark).session(session).with(csrf()))
|
||||
.andExpect(status().isNoContent());
|
||||
mvc.perform(delete("/api/v1/inbox/" + item).session(session).with(csrf())).andExpect(status().isNoContent());
|
||||
|
||||
var rows = json.readTree(mvc.perform(get("/api/v1/admin-tools/trash").session(session))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
|
||||
var ids = new java.util.LinkedHashSet<String>();
|
||||
for (var row : rows) {
|
||||
assertTrue(ids.add(row.get("kind").asText() + ":" + row.get("id").asText()), "回收站列表出现重复行");
|
||||
assertTrue(kindIds.contains(row.get("kind").asText()), "出现未知 kind:" + row.get("kind").asText());
|
||||
}
|
||||
assertEquals(2, ids.size());
|
||||
mvc.perform(get("/api/v1/admin-tools/summary").session(session))
|
||||
.andExpect(jsonPath("$.trash").value(2));
|
||||
|
||||
// 两套路由对同一条记录等价:用 /admin-tools 恢复,用 /library 永久删除
|
||||
mvc.perform(post("/api/v1/admin-tools/trash/bookmarks/" + bookmark).session(session).with(csrf()))
|
||||
.andExpect(status().isNoContent());
|
||||
mvc.perform(get("/api/v1/bookmarks/" + bookmark).session(session)).andExpect(status().isOk());
|
||||
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(delete("/api/v1/bookmarks/" + bookmark).session(session).with(csrf()))
|
||||
.andExpect(status().isNoContent());
|
||||
mvc.perform(delete("/api/v1/admin-tools/trash/bookmarks/" + bookmark).session(session).with(csrf()))
|
||||
.andExpect(status().isNoContent());
|
||||
mvc.perform(post("/api/v1/library/bookmarks/trash/" + bookmark).session(session).with(csrf()))
|
||||
.andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
/**
|
||||
* XZH-21 回归:开发环境的库已经按旧版 V1–V17 建过,V18 加了列但升级前写入的 note_history 行是
|
||||
* 「旧口径」且 LegacyVersioning 标记不会自动出现(只有真正跑过 V18 的 update 才会有)。读历史不能 500、
|
||||
* 不能空,恢复也不能写回错位的内容。这条按 FE 的真实调用补充。
|
||||
*/
|
||||
@Test
|
||||
void legacyHistoryReadAndRestoreSupportPartialMarks() throws Exception {
|
||||
var session = login();
|
||||
var input = new java.util.HashMap<String, Object>(Map.of(
|
||||
"title", "旧库笔记", "body", "n0", "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();
|
||||
// 模拟升级前写入的旧口径历史:0=第一版保存前(n0),1=第二版保存前(n1),笔记当前是第 2 版(n2)
|
||||
db.update("delete from note_history where note_id=?", java.util.UUID.fromString(id));
|
||||
db.update("insert into note_history(note_id,version,title,body,category,folder,tags,star,legacy_versioning)"
|
||||
+ " values (?,0,'旧库笔记','n0','技术笔记','默认文件夹','',false,true),"
|
||||
+ " (?,1,'旧库笔记','n1','技术笔记','默认文件夹','',false,true)", java.util.UUID.fromString(id), java.util.UUID.fromString(id));
|
||||
db.update("update notes set body='n2',version=2 where id=?", java.util.UUID.fromString(id));
|
||||
// 与前端 NoteHistory.vue 一致:列表取首条的 version 再点「恢复」
|
||||
var list = json.readTree(mvc.perform(get("/api/v1/notes/" + id + "/history").session(session))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
|
||||
assertTrue(list.size() >= 1);
|
||||
long newest = list.get(0).get("version").asLong();
|
||||
assertEquals(1, newest, "旧库的最近一版历史(第 1 版保存前 = n1)");
|
||||
mvc.perform(get("/api/v1/notes/" + id + "/history/" + newest).session(session))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.body").value("n1"));
|
||||
// 与升级前一致的语义:旧口径 history/2 是第 2 版保存前 = n1(旧库没有更新历史)
|
||||
mvc.perform(get("/api/v1/notes/" + id + "/history/2").session(session))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.body").value("n1"));
|
||||
mvc.perform(post("/api/v1/notes/" + id + "/history/2").session(session).with(csrf())
|
||||
.contentType("application/json").content("{}"))
|
||||
.andExpect(status().isOk()).andExpect(jsonPath("$.body").value("n1"));
|
||||
}
|
||||
|
||||
/** XZH-21 回归:不存在的版本号返回 404(不能兜底成当前内容),恢复同理。 */
|
||||
@Test
|
||||
void missingHistoryVersionIsNotFoundForReadAndRestore() throws Exception {
|
||||
var session = login();
|
||||
var input = new java.util.HashMap<String, Object>(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();
|
||||
input.put("body", "v1");
|
||||
mvc.perform(put("/api/v1/notes/" + id).session(session).with(csrf())
|
||||
.contentType("application/json").content(json.writeValueAsBytes(input))).andExpect(status().isOk());
|
||||
mvc.perform(get("/api/v1/notes/" + id + "/history/9").session(session)).andExpect(status().isNotFound());
|
||||
mvc.perform(post("/api/v1/notes/" + id + "/history/9").session(session).with(csrf())
|
||||
.contentType("application/json").content("{}")).andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
/**
|
||||
* XZH-21 回归(第三轮补充问题):/library/{kind}/trash 列表与恢复/永久删除接受同一组 kind。
|
||||
* 之前列表对 rss/prompts/flows/inbox 抛 404,而恢复是 204,「两套路由等价」在列表这一侧不成立。
|
||||
*/
|
||||
@Test
|
||||
void libraryTrashListAcceptsEveryTrashKind() throws Exception {
|
||||
var session = login();
|
||||
long stamp = System.nanoTime();
|
||||
String day = java.time.LocalDate.now().plusDays(5).toString();
|
||||
String task = json.readTree(mvc.perform(post("/api/v1/planner/tasks").session(session).with(csrf())
|
||||
.contentType("application/json").content(json.writeValueAsBytes(Map.of(
|
||||
"title", "列表-待办-" + stamp, "body", ""))))
|
||||
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
|
||||
String event = json.readTree(mvc.perform(post("/api/v1/planner/events").session(session).with(csrf())
|
||||
.contentType("application/json").content(json.writeValueAsBytes(Map.of(
|
||||
"title", "列表-日程-" + stamp, "body", "", "starts_at", day + "T07:30"))))
|
||||
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
|
||||
mvc.perform(delete("/api/v1/planner/tasks/" + task).session(session).with(csrf())).andExpect(status().isNoContent());
|
||||
mvc.perform(delete("/api/v1/planner/events/" + event).session(session).with(csrf())).andExpect(status().isNoContent());
|
||||
for (String kind : List.of("notes", "blogs", "bookmarks", "assets", "tasks", "rss", "prompts", "flows", "inbox")) {
|
||||
var rows = json.readTree(mvc.perform(get("/api/v1/library/" + kind + "/trash").session(session))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
|
||||
assertTrue(rows.isArray(), kind + " 列表不是数组");
|
||||
}
|
||||
// planner 共用一张表,列表必须按 kind 过滤
|
||||
var tasks = json.readTree(mvc.perform(get("/api/v1/library/tasks/trash").session(session))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
|
||||
assertEquals(List.of("列表-待办-" + stamp), tasks.findValuesAsText("title"));
|
||||
var events = json.readTree(mvc.perform(get("/api/v1/library/events/trash").session(session))
|
||||
.andExpect(status().isOk()).andReturn().getResponse().getContentAsByteArray());
|
||||
assertEquals(List.of("列表-日程-" + stamp), events.findValuesAsText("title"));
|
||||
// 未知 kind 仍然是 404
|
||||
mvc.perform(get("/api/v1/library/unknown/trash").session(session)).andExpect(status().isNotFound());
|
||||
}
|
||||
|
||||
/** XZH-21 回归:/library 的删除通知要写对模块名(笔记不能写成"素材")。 */
|
||||
@Test
|
||||
void libraryTrashNoticeUsesModuleLabel() throws Exception {
|
||||
var session = login();
|
||||
String id = json.readTree(mvc.perform(post("/api/v1/notes").session(session).with(csrf())
|
||||
.contentType("application/json").content(json.writeValueAsBytes(Map.of(
|
||||
"title", "通知文案笔记", "body", "内容", "category", "技术笔记", "tag", ""))))
|
||||
.andExpect(status().isCreated()).andReturn().getResponse().getContentAsByteArray()).get("id").asText();
|
||||
// 知识库列表的「移入回收站」走批量接口
|
||||
mvc.perform(post("/api/v1/library/notes/batch").session(session).with(csrf()).contentType("application/json")
|
||||
.content(json.writeValueAsBytes(Map.of("action", "trash", "ids", List.of(id))))).andExpect(status().isNoContent());
|
||||
mvc.perform(get("/api/v1/admin-tools/notifications").session(session))
|
||||
.andExpect(jsonPath("$[0].title").value(org.hamcrest.Matchers.containsString("已删除笔记「通知文案笔记」")));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
package com.myspace;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.Statement;
|
||||
import java.util.UUID;
|
||||
import org.flywaydb.core.Flyway;
|
||||
import org.junit.jupiter.api.*;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.mock.web.MockHttpSession;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
/**
|
||||
* XZH-21 回归:升级路径。既有测试类都在「全新的库」上由 Flyway 一次建到最新,覆盖不到
|
||||
* 「已经在 V17 上跑过的库用新代码启动」这条路径——第二轮测试报告正是在这里报出升级后版本历史 500。
|
||||
*
|
||||
* <p>本类用独立库(TEST_UPGRADE_DB_URL,默认 myspace_upgrade_test,每次删表重建):
|
||||
* <ol>
|
||||
* <li>只迁移到 V17,写入旧口径数据(note_history 里没有 legacy_versioning 列);
|
||||
* <li>再迁移到全部版本,断言列已补上、旧行标记为 true 并保留原有 version 编号;
|
||||
* <li>迁移后再迁移一次(幂等);
|
||||
* <li>应用启动后经接口读取并恢复旧口径历史:不能 500,内容必须是该版本保存前的内容。
|
||||
* </ol>
|
||||
* 第 4 步是 XZH-21 第三轮发现的缺口:升级后 history/{n} 对旧行取到了「下一版」的内容,恢复会写回错误内容。
|
||||
*/
|
||||
@SpringBootTest(
|
||||
properties = {
|
||||
"spring.datasource.url=${TEST_UPGRADE_DB_URL:jdbc:postgresql://localhost:55432/myspace_upgrade_test}",
|
||||
"spring.datasource.username=${TEST_DB_USER:myspace}",
|
||||
"spring.datasource.password=${TEST_DB_PASSWORD:}",
|
||||
"app.admin-password=integration-test-password",
|
||||
"app.storage=target/test-assets"
|
||||
})
|
||||
@AutoConfigureMockMvc
|
||||
class UpgradePathTest {
|
||||
static final String URL = System.getenv("TEST_UPGRADE_DB_URL");
|
||||
static final String USER = value("TEST_DB_USER", "myspace");
|
||||
static final String PASSWORD = value("TEST_DB_PASSWORD", "");
|
||||
|
||||
static String value(String name, String fallback) {
|
||||
String v = System.getenv(name);
|
||||
return v == null || v.isBlank() ? fallback : v;
|
||||
}
|
||||
static final String BASE = URL != null ? URL : "jdbc:postgresql://localhost:55432/myspace_upgrade_test";
|
||||
static String db;
|
||||
@Autowired MockMvc mvc;
|
||||
@Autowired com.fasterxml.jackson.databind.ObjectMapper json;
|
||||
@Autowired JdbcTemplate jdbc;
|
||||
|
||||
static Flyway flyway(String url) {
|
||||
return Flyway.configure().dataSource(url, USER, PASSWORD).cleanDisabled(false).load();
|
||||
}
|
||||
|
||||
/** Spring 容器启动时会把库迁到最新;建库/清空必须放在启动之后、测试之前。 */
|
||||
@BeforeEach
|
||||
void prepare() throws Exception {
|
||||
String admin = BASE.replaceFirst("/[^/]*$", "/postgres");
|
||||
// 库不存在时创建;权限不足时请先手工 create database
|
||||
try (Connection c = DriverManager.getConnection(admin, USER, PASSWORD); Statement s = c.createStatement()) {
|
||||
s.execute("create database " + BASE.substring(BASE.lastIndexOf('/') + 1));
|
||||
} catch (java.sql.SQLException exists) {
|
||||
// already exists
|
||||
}
|
||||
db = BASE;
|
||||
flyway(db).clean();
|
||||
}
|
||||
|
||||
@Test
|
||||
void upgradeFromV17KeepsOldHistoryReadable() throws Exception {
|
||||
Flyway v17 = Flyway.configure().dataSource(db, USER, PASSWORD)
|
||||
.target("17").cleanDisabled(true).load();
|
||||
v17.migrate();
|
||||
assertEquals("17", flyway(db).info().current().getVersion().getVersion());
|
||||
|
||||
// 旧口径数据:note_history 有 0/1 两行、没有 legacy_versioning 列,笔记版本为 2
|
||||
UUID id = UUID.randomUUID();
|
||||
try (Connection c = DriverManager.getConnection(db, USER, PASSWORD); Statement s = c.createStatement()) {
|
||||
s.execute("insert into notes(id,title,body,category,version) values ('" + id
|
||||
+ "','old','v2','技术笔记',2)");
|
||||
s.execute("insert into note_history(note_id,version,title,body,category,folder,tags,star) values ('" + id
|
||||
+ "',0,'old','orig','技术笔记','默认文件夹','',false),('" + id
|
||||
+ "',1,'old','v1','技术笔记','默认文件夹','',false)");
|
||||
}
|
||||
|
||||
Flyway upgrade = flyway(db);
|
||||
upgrade.migrate();
|
||||
// 幂等:再次执行不应再应用任何脚本
|
||||
assertEquals(0, upgrade.migrate().migrationsExecuted);
|
||||
|
||||
try (Connection c = DriverManager.getConnection(db, USER, PASSWORD); Statement s = c.createStatement()) {
|
||||
var column = s.executeQuery("select count(*) from information_schema.columns where table_name='note_history'"
|
||||
+ " and column_name='legacy_versioning'");
|
||||
column.next();
|
||||
assertEquals(1, column.getInt(1), "升级后缺少 legacy_versioning 列");
|
||||
var rows = s.executeQuery("select version,legacy_versioning from note_history where note_id='" + id
|
||||
+ "' order by version");
|
||||
var flags = new StringBuilder();
|
||||
while (rows.next()) flags.append(rows.getInt(1)).append(':').append(rows.getBoolean(2)).append(' ');
|
||||
assertEquals("0:true 1:true ", flags.toString(), "旧行必须标记为旧口径并保留原编号");
|
||||
var latest = s.executeQuery("select version from flyway_schema_history where success order by installed_rank desc limit 1");
|
||||
latest.next();
|
||||
assertEquals("18", latest.getString(1));
|
||||
}
|
||||
|
||||
if (jdbc.queryForObject("select count(*) from app_user", Integer.class) == 0)
|
||||
jdbc.update("insert into app_user values (1,'admin',?)",
|
||||
new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder().encode("integration-test-password"));
|
||||
// 应用启动后:旧口径行(0=原始, 1=v1,笔记版本 2)读回的是各自保存前的内容,不串到下一版
|
||||
MockHttpSession session = (MockHttpSession) mvc.perform(
|
||||
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/api/v1/auth/login")
|
||||
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
|
||||
.param("username", "admin").param("password", "integration-test-password"))
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
|
||||
.andReturn().getRequest().getSession();
|
||||
historyBody(session, id, 1, "v1");
|
||||
historyBody(session, id, 0, "orig");
|
||||
// 与升级前一致的语义:history/{n} 是「第 n 版保存前」的内容。旧库最高版本是 2,因此唯一可读的是 history/2 = v1
|
||||
historyBody(session, id, 2, "v1");
|
||||
// 恢复 history/2 必须回到 v1,不能被「版本号 ≥ n 的最新一行」顶替成 v2
|
||||
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
|
||||
.post("/api/v1/notes/" + id + "/history/2").session(session)
|
||||
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.body").value("v1"));
|
||||
// 第三轮阻断 B1:旧库上 n 大于所有旧行版本号时必须 404,不能回落成某个旧快照(读取与恢复都算)
|
||||
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
|
||||
.get("/api/v1/notes/" + id + "/history/9").session(session))
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isNotFound());
|
||||
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
|
||||
.post("/api/v1/notes/" + id + "/history/9").session(session)
|
||||
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isNotFound());
|
||||
assertEquals(3, jdbc.queryForObject("select version from notes where id=?::uuid", Integer.class, id),
|
||||
"恢复不存在的版本不能改动笔记版本");
|
||||
assertEquals("v1", jdbc.queryForObject("select body from notes where id=?::uuid", String.class, id));
|
||||
}
|
||||
|
||||
/**
|
||||
* 旧库有 0/1/2 三条旧行、笔记 version=3(第三轮报告「残留风险」):读取与恢复都要落在「≤ n 的最大旧行」,
|
||||
* 大于旧行最大版本号的 n 一律 404。
|
||||
*/
|
||||
@Test
|
||||
void upgradeWithThreeLegacyRowsResolvesEachVersionOnce() throws Exception {
|
||||
Flyway.configure().dataSource(db, USER, PASSWORD).target("17").cleanDisabled(true).load().migrate();
|
||||
UUID id = UUID.randomUUID();
|
||||
UUID note2 = UUID.randomUUID();
|
||||
try (Connection c = DriverManager.getConnection(db, USER, PASSWORD); Statement s = c.createStatement()) {
|
||||
s.execute("insert into notes(id,title,body,category,version) values ('" + id
|
||||
+ "','old','v3','技术笔记',3),('" + note2 + "','old2','v3','技术笔记',3)");
|
||||
for (String n : new String[] {id.toString(), note2.toString()})
|
||||
s.execute("insert into note_history(note_id,version,title,body,category,folder,tags,star) values ('" + n
|
||||
+ "',0,'old','orig','技术笔记','默认文件夹','',false),('" + n
|
||||
+ "',1,'old','v1','技术笔记','默认文件夹','',false),('" + n
|
||||
+ "',2,'old','v2','技术笔记','默认文件夹','',false)");
|
||||
}
|
||||
flyway(db).migrate();
|
||||
|
||||
if (jdbc.queryForObject("select count(*) from app_user", Integer.class) == 0)
|
||||
jdbc.update("insert into app_user values (1,'admin',?)",
|
||||
new org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder().encode("integration-test-password"));
|
||||
MockHttpSession session = (MockHttpSession) mvc.perform(
|
||||
org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post("/api/v1/auth/login")
|
||||
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
|
||||
.param("username", "admin").param("password", "integration-test-password"))
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
|
||||
.andReturn().getRequest().getSession();
|
||||
historyBody(session, id, 0, "orig");
|
||||
historyBody(session, id, 1, "v1");
|
||||
historyBody(session, id, 2, "v2");
|
||||
historyBody(session, id, 3, "v2");
|
||||
for (long n : new long[] {4, 9}) {
|
||||
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
|
||||
.get("/api/v1/notes/" + id + "/history/" + n).session(session))
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isNotFound());
|
||||
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
|
||||
.post("/api/v1/notes/" + id + "/history/" + n).session(session)
|
||||
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isNotFound());
|
||||
}
|
||||
// 恢复 history/2 → 正文 v2,恢复前的当前内容 v3 记为历史
|
||||
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
|
||||
.post("/api/v1/notes/" + note2 + "/history/2").session(session)
|
||||
.with(org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.csrf())
|
||||
.contentType(MediaType.APPLICATION_JSON).content("{}"))
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.body").value("v2"));
|
||||
historyBody(session, note2, 4, "v3");
|
||||
}
|
||||
|
||||
private void historyBody(MockHttpSession session, UUID id, long version, String expected) throws Exception {
|
||||
mvc.perform(org.springframework.test.web.servlet.request.MockMvcRequestBuilders
|
||||
.get("/api/v1/notes/" + id + "/history/" + version).session(session))
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.status().isOk())
|
||||
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.body").value(expected));
|
||||
}
|
||||
}
|
||||
@@ -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'">
|
||||
|
||||
+15
-3
@@ -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() {
|
||||
user.value = "";
|
||||
// 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) {
|
||||
|
||||
@@ -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"];
|
||||
Reference in new issue
Block a user