diff --git a/backend/routes/sectors.py b/backend/routes/sectors.py index 5e10e76..c45fde6 100644 --- a/backend/routes/sectors.py +++ b/backend/routes/sectors.py @@ -1,4 +1,8 @@ -"""板块数据路由:行业板块、概念板块""" +"""板块数据路由:行业板块、概念板块 + +注意:行业/概念必须走不同 path(/industry、/concept),不能仅靠 query 参数区分。 +上游反代/CDN 可能按 path 缓存并忽略 query,导致两个 tab 返回相同数据。 +""" from fastapi import APIRouter, Query, HTTPException from fastapi.responses import JSONResponse @@ -6,34 +10,63 @@ from services import eastmoney, mootdx router = APIRouter() -# 行业/概念通过 query 参数区分,但上游反代/CDN 可能按 path 缓存而忽略 query, -# 导致两个 tab 返回相同数据。显式禁止缓存,保证按 query 区分。 +# 禁止任何中间层缓存,确保每次请求都打到后端 _NO_CACHE_HEADERS = {"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0"} +_SORT_KEYS = {"mainNetInflow", "changePercent"} -@router.get("", summary="板块列表") -async def sector_list( - type: str = Query("industry", description="板块类型:industry=行业板块, concept=概念板块"), -): - if type not in ("industry", "concept"): - raise HTTPException(status_code=400, detail="板块类型错误,仅支持 industry/concept") - data = await eastmoney.fetch_sector_list(type) +def _sort_sectors(data: list[dict], sort: str, order: str) -> list[dict]: + """后端排序:mainNetInflow=资金流入,changePercent=涨幅%""" + reverse = order != "asc" + if sort == "changePercent": + # changePercent 为 None 的排到最后(与方向无关) + return sorted( + data, + key=lambda x: (x.get("changePercent") is None, -(x.get("changePercent") or 0)), + reverse=reverse, + ) + return sorted(data, key=lambda x: -(x.get("mainNetInflow") or 0), reverse=reverse) + + +async def _sector_response(sector_type: str, sort: str, order: str) -> JSONResponse: + data = await eastmoney.fetch_sector_list(sector_type) + source = None + if not data: + # 降级:通达信 mootdx(不含实时资金流数据) + md_data = await mootdx.fetch_sector_list(sector_type) + if md_data: + data = md_data + source = "mootdx" + if data: - return JSONResponse( - {"data": data, "count": len(data), "type": type}, - headers=_NO_CACHE_HEADERS, - ) + data = _sort_sectors(data, sort, order) - # 降级:通达信 mootdx(不含实时资金流数据) - md_data = await mootdx.fetch_sector_list(type) - if md_data: - return JSONResponse( - {"data": md_data, "count": len(md_data), "type": type, "source": "mootdx"}, - headers=_NO_CACHE_HEADERS, - ) + payload: dict = {"data": data, "count": len(data), "type": sector_type} + if source: + payload["source"] = source + return JSONResponse(payload, headers=_NO_CACHE_HEADERS) - return JSONResponse( - {"data": [], "count": 0, "type": type}, - headers=_NO_CACHE_HEADERS, - ) + +@router.get("/industry", summary="行业板块列表") +async def sector_industry( + sort: str = Query("mainNetInflow", description="排序字段:mainNetInflow=资金流入, changePercent=涨幅%"), + order: str = Query("desc", description="排序方向:asc=升序, desc=降序"), +): + if sort not in _SORT_KEYS: + sort = "mainNetInflow" + if order not in ("asc", "desc"): + order = "desc" + return await _sector_response("industry", sort, order) + + +@router.get("/concept", summary="概念板块列表") +async def sector_concept( + sort: str = Query("mainNetInflow", description="排序字段:mainNetInflow=资金流入, changePercent=涨幅%"), + order: str = Query("desc", description="排序方向:asc=升序, desc=降序"), +): + if sort not in _SORT_KEYS: + sort = "mainNetInflow" + if order not in ("asc", "desc"): + order = "desc" + return await _sector_response("concept", sort, order) diff --git a/src/lib/stock-api.ts b/src/lib/stock-api.ts index a334065..78ab078 100755 --- a/src/lib/stock-api.ts +++ b/src/lib/stock-api.ts @@ -460,15 +460,23 @@ export interface SectorResponse { } /** - * 获取东方财富板块列表(按主力净流入排序) + * 获取东方财富板块列表 + * 行业/概念走不同 path(/industry、/concept),避免上游反代按 path 缓存忽略 query 导致数据串味 * @param type industry=行业板块, concept=概念板块 + * @param sort mainNetInflow=资金流入, changePercent=涨幅% + * @param order asc=升序, desc=降序 */ -export async function fetchSectors(type: SectorType, signal?: AbortSignal): Promise { +export async function fetchSectors( + type: SectorType, + opts?: { sort?: "mainNetInflow" | "changePercent"; order?: "asc" | "desc"; signal?: AbortSignal }, +): Promise { const baseUrl = getApiBaseUrl(); - const url = `${baseUrl}/api/sectors?type=${type}`; + const sort = opts?.sort ?? "mainNetInflow"; + const order = opts?.order ?? "desc"; + const url = `${baseUrl}/api/sectors/${type}?sort=${sort}&order=${order}`; try { - const resp = await fetch(url, { method: "GET", signal, cache: "no-store" }); + const resp = await fetch(url, { method: "GET", signal: opts?.signal, cache: "no-store" }); if (!resp.ok) return []; const result: SectorResponse = await resp.json(); return result.data || []; diff --git a/src/routes/sectors.tsx b/src/routes/sectors.tsx index bf738e5..81f47f5 100644 --- a/src/routes/sectors.tsx +++ b/src/routes/sectors.tsx @@ -1,6 +1,5 @@ import { createFileRoute, Link } from "@tanstack/react-router"; -import { useMemo, useState } from "react"; -import { useQuery } from "@tanstack/react-query"; +import { useEffect, useMemo, useRef, useState } from "react"; import { fetchSectors, type SectorItem, type SectorType } from "@/lib/stock-api"; import { Card, CardContent } from "@/components/ui/card"; import { ArrowLeft, RefreshCw, ArrowDown, ArrowUp, TrendingUp, TrendingDown } from "lucide-react"; @@ -9,7 +8,7 @@ export const Route = createFileRoute("/sectors")({ component: SectorsPage, }); -/* ── Tabs:行业 / 概念 ── */ +/* ── Tabs:行业 / 概念(各自独立 path,互不串数据)── */ const TABS: { key: SectorType; label: string }[] = [ { key: "industry", label: "行业" }, { key: "concept", label: "概念" }, @@ -22,30 +21,27 @@ function SectorsPage() { const [tab, setTab] = useState("industry"); const [sortKey, setSortKey] = useState("mainNetInflow"); const [asc, setAsc] = useState(true); + const [data, setData] = useState([]); + const [loading, setLoading] = useState(true); + const abortRef = useRef(null); - // 行业 / 概念 各自独立的 Query,数据完全隔离,杜绝来回切换时的合并 - const industryQ = useQuery({ - queryKey: ["sectors", "industry"], - queryFn: ({ signal }) => fetchSectors("industry", signal), - staleTime: 30_000, - retry: false, - }); - const conceptQ = useQuery({ - queryKey: ["sectors", "concept"], - queryFn: ({ signal }) => fetchSectors("concept", signal), - staleTime: 30_000, - retry: false, - }); - - const { data = [], isLoading, isFetching, refetch } = - tab === "industry" ? industryQ : conceptQ; - - // 切换 tab 时强制重新请求,绕过 React Query 缓存和上游反代缓存,确保拿到对应类型的数据 - const handleTab = (t: SectorType) => { - setTab(t); - (t === "industry" ? industryQ : conceptQ).refetch(); - }; + // 每次 tab / 排序变化都重新发起请求(带 no-store,不缓存) + useEffect(() => { + abortRef.current?.abort(); + const controller = new AbortController(); + abortRef.current = controller; + setLoading(true); + fetchSectors(tab, { sort: sortKey, order: asc ? "asc" : "desc", signal: controller.signal }) + .then((items) => { + if (!controller.signal.aborted) { + setData(items); + setLoading(false); + } + }); + return () => controller.abort(); + }, [tab, sortKey, asc]); + // 后端已按 sort/order 排序;此处再排一次作为兜底,确保 UI 一定响应排序 const sorted = useMemo(() => { const dir = asc ? 1 : -1; return [...data].sort((a, b) => { @@ -63,6 +59,21 @@ function SectorsPage() { } }; + const reload = () => { + abortRef.current?.abort(); + const controller = new AbortController(); + abortRef.current = controller; + setLoading(true); + fetchSectors(tab, { sort: sortKey, order: asc ? "asc" : "desc", signal: controller.signal }).then( + (items) => { + if (!controller.signal.aborted) { + setData(items); + setLoading(false); + } + }, + ); + }; + return (
{/* 顶栏 */} @@ -75,21 +86,21 @@ function SectorsPage() {

板块资金流向

- {/* Tab 切换:行业 / 概念 */} + {/* Tab 切换:行业 / 概念(不同 path 请求) */}
{TABS.map((t) => (