package com.example.rzgb; import org.junit.jupiter.api.*; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.DynamicPropertyRegistry; import org.springframework.test.context.DynamicPropertySource; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.web.servlet.*; import org.springframework.mock.web.MockHttpSession; import org.springframework.jdbc.core.JdbcTemplate; import com.example.rzgb.common.Json; import com.example.rzgb.task.*; import com.example.rzgb.opportunity.OpportunityQuery; import com.example.rzgb.evidence.EvidenceService; import java.math.BigDecimal; import java.net.*; import java.nio.charset.StandardCharsets; import java.util.*; import java.util.concurrent.*; import com.sun.net.httpserver.HttpServer; import static org.assertj.core.api.Assertions.*; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.*; import static org.awaitility.Awaitility.await; @SpringBootTest @AutoConfigureMockMvc @ActiveProfiles("test") class RzGbApplicationTests { @Autowired MockMvc mvc; @Autowired JdbcTemplate jdbc; @Autowired Json json; @Autowired TaskService tasks; @Autowired EvidenceService evidence; @Autowired com.example.rzgb.config.AppProperties properties; @Autowired org.springframework.context.ApplicationContext context; private static HttpServer upstream; private static final Map CLIENTS = new ConcurrentHashMap<>(); /** 固定本地协议样例,只测试适配与安全边界,不冒充真实供应商联调。 */ @DynamicPropertySource static void providers(DynamicPropertyRegistry registry) throws Exception { upstream = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0); upstream.setExecutor(Executors.newCachedThreadPool()); upstream.createContext("/", exchange -> { String body = new String(exchange.getRequestBody().readAllBytes(), StandardCharsets.UTF_8); String path = exchange.getRequestURI().getPath(); CLIENTS.put(body, Objects.toString(exchange.getRequestHeaders().getFirst("X-Client"), "")); int code = 200; String response; if (body.contains("余额不足")) response = "{\"success\":false,\"error\":{\"code\":\"insufficient_balance\"}}"; else if (body.contains("业务失败")) response = "{\"success\":false,\"error\":\"invalid_company\"}"; else if (body.contains("限流")) { code = 429; response = "{}"; } else if (path.equals("/get_top_purchasers")) response="{\"data\":{\"total\":80,\"items\":[{\"company_name\":\"测试采购方\",\"purchase_count\":12,\"total_amount\":1000000}]},\"meta\":{\"cost_units\":0.5}}"; else if (path.equals("/get_top_suppliers")) response="{\"data\":{\"total\":40,\"items\":[{\"company_name\":\"测试供应商\",\"win_count\":8,\"total_amount_wan\":200}]},\"meta\":{\"cost_units\":0.5}}"; else if (path.equals("/aggregate_bids_advanced")) response="{\"data\":{\"total_count\":800,\"buckets\":[{\"key\":\"2026-10\",\"count\":80,\"sum_amount\":3000000}]},\"meta\":{\"cost_units\":0.5}}"; else if ((path.equals("/search_bids") || path.equals("/query_bids_advanced")) && body.contains("预算交集验收")) { var j=new Json(); var request=j.read(body); int page=request.path("page").asInt(); List> fixtures=List.of(Map.of("money",2075000),Map.of("money_wan",new BigDecimal("313.198")), Map.of("money",7275620),Map.of("money_wan",new BigDecimal("307.962")),Map.of("money_wan",500),Map.of("money",20000000)); List> items=new ArrayList<>(); for(int i=(page-1)*2;i item=new LinkedHashMap<>(fixtures.get(i)); item.put("bid_id",99700+i); item.put("title","预算交集验收项目"+i); item.put("province","江苏"); item.put("pub_time",request.path("end_date").asText()); item.put("bid_process",4); items.add(item); } response=j.write(Map.of("data",Map.of("total",fixtures.size(),"items",items),"meta",Map.of("cost_units",0.5))); } else if (path.equals("/search_bids") && body.contains("排除中标阶段验收")) { var mapper=new Json(); int page=mapper.read(body).path("page").asInt(); // 第一页误返两条中标公告,第二页才有其余四类;排除中标后仍须继续读取。 var items=page==1 ? List.of(Map.of("bid_id",93301,"bid_process","中标结果"),Map.of("bid_id",93302,"bid_process","中标公告")) : List.of(Map.of("bid_id",93303,"bid_process","招标"),Map.of("bid_id",93304,"bid_process","采购意向"), Map.of("bid_id",93305,"bid_process","预招标"),Map.of("bid_id",93306,"bid_process","合同")); response=mapper.write(Map.of("data",Map.of("total",6,"items",items),"meta",Map.of("cost_units",0.5))); } else if ((path.equals("/search_bids") || path.equals("/query_bids_advanced")) && (body.contains("集成获客") || body.contains("智慧水务监测"))) { var request = new Json().read(body); int page = request.path("page").asInt(); if (body.contains("取消分页")) try { Thread.sleep(250); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } if (body.contains("后页失败") && page == 2) { code = 502; response = "{}"; } else { Object first = Map.of("bid_id",99101,"title","智慧水务集成获客项目","province","浙江","money",1000000,"pub_time","2026-10-20","bid_process",4,"url","https://example.com/notice/99101?sk=public-test-signature"); Object second = Map.of("bid_id",99102,"title","智慧水务集成获客项目","province","安徽","pub_time","2026-10-25","bid_process",4); Object third = Map.of("bid_id",99103,"title","智慧水务集成获客项目","province","江苏","money_wan",80,"pub_time","2026-10-24","bid_process",body.contains("智慧水务监测")?4:7); if (body.contains("阶段归并")) { first=Map.of("bid_id",99101,"title","智慧水务意向","caller_name","测试同一采购方","province","浙江","project_code","TEST-CODE-2026","bid_process",1); third=Map.of("bid_id",99103,"title","智慧水务合同","caller_name","测试同一采购方","province","浙江","project_code","TEST-CODE-2026","bid_process",8); } List items = page == 1 || body.contains("重复页") ? List.of(first,second) : List.of(second,third); if (body.contains("空结果")) items = List.of(); if (body.contains("分页上限")) items = List.of( Map.of("bid_id",100000+page*2,"title","智慧水务第 "+page+" 页公告"), Map.of("bid_id",100001+page*2,"title","智慧水务第 "+page+" 页公告")); var data = Map.of("total",body.contains("空结果") ? 0 : body.contains("重复页") || body.contains("分页上限") ? 99 : 4,"items",items); response = new Json().write(body.contains("未知费用") ? Map.of("success",true,"data",data) : Map.of("success",true,"data",data,"meta",Map.of("cost_units",0.5))); } } else if (path.equals("/search_bids") && body.contains("商机列表结论验收")) response = """ {"data":{"total":1,"items":[{"bid_id":93214,"title":"监测设备安装","province":"浙江","bid_process":"招标", "fulltext":"项目概况:安装监测设备。二、投标人资格要求:"}]},"meta":{"cost_units":0.5}} """; else if (path.equals("/get_bid_detail") && body.contains("93214")) response = """ {"data":{"bid_id":93214,"url":"https://example.com/detail?signature=original","registration_deadline":"2026-11-15 17:00:00", "source":"

建设内容:安装水质监测设备并接入平台。

服务期90天。

不接受联合体,不接受中标后分包。

⑦特殊要求:投标人具有2023年1月1日至网上公告日(以发票开具时间为准)的同品牌产品销售业绩。

"},"meta":{"cost_units":1}} """; else if (path.equals("/chat/completions") && body.contains("zlbx-93214")) { var mapper=new Json(); String output=mapper.write(Map.of("zlbx-93214",Map.of("participation",Map.of("text","需同品牌产品销售业绩", "quote","投标人具有2023年1月1日至网上公告日(以发票开具时间为准)的同品牌产品销售业绩"), "construction",Map.of("text","安装水质监测设备并接入平台","quote","安装水质监测设备并接入平台"), "region",Map.of("text","浙江","quote","浙江"),"timing",Map.of("text","服务期91天","quote","服务期90天")))); response=mapper.write(Map.of("model","list-test-model","choices",List.of(Map.of("message",Map.of("content",output))),"usage",Map.of("prompt_tokens",20,"completion_tokens",15))); } else if (path.equals("/search_bids")) response = "{\"success\":true,\"data\":{\"total\":1,\"items\":[{\"bid_id\":8240,\"title\":\"测试水务项目\",\"url\":\"https://example.com/bid/8240\"}]},\"meta\":{\"cost_units\":0.5}}"; else if (path.equals("/search_company")) response = "{\"data\":{\"total\":0,\"items\":[]}}"; else if (path.equals("/get_company_profile")) response = "{\"data\":{\"fullname\":\"已确认测试公司\"}}"; else if (path.equals("/get_bid_detail")) response = "{\"data\":{\"bid_id\":8240,\"title\":\"测试公告详情\"}}"; else if (path.equals("/v1/tools/search")) response = "{\"results\":[{\"title\":\"测试网页\",\"url\":\"https://example.com/source\",\"snippet\":\"公开网页摘要\"}]}"; else if (path.equals("/v1/tools/fetch")) response = "{\"title\":\"测试网页\",\"content\":\"公开网页正文\"}"; else if (path.equals("/account/balance")) response = "{\"success\":true,\"data\":{\"balance\":100}}"; else if (body.contains("\"response_format\"")) response = "{\"model\":\"test-json-model\",\"choices\":[{\"message\":{\"content\":\"{\\\"answer\\\":\\\"JSON测试\\\"}\"}}],\"usage\":{\"prompt_tokens\":8,\"completion_tokens\":5}}"; else if (body.contains("\"stream\":true")) { response = "data: {\"model\":\"test-actual-model\",\"choices\":[{\"delta\":{\"content\":\"真实片段\",\"reasoning_content\":\"private-test-reasoning\"}}]}\n\n" + "data: {\"usage\":{\"prompt_tokens\":9,\"completion_tokens\":4},\"choices\":[]}\n\ndata: [DONE]\n\n"; } else response = "{\"model\":\"test-actual-model\",\"choices\":[{\"message\":{\"content\":\"测试回复\",\"reasoning_content\":\"private-test-reasoning\"}}],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":3}}"; exchange.getResponseHeaders().set("Content-Type", "application/json"); byte[] bytes = response.getBytes(StandardCharsets.UTF_8); exchange.sendResponseHeaders(code, bytes.length); exchange.getResponseBody().write(bytes); exchange.close(); }); upstream.start(); String url = "http://127.0.0.1:" + upstream.getAddress().getPort(); registry.add("rz.zlbx-base-url", () -> url); registry.add("rz.deepseek-base-url", () -> url); registry.add("rz.request-timeout-seconds", () -> 3); registry.add("rz.search-page-size", () -> 2); } @AfterAll static void stopUpstream() { upstream.stop(0); } private String owner() { return jdbc.queryForObject("SELECT id FROM app_user WHERE username='admin'", String.class); } private TaskRequest request(TaskRequest.Operation op, String input, boolean confirmed) { return new TaskRequest(op, op.name().startsWith("COMPANY_") ? TaskRequest.Workflow.COMPANY_INTEL : TaskRequest.Workflow.TENDER_SEARCH, input, confirmed, 1, BigDecimal.ONE); } private String create(TaskRequest r) { return tasks.create(owner(), UUID.randomUUID().toString(), r).get("id").toString(); } private Map settled(String id) { await().atMost(java.time.Duration.ofSeconds(10)).until(() -> { String state = tasks.get(owner(), id).get("status").toString(); return TaskService.terminal(state) || state.startsWith("WAITING_"); }); return tasks.get(owner(), id); } @Test void contextLoads() { assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM flyway_schema_history WHERE success=TRUE AND version IS NOT NULL", Integer.class)).isEqualTo(7); assertThat(jdbc.queryForObject("SELECT password_hash FROM app_user WHERE username='admin'", String.class)).startsWith("$2"); } @Test void anonymousCannotReadPrivateResources() throws Exception { for (String path : List.of("/api/company-profile", "/api/agent/tasks", "/api/agent/tasks/missing/events", "/api/files/missing", "/api/watch")) mvc.perform(get(path)).andExpect(status().isUnauthorized()); } @Test void loginRequiresCorrectPasswordAndRealCsrfAndLogoutInvalidatesSession() throws Exception { mvc.perform(post("/api/auth/login").param("username", "admin").param("password", "anything")).andExpect(status().isForbidden()); mvc.perform(post("/api/auth/login").with(csrf()).param("username", "admin").param("password", "incorrect")).andExpect(status().isUnauthorized()); var bootstrap = mvc.perform(get("/api/auth/csrf")).andExpect(status().isOk()).andReturn(); var token = json.read(bootstrap.getResponse().getContentAsString()); var session = (MockHttpSession) bootstrap.getRequest().getSession(); var login = mvc.perform(post("/api/auth/login").session(session).header(token.path("headerName").asText(), token.path("token").asText()) .param("username", "admin").param("password", "test-only-admin-pass-2026")).andExpect(status().isOk()).andReturn(); session = (MockHttpSession) login.getRequest().getSession(); mvc.perform(get("/api/auth/me").session(session)).andExpect(jsonPath("$.username").value("admin")); var refresh = mvc.perform(get("/api/auth/csrf").session(session)).andReturn(); token = json.read(refresh.getResponse().getContentAsString()); mvc.perform(post("/api/auth/logout").session(session).header(token.path("headerName").asText(), token.path("token").asText())).andExpect(status().isOk()); assertThat(session.isInvalid()).isTrue(); mvc.perform(get("/api/auth/me")).andExpect(status().isUnauthorized()); } @Test void profileIsSavedWithServerVersionCompletionAndStaleWriteProtection() throws Exception { var read = mvc.perform(get("/api/company-profile").with(user("admin"))).andReturn(); var doc = (tools.jackson.databind.node.ObjectNode) json.read(read.getResponse().getContentAsString()); doc.put("companyName", "测试水务公司"); doc.put("mainBusiness", "智慧水务"); doc.put("completed", false); var saved = mvc.perform(put("/api/company-profile").with(user("admin")).with(csrf()).contentType("application/json").content(doc.toString())) .andExpect(status().isOk()).andExpect(jsonPath("$.completed").value(true)).andReturn(); long version = json.read(saved.getResponse().getContentAsString()).path("version").asLong(); mvc.perform(get("/api/company-profile").with(user("admin"))).andExpect(jsonPath("$.version").value(version)).andExpect(jsonPath("$.companyName").value("测试水务公司")); mvc.perform(put("/api/company-profile").with(user("admin")).with(csrf()).contentType("application/json").content(doc.toString())) .andExpect(status().isConflict()); doc.put("version", version); doc.set("matchWeights", json.read("{\"business\":0,\"region\":0,\"amount\":0,\"track\":0}")); mvc.perform(put("/api/company-profile").with(user("admin")).with(csrf()).contentType("application/json").content(doc.toString())) .andExpect(status().isBadRequest()); } @Test void concurrentIdempotencyCreatesExactlyOneActualCall() throws Exception { String key = UUID.randomUUID().toString(); var r = request(TaskRequest.Operation.BID_SEARCH, "幂等水务", false); List>> futures = new ArrayList<>(); try (var pool = Executors.newFixedThreadPool(4)) { for (int i=0;i<4;i++) futures.add(pool.submit(() -> tasks.create(owner(), key, r))); Set ids = new HashSet<>(); for (var f : futures) ids.add(f.get().get("id").toString()); assertThat(ids).hasSize(1); var task = settled(ids.iterator().next()); assertThat(task.get("status")).isEqualTo("SUCCEEDED"); assertThat((List) task.get("calls")).hasSize(1); assertThat(task.toString()).contains("0.5000"); assertThat(CLIENTS.values()).contains("zlbx-bidding/2.3.0"); } assertThatThrownBy(() -> tasks.create(owner(), key, request(TaskRequest.Operation.BID_SEARCH, "不同条件", false))) .isInstanceOf(com.example.rzgb.common.ApiException.class).hasMessageContaining("相同幂等键"); } @Test void entityConfirmationDoesNotCallUntilExplicitResumeAndResumeIsIdempotent() { String id = create(request(TaskRequest.Operation.COMPANY_PROFILE, "待确认公司", false)); assertThat(settled(id).get("status")).isEqualTo("WAITING_ENTITY"); assertThat((List) tasks.get(owner(), id).get("calls")).isEmpty(); var confirmed = request(TaskRequest.Operation.COMPANY_PROFILE, "已确认公司", true); String key = UUID.randomUUID().toString(); tasks.resume(owner(), id, key, confirmed); tasks.resume(owner(), id, key, confirmed); var task = settled(id); assertThat(task.get("status")).isEqualTo("SUCCEEDED"); assertThat((List) task.get("calls")).hasSize(1); assertThat(CLIENTS.values()).contains("company-intel/1.0.2"); } @Test void missingInputWaitsAndCanBeCancelledWithoutAnyCall() { String id = create(request(TaskRequest.Operation.BID_SEARCH, "", false)); assertThat(settled(id).get("status")).isEqualTo("WAITING_INPUT"); tasks.cancel(owner(), id); assertThat(tasks.get(owner(), id).get("status")).isEqualTo("CANCELLED"); assertThat((List) tasks.get(owner(), id).get("calls")).isEmpty(); } @Test void distinguishesBusinessFailureBalanceAndEmptyResult() { assertThat(settled(create(request(TaskRequest.Operation.COMPANY_SEARCH, "业务失败", false))).get("status")).isEqualTo("FAILED"); assertThat(settled(create(request(TaskRequest.Operation.COMPANY_SEARCH, "余额不足", false))).get("status")).isEqualTo("WAITING_BUDGET"); var empty = settled(create(request(TaskRequest.Operation.COMPANY_SEARCH, "无匹配公司", false))); assertThat(empty.get("status")).isEqualTo("SUCCEEDED"); assertThat(empty.toString()).contains("cost_units=null"); var limited = settled(create(request(TaskRequest.Operation.MODEL_TEXT, "限流", false))); assertThat(limited.get("status")).isEqualTo("FAILED"); assertThat(limited.toString()).contains("UPSTREAM_RATE_LIMIT"); } @Test void realStreamContentAndUsageAreSavedWithoutPrivateReasoning() { String id = create(request(TaskRequest.Operation.MODEL_STREAM, "测试真实流式", false)); var task = settled(id); assertThat(task.get("status")).isEqualTo("SUCCEEDED"); assertThat(task.toString()).contains("真实片段", "test-actual-model", "input_tokens=9").doesNotContain("private-test-reasoning"); var events = tasks.events(owner(), id, 0); assertThat(events.toString()).contains("REPORT_FRAGMENT", "真实片段").doesNotContain("private-test-reasoning"); } @Test void eventReplayIsOrderedAndSseReconnectDoesNotCreateAnotherCall() throws Exception { String id = create(request(TaskRequest.Operation.ZLBX_BALANCE, "", false)); settled(id); var all = tasks.events(owner(), id, 0); long first = ((Number) all.getFirst().get("id")).longValue(); assertThat(tasks.events(owner(), id, first)).hasSize(all.size()-1); long previous = 0; for (var event : all) { assertThat(((Number) event.get("id")).longValue()).isGreaterThan(previous); previous = ((Number) event.get("id")).longValue(); } var result = mvc.perform(get("/api/agent/tasks/"+id+"/events").with(user("admin")).header("Last-Event-ID", first)) .andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.request().asyncStarted()).andReturn(); result.getAsyncResult(5000); mvc.perform(asyncDispatch(result)).andExpect(status().isOk()).andExpect(content().contentTypeCompatibleWith("text/event-stream")); assertThat(result.getResponse().getContentAsString()).contains("event:task-event", "event:idle"); assertThat((List) tasks.get(owner(), id).get("calls")).hasSize(1); } @Test void taskOwnershipAndWatchCascadeAreEnforced() throws Exception { String id = create(request(TaskRequest.Operation.BID_SEARCH, "关注水务", false)); settled(id); String other = UUID.randomUUID().toString(); jdbc.update("INSERT INTO app_user(id,username,password_hash) VALUES(?,?,'test-only')", other, other); mvc.perform(get("/api/agent/tasks/"+id).with(user(other))).andExpect(status().isNotFound()); mvc.perform(post("/api/agent/tasks/"+id+"/cancel").with(user(other)).with(csrf())).andExpect(status().isNotFound()); for (int i=0;i<2;i++) mvc.perform(post("/api/watch/zlbx-8240").with(user("admin")).with(csrf())).andExpect(status().isOk()); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_record WHERE user_id=?", Integer.class, owner())).isEqualTo(1); mvc.perform(get("/api/watch/zlbx-8240/history").with(user(other))).andExpect(status().isNotFound()); mvc.perform(delete("/api/watch/zlbx-8240").with(user("admin")).with(csrf())).andExpect(status().isOk()); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_history", Integer.class)).isZero(); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM project WHERE id='zlbx-8240'", Integer.class)).isEqualTo(1); } @Test void rejectsInvalidBudgetsAndPrivateFetchUrl() throws Exception { var r = new TaskRequest(TaskRequest.Operation.MODEL_TEXT, TaskRequest.Workflow.TENDER_SEARCH, "hello", false, properties.maxCalls()+1, BigDecimal.ONE); mvc.perform(post("/api/agent/tasks").with(user("admin")).with(csrf()).header("Idempotency-Key", UUID.randomUUID()) .contentType("application/json").content(json.write(r))).andExpect(status().isBadRequest()); assertThatThrownBy(() -> com.example.rzgb.provider.ProviderClient.publicUrl("http://127.0.0.1/private")) .isInstanceOf(com.example.rzgb.common.ApiException.class); } @Test void missingCredentialsAreDetectedBeforeAnyHttpRequest() { var configuration = (tools.jackson.databind.node.ObjectNode) json.read(json.write(properties)); configuration.put("zlbxApiKey", ""); configuration.put("deepseekApiKey", ""); var client = new com.example.rzgb.provider.ProviderClient(json.convert(configuration.toString(), com.example.rzgb.config.AppProperties.class), json); assertThat(client.question(request(TaskRequest.Operation.ZLBX_BALANCE, "", false))).contains("ZLBX_API_KEY"); assertThat(client.question(request(TaskRequest.Operation.MODEL_TEXT, "hello", false))).contains("DEEPSEEK_API_KEY"); } @Test void independentModelJsonWebVisionAndBidDetailContractsAreSupported() { for (var op : List.of(TaskRequest.Operation.MODEL_TEXT, TaskRequest.Operation.MODEL_JSON, TaskRequest.Operation.WEB_SEARCH, TaskRequest.Operation.WEB_FETCH, TaskRequest.Operation.VISION, TaskRequest.Operation.BID_DETAIL)) { String input = op == TaskRequest.Operation.WEB_FETCH ? "https://93.184.216.34/public" : op == TaskRequest.Operation.BID_DETAIL ? "8240" : "协议自测"; var task = settled(create(request(op, input, false))); assertThat(task.get("status")).as(op.name()).isEqualTo("SUCCEEDED"); assertThat((List) task.get("calls")).hasSize(1); } assertThat(CLIENTS.keySet().stream().anyMatch(body -> body.contains("data:image/png;base64,"))).isTrue(); } @Test void restartRecoveryMarksUnknownCallsWithoutDispatchingThemAgain() throws Exception { String id = create(request(TaskRequest.Operation.BID_SEARCH, "", false)); settled(id); jdbc.update("UPDATE agent_task SET status='RUNNING' WHERE id=?", id); jdbc.update("INSERT INTO tool_call(id,task_id,provider,tool_name,client_version,status) VALUES(?,?,'ZLBX','BID_SEARCH','zlbx-bidding/2.3.0','STARTED')", UUID.randomUUID().toString(), id); context.getBean("recoverInterruptedTasks", org.springframework.boot.ApplicationRunner.class) .run(new org.springframework.boot.DefaultApplicationArguments()); var recovered = tasks.get(owner(), id); assertThat(recovered.get("status")).isEqualTo("PARTIAL"); assertThat(recovered.toString()).contains("UNKNOWN", "RESTART_INTERRUPTED"); assertThat((List) recovered.get("calls")).hasSize(1); } private TaskRequest opportunity(String marker, int calls) { var today = java.time.LocalDate.now(java.time.ZoneId.of("Asia/Shanghai")); var query = new OpportunityQuery(List.of("智慧水务","集成获客"+marker),today.minusDays(89),today,List.of(1,2,4,7,8), OpportunityQuery.Preference.REGION,List.of("浙江"),new BigDecimal("80"),new BigDecimal("120")); return new TaskRequest(TaskRequest.Operation.OPPORTUNITY_SEARCH,TaskRequest.Workflow.TENDER_SEARCH,"",false,calls,new BigDecimal("5"),query); } @Test void realPaginatedWorkflowRanksAllReadCandidatesAndKeepsUnknownAmounts() { String id = create(opportunity("完整召回",3)); var task = settled(id); var report = json.read(json.write(task.get("result"))); assertThat(task.get("status")).isEqualTo("SUCCEEDED"); assertThat((List)task.get("calls")).hasSize(2); assertThat(report.path("scope").path("platformTotal").asInt()).isEqualTo(4); assertThat(report.path("scope").path("fetchedCount").asInt()).isEqualTo(4); assertThat(report.path("scope").path("uniqueCount").asInt()).isEqualTo(3); assertThat(report.path("scope").path("complete").asBoolean()).isTrue(); assertThat(report.path("items").path(0).path("facts").path("region").asText()).isEqualTo("浙江"); assertThat(report.path("items").toString()).contains("安徽","江苏","预算未披露"); assertThat(task.toString()).contains("记录").doesNotContain("COMPANY_PROFILE","get_company_profile"); for (String body : CLIENTS.keySet().stream().filter(text -> text.contains("完整召回")).toList()) { var request = json.read(body); assertThat(request.has("provinces")).isFalse(); assertThat(request.has("min_amount")).isFalse(); assertThat(request.has("max_amount")).isFalse(); } assertThat(evidence.list(id)).hasSize(3).allSatisfy(item -> assertThat(item.get("verified")).isEqualTo(true)); assertThat(evidence.list(id).toString()).contains("?sk=public-test-signature"); } @Test void budgetPauseResumesAtNextPageAndNeverChangesFrozenConditions() { var original = opportunity("预算续页",1); String id = create(original); var paused = settled(id); assertThat(paused.get("status")).isEqualTo("WAITING_BUDGET"); assertThat((List)paused.get("calls")).hasSize(1); assertThat(json.read(json.write(paused.get("result"))).path("scope").path("complete").asBoolean()).isFalse(); assertThatThrownBy(() -> tasks.resume(owner(),id,UUID.randomUUID().toString(),opportunity("更改条件",3))) .isInstanceOf(com.example.rzgb.common.ApiException.class).hasMessageContaining("不能改写"); var resumed = new TaskRequest(original.operation(),original.workflow(),"",false,3,new BigDecimal("5"),original.opportunity()); String command = UUID.randomUUID().toString(); tasks.resume(owner(),id,command,resumed); tasks.resume(owner(),id,command,resumed); assertThat(settled(id).get("status")).isEqualTo("SUCCEEDED"); assertThat((List)tasks.get(owner(),id).get("calls")).hasSize(2); assertThat(CLIENTS.keySet().stream().filter(body -> body.contains("预算续页")).count()).isEqualTo(2); } @Test void unknownCostAndRepeatedPagesStopWithoutPretendingFullCoverage() { var unknown = settled(create(opportunity("未知费用",3))); assertThat(unknown.get("status")).isEqualTo("PARTIAL"); assertThat((List)unknown.get("calls")).hasSize(1); assertThat(unknown.toString()).contains("COST_UNKNOWN"); var repeated = settled(create(opportunity("重复页",3))); assertThat(repeated.get("status")).isEqualTo("PARTIAL"); assertThat((List)repeated.get("calls")).hasSize(2); assertThat(repeated.toString()).contains("REPEATED_PAGE"); } @Test void failedLaterPageKeepsEarlierEvidenceAndRecordsActualFailure() { var task = settled(create(opportunity("后页失败",3))); assertThat(task.get("status")).isEqualTo("PARTIAL"); assertThat((List)task.get("calls")).hasSize(2); assertThat(json.read(json.write(task.get("result"))).path("items").size()).isEqualTo(2); assertThat(task.toString()).contains("UPSTREAM_HTTP_502","SUCCEEDED","FAILED"); } @Test void reportRefusesMutatedSnapshotsAndCrossTaskCitations() { String id = create(opportunity("证据校验",3)); settled(id); String evidenceId = evidence.list(id).getFirst().get("id").toString(); String other = create(opportunity("另一任务",3)); settled(other); assertThatThrownBy(() -> evidence.requireVerified(other,List.of(evidenceId))) .isInstanceOf(com.example.rzgb.common.ApiException.class).hasMessageContaining("引用不存在"); jdbc.update("UPDATE evidence SET excerpt='篡改后的事实' WHERE id=?",evidenceId); assertThatThrownBy(() -> tasks.get(owner(),id)).isInstanceOf(com.example.rzgb.common.ApiException.class).hasMessageContaining("报告已停止展示"); // 即使引用编号存在,候选快照也必须与证据重新标准化出的事实完全一致。 jdbc.update("UPDATE search_item SET snapshot=REPLACE(snapshot,'智慧水务集成获客项目','没有依据的高收益项目') WHERE batch_id=?",other); assertThatThrownBy(() -> tasks.get(owner(),other)).isInstanceOf(com.example.rzgb.common.ApiException.class); } @Test void filteredTaskHistoryAndEvidenceAreOnlyVisibleToOwner() throws Exception { String id = create(opportunity("归属范围",3)); settled(id); mvc.perform(get("/api/agent/tasks").param("operation","OPPORTUNITY_SEARCH").with(user("admin"))) .andExpect(status().isOk()).andExpect(content().string(org.hamcrest.Matchers.containsString(id))); mvc.perform(get("/api/agent/tasks/"+id+"/report").with(user("admin"))) .andExpect(status().isOk()).andExpect(jsonPath("$.result.referencesVerified").value(true)); String stranger = UUID.randomUUID().toString(); jdbc.update("INSERT INTO app_user(id,username,password_hash) VALUES(?,?,'test-only')",stranger,stranger); mvc.perform(get("/api/agent/tasks/"+id+"/report").with(user(stranger))).andExpect(status().isNotFound()); } @Test void pageLimitIsExplicitAndEmptyResultsAreNotServiceFailures() { var limited = settled(create(opportunity("分页上限",5))); assertThat(limited.get("status")).isEqualTo("PARTIAL"); assertThat((List)limited.get("calls")).hasSize(5); var scope = json.read(json.write(limited.get("result"))).path("scope"); assertThat(scope.path("stopReason").asText()).isEqualTo("PAGE_LIMIT"); assertThat(scope.path("uniqueCount").asInt()).isEqualTo(10); assertThat(scope.path("complete").asBoolean()).isFalse(); var empty = settled(create(opportunity("空结果",3))); assertThat(empty.get("status")).isEqualTo("SUCCEEDED"); assertThat(json.read(json.write(empty.get("result"))).path("items").isEmpty()).isTrue(); } @Test void cancellationPreservesInFlightCostAndNeverStartsNextPage() { String id = create(opportunity("取消分页",3)); await().atMost(java.time.Duration.ofSeconds(5)).until(() -> !((List)tasks.get(owner(),id).get("calls")).isEmpty()); tasks.cancel(owner(),id); await().atMost(java.time.Duration.ofSeconds(5)).until(() -> { var calls = (List)tasks.get(owner(),id).get("calls"); return calls.size() == 1 && ((Map)calls.getFirst()).get("status").equals("SUCCEEDED"); }); var task = tasks.get(owner(),id); assertThat(task.get("status")).isEqualTo("CANCELLED"); assertThat((List)task.get("calls")).hasSize(1); assertThat(task.toString()).contains("0.5000"); } /** D2 关注事务:备注独立留痕、任意恢复、幂等重放、旧版本拒绝,标签与账号隔离。 */ @Test void watchChangesAreAtomicVersionedIdempotentAndTagsStayPrivate() throws Exception { String project="watch-test-"+UUID.randomUUID(); jdbc.update("INSERT INTO project(id,source_id,document) VALUES(?,?,?)",project,project,"{\"title\":\"测试关注事务\"}"); mvc.perform(post("/api/watch/"+project).with(user("admin")).with(csrf())).andExpect(status().isOk()); String watch=jdbc.queryForObject("SELECT id FROM watch_record WHERE project_id=? AND user_id=?",String.class,project,owner()); String key=UUID.randomUUID().toString(); String body=json.write(Map.of("status","准备投标","note","开始备标","version",1)); for(int n=0;n<2;n++) mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf()) .header("Idempotency-Key",key).contentType("application/json").content(body)).andExpect(status().isOk()).andExpect(jsonPath("$.version").value(2)); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_history WHERE watch_id=?",Integer.class,watch)).isEqualTo(2); mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf()).header("Idempotency-Key",key) .contentType("application/json").content(body.replace("开始备标","不同命令"))).andExpect(status().isConflict()); mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString()) .contentType("application/json").content(body)).andExpect(status().isConflict()); long version=2; for(String state:List.of("已报名","已提交投标文件","已中标","未中标","已流标","暂不考虑","已关注")) { mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString()) .contentType("application/json").content(json.write(Map.of("status",state,"note",state,"version",version)))) .andExpect(status().isOk()).andExpect(jsonPath("$.version").value(++version)); } mvc.perform(post("/api/watch/"+project+"/changes").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString()) .contentType("application/json").content(json.write(Map.of("note","单独编辑备注","version",version)))) .andExpect(status().isOk()).andExpect(jsonPath("$.status").value("已关注")); version++; assertThat(jdbc.queryForMap("SELECT status,note,version FROM watch_record WHERE id=?",watch)) .containsEntry("status","已关注").containsEntry("note","单独编辑备注").containsEntry("version",version); String tagName="重点-"+UUID.randomUUID(); var tagResponse=mvc.perform(post("/api/tags").with(user("admin")).with(csrf()).contentType("application/json") .content(json.write(Map.of("name",tagName)))).andExpect(status().isOk()).andReturn(); String tag=json.read(tagResponse.getResponse().getContentAsString()).path("id").asText(); mvc.perform(put("/api/watch/"+project+"/tags").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString()) .contentType("application/json").content(json.write(Map.of("tags",List.of(tagName),"version",version)))) .andExpect(status().isOk()).andExpect(jsonPath("$.version").value(version+1)); mvc.perform(get("/api/watch").param("group","跟进中").param("tag",tagName).with(user("admin"))) .andExpect(status().isOk()).andExpect(jsonPath("$[0].projectId").value(project)); String outsider="outsider-"+UUID.randomUUID(); jdbc.update("INSERT INTO app_user(id,username,password_hash) VALUES(?,?,?)",UUID.randomUUID().toString(),outsider,"unused-test-hash"); mvc.perform(get("/api/watch/"+project+"/history").with(user(outsider))).andExpect(status().isNotFound()); mvc.perform(delete("/api/tags/"+tag).with(user(outsider)).with(csrf())).andExpect(status().isOk()); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_tag WHERE watch_id=?",Integer.class,watch)).isEqualTo(1); mvc.perform(delete("/api/tags/"+tag).with(user("admin")).with(csrf())).andExpect(status().isOk()); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_tag WHERE watch_id=?",Integer.class,watch)).isZero(); mvc.perform(delete("/api/watch/"+project).with(user("admin")).with(csrf())).andExpect(status().isOk()); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM watch_history WHERE watch_id=?",Integer.class,watch)).isZero(); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM project WHERE id=?",Integer.class,project)).isEqualTo(1); } /** 执行与版本绑定;编辑/删除方案、修改档案及临时重排都不能改变旧快照或额外收费。 */ @Test void schemesFreezeRunsAndReadOnlyPreferenceViewKeepsSameCandidates() throws Exception { var original=opportunity("方案快照",3); String body=json.write(Map.of("name","D2测试方案","conditions",original.opportunity(),"version",0)); var saved=mvc.perform(post("/api/search-schemes").with(user("admin")).with(csrf()).contentType("application/json").content(body)) .andExpect(status().isOk()).andReturn(); String scheme=json.read(saved.getResponse().getContentAsString()).path("id").asText(),key=UUID.randomUUID().toString(); String run=mvc.perform(post("/api/search-schemes/"+scheme+"/runs").with(user("admin")).with(csrf()).header("Idempotency-Key",key)) .andExpect(status().isOk()).andReturn().getResponse().getContentAsString(); String id=json.read(run).path("id").asText(); var first=settled(id); String frozen=json.write(first.get("result")); mvc.perform(put("/api/search-schemes/"+scheme).with(user("admin")).with(csrf()).contentType("application/json") .content(json.write(Map.of("name","改名方案","conditions",opportunity("新方案内容",3).opportunity(),"version",1)))) .andExpect(status().isOk()).andExpect(jsonPath("$.version").value(2)); mvc.perform(post("/api/search-schemes/"+scheme+"/runs").with(user("admin")).with(csrf()).header("Idempotency-Key",key)) .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(id)); assertThat(json.write(tasks.get(owner(),id).get("result"))).isEqualTo(frozen); var view=mvc.perform(post("/api/searches/"+id+"/view").with(user("admin")).with(csrf()).contentType("application/json") .content("{\"preference\":\"AMOUNT\",\"regions\":[],\"minWan\":80,\"maxWan\":120}")) .andExpect(status().isOk()).andReturn(); assertThat(json.read(view.getResponse().getContentAsString()).path("items").size()).isEqualTo(3); mvc.perform(get("/api/searches/"+id+"/items").param("page","2").param("size","2").with(user("admin"))) .andExpect(status().isOk()).andExpect(jsonPath("$.items.length()").value(1)); mvc.perform(delete("/api/search-schemes/"+scheme).with(user("admin")).with(csrf())).andExpect(status().isOk()); assertThat(json.write(tasks.get(owner(),id).get("result"))).isEqualTo(frozen); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=?",Integer.class,id)).isEqualTo(2); assertThat(jdbc.queryForMap("SELECT scheme_name,scheme_version FROM search_run WHERE task_id=?",id)) .containsEntry("scheme_name","D2测试方案").containsEntry("scheme_version",1L); jdbc.update("UPDATE search_item SET ranking_snapshot=REPLACE(ranking_snapshot,'标题命中','无依据排序') WHERE batch_id=?",id); assertThatThrownBy(() -> tasks.get(owner(),id)).hasMessageContaining("排序快照已变化"); } @Test void ordinarySearchUsesPublishOrderAndFrozenProfileSurvivesLaterEdits() { var lead=opportunity("普通检索",3); var q=lead.opportunity(); var query=new OpportunityQuery(q.keywords(),q.beginDate(),q.endDate(),q.stages(),q.preference(),q.preferredRegions(),q.budgetMinWan(),q.budgetMaxWan(), OpportunityQuery.Mode.SEARCH,OpportunityQuery.KeywordMode.ANY,List.of(),null,null); String id=create(new TaskRequest(lead.operation(),lead.workflow(),"",false,3,new BigDecimal("5"),query)); var result=settled(id); var report=json.read(json.write(result.get("result"))); assertThat(report.path("items").path(0).path("facts").path("sourceId").asText()).isEqualTo("99102"); String before=json.write(result.get("result")); // 故意修改当前档案版本;旧报告必须仍读取任务创建时的冻结档案。 var old=jdbc.queryForList("SELECT document FROM company_profile WHERE user_id=?",String.class,owner()); if(old.isEmpty()) { var temporary=com.example.rzgb.profile.CompanyProfile.empty().saved(9999,java.time.Instant.now()); jdbc.update("INSERT INTO company_profile(user_id,document,version,completed,updated_at) VALUES(?,?,9999,FALSE,CURRENT_TIMESTAMP)",owner(),json.write(temporary)); try { assertThat(json.write(tasks.get(owner(),id).get("result"))).isEqualTo(before); } finally { jdbc.update("DELETE FROM company_profile WHERE user_id=?",owner()); } } else { var updated=(tools.jackson.databind.node.ObjectNode)json.read(old.getFirst()); updated.put("version",9999); jdbc.update("UPDATE company_profile SET document=? WHERE user_id=?",updated.toString(),owner()); try { assertThat(json.write(tasks.get(owner(),id).get("result"))).isEqualTo(before); } finally { jdbc.update("UPDATE company_profile SET document=? WHERE user_id=?",old.getFirst(),owner()); } } jdbc.update("UPDATE search_item SET analysis_snapshot=REPLACE(analysis_snapshot,'规则匹配分','篡改分数') WHERE batch_id=?",id); assertThatThrownBy(() -> tasks.get(owner(),id)).hasMessageContaining("快照已变化"); } /** 第一页没有预算命中仍应继续分页;地区与发布时间仍随每页请求发给供应商。 */ @Test void ordinarySearchRetainsDateAndRegionWhileFilteringBudgetAcrossPages() throws Exception { var today=java.time.LocalDate.now(java.time.ZoneId.of("Asia/Shanghai")); var query=new OpportunityQuery(List.of("智慧水务监测"),today.minusDays(29),today,List.of(4), OpportunityQuery.Preference.COMPREHENSIVE,List.of(),null,null,OpportunityQuery.Mode.SEARCH, OpportunityQuery.KeywordMode.ANY,List.of("江苏"),new BigDecimal("75"),new BigDecimal("90")); String body=json.write(Map.of("conditions",query,"maxCalls",1,"maxCostUnits",5)); var response=mvc.perform(post("/api/searches").with(user("admin")).with(csrf()) .header("Idempotency-Key",UUID.randomUUID().toString()).contentType("application/json").content(body)) .andExpect(status().isOk()).andReturn(); String id=json.read(response.getResponse().getContentAsString()).path("id").asText(); var paused=settled(id); assertThat(paused.get("status")).isEqualTo("WAITING_BUDGET"); assertThat(json.read(json.write(paused.get("result"))).path("items")).isEmpty(); mvc.perform(post("/api/searches/"+id+"/continue").with(user("admin")).with(csrf()) .header("Idempotency-Key",UUID.randomUUID().toString()).contentType("application/json") .content(json.write(Map.of("conditions",query,"maxCalls",3,"maxCostUnits",5)))).andExpect(status().isOk()); var result=settled(id); assertThat(result.get("status")).isEqualTo("SUCCEEDED"); var report=json.read(json.write(result.get("result"))); assertThat(report.path("items")).hasSize(1); assertThat(report.path("items").path(0).path("facts").path("sourceId").asText()).isEqualTo("99103"); assertThat(report.path("scope").path("fetchedCount").asInt()).isEqualTo(4); var sent=CLIENTS.keySet().stream().map(json::read) .filter(data -> data.path("keywords").toString().equals("[\"智慧水务监测\"]")).toList(); assertThat(sent).hasSize(2).allSatisfy(data -> { assertThat(data.path("provinces").toString()).isEqualTo("[\"江苏\"]"); assertThat(data.has("min_amount") || data.has("max_amount")).isFalse(); assertThat(data.path("begin_date").asText()).isEqualTo(today.minusDays(29).toString()); assertThat(data.path("end_date").asText()).isEqualTo(today.toString()); }); assertThat(sent.stream().map(data -> data.path("page").asInt())).containsExactlyInAnyOrder(1,2); } @Test void discoveryExcludesAwardsAndKeepsOtherDefaultStagesAcrossFilteredPages() throws Exception { var query=new OpportunityQuery(List.of("排除中标阶段验收"),null,null,List.of(1,2,4,7,8), null,null,null,null,OpportunityQuery.Mode.SEARCH,null,null,null,null); var response=mvc.perform(post("/api/searches").with(user("admin")).with(csrf()) .header("Idempotency-Key",UUID.randomUUID().toString()).contentType("application/json") .content(json.write(Map.of("conditions",query,"maxCalls",3,"maxCostUnits",3)))) .andExpect(status().isOk()).andReturn(); String id=json.read(response.getResponse().getContentAsString()).path("id").asText(); var task=settled(id); assertThat(task.get("status")).isEqualTo("SUCCEEDED"); var report=json.read(json.write(task.get("result"))); assertThat(report.path("conditions").path("stages").toString()).isEqualTo("[1,2,4,8]"); assertThat(report.path("items")).hasSize(4); assertThat(report.path("items")).extracting(item -> item.path("facts").path("stage").asInt()) .containsExactlyInAnyOrder(1,2,4,8); assertThat(CLIENTS.keySet().stream().filter(body -> body.contains("排除中标阶段验收")).map(json::read).toList()) .hasSize(2).allSatisfy(sent -> assertThat(sent.path("bid_process").toString()).isEqualTo("[1,2,4,8]")); // 模拟升级前的中文阶段快照。历史未知阶段按旧口径校验,其余事实和摘要继续严格核对。 var row=jdbc.queryForMap("SELECT snapshot,ranking_snapshot FROM search_item WHERE batch_id=? AND project_id='zlbx-93303'",id); var oldFacts=(tools.jackson.databind.node.ObjectNode)json.read(row.get("snapshot").toString()); oldFacts.putNull("stage"); var oldGaps=(tools.jackson.databind.node.ArrayNode)oldFacts.path("gaps"); oldGaps.insert(oldGaps.size()-1,"公告阶段待核验"); var oldRanking=(tools.jackson.databind.node.ObjectNode)json.read(row.get("ranking_snapshot").toString()); oldRanking.set("facts",oldFacts); String rankingJson=json.write(oldRanking); jdbc.update("UPDATE search_item SET snapshot=?,ranking_snapshot=?,ranking_hash=? WHERE batch_id=? AND project_id='zlbx-93303'", json.write(oldFacts),rankingJson,EvidenceService.hash(rankingJson),id); var historical=json.read(json.write(tasks.get(owner(),id).get("result"))); assertThat(historical.path("items")).anySatisfy(item -> { assertThat(item.path("facts").path("sourceId").asText()).isEqualTo("93303"); assertThat(item.path("facts").path("stage").isNull()).isTrue(); }); } @Test void discoveryListSummarizesVerifiedDetailWithinTheOriginalCallBudget() throws Exception { var query=new OpportunityQuery(List.of("商机列表结论验收"),null,null,null,null,null,null,null, OpportunityQuery.Mode.SEARCH,null,null,null,null); var response=mvc.perform(post("/api/searches").with(user("admin")).with(csrf()).header("Idempotency-Key",UUID.randomUUID().toString()) .contentType("application/json").content(json.write(Map.of("conditions",query,"maxCalls",3,"maxCostUnits",3,"summarizeList",true)))) .andExpect(status().isOk()).andReturn(); String id=json.read(response.getResponse().getContentAsString()).path("id").asText(); var result=settled(id); assertThat(result.get("status")).isEqualTo("SUCCEEDED"); assertThat(result.get("calls").toString()).contains("search_bids","get_bid_detail","opportunity_summary"); assertThat(result.get("calls")).asList().hasSize(3); var report=json.read(json.write(result.get("result"))); var summary=report.path("items").path(0).path("analysis").path("summary"); assertThat(summary.path("conclusion").path("participation").asText()).isEqualTo("需同品牌产品销售业绩"); var modelRequest=CLIENTS.keySet().stream().map(json::read) .filter(request -> request.path("messages").path(1).path("content").isTextual()) .filter(request -> request.path("messages").path(1).path("content").asText().contains("zlbx-93214")) .findFirst().orElseThrow(); // 检查真实发往模拟 DeepSeek 的用户消息,避免系统提示里的示例掩盖实际公告依据缺失。 var modelInput=json.read(modelRequest.path("messages").path(1).path("content").asText()).path(0); assertThat(modelRequest.path("model").asText()).isEqualTo(properties.deepseekModel()); assertThat(modelInput.path("participation").asText()).contains("同品牌产品销售业绩","不接受联合体"); assertThat(summary.path("conclusion").path("timing").asText()).isEmpty(); assertThat(summary.path("schedule").toString()).contains("报名截止时间:2026-11-15 17:00:00","服务期90天"); assertThat(report.path("summaryProgress").path("completed").asInt()).isEqualTo(1); assertThat(evidence.list(id)).anySatisfy(ref -> { assertThat(ref.get("id")).isEqualTo(summary.path("evidenceId").asText()); assertThat(ref.get("url")).isEqualTo("https://example.com/detail?signature=original"); }); } @Test void ordinaryBudgetUsesDisplayedYuanAndWanValuesWithInclusiveBounds() { var today=java.time.LocalDate.now(java.time.ZoneId.of("Asia/Shanghai")); for (var range : List.of(List.of("500","2000"),List.of("100","1000"))) { var query=new OpportunityQuery(List.of("预算交集验收","水务"),today.minusDays(29),today,List.of(4),null,null,null,null, OpportunityQuery.Mode.SEARCH,OpportunityQuery.KeywordMode.ALL,List.of("江苏"),new BigDecimal(range.getFirst()),new BigDecimal(range.getLast())); var result=settled(create(new TaskRequest(TaskRequest.Operation.OPPORTUNITY_SEARCH,TaskRequest.Workflow.TENDER_SEARCH,"",false,3,BigDecimal.TEN,query))); assertThat(result.get("status")).isEqualTo("SUCCEEDED"); var report=json.read(json.write(result.get("result"))); List amounts=new ArrayList<>(); for(var item:report.path("items")) amounts.add(item.path("facts").path("budgetWan").decimalValue().stripTrailingZeros().toPlainString()); if(range.getFirst().equals("500")) assertThat(amounts).containsExactlyInAnyOrder("500","727.562","2000"); else assertThat(amounts).containsExactlyInAnyOrder("207.5","313.198","727.562","307.962","500"); } assertThat(CLIENTS.keySet().stream().filter(body->body.contains("预算交集验收")).map(json::read).toList()).hasSize(3).allSatisfy(request->{ assertThat(request.path("provinces").toString()).isEqualTo("[\"江苏\"]"); assertThat(request.path("keyword_groups").path(0).path("keywords").toString()).isEqualTo("[\"水务\"]"); assertThat(request.has("min_money") || request.has("max_money")).isFalse(); assertThat(request.path("begin_date").asText()).isEqualTo(today.minusDays(29).toString()); }); } /** 旧方案只在发现商机明确要求硬筛选时转换,原方案、日期及其他获客调用均保持原语义。 */ @Test void discoveryCanRunLegacySchemeWithStrictFiltersWithoutRewritingSavedConditions() throws Exception { var base=opportunity("旧方案硬筛选",3).opportunity(); var query=new OpportunityQuery(base.keywords(),base.beginDate(),base.endDate(),base.stages(), base.preference(),List.of("江苏"),new BigDecimal("50"),new BigDecimal("200")); var saved=mvc.perform(post("/api/search-schemes").with(user("admin")).with(csrf()).contentType("application/json") .content(json.write(Map.of("name","旧版地区预算方案","conditions",query,"version",0)))) .andExpect(status().isOk()).andReturn(); String scheme=json.read(saved.getResponse().getContentAsString()).path("id").asText(); String key=UUID.randomUUID().toString(); var response=mvc.perform(post("/api/search-schemes/"+scheme+"/runs").param("strictFilters","true") .with(user("admin")).with(csrf()).header("Idempotency-Key",key)).andExpect(status().isOk()).andReturn(); String id=json.read(response.getResponse().getContentAsString()).path("id").asText(); var result=settled(id); assertThat(result.get("status")).isEqualTo("SUCCEEDED"); var conditions=json.read(json.write(result.get("result"))).path("conditions"); assertThat(conditions.path("mode").asText()).isEqualTo("SEARCH"); assertThat(conditions.path("stages").toString()).isEqualTo("[1,2,4,8]"); assertThat(conditions.path("hardRegions").toString()).isEqualTo("[\"江苏\"]"); assertThat(conditions.path("hardMinWan").asInt()).isEqualTo(50); assertThat(conditions.path("hardMaxWan").asInt()).isEqualTo(200); assertThat(conditions.path("beginDate").asText()).isEqualTo(query.beginDate().toString()); assertThat(conditions.path("endDate").asText()).isEqualTo(query.endDate().toString()); var sent=CLIENTS.keySet().stream().filter(body -> body.contains("旧方案硬筛选")).map(json::read).toList(); assertThat(sent).hasSize(2).allSatisfy(data -> { assertThat(data.path("provinces").toString()).isEqualTo("[\"江苏\"]"); assertThat(data.has("min_amount") || data.has("max_amount")).isFalse(); assertThat(data.path("begin_date").asText()).isEqualTo(query.beginDate().toString()); assertThat(data.path("end_date").asText()).isEqualTo(query.endDate().toString()); }); assertThat(jdbc.queryForObject("SELECT conditions FROM search_scheme WHERE id=?",String.class,scheme)).isEqualTo(json.write(query)); mvc.perform(post("/api/search-schemes/"+scheme+"/runs").param("strictFilters","true") .with(user("admin")).with(csrf()).header("Idempotency-Key",key)) .andExpect(status().isOk()).andExpect(jsonPath("$.id").value(id)); var legacy=mvc.perform(post("/api/search-schemes/"+scheme+"/runs").with(user("admin")).with(csrf()) .header("Idempotency-Key",UUID.randomUUID().toString())).andExpect(status().isOk()).andReturn(); String legacyId=json.read(legacy.getResponse().getContentAsString()).path("id").asText(); assertThat(json.read(json.write(settled(legacyId).get("result"))).path("conditions").path("mode").asText()).isEqualTo("LEADS"); } @Test void marketAggregationAndSampleHaveSeparateScopesAndResumeSkipsCompletedTools() { var basic=opportunity("市场聚合",2); var q=basic.opportunity(); var query=new OpportunityQuery(q.keywords(),q.beginDate(),q.endDate(),q.stages(),q.preference(),List.of(),null,null, OpportunityQuery.Mode.MARKET,OpportunityQuery.KeywordMode.ANY,List.of("浙江"),new BigDecimal("10"),null); var request=new TaskRequest(basic.operation(),basic.workflow(),"",false,2,new BigDecimal("5"),query); String id=create(request); var first=settled(id); assertThat(first.get("status")).isEqualTo("WAITING_BUDGET"); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM market_snapshot WHERE task_id=?",Integer.class,id)).isEqualTo(2); var resumed=new TaskRequest(basic.operation(),basic.workflow(),"",false,5,new BigDecimal("5"),query); tasks.resume(owner(),id,UUID.randomUUID().toString(),resumed); var result=settled(id); assertThat(result.get("status")).isEqualTo("SUCCEEDED"); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=?",Integer.class,id)).isEqualTo(5); assertThat(jdbc.queryForObject("SELECT COUNT(*) FROM tool_call WHERE task_id=? AND tool_name='get_top_purchasers'",Integer.class,id)).isEqualTo(1); var report=json.read(json.write(result.get("result"))); assertThat(report.path("market").path("platformAggregations").size()).isEqualTo(3); assertThat(report.path("market").path("basis").asText()).contains("样本"); assertThat(report.path("scope").path("uniqueCount").asInt()).isEqualTo(3); assertThat(report.path("market").toString()).contains("测试采购方","测试供应商","30"); assertThat(evidence.list(id)).hasSize(6).allSatisfy(item -> assertThat(item.get("verified")).isEqualTo(true)); for(String body:CLIENTS.keySet().stream().filter(value -> value.contains("市场聚合")).toList()) { var data=json.read(body); if(data.has("filters")) assertThat(data.path("filters").path("min_money").asInt()).isEqualTo(100000); else if(data.has("limit")) assertThat(data.path("min_amount").asInt()).isEqualTo(100000); } } @Test void reliableProjectNumberLinksStagesWithoutDroppingNoticeSources() { String id=create(opportunity("阶段归并",3)); var report=json.read(json.write(settled(id).get("result"))); assertThat(report.path("items").size()).isEqualTo(3); assertThat(report.path("stageChains").size()).isEqualTo(1); assertThat(report.path("stageChains").path(0).path("notices").size()).isEqualTo(2); assertThat(report.path("stageChains").toString()).contains("TEST-CODE-2026","99101","99103"); } @Test void allKeywordWorkflowUsesAdvancedEndpointAndRecordsActualToolName() { var basic=opportunity("AND工具契约",3); var q=basic.opportunity(); var query=new OpportunityQuery(q.keywords(),q.beginDate(),q.endDate(),q.stages(),q.preference(),q.preferredRegions(),null,null, OpportunityQuery.Mode.SEARCH,OpportunityQuery.KeywordMode.ALL,List.of("浙江"),new BigDecimal("10"),null); String id=create(new TaskRequest(basic.operation(),basic.workflow(),"",false,3,new BigDecimal("5"),query)); assertThat(settled(id).get("status")).isEqualTo("SUCCEEDED"); assertThat(jdbc.queryForList("SELECT DISTINCT tool_name FROM tool_call WHERE task_id=?",String.class,id)).containsExactly("query_bids_advanced"); assertThat(CLIENTS.keySet().stream().filter(body -> body.contains("AND工具契约")).map(json::read)) .allSatisfy(data -> { assertThat(data.has("keyword_groups")).isTrue(); assertThat(data.has("min_money") || data.has("min_amount")).isFalse(); }); } }