app.js 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. const endpoints = {
  2. orders: "/api/orders",
  3. risks: "/api/risks",
  4. flow: "/api/flow",
  5. nodeTimes: "/api/node-times",
  6. cutoffs: "/api/order-cutoffs",
  7. exceptionMap: "/api/exception-map",
  8. };
  9. const labels = {
  10. orderNo: "订单号",
  11. customerName: "客户",
  12. status: "状态",
  13. currentNodeName: "当前节点",
  14. ownerName: "责任人",
  15. riskName: "风险",
  16. exceptionName: "异常",
  17. affectedNodeName: "影响节点",
  18. sequence: "顺序",
  19. nodeName: "节点",
  20. nextNodeName: "下一节点",
  21. deadlineName: "关键时限",
  22. plannedTime: "计划时间",
  23. cutoffTime: "截止时间",
  24. actualTime: "实际完成",
  25. isCompleted: "完成",
  26. isDelayed: "超时",
  27. customsCutoffTime: "截关",
  28. terminalCutoffTime: "截港",
  29. vgmCutoffTime: "VGM截止",
  30. estimatedSailingTime: "预计开船",
  31. };
  32. let currentRunId = null;
  33. let operationsLoaded = false;
  34. let marketOptions = null;
  35. let mockCatalog = null;
  36. let activeCatalog = "routes";
  37. document.querySelectorAll(".view-tab").forEach(button => {
  38. button.addEventListener("click", () => switchView(button.dataset.view));
  39. });
  40. document.getElementById("inquiryForm").addEventListener("submit", submitInquiry);
  41. document.getElementById("recommendBtn").addEventListener("click", submitInquiry);
  42. document.getElementById("refreshBtn").addEventListener("click", loadOperations);
  43. document.getElementById("auditBtn").addEventListener("click", openAudit);
  44. document.getElementById("generateMockBtn").addEventListener("click", generateMockBatch);
  45. document.getElementById("resetMockBtn").addEventListener("click", resetMockData);
  46. document.getElementById("origin").addEventListener("change", () => syncRouteControls(true));
  47. document.getElementById("destination").addEventListener("change", () => applyRouteDefaults(true));
  48. document.querySelectorAll(".catalog-tab").forEach(button => {
  49. button.addEventListener("click", () => selectCatalog(button.dataset.catalog));
  50. });
  51. document.getElementById("closeAuditBtn").addEventListener("click", () => {
  52. document.getElementById("auditDialog").close();
  53. });
  54. initialize();
  55. async function initialize() {
  56. try {
  57. const [health, options] = await Promise.all([
  58. fetchJson("/health"),
  59. fetchJson("/api/market/form-options"),
  60. ]);
  61. document.getElementById("systemStatus").textContent =
  62. `本地知识图谱 · ${numberFormat(health.triple_count)} triples`;
  63. marketOptions = options;
  64. populateInquiryForm(options);
  65. await requestRecommendation(options.defaults);
  66. } catch (error) {
  67. renderMarketError(error.message);
  68. }
  69. }
  70. function switchView(view) {
  71. document.querySelectorAll(".view-tab").forEach(button => {
  72. button.classList.toggle("is-active", button.dataset.view === view);
  73. });
  74. document.querySelectorAll(".app-view").forEach(section => {
  75. section.classList.toggle("is-active", section.id === `${view}View`);
  76. });
  77. if (view === "operations" && !operationsLoaded) loadOperations();
  78. if (view === "mock" && !mockCatalog) loadMockCatalog();
  79. }
  80. function populateInquiryForm(options) {
  81. populateSelect("customer", options.customers, "id", "name", options.defaults.customer);
  82. populateSelect("origin", options.origins, null, null, options.defaults.origin);
  83. syncRouteControls(false, options.defaults.destination);
  84. const defaultRoute = options.routes.find(route =>
  85. route.origin === options.defaults.origin && route.destination === options.defaults.destination
  86. );
  87. if (defaultRoute) {
  88. populateSelect(
  89. "routeType",
  90. defaultRoute.route_types,
  91. null,
  92. null,
  93. options.defaults.preferred_route_type,
  94. );
  95. }
  96. document.getElementById("cargoName").value = options.defaults.cargo_name;
  97. document.getElementById("cargoVolume").value = options.defaults.cargo_volume;
  98. document.getElementById("evaluationDate").value = options.defaults.evaluation_date;
  99. document.getElementById("departureDate").value = options.defaults.requested_departure_date;
  100. document.getElementById("maxTransitDays").value = options.defaults.max_transit_days;
  101. document.getElementById("targetAmount").value = options.defaults.target_amount;
  102. document.getElementById("dangerousGoods").checked = options.defaults.dangerous_goods;
  103. populateMockRouteSelect();
  104. }
  105. function syncRouteControls(updateDefaults, selectedDestination) {
  106. if (!marketOptions) return;
  107. const origin = document.getElementById("origin").value;
  108. const destinations = marketOptions.routes
  109. .filter(route => route.origin === origin)
  110. .map(route => route.destination);
  111. const preferredDestination = selectedDestination && destinations.includes(selectedDestination)
  112. ? selectedDestination
  113. : destinations[0];
  114. populateSelect("destination", destinations, null, null, preferredDestination);
  115. applyRouteDefaults(updateDefaults);
  116. }
  117. function applyRouteDefaults(updateValues) {
  118. if (!marketOptions) return;
  119. const origin = document.getElementById("origin").value;
  120. const destination = document.getElementById("destination").value;
  121. const route = marketOptions.routes.find(item => item.origin === origin && item.destination === destination);
  122. if (!route) return;
  123. const currentRouteType = document.getElementById("routeType").value;
  124. const preferredRouteType = route.route_types.includes(currentRouteType)
  125. ? currentRouteType
  126. : route.route_types[0];
  127. populateSelect("routeType", route.route_types, null, null, preferredRouteType);
  128. if (updateValues) {
  129. document.getElementById("targetAmount").value = route.target_amount;
  130. document.getElementById("departureDate").value = route.requested_departure_date;
  131. document.getElementById("maxTransitDays").value = Math.ceil(route.max_transit_days);
  132. }
  133. }
  134. function populateMockRouteSelect() {
  135. if (!marketOptions) return;
  136. const routes = marketOptions.routes.map((route, index) => ({
  137. id: String(index),
  138. name: `${route.origin} → ${route.destination}`,
  139. }));
  140. populateSelect("mockRoute", routes, "id", "name", "0");
  141. }
  142. function populateSelect(id, values, valueKey, labelKey, selectedValue) {
  143. const select = document.getElementById(id);
  144. select.innerHTML = values.map(item => {
  145. const value = valueKey ? item[valueKey] : item;
  146. const label = labelKey ? item[labelKey] : item;
  147. return `<option value="${escapeHtml(value)}"${value === selectedValue ? " selected" : ""}>${escapeHtml(label)}</option>`;
  148. }).join("");
  149. }
  150. async function submitInquiry(event) {
  151. event.preventDefault();
  152. const form = new FormData(document.getElementById("inquiryForm"));
  153. const inquiry = {
  154. customer: form.get("customer"),
  155. origin: form.get("origin"),
  156. destination: form.get("destination"),
  157. cargo_name: form.get("cargo_name"),
  158. cargo_volume: Number(form.get("cargo_volume")),
  159. evaluation_date: form.get("evaluation_date"),
  160. requested_departure_date: form.get("requested_departure_date"),
  161. max_transit_days: Number(form.get("max_transit_days")),
  162. target_amount: Number(form.get("target_amount")),
  163. preferred_route_type: form.get("preferred_route_type"),
  164. dangerous_goods: document.getElementById("dangerousGoods").checked,
  165. salesperson_adjustment: 0,
  166. };
  167. await requestRecommendation(inquiry);
  168. }
  169. async function requestRecommendation(inquiry) {
  170. setRecommendationLoading(true);
  171. try {
  172. const result = await fetchJson("/api/market/recommend", {
  173. method: "POST",
  174. headers: { "Content-Type": "application/json" },
  175. body: JSON.stringify(inquiry),
  176. });
  177. currentRunId = result.run_id;
  178. renderMarketResult(result);
  179. } catch (error) {
  180. currentRunId = null;
  181. renderMarketError(error.message);
  182. } finally {
  183. setRecommendationLoading(false);
  184. }
  185. }
  186. function setRecommendationLoading(loading) {
  187. const button = document.getElementById("recommendBtn");
  188. button.disabled = loading;
  189. button.querySelector("span:first-child").textContent = loading ? "正在计算" : "生成市场方案";
  190. document.getElementById("inquiryState").textContent = loading ? "决策计算中" : "已标准化";
  191. if (loading) {
  192. document.getElementById("recommendationBand").className = "recommendation-band is-loading";
  193. document.getElementById("recommendationBand").innerHTML = `
  194. <div class="loading-block"><span class="loading-line"></span><span class="loading-line short"></span></div>`;
  195. }
  196. }
  197. function renderMarketResult(result) {
  198. const inquiry = result.normalized_inquiry;
  199. const recommendation = result.recommendation;
  200. document.getElementById("decisionTitle").textContent = `${inquiry.customer_name} · ${inquiry.route}`;
  201. document.getElementById("inquiryState").textContent = `任务 ${result.run_id}`;
  202. document.getElementById("auditBtn").disabled = false;
  203. renderPipeline(result.pipeline);
  204. renderRecommendation(result);
  205. renderCandidates(result.candidates);
  206. renderRejected(result.rejected_candidates);
  207. }
  208. function renderPipeline(pipeline) {
  209. const steps = [
  210. ["DISCOVER", pipeline.discovered, "发现候选", ""],
  211. ["REJECT", pipeline.rejected, "硬条件淘汰", "is-rejected"],
  212. ["FEASIBLE", pipeline.feasible, "通过可执行校验", "is-accent"],
  213. ["SOLUTIONS", pipeline.generated_solutions, "生成市场方案", "is-accent"],
  214. ];
  215. document.getElementById("pipeline").innerHTML = steps.map(([code, value, label, className]) => `
  216. <div class="pipeline-step ${className}">
  217. <span>${code}</span><strong>${escapeHtml(value)}</strong><em>${label}</em>
  218. </div>`).join("");
  219. }
  220. function renderRecommendation(result) {
  221. const recommendation = result.recommendation;
  222. const top = result.candidates.find(item => item.id === recommendation.candidate_id);
  223. const pricing = top.pricing;
  224. const context = result.market_context;
  225. const confidence = Math.round(recommendation.confidence_score * 100);
  226. const band = document.getElementById("recommendationBand");
  227. band.className = "recommendation-band";
  228. band.innerHTML = `
  229. <div class="recommendation-copy">
  230. <span class="recommendation-label">AI MARKET RECOMMENDATION</span>
  231. <h2>${escapeHtml(recommendation.solution_type)} · ${escapeHtml(recommendation.supplier_name)}</h2>
  232. <p>${escapeHtml(recommendation.summary)}</p>
  233. <div class="recommendation-tags">
  234. <span>${escapeHtml(top.route_type)}</span>
  235. <span>${escapeHtml(top.transit_days)} 天</span>
  236. <span>可靠性 ${percent(top.reliability_rate)}</span>
  237. <span>${escapeHtml(context.strategy_name)}</span>
  238. </div>
  239. </div>
  240. <div class="quote-block">
  241. <span>客户最终建议报价</span>
  242. <div class="quote-amount">${money(pricing.final_quote_amount)}<small>${escapeHtml(pricing.currency)}</small></div>
  243. <div class="quote-range">授权区间 ${money(pricing.allowed_quote_lower_amount)} – ${money(pricing.allowed_quote_upper_amount)}</div>
  244. <div class="confidence-row">
  245. <span>置信度 ${confidence}%</span>
  246. <div class="confidence-track"><span style="width:${confidence}%"></span></div>
  247. </div>
  248. </div>`;
  249. }
  250. function renderCandidates(candidates) {
  251. document.getElementById("candidateMeta").textContent = `${candidates.length} 套可执行方案 · 按综合得分排序`;
  252. document.getElementById("candidateGrid").innerHTML = candidates.map((candidate, index) => {
  253. const typeClass = candidate.solution_type === "经济方案"
  254. ? "type-economy"
  255. : candidate.solution_type === "时效方案" ? "type-speed" : "type-balanced";
  256. const riskClass = candidate.pricing.cost_risk_status.includes("底线")
  257. ? "is-danger"
  258. : candidate.pricing.cost_risk_status.includes("安全") ? "is-safe" : "";
  259. return `
  260. <article class="candidate-card ${typeClass}" style="animation-delay:${index * 70}ms">
  261. <div class="candidate-head">
  262. <div class="candidate-type-row">
  263. <span class="candidate-type">${escapeHtml(candidate.solution_type)}</span>
  264. <span class="candidate-rank">RANK ${candidate.rank}</span>
  265. </div>
  266. <h3>${escapeHtml(candidate.product_name)}</h3>
  267. <p class="candidate-supplier">${escapeHtml(candidate.supplier_name)} · ${escapeHtml(candidate.offering_channel)}</p>
  268. </div>
  269. <div class="candidate-facts">
  270. <div><span>预计时效</span><strong>${escapeHtml(candidate.transit_days)} 天</strong></div>
  271. <div><span>预计开航</span><strong>${shortDate(candidate.departure_date)}</strong></div>
  272. <div><span>综合得分</span><strong>${candidate.total_score}</strong></div>
  273. </div>
  274. <div class="score-list">
  275. ${scoreRow("客户匹配", candidate.customer_fit_score)}
  276. ${scoreRow("价格竞争", candidate.price_score)}
  277. ${scoreRow("运输时效", candidate.transit_score)}
  278. ${scoreRow("供应履约", candidate.supplier_execution_score)}
  279. ${scoreRow("产品策略", candidate.product_strategy_score)}
  280. </div>
  281. <div class="candidate-reason">${candidate.reasons.slice(0, 2).map(escapeHtml).join(";")}</div>
  282. <div class="candidate-price">
  283. <div><span>建议客户报价</span><strong>${money(candidate.pricing.final_quote_amount)}</strong></div>
  284. <em class="risk-label ${riskClass}">${escapeHtml(candidate.pricing.cost_risk_status)}</em>
  285. </div>
  286. </article>`;
  287. }).join("");
  288. }
  289. function scoreRow(label, value) {
  290. const width = Math.max(0, Math.min(100, Number(value)));
  291. return `<div class="score-row"><span>${label}</span><div class="score-track"><span style="width:${width}%"></span></div><strong>${value}</strong></div>`;
  292. }
  293. function renderRejected(rejected) {
  294. document.getElementById("rejectedMeta").textContent = `${rejected.length} 个淘汰候选`;
  295. document.getElementById("rejectedList").innerHTML = rejected.length
  296. ? rejected.map(item => `
  297. <div class="rejected-row">
  298. <strong>${escapeHtml(item.product_name)}</strong>
  299. <span>${escapeHtml(item.supplier_name)} · ${escapeHtml(item.quote_no)}</span>
  300. <div class="rejected-reasons">${item.reasons.map(reason => `<em>${escapeHtml(reason)}</em>`).join("")}</div>
  301. </div>`).join("")
  302. : `<div class="empty">本次没有候选被硬条件淘汰</div>`;
  303. }
  304. function renderMarketError(message) {
  305. document.getElementById("decisionTitle").textContent = "当前询价无法生成可执行方案";
  306. document.getElementById("auditBtn").disabled = true;
  307. document.getElementById("pipeline").innerHTML = "";
  308. const band = document.getElementById("recommendationBand");
  309. band.className = "recommendation-band";
  310. band.innerHTML = `<div class="recommendation-copy"><span class="recommendation-label">DECISION STOPPED</span><h2>${escapeHtml(message)}</h2></div>`;
  311. document.getElementById("candidateGrid").innerHTML = "";
  312. document.getElementById("candidateMeta").textContent = "0 套可执行方案";
  313. }
  314. async function openAudit() {
  315. if (!currentRunId) return;
  316. const dialog = document.getElementById("auditDialog");
  317. const target = document.getElementById("auditContent");
  318. target.innerHTML = `<div class="empty">正在读取审计记录</div>`;
  319. dialog.showModal();
  320. try {
  321. const audit = await fetchJson(`/api/market/recommendations/${encodeURIComponent(currentRunId)}/audit`);
  322. target.innerHTML = `
  323. <div class="audit-grid">
  324. ${auditItem("推荐任务", audit.run_id)}
  325. ${auditItem("生成时间", audit.generated_at)}
  326. ${auditItem("客户与路线", `${audit.input.customer_name} · ${audit.input.route}`)}
  327. ${auditItem("候选结果", `${audit.candidate_count} 个通过 / ${audit.rejected_count} 个淘汰`)}
  328. ${auditItem("市场策略", audit.market_context.strategy_name)}
  329. ${auditItem("RDF决策断言", `${audit.rdf_assertions} 条`)}
  330. </div>
  331. <div class="audit-sources">
  332. <h3>本次决策数据来源</h3>
  333. ${audit.sources.map(source => `<code>${escapeHtml(source)}</code>`).join("")}
  334. </div>`;
  335. } catch (error) {
  336. target.innerHTML = `<div class="error">${escapeHtml(error.message)}</div>`;
  337. }
  338. }
  339. function auditItem(label, value) {
  340. return `<div class="audit-item"><span>${escapeHtml(label)}</span><strong>${escapeHtml(value)}</strong></div>`;
  341. }
  342. async function loadMockCatalog() {
  343. const target = document.getElementById("mockCatalogTable");
  344. target.innerHTML = `<div class="empty">正在读取本地 RDF 数据</div>`;
  345. try {
  346. mockCatalog = await fetchJson("/api/mock/catalog");
  347. renderMockCatalog();
  348. } catch (error) {
  349. target.innerHTML = `<div class="error">${escapeHtml(error.message)}</div>`;
  350. }
  351. }
  352. function renderMockCatalog() {
  353. if (!mockCatalog) return;
  354. const summary = mockCatalog.summary;
  355. const stats = [
  356. ["RDF 三元组", summary.triple_count, summary.in_memory_triple_count ? `+${summary.in_memory_triple_count} 内存` : "基础图", summary.in_memory_triple_count > 0],
  357. ["客户", summary.customer_count, "Customer", false],
  358. ["供应商", summary.supplier_count, "Supplier", false],
  359. ["产品", summary.product_count, "ServiceProduct", false],
  360. ["报价", summary.quote_count, "SupplierQuote", false],
  361. ["路线", summary.route_count, "Route", false],
  362. ["启用策略", summary.strategy_count, "Strategy", false],
  363. ];
  364. document.getElementById("mockSummary").innerHTML = stats.map(([label, value, note, hasMemory]) => `
  365. <div class="data-stat ${hasMemory ? "has-memory" : ""}">
  366. <span>${escapeHtml(label)}</span><strong>${numberFormat(value)}</strong><em>${escapeHtml(note)}</em>
  367. </div>`).join("");
  368. document.getElementById("mockSources").innerHTML = mockCatalog.loaded_files
  369. .map(source => `<code>${escapeHtml(source)}</code>`).join("");
  370. document.getElementById("systemStatus").textContent = summary.in_memory_triple_count
  371. ? `本地知识图谱 · ${numberFormat(summary.triple_count)} triples · +${summary.in_memory_triple_count} 内存`
  372. : `本地知识图谱 · ${numberFormat(summary.triple_count)} triples`;
  373. renderActiveCatalogTable();
  374. }
  375. function selectCatalog(catalog) {
  376. activeCatalog = catalog;
  377. document.querySelectorAll(".catalog-tab").forEach(button => {
  378. button.classList.toggle("is-active", button.dataset.catalog === catalog);
  379. });
  380. renderActiveCatalogTable();
  381. }
  382. function renderActiveCatalogTable() {
  383. if (!mockCatalog) return;
  384. const definitions = {
  385. routes: {
  386. columns: [
  387. ["origin", "起运地"], ["destination", "目的地"], ["transport_modes", "运输方式"],
  388. ["product_count", "产品"], ["supplier_count", "供应商"], ["quote_count", "全部报价"],
  389. ["current_quote_count", "当前有效"],
  390. ],
  391. rows: mockCatalog.routes,
  392. },
  393. customers: {
  394. columns: [
  395. ["name", "客户"], ["industry", "行业"], ["preferred_route", "主要路线"],
  396. ["repeat_purchase_count", "复购"], ["price_sensitivity", "价格敏感"],
  397. ["time_sensitivity", "时效敏感"], ["reliability_sensitivity", "可靠性敏感"],
  398. ],
  399. rows: mockCatalog.customers,
  400. },
  401. quotes: {
  402. columns: [
  403. ["quote_no", "报价编号"], ["route", "路线"], ["transport_mode", "方式"],
  404. ["product_name", "产品"], ["supplier_name", "供应商"],
  405. ["supplier_cost_amount", "采购金额"], ["valid_to", "有效至"], ["status", "状态"],
  406. ],
  407. rows: mockCatalog.quotes,
  408. },
  409. strategies: {
  410. columns: [
  411. ["name", "策略"], ["route", "适用路线"], ["objective", "目标"],
  412. ["adjustment_rate", "价格调整"], ["valid_to", "有效至"],
  413. ],
  414. rows: mockCatalog.strategies,
  415. },
  416. };
  417. const definition = definitions[activeCatalog];
  418. document.getElementById("mockCatalogTable").innerHTML = renderCatalogTable(
  419. definition.rows,
  420. definition.columns,
  421. );
  422. }
  423. function renderCatalogTable(rows, columns) {
  424. if (!rows.length) return `<div class="empty">当前分类没有数据</div>`;
  425. const head = columns.map(([, label]) => `<th>${escapeHtml(label)}</th>`).join("");
  426. const body = rows.map(row => `
  427. <tr>${columns.map(([key]) => `<td>${formatCatalogCell(key, row[key], row)}</td>`).join("")}</tr>`
  428. ).join("");
  429. return `<table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`;
  430. }
  431. function formatCatalogCell(key, value, row) {
  432. if (["price_sensitivity", "time_sensitivity", "reliability_sensitivity"].includes(key)) {
  433. const width = Math.round(Number(value || 0) * 100);
  434. return `<div class="sensitivity-cell"><span>${width}%</span><div class="sensitivity-track"><span style="width:${width}%"></span></div></div>`;
  435. }
  436. if (key === "supplier_cost_amount") {
  437. return `${money(value)} ${escapeHtml(row.currency || "CNY")}${row.runtime_mock ? ` <span class="runtime-mark">内存</span>` : ""}`;
  438. }
  439. if (key === "status") {
  440. const className = value === "当前有效" ? "status-current" : value === "已过期" ? "status-expired" : "";
  441. return `<span class="${className}">${escapeHtml(value)}</span>`;
  442. }
  443. if (key === "adjustment_rate") return percent(value);
  444. return escapeHtml(value ?? "");
  445. }
  446. async function generateMockBatch() {
  447. if (!marketOptions?.routes?.length) return;
  448. const button = document.getElementById("generateMockBtn");
  449. const route = marketOptions.routes[Number(document.getElementById("mockRoute").value)];
  450. if (!route) return;
  451. button.disabled = true;
  452. button.querySelector("span:first-child").textContent = "正在写入内存图";
  453. document.getElementById("mockStatus").textContent = "正在生成供应商、产品、班期、报价和客户画像";
  454. try {
  455. const result = await fetchJson("/api/mock/generate", {
  456. method: "POST",
  457. headers: { "Content-Type": "application/json" },
  458. body: JSON.stringify({
  459. origin: route.origin,
  460. destination: route.destination,
  461. supplier_count: Number(document.getElementById("mockSupplierCount").value),
  462. customer_count: Number(document.getElementById("mockCustomerCount").value),
  463. evaluation_date: document.getElementById("evaluationDate").value || "2026-07-20",
  464. }),
  465. });
  466. mockCatalog = result.catalog;
  467. document.getElementById("mockStatus").textContent =
  468. `批次 ${result.batch_id} 已增加 ${result.added_triples} 条内存三元组`;
  469. await refreshMarketOptions();
  470. renderMockCatalog();
  471. } catch (error) {
  472. document.getElementById("mockStatus").textContent = error.message;
  473. } finally {
  474. button.disabled = false;
  475. button.querySelector("span:first-child").textContent = "添加一批 Mock 数据";
  476. }
  477. }
  478. async function resetMockData() {
  479. const button = document.getElementById("resetMockBtn");
  480. button.disabled = true;
  481. try {
  482. mockCatalog = await fetchJson("/api/mock/reset", { method: "POST" });
  483. document.getElementById("mockStatus").textContent = "动态数据已清空,已恢复本地 TTL 基础图";
  484. await refreshMarketOptions();
  485. await requestRecommendation(marketOptions.defaults);
  486. renderMockCatalog();
  487. } catch (error) {
  488. document.getElementById("mockStatus").textContent = error.message;
  489. } finally {
  490. button.disabled = false;
  491. }
  492. }
  493. async function refreshMarketOptions() {
  494. marketOptions = await fetchJson("/api/market/form-options");
  495. populateInquiryForm(marketOptions);
  496. }
  497. async function loadOperations() {
  498. await Promise.all([
  499. loadTable("orders", endpoints.orders, ["orderNo", "customerName", "status", "currentNodeName", "ownerName"]),
  500. loadTable("risks", endpoints.risks, ["orderNo", "riskName", "exceptionName", "affectedNodeName"]),
  501. loadFlow(),
  502. loadTable("nodeTimes", endpoints.nodeTimes, ["sequence", "nodeName", "deadlineName", "plannedTime", "cutoffTime", "actualTime", "isCompleted", "isDelayed"]),
  503. loadTable("cutoffs", endpoints.cutoffs, ["orderNo", "customsCutoffTime", "terminalCutoffTime", "vgmCutoffTime", "estimatedSailingTime"]),
  504. loadTable("exceptionMap", endpoints.exceptionMap, ["exceptionName", "affectedNodeName", "riskName"]),
  505. ]);
  506. operationsLoaded = true;
  507. }
  508. async function fetchJson(url, options) {
  509. const response = await fetch(url, options);
  510. if (!response.ok) {
  511. let detail = `请求失败:HTTP ${response.status}`;
  512. try {
  513. const payload = await response.json();
  514. detail = payload.detail || detail;
  515. } catch (_) {
  516. // Preserve the HTTP message when the response is not JSON.
  517. }
  518. throw new Error(detail);
  519. }
  520. return response.json();
  521. }
  522. async function fetchRows(url) {
  523. const data = await fetchJson(url);
  524. return data.rows || [];
  525. }
  526. async function loadTable(id, url, columns) {
  527. const target = document.getElementById(id);
  528. const counter = document.getElementById(`${id}Count`);
  529. try {
  530. const rows = await fetchRows(url);
  531. if (counter) counter.textContent = rows.length;
  532. target.innerHTML = renderTable(rows, columns);
  533. } catch (error) {
  534. target.innerHTML = `<div class="error">本地RDF数据读取失败</div>`;
  535. }
  536. }
  537. async function loadFlow() {
  538. const target = document.getElementById("flow");
  539. try {
  540. const rows = await fetchRows(endpoints.flow);
  541. if (!rows.length) {
  542. target.innerHTML = `<div class="empty">暂无流程数据</div>`;
  543. return;
  544. }
  545. target.innerHTML = rows.map(row => `
  546. <div class="step">
  547. <strong>${escapeHtml(row.sequence)}. ${escapeHtml(row.nodeName)}</strong>
  548. <span>${row.deadlineName ? `时限:${escapeHtml(row.deadlineName)}` : "无关键时限"}</span>
  549. <span>${row.nextNodeName ? `下一步:${escapeHtml(row.nextNodeName)}` : "流程结束"}</span>
  550. </div>`).join("");
  551. } catch (error) {
  552. target.innerHTML = `<div class="error">流程读取失败</div>`;
  553. }
  554. }
  555. function renderTable(rows, columns) {
  556. if (!rows.length) return `<div class="empty">暂无数据</div>`;
  557. const head = columns.map(column => `<th>${labels[column] || column}</th>`).join("");
  558. const body = rows.map(row => `
  559. <tr>${columns.map(column => `<td>${formatCell(column, row[column])}</td>`).join("")}</tr>`).join("");
  560. return `<table><thead><tr>${head}</tr></thead><tbody>${body}</tbody></table>`;
  561. }
  562. function formatCell(column, value) {
  563. if (!value) return "";
  564. if (column === "isDelayed" && value === "true") return `<span class="badge-danger">是</span>`;
  565. if (column === "isDelayed" && value === "false") return "否";
  566. if (column === "isCompleted" && value === "true") return "是";
  567. if (column === "isCompleted" && value === "false") return `<span class="badge-warning">否</span>`;
  568. if (column.endsWith("Time")) return escapeHtml(value.replace("T", " ").replace("+08:00", ""));
  569. return escapeHtml(value);
  570. }
  571. function money(value) {
  572. return new Intl.NumberFormat("zh-CN", { maximumFractionDigits: 0 }).format(Number(value));
  573. }
  574. function numberFormat(value) {
  575. return new Intl.NumberFormat("zh-CN").format(Number(value));
  576. }
  577. function percent(value) {
  578. return `${Math.round(Number(value) * 100)}%`;
  579. }
  580. function shortDate(value) {
  581. return value ? value.slice(5).replace("-", "/") : "待确认";
  582. }
  583. function escapeHtml(value) {
  584. return String(value ?? "")
  585. .replaceAll("&", "&amp;")
  586. .replaceAll("<", "&lt;")
  587. .replaceAll(">", "&gt;")
  588. .replaceAll('"', "&quot;")
  589. .replaceAll("'", "&#039;");
  590. }