package com.example.rzgb.opportunity; import com.example.rzgb.auth.CurrentUser; import com.example.rzgb.common.*; import com.example.rzgb.config.AppProperties; import com.example.rzgb.task.*; import jakarta.validation.Valid; import jakarta.validation.constraints.*; import java.math.BigDecimal; 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.*; /** * 检索、方案和手动执行共用一个任务入口与收费账本。 * 方案编辑只影响未来执行;历史 Tab 始终读取任务中的固定条件、档案与公告快照。 */ @RestController @RequestMapping("/api") public class SearchController { private final JdbcTemplate jdbc; private final Json json; private final CurrentUser user; private final TaskService tasks; private final AppProperties limits; public SearchController(JdbcTemplate jdbc, Json json, CurrentUser user, TaskService tasks, AppProperties limits) { this.jdbc=jdbc; this.json=json; this.user=user; this.tasks=tasks; this.limits=limits; } public record Execution(@NotNull @Valid OpportunityQuery conditions, @Min(1) @Max(25) int maxCalls, @NotNull @DecimalMin("0.01") @DecimalMax("1000") BigDecimal maxCostUnits) {} public record Scheme(@NotBlank @Size(max=128) String name, @NotNull @Valid OpportunityQuery conditions, @Min(0) long version) {} @PostMapping("/searches") public Map create(Authentication auth,@RequestHeader("Idempotency-Key") String key, @Valid @RequestBody Execution execution) { return tasks.create(user.id(auth),key,request(execution)); } @GetMapping("/searches") public List> list(Authentication auth) { return jdbc.query("SELECT t.id,t.status,t.created_at,r.scheme_id,r.scheme_name,r.scheme_version FROM agent_task t LEFT JOIN search_run r ON r.task_id=t.id WHERE t.user_id=? AND t.operation='OPPORTUNITY_SEARCH' ORDER BY t.created_at DESC,t.id LIMIT 50",(rs,n) -> { Map row=new LinkedHashMap<>(); row.put("id",rs.getString(1)); row.put("status",rs.getString(2)); row.put("createdAt",rs.getTimestamp(3).toInstant()); row.put("schemeId",rs.getString(4)); row.put("schemeName",rs.getString(5)); row.put("schemeVersion",rs.getObject(6)); return row; },user.id(auth)); } @GetMapping("/searches/{id}") public Map get(Authentication auth,@PathVariable String id) { return search(user.id(auth),id); } private Map search(String owner,String id) { var task=tasks.get(owner,id); if (!"OPPORTUNITY_SEARCH".equals(task.get("operation"))) throw new ApiException(404,"NOT_FOUND","检索批次不存在"); return task; } @SuppressWarnings("unchecked") @GetMapping("/searches/{id}/items") public Map items(Authentication auth,@PathVariable String id, @RequestParam(defaultValue="1") int page,@RequestParam(defaultValue="20") int size) { if(page<1 || size<1 || size>50) throw new ApiException(400,"INVALID_PAGE","页码须为正整数,每页 1–50 条"); var report=(Map)search(user.id(auth),id).get("result"); List items=report==null?List.of():(List)report.get("items"); int start=(int)Math.min(items.size(),(long)(page-1)*size), end=Math.min(items.size(),start+size); return Map.of("items",items.subList(start,end),"total",items.size(),"page",page,"size",size); } @PostMapping("/searches/{id}/continue") public Map resume(Authentication auth,@PathVariable String id, @RequestHeader("Idempotency-Key") String key,@Valid @RequestBody Execution execution) { String owner=user.id(auth); search(owner,id); return tasks.resume(owner,id,key,request(execution)); } public record PreferenceView(@NotNull OpportunityQuery.Preference preference, @NotNull @Size(max=20) List<@NotBlank @Size(max=40) String> regions, BigDecimal minWan, BigDecimal maxWan) {} /** 临时偏好视图只读取原批次,不改写历史快照、不产生新的工具请求。 */ @SuppressWarnings("unchecked") @PostMapping("/searches/{id}/view") public Object view(Authentication auth,@PathVariable String id,@Valid @RequestBody PreferenceView preference) { var task=search(user.id(auth),id); var report=(Map)task.get("result"); if(report==null) throw new ApiException(409,"NO_RESULTS","尚未取得可排序的结果"); var original=(OpportunityQuery)report.get("conditions"); if(original.mode()==OpportunityQuery.Mode.SEARCH) throw new ApiException(400,"ORDER_FIXED","普通检索始终按发布时间排序"); var query=new OpportunityQuery(original.keywords(),original.beginDate(),original.endDate(),original.stages(),preference.preference(), preference.regions(),preference.minWan(),preference.maxWan(),original.mode(),original.keywordMode(),List.of(),null,null); query.validate(); List> rows=(List>)report.get("items"); Map> byId=new HashMap<>(); List facts=new ArrayList<>(); for(var row:rows) { var fact=(OpportunityRanking.Candidate)row.get("facts"); facts.add(fact); byId.put(fact.id(),row); } List> sorted=new ArrayList<>(); for(var ranked:new OpportunityRanking(json).rank(facts,query)) { var row=new LinkedHashMap<>(byId.get(ranked.facts().id())); row.put("relevance",ranked.relevance()); row.put("preferenceBonus",ranked.preferenceBonus()); row.put("reasoning",ranked.reasoning()); sorted.add(row); } var result=new LinkedHashMap<>(report); result.put("items",sorted); result.put("viewPreference",preference); return result; } private TaskRequest request(Execution e) { e.conditions().validate(); return new TaskRequest(TaskRequest.Operation.OPPORTUNITY_SEARCH,TaskRequest.Workflow.TENDER_SEARCH,"",false,e.maxCalls(),e.maxCostUnits(),e.conditions()); } @GetMapping("/search-schemes") public List> schemes(Authentication auth) { return jdbc.query("SELECT id,name,conditions,version FROM search_scheme WHERE user_id=? ORDER BY name,id",(rs,n) -> Map.of("id",rs.getString(1),"name",rs.getString(2),"conditions",json.read(rs.getString(3)),"version",rs.getLong(4)),user.id(auth)); } @PostMapping("/search-schemes") @Transactional public Map save(Authentication auth,@Valid @RequestBody Scheme scheme) { scheme.conditions().validate(); String id=UUID.randomUUID().toString(),owner=user.id(auth); jdbc.update("INSERT INTO search_scheme(id,user_id,name,conditions) VALUES(?,?,?,?)",id,owner,scheme.name().trim(),json.write(scheme.conditions())); return scheme(owner,id,false); } @PutMapping("/search-schemes/{id}") @Transactional public Map edit(Authentication auth,@PathVariable String id,@Valid @RequestBody Scheme scheme) { scheme.conditions().validate(); String owner=user.id(auth); scheme(owner,id,true); if(jdbc.update("UPDATE search_scheme SET name=?,conditions=?,version=version+1 WHERE id=? AND user_id=? AND version=?", scheme.name().trim(),json.write(scheme.conditions()),id,owner,scheme.version())!=1) throw new ApiException(409,"VERSION_CONFLICT","方案已被修改,请刷新后重试"); return scheme(owner,id,false); } @DeleteMapping("/search-schemes/{id}") @Transactional public Map delete(Authentication auth,@PathVariable String id) { jdbc.update("DELETE FROM search_scheme WHERE id=? AND user_id=?",id,user.id(auth)); return Map.of("deleted",true); } private Map scheme(String owner,String id,boolean lock) { var rows=jdbc.query("SELECT id,name,conditions,version FROM search_scheme WHERE id=? AND user_id=?"+(lock?" FOR UPDATE":""),(rs,n) -> Map.of("id",rs.getString(1),"name",rs.getString(2),"conditions",json.read(rs.getString(3)),"version",rs.getLong(4)),id,owner); if(rows.isEmpty()) throw new ApiException(404,"NOT_FOUND","方案不存在"); return rows.getFirst(); } /** 相同执行键只回查原任务;即使方案后来改版,也不能用重复点击发起第二轮收费。 */ @PostMapping("/search-schemes/{id}/runs") @Transactional public Map run(Authentication auth,@PathVariable String id, @RequestHeader("Idempotency-Key") String key,@RequestParam(defaultValue="false") boolean strictFilters) { if(key==null || !key.matches("[A-Za-z0-9._:-]{8,128}")) throw new ApiException(400,"INVALID_IDEMPOTENCY_KEY","执行需要 8–128 字符幂等键"); String owner=user.id(auth); jdbc.queryForObject("SELECT id FROM app_user WHERE id=? FOR UPDATE",String.class,owner); var previous=jdbc.queryForList("SELECT t.id,r.scheme_id FROM agent_task t LEFT JOIN search_run r ON r.task_id=t.id WHERE t.user_id=? AND t.idempotency_key=?",owner,key); if(!previous.isEmpty()) { if(!id.equals(previous.getFirst().get("scheme_id"))) throw new ApiException(409,"IDEMPOTENCY_CONFLICT","该键已用于其他操作"); return tasks.get(owner,previous.getFirst().get("id").toString()); } var scheme=scheme(owner,id,true); var query=json.convert(json.write(scheme.get("conditions")),OpportunityQuery.class); // 发现商机显式按筛选条件执行旧方案:把误存的地区/金额偏好转为硬条件,日期原样传递。 // 只改变新任务快照,不改写方案或已执行结果;其他调用方仍可沿用获客偏好语义。 if(strictFilters && query.mode()==OpportunityQuery.Mode.LEADS) { query=new OpportunityQuery(query.keywords(),query.beginDate(),query.endDate(),query.stages(), OpportunityQuery.Preference.COMPREHENSIVE,List.of(),null,null,OpportunityQuery.Mode.SEARCH, query.keywordMode(),query.preferredRegions(),query.budgetMinWan(),query.budgetMaxWan()); } var task=tasks.create(owner,key,request(new Execution(query,limits.maxCalls(),limits.maxCostUnits()))); jdbc.update("INSERT INTO search_run(task_id,scheme_id,scheme_name,scheme_version) VALUES(?,?,?,?)",task.get("id"),id,scheme.get("name"),scheme.get("version")); return task; } @GetMapping("/search-schemes/{id}/runs") public List runs(Authentication auth,@PathVariable String id) { String owner=user.id(auth); scheme(owner,id,false); return jdbc.queryForList("SELECT t.id FROM search_run r JOIN agent_task t ON t.id=r.task_id WHERE r.scheme_id=? AND t.user_id=? ORDER BY t.created_at DESC,t.id",String.class,id,owner); } /** 公告只向曾取得该公告或已关注它的账号返回;前端无法借接口写入演示公告。 */ @GetMapping("/projects/{id}") public Object project(Authentication auth,@PathVariable String id) { String owner=user.id(auth); var snapshots=jdbc.queryForList("SELECT s.snapshot FROM search_item s JOIN search_batch b ON b.id=s.batch_id WHERE s.project_id=? AND b.user_id=? ORDER BY b.created_at DESC LIMIT 1",String.class,id,owner); if(!snapshots.isEmpty()) return json.read(snapshots.getFirst()); var docs=jdbc.queryForList("SELECT p.document FROM project p JOIN watch_record w ON w.project_id=p.id WHERE p.id=? AND w.user_id=?",String.class,id,owner); if(docs.isEmpty()) throw new ApiException(404,"NOT_FOUND","公告不存在或尚未取得"); return new OpportunityRanking(json).normalize(json.read(docs.getFirst()),null); } }