package com.myspace.notes; import com.myspace.common.WorkspaceNotifications; import com.myspace.library.LibraryFields; import com.myspace.library.TrashService; import jakarta.validation.Valid; import jakarta.validation.constraints.*; import java.util.*; import org.springframework.http.HttpStatus; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; import org.springframework.web.server.ResponseStatusException; @RestController @RequestMapping("/api/v1/notes") public class NotesController { private final JdbcTemplate db; private final TrashService trash; public NotesController(JdbcTemplate db, TrashService trash) { this.db = db; this.trash = trash; } public record Input( @NotBlank @Size(max = 120) String title, @NotNull @Size(max = 1000000) String body, @NotBlank @Size(max = 60) String category, @NotNull @Size(max = 60) String tag, boolean star, @Min(0) long version, @Size(max = 60) String folder, @Size(max = 1500) String tags) {} @GetMapping public List> list( @RequestParam(defaultValue = "") String q, @RequestParam(defaultValue = "") String category, @RequestParam(defaultValue = "false") boolean starred, @RequestParam(defaultValue = "") String folder, @RequestParam(defaultValue = "") String tag, @RequestParam(defaultValue = "updated") String sort, @RequestParam(defaultValue = "false") boolean excerpt, @RequestParam(defaultValue = "0") @Min(0) int offset) { String order = switch (sort) { case "created" -> "created_at desc"; case "name" -> "lower(title)"; default -> "updated_at desc"; }; return db.queryForList( "select " + (excerpt ? "id,title,left(body,180) as body,category,folder,tags,tag,star,version,created_at,updated_at" : "*") + " from notes where deleted_at is null and position(lower(?) in lower(title || ' ' || body || ' ' || tags))>0" + " and (?='' or category=?) and (?=false or star) and (?='' or folder=?)" + " and (?='' or ?=any(string_to_array(tags,','))) order by " + order + ",id limit 100 offset ?", q, category, category, starred, folder, folder, tag, tag, offset); } @GetMapping("/resolve") public List> resolve(@RequestParam String title) { return db.queryForList("select id,title from notes where title=? and deleted_at is null" + " order by updated_at desc,id limit 50", title); } @GetMapping("/graph") public Map graph(@RequestParam(defaultValue = "") String q, @RequestParam(defaultValue = "") String category) { var nodes = db.queryForList("select id,title,category from notes where deleted_at is null" + " and (?='' or category=?) and position(lower(?) in lower(title || ' ' || tags))>0" + " order by updated_at desc,id limit 24", category, category, q); var edges = db.queryForList("with scope as (select id,title,body from notes where deleted_at is null" + " and (?='' or category=?) and position(lower(?) in lower(title || ' ' || tags))>0" + " order by updated_at desc,id limit 24)" + " select a.id as source,b.id as target from scope a join scope b on a.id<>b.id" + " and position('[[' || b.title || ']]' in a.body)>0", category, category, q); return Map.of("nodes", nodes, "edges", edges); } @GetMapping("/{id}") public Map get(@PathVariable UUID id) { return db.queryForList("select * from notes where id=? and deleted_at is null", id).stream() .findFirst() .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "笔记不存在")); } @PostMapping @ResponseStatus(HttpStatus.CREATED) @Transactional public Map create(@Valid @RequestBody Input n) { UUID id = UUID.randomUUID(); ensureCategory(n.category()); String tags = LibraryFields.tags(n.tags() == null ? n.tag() : n.tags()); db.update( "insert into notes(id,title,body,category,tag,star,folder,tags) values(?,?,?,?,?,?,?,?)", id, n.title().trim(), n.body(), n.category(), LibraryFields.firstTag(tags), n.star(), LibraryFields.folder(db, "notes", n.folder()), tags); return get(id); } /** * 兼容前端笔记列表的整批保存:一次提交多条笔记,逐条走 update 的快照与合并逻辑。 */ public record BatchItem(@NotNull UUID id, Input note) {} @PutMapping("/batch") @Transactional public List> batchUpdate(@Valid @RequestBody @Size(max = 200) List items) { List> saved = new ArrayList<>(); for (BatchItem item : items) saved.add(update(item.id(), item.note())); return saved; } @PutMapping("/{id}") @Transactional public Map update(@PathVariable UUID id, @Valid @RequestBody Input n) { Map current = lock(id); // 只有真的改到别的分类时才补建分类,避免过期保存把已删除的分类重新创建出来 if (!Objects.equals(current.get("category"), n.category())) ensureCategory(n.category()); String tags = LibraryFields.tags(n.tags() == null ? Objects.equals(n.tag(), current.get("tag")) ? (String) current.get("tags") : n.tag() : n.tags()); String folder = n.folder() == null ? (String) current.get("folder") : LibraryFields.folder(db, "notes", n.folder()); if (Objects.equals(current.get("title"), n.title().strip()) && Objects.equals(current.get("body"), n.body()) && Objects.equals(current.get("category"), n.category()) && Objects.equals(current.get("folder"), folder) && 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()) { Map merged = new HashMap<>(current); String currentTag = (String) current.get("tag"); merged.put("title", n.title().strip()); merged.put("body", n.body()); // 过期保存不改动分类:分类可能已在别处迁移或删除,沿用库内最新值 merged.put("category", current.get("category")); if (!Objects.equals(n.tag(), currentTag)) merged.put("tags", tags); 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, 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); } // Existing note API clients can still submit a category name directly. private void ensureCategory(String name) { 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 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) { 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) {} @PostMapping("/{id}/history/{version}") @Transactional public Map restore(@PathVariable UUID id, @PathVariable long version, @RequestBody(required = false) Restore input) { 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, "版本不存在")); 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, ((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); } @GetMapping("/{id}/backlinks") public List> backlinks(@PathVariable UUID id) { String title = (String) get(id).get("title"); return db.queryForList("select id,title from notes where id<>? and deleted_at is null" + " and position(? in body)>0 order by updated_at desc", id, "[[" + title + "]]"); } private Map lock(UUID id) { return db.queryForList("select * from notes where id=? and deleted_at is null for update", id) .stream().findFirst().orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "笔记不存在")); } private void checkVersion(Map note, long version) { if (((Number) note.get("version")).longValue() != version) throw new ResponseStatusException(HttpStatus.CONFLICT, "笔记已在其他页面更新,请重新打开后编辑"); } /** * 以「保存后的版本号」写入快照(即本次保存的「保存前内容」)。此后该版本被再次保存或恢复时, * 先读取 contentAt 取回内容,再写入新版本的快照,因此不会出现历史被覆盖或版本错位。 */ 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")); } @DeleteMapping("/{id}") @ResponseStatus(HttpStatus.NO_CONTENT) @Transactional public void delete(@PathVariable UUID id) { Map current = lock(id); db.update("update notes set deleted_at=now(),version=version+1 where id=?", id); trash.notifyTrashed("notes", (String) current.get("title")); } }