package com.example.rzgb.watch; import com.example.rzgb.auth.CurrentUser; import com.example.rzgb.common.*; import com.example.rzgb.evidence.EvidenceService; import com.example.rzgb.opportunity.OpportunityRanking; import com.example.rzgb.opportunity.OpportunityAnalysis; import com.example.rzgb.profile.CompanyProfile; import com.example.rzgb.files.BidFileService; import java.math.BigDecimal; import jakarta.validation.Valid; import jakarta.validation.constraints.*; import java.util.*; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.security.core.Authentication; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.bind.annotation.*; /** * 人工关注闭环。八状态允许人工自由跳转(包括恢复),公告截止、阶段与 AI 结论不能自动改状态。 * 状态、备注和历史原子提交;版本防覆盖,幂等键防止网络重试重复写历史。 */ @RestController @RequestMapping("/api") public class WatchController { public static final Set STATUSES=Set.of("已关注","准备投标","已报名","已提交投标文件","已中标","未中标","已流标","暂不考虑"); private static final Set RESULTS=Set.of("已中标","未中标","已流标"); private final JdbcTemplate jdbc; private final CurrentUser user; private final Json json; private final OpportunityRanking ranking; private final BidFileService files; private final OpportunityAnalysis analysis; public WatchController(JdbcTemplate jdbc,CurrentUser user,Json json,OpportunityRanking ranking,BidFileService files,OpportunityAnalysis analysis) { this.jdbc=jdbc; this.user=user; this.json=json; this.ranking=ranking; this.files=files; this.analysis=analysis; } @GetMapping("/watch") public List> list(Authentication auth, @RequestParam(required=false) String group,@RequestParam(required=false) String tag) { if(group!=null && !Set.of("跟进中","已有结果","暂不考虑").contains(group)) throw new ApiException(400,"INVALID_GROUP","关注分组无效"); return jdbc.query("SELECT w.*,p.document FROM watch_record w JOIN project p ON p.id=w.project_id WHERE w.user_id=? ORDER BY w.created_at DESC,w.id",(rs,n) -> { String watch=rs.getString("id"),status=rs.getString("status"); Map row=new LinkedHashMap<>(); row.put("projectId",rs.getString("project_id")); row.put("status",status); row.put("note",rs.getString("note")); row.put("version",rs.getLong("version")); row.put("createdAt",rs.getTimestamp("created_at").toInstant()); row.put("tags",jdbc.queryForList("SELECT t.name FROM tag t JOIN watch_tag wt ON wt.tag_id=t.id WHERE wt.watch_id=? ORDER BY t.name",String.class,watch)); row.put("history",history(watch)); row.put("group",group(status)); var raw=json.read(rs.getString("document")); var project=ranking.normalize(raw,null); row.put("project",project); // 复用列表摘录读取已有原文,不发外部请求;附件信息单列,避免改变历史检索快照的字段与哈希。 row.put("summary",analysis.analyze(project,raw,CompanyProfile.empty()).summary()); row.put("fileId",raw.path("user_file_id").asText(null)); return row; },user.id(auth)).stream().filter(row -> group==null || group.equals(row.get("group"))) .filter(row -> tag==null || ((List)row.get("tags")).contains(tag)).toList(); } private static String group(String status) { return status.equals("暂不考虑")?"暂不考虑":RESULTS.contains(status)?"已有结果":"跟进中"; } private List> history(String watch) { return jdbc.query("SELECT status,note,created_at,record_version FROM watch_history WHERE watch_id=? ORDER BY COALESCE(record_version,1),created_at,id",(rs,n) -> { Map row=new LinkedHashMap<>(); row.put("status",rs.getString(1)); row.put("note",rs.getString(2)); row.put("time",rs.getTimestamp(3).toInstant()); row.put("version",rs.getObject(4)); return row; },watch); } @GetMapping("/watch/{projectId}/history") public List> history(Authentication auth,@PathVariable String projectId) { return history(owned(user.id(auth),projectId).get("id").toString()); } /** 账号锁统一增删、变更和标签操作的顺序,唯一约束负责最终防重。 */ private void lock(String owner) { jdbc.queryForObject("SELECT id FROM app_user WHERE id=? FOR UPDATE",String.class,owner); } private Map owned(String owner,String project) { var rows=jdbc.queryForList("SELECT * FROM watch_record WHERE user_id=? AND project_id=?",owner,project); if(rows.isEmpty()) throw new ApiException(404,"NOT_FOUND","关注记录不存在"); return rows.getFirst(); } @PostMapping("/watch/{projectId}") @Transactional public Map add(Authentication auth,@PathVariable String projectId) { String owner=user.id(auth); lock(owner); var documents=jdbc.queryForList("SELECT document FROM project WHERE id=?",String.class,projectId); if(documents.isEmpty()) throw new ApiException(404,"NOT_FOUND","请先检索并取得真实公告"); // 手动项目包含用户填写信息和私有文件,不能凭其他账号的项目 ID 添加到自己的关注中。 var document=json.read(documents.getFirst()); if("USER_INPUT".equals(document.path("origin").asText()) && !owner.equals(document.path("owner_id").asText())) throw new ApiException(404,"NOT_FOUND","项目不存在"); if(jdbc.queryForObject("SELECT COUNT(*) FROM watch_record WHERE user_id=? AND project_id=?",Integer.class,owner,projectId)==0) { String id=UUID.randomUUID().toString(); jdbc.update("INSERT INTO watch_record(id,user_id,project_id,status,note) VALUES(?,?,?,'已关注','')",id,owner,projectId); jdbc.update("INSERT INTO watch_history(id,watch_id,status,note,actor_id,record_version) VALUES(?,?,'已关注','',?,1)",UUID.randomUUID().toString(),id,owner); } return Map.of("watched",true); } public record ManualProject(@NotBlank @Pattern(regexp="[A-Za-z0-9-]{8,64}") String commandId, @NotBlank @Size(max=512) String title,@Size(max=2048) String url, @Size(max=512) String purchaser,@Size(max=120) String region, @DecimalMin("0") @DecimalMax("100000000") BigDecimal budgetWan, @Size(max=36) String fileId) {} /** * 原型的“添加项目”改为真实持久化:只保存用户提供的事实,不抓取网址、不生成公告或评分。 * 账号锁与 commandId 保证重复提交只新增一次;同一键改内容则拒绝,避免静默覆盖。 * 文件只引用当前账号仍有效的已上传原件,不复制全文,也不改变既有文件到期清理规则。 */ @PostMapping("/watch/manual") @Transactional public Object manual(Authentication auth,@Valid @RequestBody ManualProject request) { String owner=user.id(auth); lock(owner); String url=EvidenceService.safeUrl(request.url()); if(request.url()!=null && !request.url().isBlank() && url==null) throw new ApiException(400,"INVALID_URL","请填写有效的 HTTP(S) 公告网址"); boolean hasFile=request.fileId()!=null && !request.fileId().isBlank(); if(url==null && !hasFile) throw new ApiException(400,"SOURCE_REQUIRED","请填写公告网址或上传公告文件"); String source="manual:"+EvidenceService.hash(owner+":"+request.commandId()).substring(0,40),id=ranking.projectId(source); String fingerprint=EvidenceService.hash(json.write(request)); var existing=jdbc.queryForList("SELECT document FROM project WHERE id=?",String.class,id); if(!existing.isEmpty()) { if(!fingerprint.equals(json.read(existing.getFirst()).path("request_hash").asText())) throw new ApiException(409,"IDEMPOTENCY_CONFLICT","该提交已保存,请刷新列表后再添加其他项目"); return Map.of("projectId",id); } if(hasFile && !"READY".equals(files.get(owner,request.fileId()).get("status"))) throw new ApiException(410,"FILE_EXPIRED","文件已删除或过期,请重新上传"); Map document=new LinkedHashMap<>(); document.put("bid_id",source); document.put("title",request.title().trim()); document.put("caller_name",Objects.toString(request.purchaser(),"").trim()); document.put("province",Objects.toString(request.region(),"").trim()); document.put("money_wan",request.budgetWan()); document.put("url",url); document.put("origin","USER_INPUT"); document.put("owner_id",owner); document.put("user_file_id",hasFile?request.fileId():null); document.put("request_hash",fingerprint); jdbc.update("INSERT INTO project(id,source_id,document) VALUES(?,?,?)",id,source,json.write(document)); add(auth,id); return Map.of("projectId",id); } @DeleteMapping("/watch/{projectId}") @Transactional public Map remove(Authentication auth,@PathVariable String projectId) { String owner=user.id(auth); lock(owner); // 只清理本人的关注历史、命令和标签绑定;公共公告、独立检索与报告保持可查。 jdbc.update("DELETE FROM watch_record WHERE user_id=? AND project_id=?",owner,projectId); return Map.of("watched",false); } public record Change(@Size(max=32) String status,@Size(max=5000) String note,@Min(1) long version) {} public record TagName(@NotBlank @Size(max=64) String name) {} public record TagSelection(@NotNull @Size(max=50) List<@NotBlank @Size(max=64) String> tags,@Min(1) long version) {} @PostMapping("/watch/{projectId}/changes") @Transactional public Object change(Authentication auth,@PathVariable String projectId, @RequestHeader("Idempotency-Key") String key,@Valid @RequestBody Change change) { if(change.status()!=null && !STATUSES.contains(change.status())) throw new ApiException(400,"INVALID_STATUS","请选择八种人工跟进状态之一"); String owner=user.id(auth); lock(owner); var row=owned(owner,projectId); String id=row.get("id").toString(); String fingerprint=EvidenceService.hash("change:"+json.write(change)); Object previous=replay(id,key,fingerprint); if(previous!=null) return previous; checkVersion(row,change.version()); String status=change.status()==null?row.get("status").toString():change.status(); String note=change.note()==null?row.get("note").toString():change.note(); long version=change.version(); if(!status.equals(row.get("status")) || !note.equals(row.get("note"))) { version++; jdbc.update("UPDATE watch_record SET status=?,note=?,version=? WHERE id=?",status,note,version,id); jdbc.update("INSERT INTO watch_history(id,watch_id,status,note,actor_id,record_version) VALUES(?,?,?,?,?,?)",UUID.randomUUID().toString(),id,status,note,owner,version); } Object result=Map.of("status",status,"note",note,"version",version); remember(id,key,fingerprint,result); return result; } private void checkVersion(Map row,long version) { if(((Number)row.get("version")).longValue()!=version) throw new ApiException(409,"VERSION_CONFLICT","关注已被修改,请刷新后重试,当前编辑未覆盖服务端数据"); } private Object replay(String id,String key,String fingerprint) { if(key==null || !key.matches("[A-Za-z0-9._:-]{8,128}")) throw new ApiException(400,"INVALID_IDEMPOTENCY_KEY","变更需要 8–128 字符幂等键"); var commands=jdbc.queryForList("SELECT request_hash,result_json FROM watch_command WHERE watch_id=? AND idempotency_key=?",id,key); if(commands.isEmpty()) return null; if(!fingerprint.equals(commands.getFirst().get("request_hash"))) throw new ApiException(409,"IDEMPOTENCY_CONFLICT","相同键不能用于不同关注变更"); return json.read(commands.getFirst().get("result_json").toString()); } private void remember(String id,String key,String fingerprint,Object result) { jdbc.update("INSERT INTO watch_command(watch_id,idempotency_key,request_hash,result_json) VALUES(?,?,?,?)",id,key,fingerprint,json.write(result)); } @GetMapping("/tags") public List> tags(Authentication auth) { return jdbc.query("SELECT id,name FROM tag WHERE user_id=? ORDER BY name,id",(rs,n) -> Map.of("id",rs.getString(1),"name",rs.getString(2)),user.id(auth)); } @PostMapping("/tags") @Transactional public Map createTag(Authentication auth,@Valid @RequestBody TagName name) { String owner=user.id(auth); lock(owner); String text=name.name().trim(); if(text.isEmpty()) throw new ApiException(400,"INVALID_TAG","标签不能为空"); var ids=jdbc.queryForList("SELECT id FROM tag WHERE user_id=? AND name=?",String.class,owner,text); if(!ids.isEmpty()) return Map.of("id",ids.getFirst(),"name",text); String id=UUID.randomUUID().toString(); jdbc.update("INSERT INTO tag(id,user_id,name) VALUES(?,?,?)",id,owner,text); return Map.of("id",id,"name",text); } @DeleteMapping("/tags/{id}") @Transactional public Map deleteTag(Authentication auth,@PathVariable String id) { String owner=user.id(auth); lock(owner); // 删除标签也改变相关关注的版本,避免旧页面用旧选择覆盖刚完成的解绑。 jdbc.update("UPDATE watch_record SET version=version+1 WHERE user_id=? AND id IN (SELECT watch_id FROM watch_tag WHERE tag_id IN (SELECT id FROM tag WHERE id=? AND user_id=?))",owner,id,owner); jdbc.update("DELETE FROM tag WHERE id=? AND user_id=?",id,owner); return Map.of("deleted",true); } @PutMapping("/watch/{projectId}/tags") @Transactional public Object selectTags(Authentication auth,@PathVariable String projectId, @RequestHeader("Idempotency-Key") String key,@Valid @RequestBody TagSelection selection) { String owner=user.id(auth); lock(owner); var row=owned(owner,projectId); String id=row.get("id").toString(); String fingerprint=EvidenceService.hash("tags:"+json.write(selection)); Object previous=replay(id,key,fingerprint); if(previous!=null) return previous; checkVersion(row,selection.version()); List names=selection.tags().stream().map(String::trim).distinct().sorted().toList(); List ids=new ArrayList<>(); for(String name:names) { var found=jdbc.queryForList("SELECT id FROM tag WHERE user_id=? AND name=?",String.class,owner,name); if(found.isEmpty()) throw new ApiException(400,"INVALID_TAG","请先创建属于当前账号的标签"); ids.add(found.getFirst()); } List current=jdbc.queryForList("SELECT t.name FROM tag t JOIN watch_tag wt ON wt.tag_id=t.id WHERE wt.watch_id=? ORDER BY t.name",String.class,id); long version=selection.version(); if(!current.equals(names)) { jdbc.update("DELETE FROM watch_tag WHERE watch_id=?",id); for(String tag:ids) jdbc.update("INSERT INTO watch_tag(watch_id,tag_id) VALUES(?,?)",id,tag); jdbc.update("UPDATE watch_record SET version=version+1 WHERE id=?",id); version++; } Object result=Map.of("tags",names,"version",version); remember(id,key,fingerprint,result); return result; } }