Compare commits

...

31 Commits

Author SHA1 Message Date
JIANG
66f2390078 暂存 2026-02-11 18:58:10 +08:00
JIANG
9d06226cb4 Implemented a Zustand-based project_id store, expanded project selection/switching to persist project_id,
and centralized backend requests via api/apiFetch (including data provider updates) to inject X-Project-ID.
2026-02-11 16:29:18 +08:00
JIANG
a2e6c1f416 修复MAP_EXTENT状态更新的BUG 2026-02-11 14:17:16 +08:00
JIANG
2911b87fac 提升extent变量状态;修改部分默认值 2026-02-11 13:53:56 +08:00
JIANG
8b6198a2ac 调整环境变量参数,支持项目切换 2026-02-11 12:07:29 +08:00
JIANG
03e5f1456c 完善比例尺控件,调整控件位置 2026-02-11 11:52:06 +08:00
JIANG
25bde02b43 为登录后的页面新增切换项目弹窗 2026-02-10 17:11:04 +08:00
JIANG
1e8af75b88 新增项目选择弹窗(预设选项),支持变更环境变量 2026-02-10 16:13:04 +08:00
JIANG
8ea70d04ad 修改环境变量 2026-02-10 15:23:23 +08:00
JIANG
1d15eeb172 水质模拟默认设置pattern修改为CONSTANT 2026-02-10 15:23:14 +08:00
JIANG
ae1f9b284f 调整环境变量配置,便于docker打包 2026-02-09 15:32:35 +08:00
JIANG
409057cef2 支持管道冲洗模块流量参数为0 2026-02-09 15:32:10 +08:00
JIANG
2c51785157 修改管道清洗默认值 2026-02-06 17:47:55 +08:00
JIANG
6be4a0de14 修改爆管分析传递的参数格式 2026-02-06 16:59:59 +08:00
JIANG
9d12b1960c 修复scheme计算属性无法显示的问题 2026-02-06 11:32:50 +08:00
JIANG
cbfce9164e 调整工具栏,新增schemeType查询 2026-02-05 18:32:14 +08:00
JIANG
62a97459d0 修改管道冲洗点击提示信息 2026-02-05 17:39:49 +08:00
JIANG
4fbe845015 完成管道冲洗功能页面;调整水质模拟默认pattern;调整sidebar菜单名; 2026-02-05 17:38:23 +08:00
JIANG
f89e43eee2 新增管道冲洗页面 2026-02-05 11:59:23 +08:00
JIANG
4bd7b48bcf 修改项目描述 2026-02-05 11:56:54 +08:00
JIANG
5b52afcc53 爆管分析、水质模拟模块分离;调整sidebar 2026-02-05 11:56:42 +08:00
JIANG
9bb0f8dcd7 重新设计关阀分析模块 2026-02-05 10:50:15 +08:00
JIANG
bc73db66de 升级nextjs,修复部分依赖 2026-02-04 15:37:08 +08:00
JIANG
b8d7974ce9 调整健康风险分析时间轴重置按钮行为 2026-02-03 11:23:02 +08:00
JIANG
0690b0b804 修复标签索引报错的问题 2026-02-03 11:11:42 +08:00
JIANG
6f0ef342e9 完善关阀分析页面设计 2026-02-03 10:56:49 +08:00
JIANG
a3f4b477bc 完善测试框架;新增部分测试文件 2026-01-30 18:27:09 +08:00
JIANG
799eab03d0 新增关阀搜索面板;升级项目依赖;建立测试框架 2026-01-30 18:22:41 +08:00
JIANG
133e812700 健康风险定位显示具体的报错信息 2026-01-30 15:55:07 +08:00
JIANG
d584268acd 新增水质分析功能模块 2026-01-30 15:22:53 +08:00
JIANG
c28325e997 注释调试输出 2026-01-29 11:43:44 +08:00
62 changed files with 8640 additions and 990 deletions

View File

@@ -1,7 +1,10 @@
**/node_modules/
**/dist
node_modules
.next
out
build
.git
npm-debug.log
.coverage
.coverage.*
.env
.env*.local
README.md
docker-compose.yml
Dockerfile
.dockerignore

15
.env Normal file
View File

@@ -0,0 +1,15 @@
KEYCLOAK_CLIENT_ID="tjwater"
KEYCLOAK_CLIENT_SECRET="83h0n413hau9bldzWdEaq6xRfASv24s5"
KEYCLOAK_ISSUER="https://keycloak.waternetwork.cn/realms/tjwater"
NEXTAUTH_SECRET="eyJhbGciOiJIUzUxMiIsInR5cCIgOiAiS"
NEXTAUTH_URL="https://demo.waternetwork.cn/"
# 为前端暴露的变量添加 NEXT_PUBLIC_ 前缀
NEXT_PUBLIC_BACKEND_URL="https://server.waternetwork.cn"
NEXT_PUBLIC_MAP_URL="https://geoserver.waternetwork.cn/geoserver"
NEXT_PUBLIC_MAP_WORKSPACE="szh"
NEXT_PUBLIC_MAP_EXTENT="13490131, 3630016, 13525879, 3666968.25"
# NEXT_PUBLIC_MAP_AVAILABLE_LAYERS="junctions, pipes, reservoirs, scada"
NEXT_PUBLIC_NETWORK_NAME="szh"
NEXT_PUBLIC_MAPBOX_TOKEN="pk.eyJ1IjoiemhpZnUiLCJhIjoiY205azNyNGY1MGkyZDJxcTJleDUwaHV1ZCJ9.wOmSdOnDDdre-mB1Lpy6Fg"
NEXT_PUBLIC_TIANDITU_TOKEN="e3e8ad95ee911741fa71ed7bff2717ec"

174
.github/copilot-instructions.md vendored Normal file
View File

@@ -0,0 +1,174 @@
# Copilot Instructions for TJWater Frontend
## Project Overview
A Next.js 16 + TypeScript water network management system built with Refine framework, featuring real-time hydraulic simulation, SCADA data management, and GIS visualization using OpenLayers and Deck.gl.
## Build, Test, and Lint Commands
```bash
# Development
npm run dev # Start dev server (uses 4GB memory allocation)
# Production
npm run build # Build for production (standalone output)
npm run start # Start production server
# Testing
npm run test # Run all tests
npm run test:watch # Run tests in watch mode
npm run test:coverage # Generate coverage report
# Linting
npm run lint # Run ESLint
```
**Run single test file:**
```bash
npm test -- path/to/test-file.test.ts
```
## Architecture
### Framework Stack
- **Next.js 16** with App Router (not Pages Router)
- **Refine** framework for admin/CRUD operations
- **NextAuth.js** with Keycloak for SSO authentication
- **Material-UI (MUI) v6** for UI components
- **OpenLayers** + **Deck.gl** for map visualization
### Route Structure
- `src/app/layout.tsx` - Root layout with RefineContext
- `src/app/(main)/` - Protected routes with shared layout
- `/network-simulation` - Real-time network simulation
- `/scada-data-cleaning` - SCADA data management
- `/monitoring-place-optimization` - Sensor placement optimization
- `/health-risk-analysis` - Health risk assessment
- `/risk-analysis-location` - Risk location analysis
- `/network-partition-optimization` - Network partitioning
- `src/app/OlMap/` - Standalone map route with custom controls
- `src/app/login/` - Public authentication pages
### Key Directories
- `src/app/_refine_context.tsx` - Refine configuration with resources, auth provider, and data provider
- `src/providers/data-provider/` - REST API data provider (currently mock, update API_URL for production)
- `src/contexts/color-mode/` - Theme switching (light/dark mode persisted in cookies)
- `src/components/` - Reusable UI components (header, loading, olmap, title)
- `src/utils/` - Map utilities (layers.ts, mapQueryService.ts, color parsing)
- `src/config/config.ts` - Environment-based configuration with fallback defaults
### Path Aliases (TypeScript)
```typescript
@app/* -> src/app/*
@assets/* -> src/assets/*
@components/* -> src/components/*
@config/* -> src/config/*
@contexts/* -> src/contexts/*
@interfaces/* -> src/interfaces/*
@libs/* -> src/libs/*
@providers/* -> src/providers/*
@utils/* -> src/utils/*
@/* -> src/*
```
### Map Architecture
The map system uses a hybrid approach:
- **OpenLayers** as the base map engine (vector tiles from GeoServer)
- **Deck.gl** overlays for advanced visualizations (trips, contours, text labels)
- **DeckLayer** custom class bridges OL and Deck.gl (`@utils/layers`)
- Map data sourced from GeoServer MVT tiles (configured in `@config/config.ts`)
- Layers: junctions, pipes, valves, reservoirs, pumps, tanks, scada
### Client vs Server Components
- Most interactive components use `"use client"` directive (~35 files)
- Map components are always client-side (OpenLayers requires browser APIs)
- Layout and page files without interactivity can be server components
## Key Conventions
### Authentication Flow
- Keycloak SSO via NextAuth.js (`src/app/api/auth/[...nextauth]/`)
- Session managed with `SessionProvider` wrapper
- Auth check redirects to `/login` if unauthenticated
- Use `useSession()` hook for current user data
### Environment Variables
- All frontend-accessible variables must have `NEXT_PUBLIC_` prefix
- Backend URL: `NEXT_PUBLIC_BACKEND_URL` (defaults to http://192.168.1.42:8000)
- GeoServer URL: `NEXT_PUBLIC_MAP_URL` (defaults to http://127.0.0.1:8080/geoserver)
- Map layers: `NEXT_PUBLIC_MAP_AVAILABLE_LAYERS` (comma-separated)
- Keycloak config in `.env.local` (not committed)
### Refine Resources
Resources defined in `_refine_context.tsx` use Chinese labels and route to pages in `(main)/`:
- Each resource has: name (Chinese), list (route path), meta (icon + label)
- Icons from `react-icons` library
- No CRUD operations defined (list-only pages)
### Map Styling
- Default styles in `config.MAP_DEFAULT_STYLE` (stroke, circle, colors)
- Circle radius uses zoom-based interpolation (1px at z12, 8px at z24)
- WebGL rendering for vector tiles
- Style legends generated dynamically in map controls
### TypeScript Configuration
- Strict mode enabled
- Path aliases match jest.config.js mappings
- Target ES5 for broader compatibility
- Incremental builds enabled
### Next.js Configuration
- **Standalone output** for Docker deployment
- SVG files handled by `@svgr/webpack` (imported as React components)
- No custom server or middleware
### Testing Setup
- Jest with React Testing Library
- jsdom environment for component testing
- Path aliases configured to match tsconfig.json
- Setup file at `jest.setup.js`
## Common Patterns
### Adding a New Route
1. Create directory in `src/app/(main)/your-route/`
2. Add `page.tsx` and optional `loading.tsx`
3. Register resource in `src/app/_refine_context.tsx` resources array
4. Import icon from `react-icons`
### Working with Maps
- Use `MapComponent` from `src/app/OlMap/MapComponent.tsx`
- Access map context via `useMapData()` hook
- Vector tile layers auto-load from GeoServer workspace
- Custom overlays use Deck.gl layers (TextLayer, TripsLayer, ContourLayer)
### API Calls
- Update `dataProvider` in `src/providers/data-provider/index.ts` for real backend
- Currently points to `https://api.fake-rest.refine.dev`
- Use Refine hooks (`useList`, `useOne`, etc.) for data fetching
### Theme Management
- Theme stored in cookies (not localStorage)
- Toggle via `ColorModeContext` from `@contexts/color-mode`
- Supports light/dark modes only
- Default mode read from cookie in root layout (server-side)

View File

@@ -1,4 +1,4 @@
FROM refinedev/node:18 AS base
FROM refinedev/node:22 AS base
FROM base AS deps
@@ -15,6 +15,16 @@ RUN \
FROM base AS builder
# 只定义 ARG 接收来自构建命令或 docker-compose.yaml 的参数
# Next.js 在 build 时会自动读取同名的 ARG 作为环境变量
ARG NEXT_PUBLIC_BACKEND_URL
ARG NEXT_PUBLIC_MAP_URL
ARG NEXT_PUBLIC_MAP_WORKSPACE
ARG NEXT_PUBLIC_MAP_EXTENT
ARG NEXT_PUBLIC_NETWORK_NAME
ARG NEXT_PUBLIC_MAPBOX_TOKEN
ARG NEXT_PUBLIC_TIANDITU_TOKEN
COPY --from=deps /app/refine/node_modules ./node_modules
COPY . .
@@ -23,7 +33,7 @@ RUN npm run build
FROM base AS runner
ENV NODE_ENV production
ENV NODE_ENV=production
COPY --from=builder /app/refine/public ./public
@@ -37,7 +47,7 @@ USER refine
EXPOSE 3000
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
CMD ["node", "server.js"]

30
jest.config.js Normal file
View File

@@ -0,0 +1,30 @@
const nextJest = require('next/jest')
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
})
// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testEnvironment: 'jest-environment-jsdom',
moduleNameMapper: {
'^@pages/(.*)$': '<rootDir>/pages/$1',
'^@/(.*)$': '<rootDir>/src/$1',
'^@app/(.*)$': '<rootDir>/src/app/$1',
'^@assets/(.*)$': '<rootDir>/src/assets/$1',
'^@components/(.*)$': '<rootDir>/src/components/$1',
'^@config/(.*)$': '<rootDir>/src/config/$1',
'^@contexts/(.*)$': '<rootDir>/src/contexts/$1',
'^@interfaces/(.*)$': '<rootDir>/src/interfaces/$1',
'^@libs/(.*)$': '<rootDir>/src/libs/$1',
'^@providers/(.*)$': '<rootDir>/src/providers/$1',
'^@utils/(.*)$': '<rootDir>/src/utils/$1',
// Handle specific aliases if generic one causes issues, but trying generic first matching tsconfig
// '^@(.*)$': '<rootDir>/src/$1',
},
}
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig)

1
jest.setup.js Normal file
View File

@@ -0,0 +1 @@
import '@testing-library/jest-dom'

View File

@@ -1,6 +1,14 @@
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "standalone",
turbopack: {
rules: {
"*.svg": {
loaders: ["@svgr/webpack"],
as: "*.js",
},
},
},
webpack(config) {
config.module.rules.push({
test: /\.svg$/,

4583
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -10,6 +10,9 @@
"build": "refine build",
"start": "refine start",
"lint": "next lint",
"test": "jest",
"test:watch": "jest --watch",
"test:coverage": "jest --coverage",
"refine": "refine"
},
"dependencies": {
@@ -22,12 +25,12 @@
"@mui/x-data-grid": "^7.22.2",
"@mui/x-date-pickers": "^8.12.0",
"@refinedev/cli": "^2.16.50",
"@refinedev/core": "^5.0.6",
"@refinedev/core": "^5.0.8",
"@refinedev/devtools": "^2.0.3",
"@refinedev/kbar": "^2.0.1",
"@refinedev/mui": "^7.0.1",
"@refinedev/mui": "^8.0.0",
"@refinedev/nextjs-router": "^7.0.4",
"@refinedev/react-hook-form": "^5.0.3",
"@refinedev/react-hook-form": "^5.0.4",
"@refinedev/simple-rest": "^6.0.1",
"@tailwindcss/postcss": "^4.1.13",
"@turf/turf": "^7.2.0",
@@ -37,7 +40,7 @@
"echarts": "^6.0.0",
"echarts-for-react": "^3.0.5",
"js-cookie": "^3.0.5",
"next": "15.5.9",
"next": "^16.1.6",
"next-auth": "^4.24.5",
"ol": "^10.7.0",
"postcss": "^8.5.6",
@@ -46,18 +49,30 @@
"react-draggable": "^4.5.0",
"react-icons": "^5.5.0",
"react-window": "^1.8.10",
"tailwindcss": "^4.1.13"
"tailwindcss": "^4.1.13",
"zustand": "^5.0.11"
},
"overrides": {
"fast-xml-parser": "5.3.4"
},
"devDependencies": {
"@svgr/webpack": "^8.1.0",
"@testing-library/dom": "^10.4.1",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@types/jest": "^30.0.0",
"@types/js-cookie": "^3.0.6",
"@types/node": "^20",
"@types/react": "^19.1.0",
"@types/react-dom": "^19.1.0",
"@types/react-window": "^1.8.8",
"baseline-browser-mapping": "^2.9.19",
"cross-env": "^7.0.3",
"eslint": "^8",
"eslint-config-next": "^15.0.3",
"eslint": "^9.39.2",
"eslint-config-next": "^16.1.6",
"jest": "^30.2.0",
"jest-environment-jsdom": "^30.2.0",
"ts-jest": "^29.4.6",
"typescript": "^5.8.3"
},
"refine": {

View File

@@ -0,0 +1 @@
<?xml version="1.0" standalone="no"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg t="1769741101058" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6910" xmlns:xlink="http://www.w3.org/1999/xlink" width="200" height="200"><path d="M102.4 921.6a25.6 25.6 0 0 1 25.6-25.6h768a25.6 25.6 0 0 1 0 51.2h-768A25.6 25.6 0 0 1 102.4 921.6zM638.464 612.5056A177.664 177.664 0 0 1 512 665.6a177.664 177.664 0 0 1-126.464-53.0944A183.6544 183.6544 0 0 1 332.8 483.328c0-20.224 10.0352-54.6304 31.232-100.352 20.3264-43.8272 47.9232-91.8016 76.1344-136.8576 25.6512-40.96 51.4048-78.7456 71.8336-107.776 20.48 29.0304 46.1824 66.816 71.8336 107.776 28.2112 45.056 55.808 93.0304 76.1344 136.8576 21.1968 45.7216 31.232 80.128 31.232 100.352 0 48.64-19.0464 95.0272-52.736 129.1264zM480.3584 94.464C417.28 182.9376 281.6 384.512 281.6 483.328c0 61.952 24.2688 121.344 67.4816 165.12A228.864 228.864 0 0 0 512 716.8a228.864 228.864 0 0 0 162.9184-68.3008A234.8544 234.8544 0 0 0 742.4 483.328c0-98.8672-135.68-300.4416-198.8096-388.9152C524.544 67.584 512 51.2 512 51.2s-12.4928 16.384-31.6416 43.264z" fill="#03a86b" p-id="6911"></path><path d="M409.6 870.4a51.2 51.2 0 1 1-102.4 0 51.2 51.2 0 0 1 102.4 0z" fill="#03a86b" p-id="6912"></path><path d="M640 780.8a38.4 38.4 0 1 1-76.8 0 38.4 38.4 0 0 1 76.8 0zM778.24 675.84a30.72 30.72 0 1 1-61.44 0 30.72 30.72 0 0 1 61.44 0zM317.44 706.56a30.72 30.72 0 1 1-61.44 0 30.72 30.72 0 0 1 61.44 0zM419.7376 435.2a25.6 25.6 0 0 1 18.0736 31.3344 76.8 76.8 0 0 0 94.0544 94.0544 25.6 25.6 0 1 1 13.2608 49.4592 128 128 0 0 1-156.7744-156.7744 25.6 25.6 0 0 1 31.3856-18.0736z" fill="#03a86b" p-id="6913"></path></svg>

After

Width:  |  Height:  |  Size: 1.7 KiB

View File

@@ -8,7 +8,7 @@ export default function Home() {
return (
<div className="relative w-full h-full overflow-hidden">
<MapComponent>
<MapToolbar queryType="scheme" />
<MapToolbar queryType="scheme" schemeType="burst_analysis" />
<BurstPipeAnalysisPanel />
</MapComponent>
</div>

View File

@@ -0,0 +1,5 @@
import { MapSkeleton } from "@components/loading/MapSkeleton";
export default function Loading() {
return <MapSkeleton />;
}

View File

@@ -0,0 +1,16 @@
"use client";
import MapComponent from "@app/OlMap/MapComponent";
import MapToolbar from "@app/OlMap/Controls/Toolbar";
import FlushingAnalysisPanel from "@/components/olmap/FlushingAnalysis/FlushingAnalysisPanel";
export default function Home() {
return (
<div className="relative w-full h-full overflow-hidden">
<MapComponent>
<MapToolbar queryType="scheme" schemeType="flushing_analysis" />
<FlushingAnalysisPanel />
</MapComponent>
</div>
);
}

View File

@@ -0,0 +1,5 @@
import { MapSkeleton } from "@components/loading/MapSkeleton";
export default function Loading() {
return <MapSkeleton />;
}

View File

@@ -0,0 +1,16 @@
"use client";
import MapComponent from "@app/OlMap/MapComponent";
import MapToolbar from "@app/OlMap/Controls/Toolbar";
import WaterQualityPanel from "@/components/olmap/ContaminantSimulation/WaterQualityPanel";
export default function Home() {
return (
<div className="relative w-full h-full overflow-hidden">
<MapComponent>
<MapToolbar queryType="scheme" schemeType="contaminant_analysis" />
<WaterQualityPanel />
</MapComponent>
</div>
);
}

View File

@@ -1,7 +1,6 @@
import type { Metadata } from "next";
import { cookies } from "next/headers";
import React, { Suspense } from "react";
import { RefineContext } from "../_refine_context";
import authOptions from "@app/api/auth/[...nextauth]/options";
import { Header } from "@components/header";
@@ -33,22 +32,20 @@ export default async function MainLayout({
}
return (
<RefineContext defaultMode={defaultMode}>
<ThemedLayout
Header={Header}
Title={Title}
childrenBoxProps={{
sx: { height: "100vh", p: 0 },
}}
containerBoxProps={{
sx: { height: "100%" },
}}
>
<Suspense fallback={<MapSkeleton />}>
{children}
</Suspense>
</ThemedLayout>
</RefineContext>
<ThemedLayout
Header={Header}
Title={Title}
childrenBoxProps={{
sx: { height: "100vh", p: 0 },
}}
containerBoxProps={{
sx: { height: "100%" },
}}
>
<Suspense fallback={<MapSkeleton />}>
{children}
</Suspense>
</ThemedLayout>
);
}

View File

@@ -179,7 +179,7 @@ const BaseLayers: React.FC = () => {
};
return (
<div className="absolute right-17 bottom-8 z-1300">
<div className="absolute right-17 bottom-11 z-1300">
<div
className="w-20 h-20 bg-white rounded-xl drop-shadow-xl shadow-black"
onMouseEnter={handleEnter}

View File

@@ -34,6 +34,7 @@ import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import { DateTimePicker, LocalizationProvider } from "@mui/x-date-pickers";
import { zhCN as pickerZhCN } from "@mui/x-date-pickers/locales";
import config from "@/config/config";
import { apiFetch } from "@/lib/apiFetch";
dayjs.extend(utc);
dayjs.extend(timezone);
@@ -103,10 +104,10 @@ const fetchFromBackend = async (
if (type === "none") {
// 查询清洗值和监测值
const [cleanedRes, rawRes] = await Promise.all([
fetch(cleanedDataUrl)
apiFetch(cleanedDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
fetch(rawDataUrl)
apiFetch(rawDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
]);
@@ -126,13 +127,13 @@ const fetchFromBackend = async (
} else if (type === "scheme") {
// 查询策略模拟值、清洗值和监测值
const [cleanedRes, rawRes, schemeSimRes] = await Promise.all([
fetch(cleanedDataUrl)
apiFetch(cleanedDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
fetch(rawDataUrl)
apiFetch(rawDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
fetch(schemeSimulationDataUrl)
apiFetch(schemeSimulationDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
]);
@@ -178,13 +179,13 @@ const fetchFromBackend = async (
} else {
// realtime: 查询模拟值、清洗值和监测值
const [cleanedRes, rawRes, simulationRes] = await Promise.all([
fetch(cleanedDataUrl)
apiFetch(cleanedDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
fetch(rawDataUrl)
apiFetch(rawDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
fetch(simulationDataUrl)
apiFetch(simulationDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
]);

View File

@@ -28,10 +28,21 @@ const LayerControl: React.FC = () => {
} = data;
const [layerItems, setLayerItems] = useState<LayerItem[]>([]);
const layerOrder = [
"junctions",
"reservoirs",
"tanks",
"pipes",
"pumps",
"valves",
"scada",
"waterflowLayer",
"junctionContourLayer",
];
// 更新图层列表
const updateLayers = useCallback(() => {
if (!map || !data) return;
const { deckLayer } = data;
const items: LayerItem[] = [];
@@ -93,19 +104,6 @@ const LayerControl: React.FC = () => {
});
}
// 3. 定义图层显示顺序和过滤白名单
const layerOrder = [
"junctions",
"reservoirs",
"tanks",
"pipes",
"pumps",
"valves",
"scada",
"waterflowLayer",
"junctionContourLayer",
];
// 过滤并排序
const sortedItems = items
.filter((item) => layerOrder.includes(item.id))
@@ -116,7 +114,7 @@ const LayerControl: React.FC = () => {
});
setLayerItems(sortedItems);
}, [map, isWaterflowLayerAvailable, isContourLayerAvailable]);
}, [map, deckLayer, isWaterflowLayerAvailable, isContourLayerAvailable]);
useEffect(() => {
updateLayers();
@@ -146,7 +144,7 @@ const LayerControl: React.FC = () => {
}
setLayerItems((prev) =>
prev.map((i) => (i.id === item.id ? { ...i, visible: checked } : i))
prev.map((i) => (i.id === item.id ? { ...i, visible: checked } : i)),
);
};

View File

@@ -1,10 +1,12 @@
import React, { useEffect, useState } from "react";
import React, { useEffect, useState, useRef } from "react";
import { useMap } from "../MapComponent";
import { ScaleLine } from "ol/control";
const Scale: React.FC = () => {
const map = useMap();
const [zoomLevel, setZoomLevel] = useState(0);
const [coordinates, setCoordinates] = useState<[number, number]>([0, 0]);
const scaleLineRef = useRef<HTMLDivElement>(null);
useEffect(() => {
if (!map) return;
@@ -28,19 +30,58 @@ const Scale: React.FC = () => {
// Initialize values
updateZoomLevel();
// ScaleLine control
const scaleControl = new ScaleLine({
target: scaleLineRef.current || undefined,
units: "metric",
bar: false,
steps: 4,
text: true,
minWidth: 64,
});
map.addControl(scaleControl);
return () => {
map.un("moveend", updateZoomLevel);
map.un("pointermove", updateCoordinates);
map.removeControl(scaleControl);
};
}, [map]);
return (
<div className="absolute bottom-0 right-0 flex col-auto px-2 bg-white bg-opacity-70 text-black rounded-tl shadow-md text-sm z-1300">
<div className="px-1">: {zoomLevel.toFixed(1)}</div>
<div className="px-1">
: {coordinates[0]}, {coordinates[1]}
<>
<style>
{`
.custom-scale-line .ol-scale-line {
position: static;
background: transparent;
padding: 0;
}
.custom-scale-line .ol-scale-line-inner {
border: 1px solid #475569;
border-top: none;
color: #334155;
font-size: 0.75rem;
font-weight: 600;
transition: all 0.3s;
}
`}
</style>
<div className="absolute bottom-0 right-0 flex items-center gap-2 px-3 py-1.5 bg-white/90 hover:bg-white rounded-tl-xl shadow-lg backdrop-blur-sm text-xs font-medium text-slate-700 z-1300 transition-all duration-300 pointer-events-auto">
<div
ref={scaleLineRef}
className="custom-scale-line flex items-center justify-center min-w-[60px]"
/>
<div className="h-3 w-px bg-slate-300 mx-1" />
<div className="min-w-[60px] text-center">
: {zoomLevel.toFixed(1)}
</div>
<div className="h-3 w-px bg-slate-300 mx-1" />
<div className="tabular-nums min-w-[140px] text-center">
: {coordinates[0]}, {coordinates[1]}
</div>
</div>
</div>
</>
);
};

View File

@@ -28,6 +28,7 @@ import { TbRewindBackward15, TbRewindForward15 } from "react-icons/tb";
import { FiSkipBack, FiSkipForward } from "react-icons/fi";
import { useData } from "../MapComponent";
import { config, NETWORK_NAME } from "@/config/config";
import { apiFetch } from "@/lib/apiFetch";
import { useMap } from "../MapComponent";
interface TimelineProps {
@@ -117,11 +118,11 @@ const Timeline: React.FC<TimelineProps> = ({
nodeRecords = nodeCacheRef.current.get(nodeCacheKey)!;
} else {
disableDateSelection && schemeName
? (nodePromise = fetch(
? (nodePromise = apiFetch(
// `${config.BACKEND_URL}/queryallschemerecordsbytimeproperty/?querytime=${query_time}&type=node&property=${junctionProperties}&schemename=${schemeName}`
`${config.BACKEND_URL}/api/v1/scheme/query/by-scheme-time-property?scheme_type=${schemeType}&scheme_name=${schemeName}&query_time=${query_time}&type=node&property=${junctionProperties}`,
))
: (nodePromise = fetch(
: (nodePromise = apiFetch(
// `${config.BACKEND_URL}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=node&property=${junctionProperties}`
`${config.BACKEND_URL}/api/v1/realtime/query/by-time-property?query_time=${query_time}&type=node&property=${junctionProperties}`,
));
@@ -138,11 +139,11 @@ const Timeline: React.FC<TimelineProps> = ({
linkRecords = linkCacheRef.current.get(linkCacheKey)!;
} else {
disableDateSelection && schemeName
? (linkPromise = fetch(
? (linkPromise = apiFetch(
// `${config.BACKEND_URL}/queryallschemerecordsbytimeproperty/?querytime=${query_time}&type=link&property=${pipeProperties}&schemename=${schemeName}`
`${config.BACKEND_URL}/api/v1/scheme/query/by-scheme-time-property?scheme_type=${schemeType}&scheme_name=${schemeName}&query_time=${query_time}&type=link&property=${pipeProperties}`,
))
: (linkPromise = fetch(
: (linkPromise = apiFetch(
// `${config.BACKEND_URL}/queryallrecordsbytimeproperty/?querytime=${query_time}&type=link&property=${pipeProperties}`
`${config.BACKEND_URL}/api/v1/realtime/query/by-time-property?query_time=${query_time}&type=link&property=${pipeProperties}`,
));
@@ -513,7 +514,7 @@ const Timeline: React.FC<TimelineProps> = ({
duration: calculatedInterval,
};
const response = await fetch(
const response = await apiFetch(
`${config.BACKEND_URL}/api/v1/runsimulationmanuallybydate/`,
{
method: "POST",

View File

@@ -20,16 +20,19 @@ import { handleMapClickSelectFeatures as mapClickSelectFeatures } from "@/utils/
import { useNotification } from "@refinedev/core";
import { config } from "@/config/config";
import { apiFetch } from "@/lib/apiFetch";
// 添加接口定义隐藏按钮的props
interface ToolbarProps {
hiddenButtons?: string[]; // 可选的隐藏按钮列表,例如 ['info', 'draw', 'style']
queryType?: string; // 可选的查询类型参数
schemeType?: string; // 可选的方案类型参数
HistoryPanel?: React.FC<any>; // 可选的自定义历史数据面板
}
const Toolbar: React.FC<ToolbarProps> = ({
hiddenButtons,
queryType,
schemeType,
HistoryPanel,
}) => {
const map = useMap();
@@ -386,12 +389,12 @@ const Toolbar: React.FC<ToolbarProps> = ({
const querytime = dateObj.toISOString(); // 例如 "2025-09-16T16:30:00.000Z"
let response;
if (queryType === "scheme") {
response = await fetch(
response = await apiFetch(
// `${config.BACKEND_URL}/queryschemesimulationrecordsbyidtime/?scheme_name=${schemeName}&id=${id}&querytime=${querytime}&type=${type}`
`${config.BACKEND_URL}/api/v1/scheme/query/by-id-time?scheme_name=${schemeName}&id=${id}&type=${type}&query_time=${querytime}`,
`${config.BACKEND_URL}/api/v1/scheme/query/by-id-time?scheme_type=${schemeType}&scheme_name=${schemeName}&id=${id}&type=${type}&query_time=${querytime}`,
);
} else {
response = await fetch(
response = await apiFetch(
// `${config.BACKEND_URL}/querysimulationrecordsbyidtime/?id=${id}&querytime=${querytime}&type=${type}`
`${config.BACKEND_URL}/api/v1/realtime/query/by-id-time?id=${id}&type=${type}&query_time=${querytime}`,
);
@@ -400,7 +403,13 @@ const Toolbar: React.FC<ToolbarProps> = ({
throw new Error("API request failed");
}
const data = await response.json();
setComputedProperties(data.results[0] || {});
if (!data.result || data.result.length === 0) {
setComputedProperties({});
} else {
setComputedProperties(data.result[0] || {});
console.log("查询到的计算属性:", data.result[0]);
console.log(computedProperties);
}
} catch (error) {
console.error("Error querying computed properties:", error);
setComputedProperties({});
@@ -408,7 +417,7 @@ const Toolbar: React.FC<ToolbarProps> = ({
};
// 仅当 currentTime 有效时查询
if (currentTime !== -1 && queryType) queryComputedProperties();
}, [highlightFeatures, currentTime, selectedDate]);
}, [highlightFeatures, currentTime, selectedDate, queryType, schemeName, schemeType]);
// 从要素属性中提取属性面板需要的数据
const getFeatureProperties = useCallback(() => {

View File

@@ -30,7 +30,7 @@ const Zoom: React.FC = () => {
};
return (
<div className="absolute right-4 bottom-8 z-1300">
<div className="absolute right-4 bottom-11 z-1300">
<div className="w-8 h-26 flex flex-col gap-2 items-center">
<div className="w-8 h-8 bg-gray-50 flex items-center justify-center rounded-xl drop-shadow-xl shadow-black">
<button

View File

@@ -1,5 +1,6 @@
"use client";
import { config } from "@/config/config";
import { useProject } from "@/contexts/ProjectContext";
import React, {
createContext,
useContext,
@@ -75,10 +76,6 @@ interface DataContextType {
const MapContext = createContext<OlMap | undefined>(undefined);
const DataContext = createContext<DataContextType | undefined>(undefined);
const MAP_EXTENT = config.MAP_EXTENT as [number, number, number, number];
const MAP_URL = config.MAP_URL;
const MAP_WORKSPACE = config.MAP_WORKSPACE;
const MAP_VIEW_STORAGE_KEY = `${MAP_WORKSPACE}_map_view`; // 持久化 key
// 添加防抖函数
function debounce<F extends (...args: any[]) => any>(func: F, waitFor: number) {
let timeout: ReturnType<typeof setTimeout> | null = null;
@@ -99,6 +96,17 @@ export const useData = () => {
};
const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
const project = useProject();
const MAP_WORKSPACE = project?.workspace || config.MAP_WORKSPACE;
const MAP_EXTENT = (project?.extent || config.MAP_EXTENT) as [
number,
number,
number,
number,
];
const MAP_URL = config.MAP_URL;
const MAP_VIEW_STORAGE_KEY = `${MAP_WORKSPACE}_map_view`; // 持久化 key
const mapRef = useRef<HTMLDivElement | null>(null);
const deckLayerRef = useRef<DeckLayer | null>(null);
@@ -111,7 +119,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
const [schemeName, setSchemeName] = useState<string>(""); // 当前方案名称
// 记录 id、对应属性的计算值
const [currentJunctionCalData, setCurrentJunctionCalData] = useState<any[]>(
[]
[],
);
const [currentPipeCalData, setCurrentPipeCalData] = useState<any[]>([]);
// junctionData 和 pipeData 分别缓存瓦片解析后节点和管道的数据,用于 deck.gl 定位、标签渲染
@@ -180,7 +188,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
setPipeData(tilePipeDataBuffer.current);
tilePipeDataBuffer.current = [];
}
}, 100)
}, 100),
);
const setJunctionData = (newData: any[]) => {
@@ -317,7 +325,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
scale: 0.12,
anchor: [0.5, 0.5],
}),
})
}),
);
}
return styles;
@@ -459,7 +467,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
const scadaLayer = new VectorLayer({
source: scadaSource,
style: scadaStyle,
// extent: extent, // 设置图层范围
extent: MAP_EXTENT, // 设置图层范围
maxZoom: 24,
minZoom: 11,
properties: {
@@ -500,7 +508,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
const uniqueData = Array.from(data.values());
if (uniqueData.length > 0) {
uniqueData.forEach((item) =>
tileJunctionDataBuffer.current.push(item)
tileJunctionDataBuffer.current.push(item),
);
debouncedUpdateData.current();
}
@@ -709,7 +717,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
if (center && typeof zoom === "number") {
localStorage.setItem(
MAP_VIEW_STORAGE_KEY,
JSON.stringify({ center, zoom })
JSON.stringify({ center, zoom }),
);
}
} catch (err) {
@@ -762,7 +770,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
map.dispose();
deck.finalize();
};
}, []);
}, [MAP_WORKSPACE, MAP_EXTENT]);
// 当数据变化时,更新 deck.gl 图层
useEffect(() => {
@@ -947,27 +955,12 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
// 动画循环
const animate = () => {
if (!flowAnimation.current) {
try {
deckLayer.removeDeckLayer("waterflowLayer");
} catch (error) {
console.error("Error in animation loop:", error);
}
return;
}
// 动画总时长(秒)
if (mergedPipeData.length === 0) {
animationFrameId = requestAnimationFrame(animate);
return;
}
const animationDuration = 10;
// 缓冲时间(秒)
const bufferTime = 2;
// 完整循环周期
const loopLength = animationDuration + bufferTime;
// 确保时间范围与你的时间戳数据匹配
const currentTime = (Date.now() / 1000) % loopLength; // (0,12) 之间循环
// console.log("Current Time:", currentTime);
const currentTime = (Date.now() / 1000) % loopLength;
const waterflowLayer = new TripsLayer({
id: "waterflowLayer",
name: "水流",
@@ -981,7 +974,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
visible:
isWaterflowLayerAvailable &&
showWaterflowLayer &&
flowAnimation.current &&
flowAnimation.current && // 保持动画标志作为可见性的一部分
currentZoom >= 12 &&
currentZoom <= 24,
widthMinPixels: 5,
@@ -990,13 +983,17 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
trailLength: 2, // 水流尾迹淡出时间
currentTime: currentTime,
});
if (deckLayer.getDeckLayerById("waterflowLayer")) {
deckLayer.updateDeckLayer("waterflowLayer", waterflowLayer);
} else {
deckLayer.addDeckLayer(waterflowLayer);
}
// 继续请求动画帧,每帧执行一次函数
animationFrameId = requestAnimationFrame(animate);
// 只有在需要动画时才请求下一帧,但图层已经添加到了 deckLayer 中
if (flowAnimation.current) {
animationFrameId = requestAnimationFrame(animate);
}
};
animate();
@@ -1007,6 +1004,7 @@ const MapComponent: React.FC<MapComponentProps> = ({ children }) => {
}
};
}, [
currentPipeCalData,
currentZoom,
mergedPipeData,
pipeText,

View File

@@ -8,12 +8,14 @@ import {
} from "@refinedev/mui";
import { SessionProvider, signIn, signOut, useSession } from "next-auth/react";
import { usePathname } from "next/navigation";
import React from "react";
import React, { useEffect } from "react";
import routerProvider from "@refinedev/nextjs-router";
import { ColorModeContextProvider } from "@contexts/color-mode";
import { dataProvider } from "@providers/data-provider";
import { ProjectProvider } from "@/contexts/ProjectContext";
import { useAuthStore } from "@/store/authStore";
import { LiaNetworkWiredSolid } from "react-icons/lia";
import { TbDatabaseEdit } from "react-icons/tb";
@@ -21,6 +23,7 @@ import { LuReplace } from "react-icons/lu";
import { AiOutlineSecurityScan } from "react-icons/ai";
import { TbLocationPin } from "react-icons/tb";
import { AiOutlinePartition } from "react-icons/ai";
import { MdWater, MdOutlineWaterDrop, MdCleaningServices } from "react-icons/md";
type RefineContextProps = {
defaultMode?: string;
@@ -31,7 +34,9 @@ export const RefineContext = (
) => {
return (
<SessionProvider>
<App {...props} />
<ProjectProvider>
<App {...props} />
</ProjectProvider>
</SessionProvider>
);
};
@@ -43,6 +48,11 @@ type AppProps = {
const App = (props: React.PropsWithChildren<AppProps>) => {
const { data, status } = useSession();
const to = usePathname();
const setAccessToken = useAuthStore((state) => state.setAccessToken);
useEffect(() => {
setAccessToken(typeof data?.accessToken === "string" ? data.accessToken : null);
}, [data?.accessToken, setAccessToken]);
if (status === "loading") {
return <span>loading...</span>;
@@ -99,6 +109,7 @@ const App = (props: React.PropsWithChildren<AppProps>) => {
if (data?.user) {
const { user } = data;
return {
id: user.id,
name: user.name,
avatar: user.image,
};
@@ -154,11 +165,37 @@ const App = (props: React.PropsWithChildren<AppProps>) => {
},
},
{
name: "风险分析定位",
list: "/risk-analysis-location",
name: "Hydraulic Simulation",
meta: {
icon: <MdWater className="w-6 h-6" />,
label: "事件模拟",
},
},
{
name: "爆管分析定位",
list: "/hydraulic-simulation/pipe-burst-analysis",
meta: {
parent: "Hydraulic Simulation",
icon: <TbLocationPin className="w-6 h-6" />,
label: "风险分析定位",
label: "爆管分析定位",
},
},
{
name: "水质模拟",
list: "/hydraulic-simulation/water-quality-simulation",
meta: {
parent: "Hydraulic Simulation",
icon: <MdOutlineWaterDrop className="w-6 h-6" />,
label: "水质模拟",
},
},
{
name: "管道冲洗",
list: "/hydraulic-simulation/pipe-flushing",
meta: {
parent: "Hydraulic Simulation",
icon: <MdCleaningServices className="w-6 h-6" />,
label: "管道冲洗",
},
},
{

View File

@@ -1,7 +1,8 @@
import { NextAuthOptions } from "next-auth";
import KeycloakProvider from "next-auth/providers/keycloak";
import Avatar from "@assets/avatar/avatar-small.jpeg";
const authOptions = {
const authOptions: NextAuthOptions = {
// Configure one or more authentication providers
providers: [
KeycloakProvider({
@@ -19,6 +20,26 @@ const authOptions = {
}),
],
secret: process.env.NEXTAUTH_SECRET,
callbacks: {
jwt: async ({ token, profile, account }) => {
if (profile?.sub) {
token.sub = profile.sub;
}
if (account?.access_token) {
token.accessToken = account.access_token;
}
return token;
},
session: async ({ session, token }) => {
if (session.user && token.sub) {
session.user.id = token.sub;
}
if (token.accessToken) {
session.accessToken = token.accessToken;
}
return session;
},
},
};
export default authOptions;

View File

@@ -3,29 +3,78 @@
import { ColorModeContext } from "@contexts/color-mode";
import DarkModeOutlined from "@mui/icons-material/DarkModeOutlined";
import LightModeOutlined from "@mui/icons-material/LightModeOutlined";
import Logout from "@mui/icons-material/Logout";
import SwapHoriz from "@mui/icons-material/SwapHoriz";
import AppBar from "@mui/material/AppBar";
import Avatar from "@mui/material/Avatar";
import ButtonBase from "@mui/material/ButtonBase";
import Divider from "@mui/material/Divider";
import IconButton from "@mui/material/IconButton";
import ListItemIcon from "@mui/material/ListItemIcon";
import ListItemText from "@mui/material/ListItemText";
import Menu from "@mui/material/Menu";
import MenuItem from "@mui/material/MenuItem";
import Stack from "@mui/material/Stack";
import Toolbar from "@mui/material/Toolbar";
import Typography from "@mui/material/Typography";
import { useGetIdentity } from "@refinedev/core";
import { useGetIdentity, useLogout } from "@refinedev/core";
import { HamburgerMenu, RefineThemedLayoutHeaderProps } from "@refinedev/mui";
import React, { useContext } from "react";
import React, { useContext, useState } from "react";
import { ProjectSelector } from "@components/project/ProjectSelector";
import { setMapExtent, setMapWorkspace, setNetworkName } from "@config/config";
import { useProjectStore } from "@/store/projectStore";
type IUser = {
id: number;
name: string;
avatar: string;
id?: string;
name?: string;
avatar?: string;
};
export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
sticky = true,
}) => {
const { mode, setMode } = useContext(ColorModeContext);
const { mutate: logout } = useLogout();
const [anchorEl, setAnchorEl] = useState<null | HTMLElement>(null);
const [showProjectSelector, setShowProjectSelector] = useState(false);
const open = Boolean(anchorEl);
const setCurrentProjectId = useProjectStore(
(state) => state.setCurrentProjectId,
);
const { data: user } = useGetIdentity<IUser>();
const handleMenuOpen = (event: React.MouseEvent<HTMLElement>) => {
setAnchorEl(event.currentTarget);
};
const handleMenuClose = () => {
setAnchorEl(null);
};
const handleSwitchProjectClick = () => {
handleMenuClose();
setShowProjectSelector(true);
};
const handleProjectSelect = (
projectId: string,
workspace: string,
networkName: string,
extent: number[],
) => {
setMapWorkspace(workspace);
setNetworkName(networkName);
setMapExtent(extent);
localStorage.setItem("NEXT_PUBLIC_MAP_WORKSPACE", workspace);
localStorage.setItem("NEXT_PUBLIC_NETWORK_NAME", networkName);
localStorage.setItem("NEXT_PUBLIC_MAP_EXTENT", extent.join(","));
localStorage.removeItem(`${workspace}_map_view`);
setCurrentProjectId(projectId || networkName || workspace);
setShowProjectSelector(false);
window.location.reload();
};
return (
<AppBar position={sticky ? "sticky" : "relative"}>
<Toolbar>
@@ -52,27 +101,118 @@ export const Header: React.FC<RefineThemedLayoutHeaderProps> = ({
</IconButton>
{(user?.avatar || user?.name) && (
<Stack
direction="row"
gap="16px"
alignItems="center"
justifyContent="center"
>
{user?.name && (
<Typography
sx={{
display: {
xs: "none",
sm: "inline-block",
},
}}
variant="subtitle2"
<>
<ButtonBase
onClick={handleMenuOpen}
sx={{
borderRadius: "30px",
padding: "6px 12px",
marginLeft: "8px",
transition: "all 0.3s ease",
border: "1px solid transparent",
"&:hover": {
backgroundColor:
mode === "dark"
? "rgba(255, 255, 255, 0.05)"
: "rgba(0, 0, 0, 0.04)",
transform: "translateY(-1px)",
border: `1px solid ${mode === "dark"
? "rgba(255, 255, 255, 0.2)"
: "rgba(0, 0, 0, 0.1)"
}`,
boxShadow:
mode === "dark"
? "0 4px 12px rgba(0,0,0,0.3)"
: "0 4px 12px rgba(0,0,0,0.08)",
},
"&:active": {
transform: "translateY(0px)",
boxShadow: "none",
},
}}
>
<Stack
direction="row"
gap="12px"
alignItems="center"
justifyContent="center"
>
{user?.name}
</Typography>
)}
<Avatar src={user?.avatar} alt={user?.name} />
</Stack>
{user?.name && (
<Typography
sx={{
display: {
xs: "none",
sm: "inline-block",
},
fontWeight: 500,
}}
variant="subtitle2"
>
{user?.name}
</Typography>
)}
<Avatar
src={user?.avatar}
alt={user?.name}
sx={{
width: 32,
height: 32,
border: `2px solid ${mode === "dark"
? "rgba(255,255,255,0.2)"
: "rgba(0,0,0,0.1)"
}`,
transition: "transform 0.3s ease",
".MuiButtonBase-root:hover &": {
transform: "rotate(5deg) scale(1.05)",
borderColor: "primary.main",
},
}}
/>
</Stack>
</ButtonBase>
<Menu
anchorEl={anchorEl}
open={open}
onClose={handleMenuClose}
transformOrigin={{ horizontal: "right", vertical: "top" }}
anchorOrigin={{ horizontal: "right", vertical: "bottom" }}
PaperProps={{
sx: {
borderRadius: 2,
minWidth: 180,
marginTop: "8px",
background:
mode === "dark"
? "rgba(30, 30, 30, 0.95)"
: "rgba(255, 255, 255, 0.95)",
backdropFilter: "blur(10px)",
boxShadow:
mode === "dark"
? "0px 4px 20px rgba(0, 0, 0, 0.5)"
: "0px 4px 20px rgba(0, 0, 0, 0.1)",
},
}}
>
<MenuItem onClick={handleSwitchProjectClick}>
<ListItemIcon>
<SwapHoriz fontSize="small" />
</ListItemIcon>
<ListItemText></ListItemText>
</MenuItem>
<Divider />
<MenuItem onClick={() => logout()}>
<ListItemIcon>
<Logout fontSize="small" />
</ListItemIcon>
<ListItemText></ListItemText>
</MenuItem>
</Menu>
<ProjectSelector
open={showProjectSelector}
onSelect={handleProjectSelect}
onClose={() => setShowProjectSelector(false)}
/>
</>
)}
</Stack>
</Stack>

View File

@@ -1,4 +1,4 @@
import { Box, Skeleton } from "@mui/material";
import { Box, Skeleton, CircularProgress } from "@mui/material";
/**
* 地图页面骨架屏组件
@@ -26,7 +26,24 @@ export function MapSkeleton() {
}}
/>
{/* 左侧工具栏骨架 */}
{/* 中央加载指示器 */}
<Box
sx={{
position: "absolute",
top: "50%",
left: "50%",
transform: "translate(-50%, -50%)",
zIndex: 10,
display: "flex",
flexDirection: "column",
alignItems: "center",
gap: 2,
}}
>
<CircularProgress size={48} thickness={4} color="primary" />
</Box>
{/* 左侧工具栏骨架 (垂直) */}
<Box
sx={{
position: "absolute",
@@ -34,100 +51,100 @@ export function MapSkeleton() {
left: 20,
display: "flex",
flexDirection: "column",
gap: 1,
gap: 1.5,
zIndex: 5,
}}
>
{[1, 2, 3, 4, 5].map((i) => (
{[1, 2, 3, 4].map((i) => (
<Skeleton
key={i}
variant="rectangular"
width={48}
height={48}
variant="circular"
width={40}
height={40}
animation="wave"
sx={{ borderRadius: 1 }}
sx={{ boxShadow: 1 }}
/>
))}
</Box>
{/* 右侧控制面板骨架 */}
{/* 右侧控制面板骨架 (抽屉式) */}
<Box
sx={{
position: "absolute",
top: 20,
right: 20,
width: 320,
top: 0,
right: 0,
width: { xs: "100%", sm: 360 },
height: "100%",
bgcolor: "background.paper",
borderRadius: 2,
p: 2,
boxShadow: 3,
borderLeft: 1,
borderColor: "divider",
p: 3,
zIndex: 5,
display: { xs: "none", md: "flex" },
flexDirection: "column",
boxShadow: -2,
}}
>
<Skeleton width="60%" height={32} animation="wave" sx={{ mb: 2 }} />
<Skeleton width="100%" height={24} animation="wave" sx={{ mb: 1 }} />
<Skeleton width="80%" height={24} animation="wave" sx={{ mb: 1 }} />
<Skeleton width="90%" height={24} animation="wave" sx={{ mb: 2 }} />
<Skeleton
variant="rectangular"
width="100%"
height={200}
animation="wave"
sx={{ borderRadius: 1 }}
/>
<Skeleton variant="text" width="60%" height={40} sx={{ mb: 3 }} />
{/* 面板内容区块 */}
<Box sx={{ flex: 1, overflow: "hidden" }}>
<Skeleton variant="rectangular" width="100%" height={100} sx={{ mb: 2, borderRadius: 1 }} />
<Skeleton variant="text" width="40%" height={24} sx={{ mb: 1 }} />
<Skeleton variant="rectangular" width="100%" height={180} sx={{ mb: 2, borderRadius: 1 }} />
<Box sx={{ mt: 2 }}>
{[1, 2, 3].map((i) => (
<Box key={i} sx={{ display: "flex", gap: 2, mb: 2 }}>
<Skeleton variant="circular" width={36} height={36} />
<Box sx={{ flex: 1 }}>
<Skeleton variant="text" width="80%" />
<Skeleton variant="text" width="50%" />
</Box>
</Box>
))}
</Box>
</Box>
</Box>
{/* 底部时间轴骨架 */}
{/* 底部时间轴/控制条骨架 */}
<Box
sx={{
position: "absolute",
bottom: 20,
bottom: 30,
left: "50%",
transform: "translateX(-50%)",
width: "60%",
width: { xs: "90%", md: "60%" },
height: 64,
bgcolor: "background.paper",
borderRadius: 2,
p: 2,
borderRadius: 4,
boxShadow: 3,
p: 2,
display: "flex",
alignItems: "center",
gap: 2,
zIndex: 5,
}}
>
<Skeleton width="100%" height={40} animation="wave" />
<Skeleton variant="circular" width={32} height={32} />
<Skeleton variant="rectangular" width="100%" height={8} sx={{ borderRadius: 4 }} />
<Skeleton variant="text" width={40} />
</Box>
{/* 缩放控制骨架 */}
{/* 缩放控制骨架 (右下) */}
<Box
sx={{
position: "absolute",
bottom: 100,
right: 20,
bottom: 110,
right: { xs: 20, md: 380 }, // Adjust if drawer is open
display: "flex",
flexDirection: "column",
gap: 1,
zIndex: 4,
}}
>
<Skeleton
variant="rectangular"
width={40}
height={40}
animation="wave"
sx={{ borderRadius: 1 }}
/>
<Skeleton
variant="rectangular"
width={40}
height={40}
animation="wave"
sx={{ borderRadius: 1 }}
/>
</Box>
{/* 比例尺骨架 */}
<Box
sx={{
position: "absolute",
bottom: 20,
left: 20,
}}
>
<Skeleton width={120} height={24} animation="wave" />
<Skeleton variant="rectangular" width={36} height={36} sx={{ borderRadius: 1 }} />
<Skeleton variant="rectangular" width={36} height={36} sx={{ borderRadius: 1 }} />
</Box>
</Box>
);

View File

@@ -23,7 +23,7 @@ import { Style, Stroke, Icon } from "ol/style";
import { handleMapClickSelectFeatures as mapClickSelectFeatures } from "@/utils/mapQueryService";
import Feature, { FeatureLike } from "ol/Feature";
import { useNotification } from "@refinedev/core";
import axios from "axios";
import { api } from "@/lib/api";
import { config, NETWORK_NAME } from "@/config/config";
import { along, lineString, length, toMercator } from "@turf/turf";
import { Point } from "ol/geom";
@@ -44,7 +44,7 @@ const AnalysisParameters: React.FC = () => {
const [startTime, setStartTime] = useState<Dayjs | null>(dayjs(new Date()));
const [duration, setDuration] = useState<number>(3600);
const [schemeName, setSchemeName] = useState<string>(
"FANGAN" + new Date().getTime()
"FANGAN" + new Date().getTime(),
);
const [network, setNetwork] = useState<string>(NETWORK_NAME);
const [isSelecting, setIsSelecting] = useState<boolean>(false);
@@ -88,7 +88,7 @@ const AnalysisParameters: React.FC = () => {
width: 3,
lineDash: [15, 10],
}),
})
}),
);
const geometry = feature.getGeometry();
const lineCoords =
@@ -115,7 +115,7 @@ const AnalysisParameters: React.FC = () => {
scale: 0.2,
anchor: [0.5, 1],
}),
})
}),
);
}
return styles;
@@ -163,14 +163,14 @@ const AnalysisParameters: React.FC = () => {
// 移除不在highlightFeatures中的
const filtered = prevPipes.filter((pipe) =>
highlightFeatures.some(
(feature) => feature.getProperties().id === pipe.id
)
(feature) => feature.getProperties().id === pipe.id,
),
);
// 添加新的
const newPipes = highlightFeatures
.filter(
(feature) =>
!filtered.some((p) => p.id === feature.getProperties().id)
!filtered.some((p) => p.id === feature.getProperties().id),
)
.map((feature) => {
const properties = feature.getProperties();
@@ -207,7 +207,7 @@ const AnalysisParameters: React.FC = () => {
const featureId = feature.getProperties().id;
setHighlightFeatures((prev) => {
const existingIndex = prev.findIndex(
(f) => f.getProperties().id === featureId
(f) => f.getProperties().id === featureId,
);
if (existingIndex !== -1) {
// 如果已存在,移除
@@ -218,7 +218,7 @@ const AnalysisParameters: React.FC = () => {
}
});
},
[map]
[map],
);
// 开始选择管道
@@ -242,14 +242,14 @@ const AnalysisParameters: React.FC = () => {
const handleRemovePipe = (id: string) => {
// 从高亮features中移除
setHighlightFeatures((prev) =>
prev.filter((f) => f.getProperties().id !== id)
prev.filter((f) => f.getProperties().id !== id),
);
};
const handleAreaChange = (id: string, value: string) => {
const numValue = parseFloat(value) || 0;
setPipePoints((prev) =>
prev.map((pipe) => (pipe.id === id ? { ...pipe, area: numValue } : pipe))
prev.map((pipe) => (pipe.id === id ? { ...pipe, area: numValue } : pipe)),
);
};
@@ -266,30 +266,29 @@ const AnalysisParameters: React.FC = () => {
const burst_ID = pipePoints.map((pipe) => pipe.id);
const burst_size = pipePoints.map((pipe) =>
parseInt(pipe.area.toString(), 10)
parseInt(pipe.area.toString(), 10),
);
// 格式化开始时间,去除秒部分
const modify_pattern_start_time = startTime
? startTime.format("YYYY-MM-DDTHH:mm:00Z")
: "";
const modify_total_duration = duration;
const body = {
name: network,
const params = {
network: network,
modify_pattern_start_time: modify_pattern_start_time,
burst_ID: burst_ID,
burst_size: burst_size,
modify_total_duration: modify_total_duration,
scheme_Name: schemeName,
scheme_name: schemeName,
};
try {
await axios.post(`${config.BACKEND_URL}/api/v1/burst_analysis/`, body, {
headers: {
"Accept-Encoding": "gzip",
"Content-Type": "application/json",
await api.get(`${config.BACKEND_URL}/api/v1/burst_analysis/`, {
params,
paramsSerializer: {
indexes: null, // 移除数组索引,即由 burst_ID[] 变为 burst_ID
},
});
// 更新弹窗为成功状态
open?.({
key: "burst-analysis",
@@ -385,7 +384,7 @@ const AnalysisParameters: React.FC = () => {
key={pipe.id}
className="flex items-center gap-2 p-2 bg-gray-50 rounded"
>
<Typography className="flex-shrink-0 text-sm">
<Typography className="flex-shrink-0 text-sm pl-1">
{pipe.id}
</Typography>
<Typography className="flex-shrink-0 text-sm text-gray-600">

View File

@@ -1,6 +1,6 @@
"use client";
import React, { useEffect, useRef, useState } from "react";
import React, { useState } from "react";
import {
Box,
Drawer,
@@ -16,36 +16,16 @@ import {
Analytics as AnalyticsIcon,
Search as SearchIcon,
MyLocation as MyLocationIcon,
Handyman as HandymanIcon,
} from "@mui/icons-material";
import AnalysisParameters from "./AnalysisParameters";
import SchemeQuery from "./SchemeQuery";
import LocationResults, { LocationResult } from "./LocationResults";
import ContaminantAnalysisParameters from "../ContaminantSimulation/AnalysisParameters";
import ContaminantSchemeQuery from "../ContaminantSimulation/SchemeQuery";
import ContaminantResultsPanel from "../ContaminantSimulation/ResultsPanel";
import axios from "axios";
import LocationResults from "./LocationResults";
import ValveIsolation from "./ValveIsolation";
import { api } from "@/lib/api";
import { config } from "@config/config";
import { useNotification } from "@refinedev/core";
import { useData } from "@app/OlMap/MapComponent";
interface SchemeDetail {
burst_ID: string[];
burst_size: number[];
modify_total_duration: number;
modify_fixed_pump_pattern: any;
modify_valve_opening: any;
modify_variable_pump_pattern: any;
}
interface SchemeRecord {
id: number;
schemeName: string;
type: string;
user: string;
create_time: string;
startTime: string;
// 详情信息
schemeDetail?: SchemeDetail;
}
import { LocationResult, SchemeRecord, ValveIsolationResult } from "./types";
interface TabPanelProps {
children?: React.ReactNode;
@@ -72,25 +52,20 @@ interface BurstPipeAnalysisPanelProps {
onToggle?: () => void;
}
type PanelMode = "burst" | "contaminant";
const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
open: controlledOpen,
onToggle,
}) => {
const [internalOpen, setInternalOpen] = useState(true);
const [currentTab, setCurrentTab] = useState(0);
const [panelMode, setPanelMode] = useState<PanelMode>("burst");
const previousMapText = useRef<{ junction?: string; pipe?: string } | null>(
null
);
const data = useData();
// 持久化方案查询结果
const [schemes, setSchemes] = useState<SchemeRecord[]>([]);
// 定位结果数据
const [locationResults, setLocationResults] = useState<LocationResult[]>([]);
// 关阀分析结果和加载状态
const [valveAnalysisLoading, setValveAnalysisLoading] = useState(false);
const [valveAnalysisResult, setValveAnalysisResult] = useState<ValveIsolationResult | null>(null);
const { open } = useNotification();
@@ -108,28 +83,10 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
setCurrentTab(newValue);
};
useEffect(() => {
if (!data) return;
if (panelMode === "contaminant") {
if (!previousMapText.current) {
previousMapText.current = {
junction: data.junctionText,
pipe: data.pipeText,
};
}
data.setJunctionText?.("quality");
data.setPipeText?.("quality");
} else if (panelMode === "burst" && previousMapText.current) {
data.setJunctionText?.(previousMapText.current.junction || "pressure");
data.setPipeText?.(previousMapText.current.pipe || "flow");
previousMapText.current = null;
}
}, [panelMode, data]);
const handleLocateScheme = async (scheme: SchemeRecord) => {
try {
const response = await axios.get(
`${config.BACKEND_URL}/api/v1/burst-locate-result/${scheme.schemeName}`
const response = await api.get(
`${config.BACKEND_URL}/api/v1/burst-locate-result/${scheme.schemeName}`,
);
setLocationResults(response.data);
setCurrentTab(2); // 切换到定位结果标签页
@@ -144,8 +101,7 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
};
const drawerWidth = 520;
const isBurstMode = panelMode === "burst";
const panelTitle = isBurstMode ? "爆管分析" : "水质模拟";
const panelTitle = "爆管分析";
return (
<>
@@ -221,32 +177,6 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
</Tooltip>
</Box>
{/* Tabs 导航 */}
<Box className="border-b border-gray-200 bg-white">
<Tabs
value={panelMode}
onChange={(_event, value: PanelMode) => setPanelMode(value)}
variant="fullWidth"
sx={{
minHeight: 46,
"& .MuiTab-root": {
minHeight: 46,
textTransform: "none",
fontSize: "0.8rem",
fontWeight: 600,
},
"& .Mui-selected": {
color: "#257DD4",
},
"& .MuiTabs-indicator": {
backgroundColor: "#257DD4",
},
}}
>
<Tab value="burst" label="爆管分析" />
<Tab value="contaminant" label="水质模拟" />
</Tabs>
</Box>
<Box className="border-b border-gray-200 bg-white">
<Tabs
value={currentTab}
@@ -282,38 +212,42 @@ const BurstPipeAnalysisPanel: React.FC<BurstPipeAnalysisPanelProps> = ({
<Tab
icon={<MyLocationIcon fontSize="small" />}
iconPosition="start"
label={isBurstMode ? "定位结果" : "模拟结果"}
label="定位结果"
/>
<Tab
icon={<HandymanIcon fontSize="small" />}
iconPosition="start"
label="关阀分析"
/>
</Tabs>
</Box>
{/* Tab 内容 */}
<TabPanel value={currentTab} index={0}>
{isBurstMode ? (
<AnalysisParameters />
) : (
<ContaminantAnalysisParameters />
)}
<AnalysisParameters />
</TabPanel>
<TabPanel value={currentTab} index={1}>
{isBurstMode ? (
<SchemeQuery
schemes={schemes}
onSchemesChange={setSchemes}
onLocate={handleLocateScheme}
/>
) : (
<ContaminantSchemeQuery />
)}
<SchemeQuery
schemes={schemes}
onSchemesChange={setSchemes}
onLocate={handleLocateScheme}
/>
</TabPanel>
<TabPanel value={currentTab} index={2}>
{isBurstMode ? (
<LocationResults results={locationResults} />
) : (
<ContaminantResultsPanel schemeName={data?.schemeName} />
)}
<LocationResults
results={locationResults}
/>
</TabPanel>
<TabPanel value={currentTab} index={3}>
<ValveIsolation
loading={valveAnalysisLoading}
result={valveAnalysisResult}
onLoadingChange={setValveAnalysisLoading}
onResultChange={setValveAnalysisResult}
/>
</TabPanel>
</Box>
</Drawer>

View File

@@ -9,7 +9,9 @@ import {
Tooltip,
Link,
} from "@mui/material";
import { LocationOn as LocationIcon } from "@mui/icons-material";
import {
LocationOn as LocationIcon,
} from "@mui/icons-material";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { useMap } from "@app/OlMap/MapComponent";
import { GeoJSON } from "ol/format";
@@ -29,21 +31,15 @@ import { Point } from "ol/geom";
import { toLonLat } from "ol/proj";
import moment from "moment";
import "moment-timezone";
export interface LocationResult {
id: number;
type: string;
burst_incident: string;
leakage: number | null;
detect_time: string;
locate_result: string[] | null;
}
import { LocationResult } from "./types";
interface LocationResultsProps {
results?: LocationResult[];
}
const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
const LocationResults: React.FC<LocationResultsProps> = ({
results = [],
}) => {
const [highlightLayer, setHighlightLayer] =
useState<VectorLayer<VectorSource> | null>(null);
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
@@ -56,14 +52,14 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
const handleLocatePipes = (pipeIds: string[]) => {
if (pipeIds.length > 0) {
queryFeaturesByIds(pipeIds).then((features) => {
queryFeaturesByIds(pipeIds, "geo_pipes_mat").then((features) => {
if (features.length > 0) {
// 设置高亮要素
setHighlightFeatures(features);
// 将 OpenLayers Feature 转换为 GeoJSON Feature
const geojsonFormat = new GeoJSON();
const geojsonFeatures = features.map((feature) =>
geojsonFormat.writeFeatureObject(feature)
geojsonFormat.writeFeatureObject(feature),
);
const extent = bbox(featureCollection(geojsonFeatures as any));
@@ -103,7 +99,7 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
width: 3,
lineDash: [15, 10],
}),
})
}),
);
const geometry = feature.getGeometry();
const lineCoords =
@@ -130,7 +126,7 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
scale: 0.2,
anchor: [0.5, 1],
}),
})
}),
);
}
return styles;
@@ -251,7 +247,9 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
{result.burst_incident}
</Typography>
<Chip
label={result.type}
label={
result.type === "burst_analysis" ? "爆管模拟" : result.type
}
size="small"
color="primary"
variant="outlined"
@@ -347,21 +345,23 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
>
</Typography>
<Tooltip title="定位所有管道">
<IconButton
size="small"
onClick={() => handleLocatePipes(result.locate_result!)}
color="primary"
sx={{
backgroundColor: "rgba(37, 125, 212, 0.1)",
"&:hover": {
backgroundColor: "rgba(37, 125, 212, 0.2)",
},
}}
>
<LocationIcon sx={{ fontSize: "1.2rem" }} />
</IconButton>
</Tooltip>
<Box className="flex items-center gap-2">
<Tooltip title="定位所有管道">
<IconButton
size="small"
onClick={() => handleLocatePipes(result.locate_result!)}
color="primary"
sx={{
backgroundColor: "rgba(37, 125, 212, 0.1)",
"&:hover": {
backgroundColor: "rgba(37, 125, 212, 0.2)",
},
}}
>
<LocationIcon sx={{ fontSize: "1.2rem" }} />
</IconButton>
</Tooltip>
</Box>
</Box>
<Box className="grid grid-cols-2 gap-2">
{result.locate_result.map((pipeId, idx) => (
@@ -369,6 +369,12 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
key={idx}
className="bg-gradient-to-r from-blue-50 to-white rounded-lg px-3 py-2 border border-blue-200 hover:border-blue-400 hover:shadow-md transition-all cursor-pointer group"
onClick={() => handleLocatePipes([pipeId])}
sx={{
"&:active": {
transform: "scale(0.98)",
boxShadow: "0 1px 2px rgba(25, 118, 210, 0.2)",
},
}}
>
<Box className="flex items-center justify-between">
<Typography
@@ -377,10 +383,24 @@ const LocationResults: React.FC<LocationResultsProps> = ({ results = [] }) => {
>
{pipeId}
</Typography>
<LocationIcon
sx={{ fontSize: "1rem" }}
className="text-blue-400 group-hover:text-blue-600 transition-colors"
/>
<Box className="flex items-center gap-1">
{/* <Tooltip title="定位管段">
<IconButton
size="small"
onClick={(e) => {
e.stopPropagation();
handleLocatePipes([pipeId]);
}}
sx={{
"&:hover": {
backgroundColor: "rgba(37, 125, 212, 0.1)",
},
}}
>
<LocationIcon sx={{ fontSize: "1rem" }} />
</IconButton>
</Tooltip> */}
</Box>
</Box>
</Box>
))}

View File

@@ -1,6 +1,6 @@
"use client";
import React, { useEffect, useState } from "react";
import React, { useEffect, useMemo, useState } from "react";
import ReactDOM from "react-dom"; // 添加这行
import {
@@ -26,7 +26,7 @@ import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn"; // 引入中文包
import dayjs, { Dayjs } from "dayjs";
import axios from "axios";
import { api } from "@/lib/api";
import moment from "moment";
import { config, NETWORK_NAME } from "@config/config";
import { useNotification } from "@refinedev/core";
@@ -49,36 +49,7 @@ import {
import { Point } from "ol/geom";
import { toLonLat } from "ol/proj";
import Timeline from "@app/OlMap/Controls/Timeline";
interface SchemeDetail {
burst_ID: string[];
burst_size: number[];
modify_total_duration: number;
modify_fixed_pump_pattern: any;
modify_valve_opening: any;
modify_variable_pump_pattern: any;
}
interface SchemeRecord {
id: number;
schemeName: string;
type: string;
user: string;
create_time: string;
startTime: string;
// 详情信息
schemeDetail?: SchemeDetail;
}
interface SchemaItem {
scheme_id: number;
scheme_name: string;
scheme_type: string;
username: string;
create_time: string;
scheme_start_time: string;
scheme_detail?: SchemeDetail;
}
import { SchemaItem, SchemeRecord } from "./types";
interface SchemeQueryProps {
schemes?: SchemeRecord[];
@@ -87,6 +58,8 @@ interface SchemeQueryProps {
network?: string;
}
const SCHEME_TYPE = "burst_analysis";
const SchemeQuery: React.FC<SchemeQueryProps> = ({
schemes: externalSchemes,
onSchemesChange,
@@ -114,8 +87,8 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
const map = useMap();
const data = useData();
if (!data) return null;
const { schemeName, setSchemeName } = data;
const { schemeName, setSchemeName } = data || {};
// 使用外部提供的 schemes 或内部状态
const schemes =
externalSchemes !== undefined ? externalSchemes : internalSchemes;
@@ -127,13 +100,17 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
return time.format("MM-DD");
};
const filteredSchemes = useMemo(() => {
return schemes.filter((scheme) => scheme.type === SCHEME_TYPE);
}, [schemes]);
const handleQuery = async () => {
if (!queryAll && !queryDate) return;
setLoading(true);
try {
const response = await axios.get(
`${config.BACKEND_URL}/api/v1/getallschemes/?network=${network}`
const response = await api.get(
`${config.BACKEND_URL}/api/v1/getallschemes/?network=${network}`,
);
let filteredResults = response.data;
@@ -154,7 +131,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
create_time: item.create_time,
startTime: item.scheme_start_time,
schemeDetail: item.scheme_detail,
}))
})),
);
if (filteredResults.length === 0) {
@@ -180,14 +157,14 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
const handleLocatePipes = (pipeIds: string[]) => {
if (pipeIds.length > 0) {
queryFeaturesByIds(pipeIds).then((features) => {
queryFeaturesByIds(pipeIds, "geo_pipes_mat").then((features) => {
if (features.length > 0) {
// 设置高亮要素
setHighlightFeatures(features);
// 将 OpenLayers Feature 转换为 GeoJSON Feature
const geojsonFormat = new GeoJSON();
const geojsonFeatures = features.map((feature) =>
geojsonFormat.writeFeatureObject(feature)
geojsonFormat.writeFeatureObject(feature),
);
const extent = bbox(featureCollection(geojsonFeatures as any));
@@ -202,25 +179,24 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
// 内部的方案查询函数
const handleViewDetails = (id: number) => {
const scheme = filteredSchemes.find((s) => s.id === id);
if (!scheme) return;
setShowTimeline(true);
// 计算时间范围
const scheme = schemes.find((s) => s.id === id);
const burstPipeIds = scheme?.schemeDetail?.burst_ID || [];
const schemeDate = scheme?.startTime
const schemeDate = scheme.startTime
? new Date(scheme.startTime)
: undefined;
if (scheme?.startTime && scheme.schemeDetail?.modify_total_duration) {
if (scheme.startTime && scheme.schemeDetail?.modify_total_duration) {
const start = new Date(scheme.startTime);
const end = new Date(
start.getTime() + scheme.schemeDetail.modify_total_duration * 1000
start.getTime() + scheme.schemeDetail.modify_total_duration * 1000,
);
setSelectedDate(schemeDate);
setTimeRange({ start, end });
if (setSchemeName) {
setSchemeName(scheme.schemeName);
}
handleLocatePipes(burstPipeIds);
}
setSchemeName?.(scheme.schemeName);
handleLocatePipes(scheme.schemeDetail?.burst_ID || []);
};
// 初始化管道图层和高亮图层
@@ -254,7 +230,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
width: 3,
lineDash: [15, 10],
}),
})
}),
);
const geometry = feature.getGeometry();
const lineCoords =
@@ -281,7 +257,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
scale: 0.2,
anchor: [0.5, 1],
}),
})
}),
);
}
return styles;
@@ -336,9 +312,9 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
timeRange={timeRange}
disableDateSelection={!!timeRange}
schemeName={schemeName}
schemeType="burst_Analysis"
schemeType={SCHEME_TYPE}
/>,
mapContainer // 渲染到地图容器中,而不是 body
mapContainer, // 渲染到地图容器中,而不是 body
)}
<Box className="flex flex-col h-full">
{/* 查询条件 - 单行布局 */}
@@ -391,7 +367,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
{/* 结果列表 */}
<Box className="flex-1 overflow-auto">
{schemes.length === 0 ? (
{filteredSchemes.length === 0 ? (
<Box className="flex flex-col items-center justify-center h-full text-gray-400">
<Box className="mb-4">
<svg
@@ -428,9 +404,9 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
) : (
<Box className="space-y-2 p-2">
<Typography variant="caption" className="text-gray-500 px-2">
{schemes.length}
{filteredSchemes.length}
</Typography>
{schemes.map((scheme) => (
{filteredSchemes.map((scheme) => (
<Card
key={scheme.id}
variant="outlined"
@@ -449,7 +425,11 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
{scheme.schemeName}
</Typography>
<Chip
label={scheme.type}
label={
scheme.type === "burst_analysis"
? "爆管模拟"
: scheme.type
}
size="small"
className="h-5"
color="primary"
@@ -475,7 +455,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
size="small"
onClick={() =>
setExpandedId(
expandedId === scheme.id ? null : scheme.id
expandedId === scheme.id ? null : scheme.id,
)
}
color="primary"
@@ -484,7 +464,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
<InfoIcon fontSize="small" />
</IconButton>
</Tooltip>
<Tooltip title="定位">
<Tooltip title="查看定位结果">
<IconButton
size="small"
onClick={() => onLocate?.(scheme)}
@@ -528,7 +508,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
>
{pipeId}
</Link>
)
),
)
) : (
<Typography
@@ -618,7 +598,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
className="font-medium text-gray-900"
>
{moment(scheme.create_time).format(
"YYYY-MM-DD HH:mm"
"YYYY-MM-DD HH:mm",
)}
</Typography>
</Box>
@@ -634,7 +614,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
className="font-medium text-gray-900"
>
{moment(scheme.startTime).format(
"YYYY-MM-DD HH:mm"
"YYYY-MM-DD HH:mm",
)}
</Typography>
</Box>
@@ -652,7 +632,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
className="border-blue-600 text-blue-600 hover:bg-blue-50"
onClick={() =>
handleLocatePipes?.(
scheme.schemeDetail!.burst_ID
scheme.schemeDetail!.burst_ID,
)
}
sx={{

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,46 @@
export interface SchemeDetail {
burst_ID: string[];
burst_size: number[];
modify_total_duration: number;
modify_fixed_pump_pattern: any;
modify_valve_opening: any;
modify_variable_pump_pattern: any;
}
export interface SchemeRecord {
id: number;
schemeName: string;
type: string;
user: string;
create_time: string;
startTime: string;
// 详情信息
schemeDetail?: SchemeDetail;
}
export interface SchemaItem {
scheme_id: number;
scheme_name: string;
scheme_type: string;
username: string;
create_time: string;
scheme_start_time: string;
scheme_detail?: SchemeDetail;
}
export interface LocationResult {
id: number;
type: string;
burst_incident: string;
leakage: number | null;
detect_time: string;
locate_result: string[] | null;
}
export interface ValveIsolationResult {
accident_elements: string[];
affected_nodes: string[];
must_close_valves: string[];
optional_valves: string[];
isolatable: boolean;
}

View File

@@ -17,12 +17,12 @@ import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn";
import dayjs, { Dayjs } from "dayjs";
import { useNotification } from "@refinedev/core";
import axios from "axios";
import { api } from "@/lib/api";
import { config, NETWORK_NAME } from "@/config/config";
import { useMap } from "@app/OlMap/MapComponent";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Stroke, Fill, Circle as CircleStyle } from "ol/style";
import { Style, Stroke, Fill, Circle as CircleStyle, Icon } from "ol/style";
import Feature from "ol/Feature";
import { handleMapClickSelectFeatures as mapClickSelectFeatures } from "@/utils/mapQueryService";
@@ -31,10 +31,13 @@ const AnalysisParameters: React.FC = () => {
const { open } = useNotification();
const network = NETWORK_NAME;
const [schemeName, setSchemeName] = useState<string>(
"WQ_" + new Date().getTime(),
);
const [startTime, setStartTime] = useState<Dayjs | null>(dayjs(new Date()));
const [sourceNode, setSourceNode] = useState<string>("");
const [concentration, setConcentration] = useState<number>(1);
const [duration, setDuration] = useState<number>(900);
const [concentration, setConcentration] = useState<number>(100);
const [duration, setDuration] = useState<number>(3600);
const [pattern, setPattern] = useState<string>("");
const [isSelecting, setIsSelecting] = useState<boolean>(false);
const [submitting, setSubmitting] = useState<boolean>(false);
@@ -42,7 +45,7 @@ const AnalysisParameters: React.FC = () => {
const [highlightLayer, setHighlightLayer] =
useState<VectorLayer<VectorSource> | null>(null);
const [highlightFeature, setHighlightFeature] = useState<Feature | null>(
null
null,
);
const isFormValid = useMemo(() => {
@@ -51,20 +54,41 @@ const AnalysisParameters: React.FC = () => {
Boolean(startTime) &&
Boolean(sourceNode) &&
concentration > 0 &&
duration > 0
duration > 0 &&
schemeName.trim() !== ""
);
}, [network, startTime, sourceNode, concentration, duration]);
}, [network, startTime, sourceNode, concentration, duration, schemeName]);
useEffect(() => {
if (!map) return;
const sourceStyle = new Style({
image: new CircleStyle({
radius: 10,
fill: new Fill({ color: "rgba(37, 125, 212, 0.35)" }),
stroke: new Stroke({ color: "rgba(37, 125, 212, 1)", width: 3 }),
const themeColor = "rgba(3, 168, 107"; // #03a86b
const sourceStyle = [
// 外层扩散光圈
new Style({
image: new CircleStyle({
radius: 12,
fill: new Fill({ color: `${themeColor}, 0.2)` }),
}),
}),
});
// 中层扩散背景
new Style({
image: new CircleStyle({
radius: 8,
stroke: new Stroke({ color: `${themeColor}, 0.5)`, width: 2 }),
fill: new Fill({ color: `${themeColor}, 0.3)` }),
}),
}),
// 上层图标
new Style({
image: new Icon({
src: "/icons/contaminant_source.svg",
scale: 0.2,
anchor: [0.5, 1],
}),
}),
];
const layer = new VectorLayer({
source: new VectorSource(),
@@ -117,7 +141,7 @@ const AnalysisParameters: React.FC = () => {
setIsSelecting(false);
map.un("click", handleMapClickSelectFeatures);
},
[map, open]
[map, open],
);
const handleStartSelection = () => {
@@ -146,18 +170,26 @@ const AnalysisParameters: React.FC = () => {
message: "方案提交分析中",
undoableTimeout: 3,
});
// 格式化开始时间,去除秒部分
const start_time = startTime
? startTime.format("YYYY-MM-DDTHH:mm:00Z")
: "";
try {
if (!pattern) {
setPattern("CONSTANT");
console.log("默认设置 pattern 为 CONSTANT");
}
const params = {
network,
start_time: startTime.toISOString(),
start_time: start_time,
source: sourceNode,
concentration,
duration,
pattern: pattern || undefined,
scheme_name: schemeName,
};
await axios.get(`${config.BACKEND_URL}/api/v1/contaminant_simulation/`, {
await api.get(`${config.BACKEND_URL}/api/v1/contaminant_simulation/`, {
params,
});
@@ -248,7 +280,7 @@ const AnalysisParameters: React.FC = () => {
<Stack spacing={2}>
{sourceNode ? (
<Box className="flex items-center gap-2 p-2 bg-gray-50 rounded">
<Typography className="flex-shrink-0 text-sm">
<Typography className="flex-shrink-0 pl-1 text-sm">
{sourceNode}
</Typography>
<Typography className="flex-shrink-0 text-sm text-gray-600">
@@ -297,13 +329,14 @@ const AnalysisParameters: React.FC = () => {
<Box className="mb-4">
<Typography variant="subtitle2" className="mb-2 font-medium">
</Typography>
<TextField
fullWidth
size="small"
value={network}
disabled
value={schemeName}
onChange={(e) => setSchemeName(e.target.value)}
placeholder="输入方案名称"
/>
</Box>
@@ -344,7 +377,7 @@ const AnalysisParameters: React.FC = () => {
size="small"
value={pattern}
onChange={(e) => setPattern(e.target.value)}
placeholder="可选,输入 pattern 名称"
placeholder="可选,输入 pattern 名称,默认为 CONSTANT"
/>
</Box>

View File

@@ -25,30 +25,42 @@ import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn";
import dayjs, { Dayjs } from "dayjs";
import axios from "axios";
import { api } from "@/lib/api";
import moment from "moment";
import { useNotification } from "@refinedev/core";
import { config, NETWORK_NAME } from "@config/config";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { useData, useMap } from "@app/OlMap/MapComponent";
import { GeoJSON } from "ol/format";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Icon, Circle, Fill, Stroke } from "ol/style";
import Feature from "ol/Feature";
import { bbox, featureCollection } from "@turf/turf";
import Timeline from "@app/OlMap/Controls/Timeline";
import { ContaminantSchemaItem, ContaminantSchemeRecord } from "./types";
interface SchemeQueryProps {
schemes?: ContaminantSchemeRecord[];
onSchemesChange?: (schemes: ContaminantSchemeRecord[]) => void;
onViewResults?: () => void;
network?: string;
}
const SCHEME_TYPE = "contaminant_simulation";
const SCHEME_TYPE = "contaminant_analysis";
const SchemeQuery: React.FC<SchemeQueryProps> = ({
schemes: externalSchemes,
onSchemesChange,
onViewResults,
network = NETWORK_NAME,
}) => {
const [queryAll, setQueryAll] = useState<boolean>(true);
const [queryDate, setQueryDate] = useState<Dayjs | null>(dayjs(new Date()));
const [highlightLayer, setHighlightLayer] =
useState<VectorLayer<VectorSource> | null>(null);
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
const [showTimeline, setShowTimeline] = useState(false);
const [selectedDate, setSelectedDate] = useState<Date | undefined>(undefined);
const [timeRange, setTimeRange] = useState<
@@ -64,8 +76,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
const { open } = useNotification();
const map = useMap();
const data = useData();
const { schemeName, setSchemeName, setJunctionText, setPipeText } =
data || {};
const { schemeName, setSchemeName } = data || {};
const schemes =
externalSchemes !== undefined ? externalSchemes : internalSchemes;
@@ -79,6 +90,83 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
}
}, [map]);
// 初始化高亮图层
useEffect(() => {
if (!map) return;
const themeColor = "rgba(3, 168, 107"; // #03a86b
const sourceStyle = [
// 外层扩散光圈
new Style({
image: new Circle({
radius: 12,
fill: new Fill({
color: `${themeColor}, 0.2)`,
}),
}),
}),
// 中层扩散背景
new Style({
image: new Circle({
radius: 8,
stroke: new Stroke({
color: `${themeColor}, 0.5)`,
width: 2,
}),
fill: new Fill({
color: `${themeColor}, 0.3)`,
}),
}),
}),
// 上层图标
new Style({
image: new Icon({
src: "/icons/contaminant_source.svg",
scale: 0.2,
anchor: [0.5, 1],
}),
}),
];
const highlightLayer = new VectorLayer({
source: new VectorSource(),
style: sourceStyle,
maxZoom: 24,
minZoom: 12,
properties: {
name: "污染源高亮",
value: "contaminant_source_highlight",
},
});
map.addLayer(highlightLayer);
setHighlightLayer(highlightLayer);
return () => {
map.removeLayer(highlightLayer);
};
}, [map]);
// 高亮要素的函数
useEffect(() => {
if (!highlightLayer) {
return;
}
const source = highlightLayer.getSource();
if (!source) {
return;
}
// 清除之前的高亮
source.clear();
// 添加新的高亮要素
highlightFeatures.forEach((feature) => {
if (feature instanceof Feature) {
source.addFeature(feature);
}
});
}, [highlightFeatures, highlightLayer]);
const formatTime = (timeStr: string) => {
const time = moment(timeStr);
return time.format("MM-DD");
@@ -92,17 +180,19 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
if (!queryAll && !queryDate) return;
setLoading(true);
try {
const response = await axios.get(
`${config.BACKEND_URL}/api/v1/getallschemes/?network=${network}`
const response = await api.get(
`${config.BACKEND_URL}/api/v1/getallschemes/?network=${network}`,
);
let filteredResults = response.data;
if (!queryAll) {
const formattedDate = queryDate!.format("YYYY-MM-DD");
filteredResults = response.data.filter((item: ContaminantSchemaItem) => {
const itemDate = moment(item.create_time).format("YYYY-MM-DD");
return itemDate === formattedDate;
});
filteredResults = response.data.filter(
(item: ContaminantSchemaItem) => {
const itemDate = moment(item.create_time).format("YYYY-MM-DD");
return itemDate === formattedDate;
},
);
}
setSchemes(
@@ -114,7 +204,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
create_time: item.create_time,
startTime: item.scheme_start_time,
schemeDetail: item.scheme_detail,
}))
})),
);
if (filteredResults.length === 0) {
@@ -138,19 +228,29 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
}
};
const handleLocateSource = (sourceId?: string) => {
if (!sourceId) return;
queryFeaturesByIds([sourceId], "geo_junctions_mat").then((features) => {
if (features.length > 0) {
const extent = features[0].getGeometry()?.getExtent();
if (extent) {
map?.getView().fit(extent, {
maxZoom: 18,
duration: 1000,
});
const handleLocateSource = (sourceIds: string[]) => {
if (sourceIds.length > 0) {
queryFeaturesByIds(sourceIds, "geo_junctions_mat").then((features) => {
if (features.length > 0) {
// 设置高亮要素
setHighlightFeatures(features);
// 将 OpenLayers Feature 转换为 GeoJSON Feature
const geojsonFormat = new GeoJSON();
const geojsonFeatures = features.map((feature) =>
geojsonFormat.writeFeatureObject(feature),
);
const extent = bbox(featureCollection(geojsonFeatures as any));
if (extent) {
map?.getView().fit(extent, {
maxZoom: 18,
duration: 1000,
});
}
}
}
});
});
}
};
const handleViewDetails = (id: number) => {
@@ -158,17 +258,21 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
if (!scheme) return;
setShowTimeline(true);
const schemeDate = scheme.startTime ? new Date(scheme.startTime) : undefined;
const schemeDate = scheme.startTime
? new Date(scheme.startTime)
: undefined;
if (scheme.startTime && scheme.schemeDetail?.duration) {
const start = new Date(scheme.startTime);
const end = new Date(start.getTime() + scheme.schemeDetail.duration * 1000);
const end = new Date(
start.getTime() + scheme.schemeDetail.duration * 1000,
);
setSelectedDate(schemeDate);
setTimeRange({ start, end });
}
setSchemeName?.(scheme.schemeName);
setJunctionText?.("quality");
setPipeText?.("quality");
handleLocateSource(scheme.schemeDetail?.source);
if (scheme.schemeDetail?.source) {
handleLocateSource([scheme.schemeDetail.source]);
}
};
return (
@@ -183,7 +287,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
schemeName={schemeName}
schemeType={SCHEME_TYPE}
/>,
mapContainer
mapContainer,
)}
<Box className="flex flex-col h-full">
<Box className="mb-2 p-2 bg-gray-50 rounded">
@@ -291,7 +395,11 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
{scheme.schemeName}
</Typography>
<Chip
label={scheme.type}
label={
scheme.type === "contaminant_analysis"
? "水质模拟"
: scheme.type
}
size="small"
className="h-5"
color="primary"
@@ -302,18 +410,21 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
variant="caption"
className="text-gray-500 block"
>
ID: {scheme.id} · : {formatTime(scheme.create_time)}
ID: {scheme.id} · :{" "}
{formatTime(scheme.create_time)}
</Typography>
</Box>
<Box className="flex gap-1 ml-2">
<Tooltip
title={expandedId === scheme.id ? "收起详情" : "查看详情"}
title={
expandedId === scheme.id ? "收起详情" : "查看详情"
}
>
<IconButton
size="small"
onClick={() =>
setExpandedId(
expandedId === scheme.id ? null : scheme.id
expandedId === scheme.id ? null : scheme.id,
)
}
color="primary"
@@ -322,16 +433,19 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
<InfoIcon fontSize="small" />
</IconButton>
</Tooltip>
<Tooltip title="定位污染源">
{/* <Tooltip title="定位污染源">
<IconButton
size="small"
onClick={() => handleLocateSource(scheme.schemeDetail?.source)}
onClick={() =>
scheme.schemeDetail?.source &&
handleLocateSource([scheme.schemeDetail.source])
}
color="primary"
className="p-1"
>
<LocationIcon fontSize="small" />
</IconButton>
</Tooltip>
</Tooltip> */}
</Box>
</Box>
@@ -355,7 +469,9 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
className="font-medium text-blue-600 hover:text-blue-800 underline cursor-pointer"
onClick={(e) => {
e.preventDefault();
handleLocateSource(scheme.schemeDetail?.source);
handleLocateSource([
scheme.schemeDetail!.source!,
]);
}}
>
{scheme.schemeDetail.source}
@@ -381,7 +497,8 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
variant="caption"
className="font-medium text-gray-900"
>
{scheme.schemeDetail?.concentration ?? "N/A"} mg/L
{scheme.schemeDetail?.concentration ?? "N/A"}{" "}
mg/L
</Typography>
</Box>
<Box className="flex items-center gap-2">
@@ -443,7 +560,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
className="font-medium text-gray-900"
>
{moment(scheme.create_time).format(
"YYYY-MM-DD HH:mm"
"YYYY-MM-DD HH:mm",
)}
</Typography>
</Box>
@@ -459,7 +576,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
className="font-medium text-gray-900"
>
{moment(scheme.startTime).format(
"YYYY-MM-DD HH:mm"
"YYYY-MM-DD HH:mm",
)}
</Typography>
</Box>
@@ -473,13 +590,16 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
fullWidth
size="small"
className="border-blue-600 text-blue-600 hover:bg-blue-50"
onClick={() => handleLocateSource(scheme.schemeDetail?.source)}
onClick={() =>
scheme.schemeDetail?.source &&
handleLocateSource([scheme.schemeDetail.source])
}
sx={{
textTransform: "none",
fontWeight: 500,
}}
>
</Button>
<Button
variant="contained"

View File

@@ -0,0 +1,208 @@
"use client";
import React, { useState } from "react";
import {
Box,
Drawer,
Tabs,
Tab,
Typography,
IconButton,
Tooltip,
} from "@mui/material";
import {
ChevronRight,
ChevronLeft,
Analytics as AnalyticsIcon,
Search as SearchIcon,
MyLocation as MyLocationIcon,
} from "@mui/icons-material";
import ContaminantAnalysisParameters from "./AnalysisParameters";
import ContaminantSchemeQuery from "./SchemeQuery";
import ContaminantResultsPanel from "./ResultsPanel";
import { useData } from "@app/OlMap/MapComponent";
interface WaterQualityPanelProps {
open?: boolean;
onToggle?: () => void;
}
const WaterQualityPanel: React.FC<WaterQualityPanelProps> = ({
open: controlledOpen,
onToggle,
}) => {
const [internalOpen, setInternalOpen] = useState(true);
const [currentTab, setCurrentTab] = useState(0);
const data = useData();
// 使用受控或非受控状态
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
const handleToggle = () => {
if (onToggle) {
onToggle();
} else {
setInternalOpen(!internalOpen);
}
};
const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
setCurrentTab(newValue);
};
const drawerWidth = 520;
const panelTitle = "水质模拟";
return (
<>
{/* 收起时的触发按钮 */}
{!isOpen && (
<Box
className="absolute top-4 right-4 bg-white shadow-2xl rounded-lg cursor-pointer hover:shadow-xl transition-all duration-300 opacity-95 hover:opacity-100"
onClick={handleToggle}
sx={{ zIndex: 1300 }}
>
<Box className="flex flex-col items-center py-3 px-3 gap-1">
<AnalyticsIcon className="text-[#257DD4] w-5 h-5" />
<Typography
variant="caption"
className="text-gray-700 font-semibold my-1 text-xs"
style={{ writingMode: "vertical-rl" }}
>
{panelTitle}
</Typography>
<ChevronLeft className="text-gray-600 w-4 h-4" />
</Box>
</Box>
)}
{/* 主面板 */}
<Drawer
anchor="right"
open={isOpen}
variant="persistent"
hideBackdrop
sx={{
// 关键:容器自身不占用布局宽度
width: 0,
flexShrink: 0,
"& .MuiDrawer-paper": {
width: drawerWidth,
boxSizing: "border-box",
position: "absolute",
top: 16,
right: 16,
height: "calc(100vh - 32px)",
maxHeight: "850px",
borderRadius: "12px",
boxShadow:
"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",
backdropFilter: "blur(8px)",
opacity: 0.95,
transition: "transform 0.3s ease-in-out, opacity 0.3s ease-in-out",
border: "none",
"&:hover": {
opacity: 1,
},
},
}}
>
<Box className="flex flex-col h-full bg-white rounded-xl overflow-hidden">
{/* 头部 */}
<Box className="flex items-center justify-between px-5 py-4 bg-[#257DD4] text-white">
<Box className="flex items-center gap-2">
<AnalyticsIcon className="w-5 h-5" />
<Typography variant="h6" className="text-lg font-semibold">
{panelTitle}
</Typography>
</Box>
<Tooltip title="收起">
<IconButton
size="small"
onClick={handleToggle}
sx={{ color: "primary.contrastText" }}
>
<ChevronRight fontSize="small" />
</IconButton>
</Tooltip>
</Box>
<Box className="border-b border-gray-200 bg-white">
<Tabs
value={currentTab}
onChange={handleTabChange}
variant="fullWidth"
sx={{
minHeight: 48,
"& .MuiTab-root": {
minHeight: 48,
textTransform: "none",
fontSize: "0.875rem",
fontWeight: 500,
transition: "all 0.2s",
},
"& .Mui-selected": {
color: "#257DD4",
},
"& .MuiTabs-indicator": {
backgroundColor: "#257DD4",
},
}}
>
<Tab
icon={<AnalyticsIcon fontSize="small" />}
iconPosition="start"
label="分析要件"
/>
<Tab
icon={<SearchIcon fontSize="small" />}
iconPosition="start"
label="方案查询"
/>
{/* <Tab
icon={<MyLocationIcon fontSize="small" />}
iconPosition="start"
label="模拟结果"
/> */}
</Tabs>
</Box>
{/* Tab 内容 */}
<TabPanel value={currentTab} index={0}>
<ContaminantAnalysisParameters />
</TabPanel>
<TabPanel value={currentTab} index={1}>
<ContaminantSchemeQuery onViewResults={() => setCurrentTab(2)} />
</TabPanel>
<TabPanel value={currentTab} index={2}>
<ContaminantResultsPanel schemeName={data?.schemeName} />
</TabPanel>
</Box>
</Drawer>
</>
);
};
interface TabPanelProps {
children?: React.ReactNode;
index: number;
value: number;
}
const TabPanel: React.FC<TabPanelProps> = ({ children, value, index }) => {
return (
<div
role="tabpanel"
hidden={value !== index}
className="flex-1 overflow-hidden flex flex-col"
>
{value === index && (
<Box className="flex-1 overflow-auto p-4">{children}</Box>
)}
</div>
);
};
export default WaterQualityPanel;

View File

@@ -3,7 +3,6 @@ export interface ContaminantSchemeDetail {
concentration: number;
duration: number;
pattern?: string | null;
start_time?: string;
}
export interface ContaminantSchemeRecord {

View File

@@ -0,0 +1,451 @@
"use client";
import React, { useState, useEffect, useCallback } from "react";
import {
Box,
TextField,
Button,
Typography,
IconButton,
Stack,
Alert,
Divider,
} from "@mui/material";
import { Close as CloseIcon } from "@mui/icons-material";
import { DateTimePicker } from "@mui/x-date-pickers/DateTimePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { zhCN as pickerZhCN } from "@mui/x-date-pickers/locales";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn";
import dayjs, { Dayjs } from "dayjs";
import { useMap } from "@app/OlMap/MapComponent";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Stroke, Fill, Circle as CircleStyle } from "ol/style";
import { handleMapClickSelectFeatures as mapClickSelectFeatures } from "@/utils/mapQueryService";
import Feature, { FeatureLike } from "ol/Feature";
import { useNotification } from "@refinedev/core";
import { api } from "@/lib/api";
import { config, NETWORK_NAME } from "@/config/config";
interface ValveItem {
id: string;
k: number;
feature?: any;
}
const AnalysisParameters: React.FC = () => {
const map = useMap();
const { open } = useNotification();
// State
const [schemeName, setSchemeName] = useState<string>(
"Flushing_" + new Date().getTime(),
);
const [valves, setValves] = useState<ValveItem[]>([]);
const [drainageNode, setDrainageNode] = useState<string | null>(null);
const [drainageFeature, setDrainageFeature] = useState<Feature | null>(null);
const [startTime, setStartTime] = useState<Dayjs | null>(dayjs(new Date()));
const [flushFlow, setFlushFlow] = useState<number>(200);
const [duration, setDuration] = useState<number>(3600);
const [selectionMode, setSelectionMode] = useState<'none' | 'valve' | 'drainage'>('none');
const [analyzing, setAnalyzing] = useState<boolean>(false);
const [highlightLayer, setHighlightLayer] = useState<VectorLayer<VectorSource> | null>(null);
// Initialize highlight layer
useEffect(() => {
if (!map) return;
const highlightStyle = function (feature: FeatureLike) {
const styles = [];
const type = feature.get("type"); // We will set this property when adding to source
if (type === "valve") {
styles.push(
new Style({
image: new CircleStyle({
radius: 8,
fill: new Fill({ color: "rgba(255, 165, 0, 0.8)" }), // Orange for valves
stroke: new Stroke({ color: "white", width: 2 }),
}),
})
);
} else if (type === "drainage") {
styles.push(
new Style({
image: new CircleStyle({
radius: 8,
fill: new Fill({ color: "rgba(0, 0, 255, 0.8)" }), // Blue for drainage
stroke: new Stroke({ color: "white", width: 2 }),
}),
})
);
}
return styles;
};
const layer = new VectorLayer({
source: new VectorSource(),
style: highlightStyle,
zIndex: 1000,
properties: {
name: "FlushingHighlight",
},
});
map.addLayer(layer);
setHighlightLayer(layer);
return () => {
map.removeLayer(layer);
map.un("click", handleMapClickSelectFeatures);
};
}, [map]);
// Update highlight layer features
useEffect(() => {
if (!highlightLayer) return;
const source = highlightLayer.getSource();
if (!source) return;
source.clear();
// Add valves
valves.forEach((v) => {
if (v.feature) {
const f = v.feature.clone(); // Clone to avoid modifying original
f.set("type", "valve");
// Ensure geometry is present (it should be for features from map)
if (f.getGeometry()) {
source.addFeature(f);
}
}
});
// Add drainage node
if (drainageFeature) {
const f = drainageFeature.clone();
f.set("type", "drainage");
source.addFeature(f);
}
}, [highlightLayer, valves, drainageFeature]);
// Map click handler
const handleMapClickSelectFeatures = useCallback(
async (event: { coordinate: number[] }) => {
if (!map || selectionMode === 'none') return;
const feature = await mapClickSelectFeatures(event, map);
if (!feature) return;
const layer = feature.getId()?.toString().split(".")[0];
const featureId = feature.getProperties().id;
if (selectionMode === 'valve') {
if (layer !== 'geo_valves') {
open?.({
type: "error",
message: "请选择阀门要素",
});
return;
}
setValves((prev) => {
if (prev.some((v) => v.id === featureId)) {
open?.({
type: "error",
message: "该阀门已添加",
});
return prev;
}
return [...prev, { id: featureId, k: 1.0, feature }]; // Default k=1.0? User can change.
});
} else if (selectionMode === 'drainage') {
if (layer !== 'geo_junctions') {
open?.({
type: "error",
message: "请选择节点要素作为排水点",
});
return;
}
setDrainageNode(featureId);
setDrainageFeature(feature);
setSelectionMode('none'); // Auto exit selection after picking one
map.un("click", handleMapClickSelectFeatures);
}
},
[map, selectionMode, open]
);
// Bind click event based on selection mode
useEffect(() => {
if (!map || selectionMode === "none") return;
map.on("click", handleMapClickSelectFeatures);
return () => {
map.un("click", handleMapClickSelectFeatures);
};
}, [map, selectionMode, handleMapClickSelectFeatures]);
// Toggle selection
const toggleSelection = (mode: 'valve' | 'drainage') => {
// If clicking same mode, turn off
if (selectionMode === mode) {
setSelectionMode('none');
} else {
setSelectionMode(mode);
}
};
const handleRemoveValve = (id: string) => {
setValves((prev) => prev.filter((v) => v.id !== id));
};
const handleValveKChange = (id: string, k: string) => {
const numK = parseFloat(k);
setValves(prev => prev.map(v => v.id === id ? { ...v, k: isNaN(numK) ? 0 : numK } : v));
};
const handleAnalyze = async () => {
if (!startTime || !drainageNode || !schemeName.trim()) {
open?.({
type: "error",
message: "请填写完整参数",
description: "方案名称、开始时间和排水点为必填项",
});
return;
}
setAnalyzing(true);
try {
const formattedTime = startTime.format("YYYY-MM-DDTHH:mm:00");
const params = {
scheme_name: schemeName,
network: NETWORK_NAME,
start_time: formattedTime,
valves: valves.map(v => v.id),
valves_k: valves.map(v => v.k),
drainage_node_ID: drainageNode,
flush_flow: flushFlow,
duration: duration
};
// Use params serializer to handle array params correctly if needed,
// but axios usually handles array as valves[]=1&valves[]=2
// FastAPI default expects repeated query params.
const response = await api.get(`${config.BACKEND_URL}/flushing_analysis/`, {
params,
// Ensure arrays are sent as repeated keys: valves=1&valves=2
paramsSerializer: {
indexes: null // Result: valves=1&valves=2
}
});
if (response.status !== 200) {
throw new Error(`分析请求失败,状态码: ${response.status}`);
}
open?.({
type: "success",
message: "方案分析成功",
description: "管道冲洗模拟完成,请在方案查询中查看结果。",
});
} catch (error) {
console.error("提交分析失败", error);
open?.({
type: "error",
message: "提交分析失败",
description: error instanceof Error ? error.message : "未知错误",
});
} finally {
setAnalyzing(false);
}
};
return (
<Box className="flex flex-col h-full gap-4 pb-4">
{/* 1. Valve Selection */}
<Box>
<Box className="flex items-center justify-between mb-2">
<Typography variant="subtitle2" className="font-medium">
</Typography>
<Button
variant={selectionMode === 'valve' ? "contained" : "outlined"}
color={selectionMode === 'valve' ? "error" : "primary"}
size="small"
onClick={() => toggleSelection('valve')}
>
{selectionMode === 'valve' ? "停止选择" : "选择阀门"}
</Button>
</Box>
{selectionMode === 'valve' && (
<Box className="mb-2 p-2 bg-blue-50 text-xs text-blue-700 rounded">
💡
</Box>
)}
<Stack spacing={1} className="max-h-50 h-48 overflow-auto">
{valves.map((valve) => (
<Box key={valve.id} className="flex items-center gap-2 p-2 bg-gray-50 rounded">
<Typography className="text-sm flex-1 pl-1">{valve.id}</Typography>
<TextField
label="开度"
size="small"
type="number"
value={valve.k}
onChange={(e) => handleValveKChange(valve.id, e.target.value)}
className="w-20"
slotProps={{ htmlInput: { step: 0.1, min: 0, max: 1 } }}
/>
<IconButton size="small" onClick={() => handleRemoveValve(valve.id)}>
<CloseIcon fontSize="small" />
</IconButton>
</Box>
))}
{valves.length === 0 && (
<Typography variant="caption" className="text-gray-400 text-center py-20">
</Typography>
)}
</Stack>
</Box>
<Divider />
{/* 2. Drainage Node Selection */}
<Box>
<Box className="flex items-center justify-between mb-2">
<Typography variant="subtitle2" className="font-medium">
</Typography>
<Button
variant={selectionMode === 'drainage' ? "contained" : "outlined"}
color={selectionMode === 'drainage' ? "error" : "primary"}
size="small"
onClick={() => toggleSelection('drainage')}
>
{selectionMode === 'drainage' ? "停止选择" : "选择节点"}
</Button>
</Box>
{selectionMode === 'drainage' && (
<Box className="mb-2 p-2 bg-blue-50 text-xs text-blue-700 rounded">
💡
</Box>
)}
<Stack spacing={1} className="h-12 overflow-auto">
{drainageNode && (
<Box className="flex items-center gap-2 p-2 bg-gray-50 rounded">
<Typography className="text-sm flex-1 pl-1">{drainageNode}</Typography>
<IconButton
size="small"
onClick={() => {
setDrainageNode(null);
setDrainageFeature(null);
}}
>
<CloseIcon fontSize="small" />
</IconButton>
</Box>
)}
{!drainageNode && (
<Typography variant="caption" className="text-gray-400 text-center py-2">
</Typography>
)}
</Stack>
</Box>
<Divider />
{/* 3. Parameters */}
<Box className="flex flex-col gap-3">
<Box>
<Typography variant="subtitle2" className="mb-1 font-medium">
</Typography>
<LocalizationProvider dateAdapter={AdapterDayjs} adapterLocale="zh-cn">
<DateTimePicker
value={startTime}
onChange={(newValue) => setStartTime(newValue)}
format="YYYY-MM-DD HH:mm"
slotProps={{ textField: { size: "small", fullWidth: true } }}
localeText={
pickerZhCN.components.MuiLocalizationProvider.defaultProps
.localeText
}
/>
</LocalizationProvider>
</Box>
{/* Scheme Name */}
<Box>
<Typography variant="subtitle2" className="mb-1 font-medium">
</Typography>
<TextField
fullWidth
size="small"
value={schemeName}
onChange={(e) => setSchemeName(e.target.value)}
placeholder="请输入方案名称"
/>
</Box>
<Box className="flex gap-2">
<Box className="flex-1">
<Typography variant="subtitle2" className="mb-1 font-medium">
(CMH)
</Typography>
<TextField
fullWidth
size="small"
type="number"
value={flushFlow}
onChange={(e) => setFlushFlow(parseFloat(e.target.value) || 0)}
/>
</Box>
<Box className="flex-1">
<Typography variant="subtitle2" className="mb-1 font-medium">
()
</Typography>
<TextField
fullWidth
size="small"
type="number"
value={duration}
onChange={(e) => setDuration(parseInt(e.target.value) || 0)}
/>
</Box>
</Box>
</Box>
<Box className="mt-2">
<Button
fullWidth
variant="contained"
onClick={handleAnalyze}
disabled={
analyzing ||
!schemeName.trim() ||
!drainageNode ||
!startTime ||
// !flushFlow ||
!duration
}
className="bg-blue-600 hover:bg-blue-700"
>
{analyzing ? "分析中..." : "开始分析"}
</Button>
</Box>
</Box>
);
};
export default AnalysisParameters;

View File

@@ -0,0 +1,194 @@
"use client";
import React, { useState } from "react";
import {
Box,
Drawer,
Tabs,
Tab,
Typography,
IconButton,
Tooltip,
} from "@mui/material";
import {
ChevronRight,
ChevronLeft,
Analytics as AnalyticsIcon,
Search as SearchIcon,
} from "@mui/icons-material";
import { MdCleaningServices } from "react-icons/md";
import AnalysisParameters from "./AnalysisParameters";
import SchemeQuery from "./SchemeQuery";
interface TabPanelProps {
children?: React.ReactNode;
index: number;
value: number;
}
const TabPanel: React.FC<TabPanelProps> = ({ children, value, index }) => {
return (
<div
role="tabpanel"
hidden={value !== index}
className="flex-1 overflow-hidden flex flex-col"
>
{value === index && (
<Box className="flex-1 overflow-auto p-4">{children}</Box>
)}
</div>
);
};
interface FlushingAnalysisPanelProps {
open?: boolean;
onToggle?: () => void;
}
const FlushingAnalysisPanel: React.FC<FlushingAnalysisPanelProps> = ({
open: controlledOpen,
onToggle,
}) => {
const [internalOpen, setInternalOpen] = useState(true);
const [currentTab, setCurrentTab] = useState(0);
// Using controlled or uncontrolled state
const isOpen = controlledOpen !== undefined ? controlledOpen : internalOpen;
const handleToggle = () => {
if (onToggle) {
onToggle();
} else {
setInternalOpen(!internalOpen);
}
};
const handleTabChange = (_event: React.SyntheticEvent, newValue: number) => {
setCurrentTab(newValue);
};
const drawerWidth = 450; // Slightly narrower than burst analysis as we have fewer tabs
const panelTitle = "管道冲洗分析";
return (
<>
{/* Toggle Button when closed */}
{!isOpen && (
<Box
className="absolute top-4 right-4 bg-white shadow-2xl rounded-lg cursor-pointer hover:shadow-xl transition-all duration-300 opacity-95 hover:opacity-100"
onClick={handleToggle}
sx={{ zIndex: 1300 }}
>
<Box className="flex flex-col items-center py-3 px-3 gap-1">
<MdCleaningServices className="text-[#257DD4] w-5 h-5" />
<Typography
variant="caption"
className="text-gray-700 font-semibold my-1 text-xs"
style={{ writingMode: "vertical-rl" }}
>
{panelTitle}
</Typography>
<ChevronLeft className="text-gray-600 w-4 h-4" />
</Box>
</Box>
)}
{/* Main Panel */}
<Drawer
anchor="right"
open={isOpen}
variant="persistent"
hideBackdrop
sx={{
width: 0,
flexShrink: 0,
"& .MuiDrawer-paper": {
width: drawerWidth,
boxSizing: "border-box",
position: "absolute",
top: 16,
right: 16,
height: "calc(100vh - 32px)",
maxHeight: "850px",
borderRadius: "12px",
boxShadow:
"0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04)",
backdropFilter: "blur(8px)",
opacity: 0.95,
transition: "transform 0.3s ease-in-out, opacity 0.3s ease-in-out",
border: "none",
"&:hover": {
opacity: 1,
},
},
}}
>
<Box className="flex flex-col h-full bg-white rounded-xl overflow-hidden">
{/* Header */}
<Box className="flex items-center justify-between px-5 py-4 bg-[#257DD4] text-white">
<Box className="flex items-center gap-2">
<MdCleaningServices className="w-5 h-5" />
<Typography variant="h6" className="text-lg font-semibold">
{panelTitle}
</Typography>
</Box>
<Tooltip title="收起">
<IconButton
size="small"
onClick={handleToggle}
sx={{ color: "primary.contrastText" }}
>
<ChevronRight fontSize="small" />
</IconButton>
</Tooltip>
</Box>
<Box className="border-b border-gray-200 bg-white">
<Tabs
value={currentTab}
onChange={handleTabChange}
variant="fullWidth"
sx={{
minHeight: 48,
"& .MuiTab-root": {
minHeight: 48,
textTransform: "none",
fontSize: "0.875rem",
fontWeight: 500,
transition: "all 0.2s",
},
"& .Mui-selected": {
color: "#257DD4",
},
"& .MuiTabs-indicator": {
backgroundColor: "#257DD4",
},
}}
>
<Tab
icon={<AnalyticsIcon fontSize="small" />}
iconPosition="start"
label="分析参数"
/>
<Tab
icon={<SearchIcon fontSize="small" />}
iconPosition="start"
label="方案查询"
/>
</Tabs>
</Box>
{/* Tab Content */}
<TabPanel value={currentTab} index={0}>
<AnalysisParameters />
</TabPanel>
<TabPanel value={currentTab} index={1}>
<SchemeQuery />
</TabPanel>
</Box>
</Drawer>
</>
);
};
export default FlushingAnalysisPanel;

View File

@@ -0,0 +1,584 @@
"use client";
import React, { useEffect, useState } from "react";
import ReactDOM from "react-dom";
import {
Box,
Button,
Typography,
Checkbox,
FormControlLabel,
IconButton,
Card,
CardContent,
Chip,
Tooltip,
Collapse,
Link,
} from "@mui/material";
import {
Info as InfoIcon,
Search as SearchIcon,
LocationOn as LocationIcon,
} from "@mui/icons-material";
import { DatePicker } from "@mui/x-date-pickers/DatePicker";
import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn";
import dayjs, { Dayjs } from "dayjs";
import { api } from "@/lib/api";
import moment from "moment";
import { config, NETWORK_NAME } from "@config/config";
import { useNotification } from "@refinedev/core";
import { useData, useMap } from "@app/OlMap/MapComponent";
import { queryFeaturesByIds } from "@/utils/mapQueryService";
import { GeoJSON } from "ol/format";
import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Style, Icon, Circle, Fill, Stroke } from "ol/style";
import Feature, { FeatureLike } from "ol/Feature";
import { bbox, featureCollection } from "@turf/turf";
import Timeline from "@app/OlMap/Controls/Timeline";
import { SchemeRecord, SchemaItem } from "./types";
interface SchemeQueryProps {
schemes?: SchemeRecord[];
onSchemesChange?: (schemes: SchemeRecord[]) => void;
network?: string;
}
const SCHEME_TYPE = "flushing_analysis";
const SchemeQuery: React.FC<SchemeQueryProps> = ({
schemes: externalSchemes,
onSchemesChange,
network = NETWORK_NAME,
}) => {
const [queryAll, setQueryAll] = useState<boolean>(true);
const [queryDate, setQueryDate] = useState<Dayjs | null>(dayjs(new Date()));
const [internalSchemes, setInternalSchemes] = useState<SchemeRecord[]>([]);
const [loading, setLoading] = useState<boolean>(false);
const [expandedId, setExpandedId] = useState<number | null>(null);
const [highlightLayer, setHighlightLayer] =
useState<VectorLayer<VectorSource> | null>(null);
const [highlightFeatures, setHighlightFeatures] = useState<Feature[]>([]);
// Timeline related state
const [showTimeline, setShowTimeline] = useState(false);
const [selectedDate, setSelectedDate] = useState<Date | undefined>(undefined);
const [timeRange, setTimeRange] = useState<{ start: Date; end: Date } | undefined>();
const [mapContainer, setMapContainer] = useState<HTMLElement | null>(null);
const { open } = useNotification();
const map = useMap();
const data = useData();
const { schemeName, setSchemeName } = data || {};
const schemes = externalSchemes !== undefined ? externalSchemes : internalSchemes;
const setSchemes = onSchemesChange || setInternalSchemes;
useEffect(() => {
if (!map) return;
const target = map.getTargetElement();
if (target) {
setMapContainer(target);
}
}, [map]);
// Initialize highlight layer
useEffect(() => {
if (!map) return;
const themeColor = "rgba(0, 0, 255"; // Blue for drainage
const valveColor = "rgba(255, 165, 0"; // Orange for valves
const sourceStyle = function (feature: FeatureLike) {
const type = (feature as any).get("type");
if (type === "valve") {
return [
new Style({
image: new Circle({
radius: 8,
fill: new Fill({ color: `${valveColor}, 0.8)` }),
stroke: new Stroke({ color: "white", width: 2 }),
}),
})
];
} else {
// Default drainage
return [
new Style({
image: new Circle({
radius: 12,
fill: new Fill({ color: `${themeColor}, 0.2)` }),
}),
}),
new Style({
image: new Circle({
radius: 8,
stroke: new Stroke({ color: `${themeColor}, 0.5)`, width: 2 }),
fill: new Fill({ color: `${themeColor}, 0.3)` }),
}),
}),
new Style({
image: new Circle({
radius: 4,
fill: new Fill({ color: `${themeColor}, 1)` }),
stroke: new Stroke({ color: "white", width: 1 }),
})
}),
];
}
};
const layer = new VectorLayer({
source: new VectorSource(),
style: sourceStyle,
zIndex: 1000,
properties: {
name: "FlushingQueryResultHighlight",
},
});
map.addLayer(layer);
setHighlightLayer(layer);
return () => {
map.removeLayer(layer);
};
}, [map]);
// Update highlight features
useEffect(() => {
if (!highlightLayer) return;
const source = highlightLayer.getSource();
if (!source) return;
source.clear();
highlightFeatures.forEach((feature) => {
if (feature instanceof Feature) {
source.addFeature(feature);
}
});
}, [highlightFeatures, highlightLayer]);
const handleLocateDrainageNode = (nodeId: string) => {
if (!nodeId) return;
queryFeaturesByIds([nodeId], "geo_junctions_mat").then((features) => {
if (features.length > 0) {
// Add type property to distinguish styling
features.forEach(f => f.set("type", "drainage"));
setHighlightFeatures(features);
zoomToFeatures(features);
} else {
open?.({
type: "error",
message: "未找到该节点要素",
});
}
});
};
const handleLocateValves = (valveIds: string[]) => {
if (!valveIds || valveIds.length === 0) return;
queryFeaturesByIds(valveIds, "geo_valves").then((features) => {
if (features.length > 0) {
features.forEach(f => f.set("type", "valve"));
setHighlightFeatures(features);
zoomToFeatures(features);
} else {
open?.({
type: "error",
message: "未找到阀门要素",
});
}
});
};
const zoomToFeatures = (features: Feature[]) => {
const geojsonFormat = new GeoJSON();
const geojsonFeatures = features.map((feature) =>
geojsonFormat.writeFeatureObject(feature),
);
const extent = bbox(featureCollection(geojsonFeatures as any));
if (extent) {
map?.getView().fit(extent, {
maxZoom: 18,
duration: 1000,
padding: [50, 50, 50, 50],
});
}
};
const formatTime = (timeStr: string) => {
return moment(timeStr).format("MM-DD HH:mm");
};
const handleQuery = async () => {
if (!queryAll && !queryDate) return;
setLoading(true);
try {
const response = await api.get(
`${config.BACKEND_URL}/api/v1/getallschemes/?network=${network}`,
);
let filteredResults = response.data;
// Filter by type
filteredResults = filteredResults.filter((item: SchemaItem) => item.scheme_type === SCHEME_TYPE);
if (!queryAll && queryDate) {
const formattedDate = queryDate.format("YYYY-MM-DD");
filteredResults = filteredResults.filter((item: SchemaItem) => {
const itemDate = moment(item.create_time).format("YYYY-MM-DD");
return itemDate === formattedDate;
});
}
setSchemes(
filteredResults.map((item: SchemaItem) => ({
id: item.scheme_id,
schemeName: item.scheme_name,
type: item.scheme_type,
user: item.username,
create_time: item.create_time,
startTime: item.scheme_start_time,
schemeDetail: item.scheme_detail,
})),
);
if (filteredResults.length === 0) {
open?.({
type: "error",
message: "未找到相关方案",
description: "请尝试更改查询条件",
});
}
} catch (error) {
console.error("查询请求失败:", error);
open?.({
type: "error",
message: "查询失败",
description: "获取方案列表失败,请稍后重试",
});
} finally {
setLoading(false);
}
};
const handleViewResults = (scheme: SchemeRecord) => {
setShowTimeline(true);
const schemeDate = scheme.startTime ? new Date(scheme.startTime) : undefined;
if (scheme.startTime && scheme.schemeDetail?.duration) {
const start = new Date(scheme.startTime);
const end = new Date(start.getTime() + scheme.schemeDetail.duration * 1000);
setSelectedDate(schemeDate);
setTimeRange({ start, end });
}
setSchemeName?.(scheme.schemeName);
// Locate drainage node by default if available
if (scheme.schemeDetail?.drainage_node_ID) {
handleLocateDrainageNode(scheme.schemeDetail.drainage_node_ID);
}
};
return (
<>
{showTimeline &&
mapContainer &&
ReactDOM.createPortal(
<Timeline
schemeDate={selectedDate}
timeRange={timeRange}
disableDateSelection={!!timeRange}
schemeName={schemeName}
schemeType={SCHEME_TYPE}
/>,
mapContainer,
)}
<Box className="flex flex-col h-full">
{/* Query Controls */}
<Box className="mb-2 p-2 bg-gray-50 rounded">
<Box className="flex items-center gap-2 justify-between">
<Box className="flex items-center gap-2">
<FormControlLabel
control={
<Checkbox
checked={queryAll}
onChange={(e) => setQueryAll(e.target.checked)}
size="small"
/>
}
label={<Typography variant="body2"></Typography>}
className="m-0"
/>
<LocalizationProvider
dateAdapter={AdapterDayjs}
adapterLocale="zh-cn"
>
<DatePicker
value={queryDate}
onChange={(value) =>
value && dayjs.isDayjs(value) && setQueryDate(value)
}
format="YYYY-MM-DD"
disabled={queryAll}
slotProps={{
textField: {
size: "small",
sx: { width: 160 },
},
}}
/>
</LocalizationProvider>
</Box>
<Button
variant="contained"
onClick={handleQuery}
disabled={loading}
size="small"
startIcon={<SearchIcon />}
className="bg-blue-600 hover:bg-blue-700"
>
</Button>
</Box>
</Box>
{/* Results List */}
<Box className="flex-1 overflow-auto">
{schemes.length === 0 ? (
<Box className="flex flex-col items-center justify-center h-full text-gray-400">
<Typography variant="body2"></Typography>
</Box>
) : (
<Box className="space-y-2 p-1">
<Typography variant="caption" className="text-gray-500 px-1">
{schemes.length}
</Typography>
{schemes.map((scheme) => (
<Card
key={scheme.id}
variant="outlined"
className="hover:shadow-md transition-shadow"
>
<CardContent className="p-3 pb-2 last:pb-3">
<Box className="flex items-start justify-between mb-2">
<Box className="flex-1 min-w-0">
<Box className="flex items-center gap-2 mb-1">
<Typography
variant="body2"
className="font-medium truncate"
title={scheme.schemeName}
>
{scheme.schemeName}
</Typography>
<Chip
label="冲洗模拟"
size="small"
className="h-5"
color="primary"
variant="outlined"
/>
</Box>
<Typography
variant="caption"
className="text-gray-500 block"
>
: {scheme.user} · : {formatTime(scheme.create_time)}
</Typography>
</Box>
<Box className="flex gap-1 ml-2">
<Tooltip title="定位排水口">
<IconButton
size="small"
onClick={() =>
scheme.schemeDetail?.drainage_node_ID &&
handleLocateDrainageNode(scheme.schemeDetail.drainage_node_ID)
}
color="primary"
className="p-1"
>
<LocationIcon fontSize="small" />
</IconButton>
</Tooltip>
<Tooltip
title={
expandedId === scheme.id ? "收起详情" : "查看详情"
}
>
<IconButton
size="small"
onClick={() =>
setExpandedId(
expandedId === scheme.id ? null : scheme.id,
)
}
color="primary"
className="p-1"
>
<InfoIcon fontSize="small" />
</IconButton>
</Tooltip>
</Box>
</Box>
<Collapse in={expandedId === scheme.id}>
<Box className="mt-2 pt-3 border-t border-gray-200">
<Box className="grid grid-cols-2 gap-x-4 gap-y-3 mb-3">
<Box className="space-y-2">
<Box className="space-y-1.5 pl-2">
{/* 排水节点 */}
<Box className="flex items-start gap-2">
<Typography variant="caption" className="text-gray-600 min-w-[70px] mt-0.5">
:
</Typography>
<Box className="flex-1">
{scheme.schemeDetail?.drainage_node_ID ? (
<Link
component="button"
variant="caption"
className="font-medium text-blue-600 hover:text-blue-800 underline cursor-pointer"
onClick={(e) => {
e.preventDefault();
handleLocateDrainageNode(scheme.schemeDetail!.drainage_node_ID);
}}
>
{scheme.schemeDetail.drainage_node_ID}
</Link>
) : (
<Typography variant="caption" className="font-medium text-gray-900">
N/A
</Typography>
)}
</Box>
</Box>
{/* 冲洗流量 */}
<Box className="flex items-center gap-2">
<Typography variant="caption" className="text-gray-600 min-w-[70px]">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{scheme.schemeDetail?.flushing_flow ?? "-"} m³/h
</Typography>
</Box>
{/* 持续时长 */}
<Box className="flex items-center gap-2">
<Typography variant="caption" className="text-gray-600 min-w-[70px]">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{scheme.schemeDetail?.duration ?? "-"}
</Typography>
</Box>
</Box>
</Box>
<Box className="space-y-2">
<Box className="space-y-1.5 pl-2">
{/* 用户 */}
<Box className="flex items-center gap-2">
<Typography variant="caption" className="text-gray-600 min-w-[70px]">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{scheme.user}
</Typography>
</Box>
{/* 创建时间 */}
<Box className="flex items-center gap-2">
<Typography variant="caption" className="text-gray-600 min-w-[70px]">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{formatTime(scheme.create_time)}
</Typography>
</Box>
{/* 开始时间 */}
<Box className="flex items-center gap-2">
<Typography variant="caption" className="text-gray-600 min-w-[70px]">
:
</Typography>
<Typography variant="caption" className="font-medium text-gray-900">
{formatTime(scheme.startTime)}
</Typography>
</Box>
</Box>
</Box>
{/* 阀门列表 */}
<Box className="col-span-2 pl-2">
<Typography variant="caption" className="text-gray-600 block mb-1">
:
</Typography>
<Box className="flex flex-wrap gap-2">
{scheme.schemeDetail?.valve_opening && Object.entries(scheme.schemeDetail.valve_opening).length > 0 ? (
Object.entries(scheme.schemeDetail.valve_opening).map(([id, k]) => (
<Tooltip key={id} title="点击定位阀门">
<Chip
label={`${id}: ${k}`}
size="small"
variant="outlined"
onClick={() => handleLocateValves([id])}
className="text-xs h-6 bg-gray-50 cursor-pointer hover:bg-orange-50 hover:border-orange-200"
/>
</Tooltip>
))
) : (
<Typography variant="caption" className="text-gray-400"></Typography>
)}
</Box>
</Box>
</Box>
<Box className="pt-2 border-t border-gray-100 flex gap-2">
<Button
variant="outlined"
fullWidth
size="small"
className="border-blue-600 text-blue-600 hover:bg-blue-50"
onClick={() =>
scheme.schemeDetail?.drainage_node_ID &&
handleLocateDrainageNode(scheme.schemeDetail.drainage_node_ID)
}
startIcon={<LocationIcon className="w-4 h-4" />}
sx={{ textTransform: "none", fontWeight: 500 }}
>
</Button>
<Button
variant="contained"
fullWidth
size="small"
className="bg-blue-600 hover:bg-blue-700"
onClick={() => handleViewResults(scheme)}
sx={{ textTransform: "none", fontWeight: 500 }}
>
</Button>
</Box>
</Box>
</Collapse>
</CardContent>
</Card>
))}
</Box>
)}
</Box>
</Box>
</>
);
};
export default SchemeQuery;

View File

@@ -0,0 +1,27 @@
export interface SchemeDetail {
valve_opening: Record<string, number>;
drainage_node_ID: string;
flushing_flow: number;
duration: number;
}
export interface SchemeRecord {
id: number;
schemeName: string;
type: string;
user: string;
create_time: string;
startTime: string;
// 详情信息
schemeDetail?: SchemeDetail;
}
export interface SchemaItem {
scheme_id: number;
scheme_name: string;
scheme_type: string;
username: string;
create_time: string;
scheme_start_time: string;
scheme_detail?: SchemeDetail;
}

View File

@@ -29,6 +29,7 @@ import { TbArrowBackUp, TbArrowForwardUp } from "react-icons/tb";
import { FiSkipBack, FiSkipForward } from "react-icons/fi";
import { useData } from "../../../app/OlMap/MapComponent";
import { config, NETWORK_NAME } from "@/config/config";
import { apiFetch } from "@/lib/apiFetch";
import { useMap } from "../../../app/OlMap/MapComponent";
import { useHealthRisk } from "./HealthRiskContext";
import {
@@ -150,7 +151,6 @@ const Timeline: React.FC<TimelineProps> = ({
const handleStop = useCallback(() => {
setIsPlaying(false);
setSelectedDateTime(getRoundedDate(new Date()));
if (intervalRef.current) {
clearInterval(intervalRef.current);
intervalRef.current = null;
@@ -344,11 +344,11 @@ const Timeline: React.FC<TimelineProps> = ({
colorCases.push(["<=", ["get", "healthRisk"], breakValue], colorStr);
widthCases.push(["<=", ["get", "healthRisk"], breakValue], width);
});
console.log(
`应用健康风险样式,年份: ${currentYear}, 分段: ${breaks.length}`,
);
console.log("颜色表达式:", colorCases);
console.log("宽度表达式:", widthCases);
// console.log(
// `应用健康风险样式,年份: ${currentYear}, 分段: ${breaks.length}`,
// );
// console.log("颜色表达式:", colorCases);
// console.log("宽度表达式:", widthCases);
// 应用样式到图层
pipeLayer.setStyle({
"stroke-color": ["case", ...colorCases, "rgba(128, 128, 128, 1)"],
@@ -423,7 +423,7 @@ const Timeline: React.FC<TimelineProps> = ({
undoableTimeout: 3,
});
try {
const response = await fetch(
const response = await apiFetch(
`${config.BACKEND_URL}/api/v1/composite/pipeline-health-prediction?query_time=${query_time}&network_name=${NETWORK_NAME}`,
);
@@ -435,16 +435,19 @@ const Timeline: React.FC<TimelineProps> = ({
message: `模拟预测完成,获取到 ${results.length} 条管道数据`,
});
} else {
// 读取后端 HTTPException 返回的 detail 信息
const errorData = await response.json().catch(() => ({}));
const errorMessage = errorData.detail || "模拟预测失败";
open?.({
type: "error",
message: "模拟预测失败",
message: errorMessage,
});
}
} catch (error) {
} catch (error: any) {
console.error("Simulation prediction failed:", error);
open?.({
type: "error",
message: "模拟预测时发生错误",
message: `模拟预测时发生错误: ${error.message || "未知错误"}`,
});
} finally {
setIsPredicting(false);

View File

@@ -12,12 +12,12 @@ import {
import { PlayArrow as PlayArrowIcon } from "@mui/icons-material";
import { useNotification } from "@refinedev/core";
import { useGetIdentity } from "@refinedev/core";
import axios from "axios";
import { api } from "@/lib/api";
import { config, NETWORK_NAME } from "@/config/config";
type IUser = {
id: number;
name: string;
id: string;
name?: string;
};
const OptimizationParameters: React.FC = () => {
@@ -83,7 +83,7 @@ const OptimizationParameters: React.FC = () => {
setAnalyzing(true);
if (!user || !user.name) {
if (!user || !user.id) {
open?.({
type: "error",
message: "用户信息无效",
@@ -93,7 +93,7 @@ const OptimizationParameters: React.FC = () => {
try {
// 发送优化请求
const response = await axios.post(
const response = await api.post(
`${config.BACKEND_URL}/api/v1/sensorplacementscheme/create`,
null,
{
@@ -104,6 +104,7 @@ const OptimizationParameters: React.FC = () => {
method: method,
sensor_count: sensorCount,
min_diameter: minDiameter,
user_id: user.id,
user_name: user.name,
},
}

View File

@@ -24,7 +24,7 @@ import { LocalizationProvider } from "@mui/x-date-pickers/LocalizationProvider";
import { AdapterDayjs } from "@mui/x-date-pickers/AdapterDayjs";
import "dayjs/locale/zh-cn"; // 引入中文包
import dayjs, { Dayjs } from "dayjs";
import axios from "axios";
import { api } from "@/lib/api";
import moment from "moment";
import { config, NETWORK_NAME } from "@config/config";
import { useNotification } from "@refinedev/core";
@@ -141,14 +141,15 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
}
});
}, [highlightFeatures]);
// 查询方案
const handleQuery = async () => {
if (!queryAll && !queryDate) return;
setLoading(true);
try {
const response = await axios.get(
`${config.BACKEND_URL}/api/v1/getallsensorplacements/?network=${network}`
const response = await api.get(
`${config.BACKEND_URL}/api/v1/getallsensorplacements/?network=${network}`,
);
let filteredResults = response.data;
@@ -171,7 +172,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
user: item.username,
create_time: item.create_time,
sensorLocation: item.sensor_location,
}))
})),
);
if (filteredResults.length === 0) {
@@ -206,14 +207,14 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
}
if (sensorIds.length > 0) {
queryFeaturesByIds(sensorIds).then((features) => {
queryFeaturesByIds(sensorIds, "geo_junctions_mat").then((features) => {
if (features.length > 0) {
// 设置高亮要素
setHighlightFeatures(features);
// 将 OpenLayers Feature 转换为 GeoJSON Feature
const geojsonFormat = new GeoJSON();
const geojsonFeatures = features.map((feature) =>
geojsonFormat.writeFeatureObject(feature)
geojsonFormat.writeFeatureObject(feature),
);
const extent = bbox(featureCollection(geojsonFeatures as any));
@@ -376,7 +377,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
size="small"
onClick={() =>
setExpandedId(
expandedId === scheme.id ? null : scheme.id
expandedId === scheme.id ? null : scheme.id,
)
}
color="primary"
@@ -385,7 +386,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
<InfoIcon fontSize="small" />
</IconButton>
</Tooltip>
<Tooltip title="定位">
{/* <Tooltip title="定位">
<IconButton
size="small"
onClick={() => onLocate?.(scheme.id)}
@@ -394,7 +395,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
>
<LocationIcon fontSize="small" />
</IconButton>
</Tooltip>
</Tooltip> */}
</Box>
</Box>
@@ -466,7 +467,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
className="font-medium text-gray-900"
>
{moment(scheme.create_time).format(
"YYYY-MM-DD HH:mm"
"YYYY-MM-DD HH:mm",
)}
</Typography>
</Box>
@@ -500,7 +501,7 @@ const SchemeQuery: React.FC<SchemeQueryProps> = ({
>
{sensorId}
</Link>
)
),
)}
</Box>
</Box>

View File

@@ -7,6 +7,7 @@ import { Stroke } from "ol/style";
import GeoJson from "ol/format/GeoJSON";
import config from "@config/config";
import { useMap } from "@app/OlMap/MapComponent";
import { useProject } from "@/contexts/ProjectContext";
interface PropertyItem {
key: string;
@@ -26,6 +27,8 @@ const ZonePropsPanel: React.FC<ZonePropsPanelProps> = ({
onClose,
}) => {
const map = useMap();
const project = useProject();
const workspace = project?.workspace;
const [props, setProps] = React.useState<
PropertyItem[] | Record<string, any>
@@ -103,9 +106,10 @@ const ZonePropsPanel: React.FC<ZonePropsPanelProps> = ({
if (!map) {
return;
}
const workspaceValue = workspace || config.MAP_WORKSPACE;
const networkZoneLayer = new VectorLayer({
source: new VectorSource({
url: `${config.MAP_URL}/${config.MAP_WORKSPACE}/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=${config.MAP_WORKSPACE}:network_zone&outputFormat=application/json`,
url: `${config.MAP_URL}/${workspaceValue}/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=${workspaceValue}:network_zone&outputFormat=application/json`,
format: new GeoJson(),
}),
style: new Style({
@@ -155,7 +159,7 @@ const ZonePropsPanel: React.FC<ZonePropsPanelProps> = ({
map.removeLayer(highlightLayer);
map.un("click", clickListener);
};
}, [map, handleMapClickSelectFeatures]);
}, [map, handleMapClickSelectFeatures, workspace]);
// 获取中文标签
const getChineseLabel = (key: string): string => {
const labelMap: Record<string, string> = {

View File

@@ -37,14 +37,15 @@ import { zhCN as pickerZhCN } from "@mui/x-date-pickers/locales";
import config from "@/config/config";
import { useGetIdentity } from "@refinedev/core";
import { useNotification } from "@refinedev/core";
import axios from "axios";
import { api } from "@/lib/api";
import { apiFetch } from "@/lib/apiFetch";
dayjs.extend(utc);
dayjs.extend(timezone);
type IUser = {
id: number;
name: string;
id: string;
name?: string;
};
export interface TimeSeriesPoint {
@@ -96,10 +97,10 @@ const fetchFromBackend = async (
try {
// 优先查询清洗数据和模拟数据
const [cleaningRes, simulationRes] = await Promise.all([
fetch(cleaningDataUrl)
apiFetch(cleaningDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
fetch(simulationDataUrl)
apiFetch(simulationDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
]);
@@ -118,7 +119,7 @@ const fetchFromBackend = async (
);
} else {
// 如果清洗数据没有数据,查询原始数据,返回模拟和原始数据
const rawRes = await fetch(rawDataUrl)
const rawRes = await apiFetch(rawDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null);
const rawData = transformBackendData(rawRes, deviceIds);
@@ -338,13 +339,13 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
const simulationDataUrl = `${config.BACKEND_URL}/api/v1/composite/scada-simulation?device_ids=${device_ids}&start_time=${start_time}&end_time=${end_time}`;
try {
const [cleanRes, rawRes, simRes] = await Promise.all([
fetch(cleaningDataUrl)
apiFetch(cleaningDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
fetch(rawDataUrl)
apiFetch(rawDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
fetch(simulationDataUrl)
apiFetch(simulationDataUrl)
.then((r) => (r.ok ? r.json() : null))
.catch(() => null),
]);
@@ -458,7 +459,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
return;
}
if (!user || !user.name) {
if (!user || !user.id) {
open?.({
type: "error",
message: "用户信息无效,请重新登录",
@@ -474,7 +475,7 @@ const SCADADataPanel: React.FC<SCADADataPanelProps> = ({
const endTime = dayjs(rangeTo).toISOString();
// 调用后端清洗接口
const response = await axios.post(
const response = await api.post(
`${
config.BACKEND_URL
}/api/v1/composite/clean-scada?device_ids=${deviceIds.join(

View File

@@ -48,11 +48,12 @@ import {
} from "@mui/icons-material";
import { FixedSizeList } from "react-window";
import { useNotification } from "@refinedev/core";
import axios from "axios";
import { api } from "@/lib/api";
import { useGetIdentity } from "@refinedev/core";
import config, { NETWORK_NAME } from "@/config/config";
import config from "@/config/config";
import { useMap } from "@app/OlMap/MapComponent";
import { useProject } from "@/contexts/ProjectContext";
import { GeoJSON } from "ol/format";
import { handleMapClickSelectFeatures as mapClickSelectFeatures } from "@/utils/mapQueryService";
import VectorLayer from "ol/layer/Vector";
@@ -103,8 +104,8 @@ interface SCADADeviceListProps {
}
type IUser = {
id: number;
name: string;
id: string;
name?: string;
};
const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
@@ -124,7 +125,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
const [isSelecting, setIsSelecting] = useState<boolean>(false);
const [internalSelection, setInternalSelection] = useState<string[]>([]);
const [pendingSelection, setPendingSelection] = useState<string[] | null>(
null
null,
);
const [internalDevices, setInternalDevices] = useState<SCADADevice[]>([]);
const [loading, setLoading] = useState<boolean>(true);
@@ -142,7 +143,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
// 清洗对话框状态
const [cleanDialogOpen, setCleanDialogOpen] = useState<boolean>(false);
const [cleanStartTime, setCleanStartTime] = useState<Dayjs>(() =>
dayjs().subtract(1, "week")
dayjs().subtract(1, "week"),
);
const [cleanEndTime, setCleanEndTime] = useState<Dayjs>(() => dayjs());
const [timeRangeError, setTimeRangeError] = useState<string>("");
@@ -180,12 +181,17 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
}
}, [pendingSelection, onSelectionChange]);
// Get workspace from context
const project = useProject();
const workspace = project?.workspace;
// 初始化 SCADA 设备列表
useEffect(() => {
const fetchScadaDevices = async () => {
setLoading(true);
try {
const url = `${config.MAP_URL}/${config.MAP_WORKSPACE}/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=${config.MAP_WORKSPACE}:geo_scada&outputFormat=application/json`;
const activeWorkspace = workspace || config.MAP_WORKSPACE;
const url = `${config.MAP_URL}/${activeWorkspace}/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=${activeWorkspace}:geo_scada&outputFormat=application/json`;
const response = await fetch(url);
if (!response.ok) throw new Error("Failed to fetch SCADA devices");
const json = await response.json();
@@ -199,7 +205,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
status: STATUS_OPTIONS[Math.floor(Math.random() * 4)],
coordinates: (feature.getGeometry() as Point)?.getCoordinates() as [
number,
number
number,
],
properties: feature.getProperties(),
}));
@@ -211,14 +217,14 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
}
};
fetchScadaDevices();
}, []);
}, [workspace]);
const effectiveDevices = devices.length > 0 ? devices : internalDevices;
// 获取设备类型列表
const deviceTypes = useMemo(() => {
const types = Array.from(
new Set(effectiveDevices.map((device) => device.type))
new Set(effectiveDevices.map((device) => device.type)),
);
return types.sort();
}, [effectiveDevices]);
@@ -406,7 +412,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
color: `rgba(255, 255, 0, ${(opacity * 0.3).toFixed(3)})`,
}),
}),
})
}),
);
vectorContext.drawGeometry(flashGeom);
@@ -423,7 +429,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
width: 2,
}),
}),
})
}),
);
vectorContext.drawGeometry(flashGeom);
@@ -436,7 +442,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
color: `rgba(255, 255, 255, ${opacity.toFixed(3)})`,
}),
}),
})
}),
);
vectorContext.drawGeometry(flashGeom);
@@ -519,7 +525,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
// 更新高亮要素
setHighlightFeatures((prev) => {
const existingIndex = prev.findIndex(
(f) => f.getProperties().id === featureId
(f) => f.getProperties().id === featureId,
);
if (existingIndex !== -1) {
// 如果已存在,移除
@@ -530,7 +536,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
}
});
},
[map, effectiveDevices, multiSelect, open]
[map, effectiveDevices, multiSelect, open],
);
// 处理清洗对话框关闭
@@ -561,7 +567,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
setTimeRangeError(error);
}
},
[cleanEndTime, validateTimeRange]
[cleanEndTime, validateTimeRange],
);
// 处理结束时间变化
@@ -574,7 +580,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
setTimeRangeError(error);
}
},
[cleanStartTime, validateTimeRange]
[cleanStartTime, validateTimeRange],
);
// 确认清洗
@@ -595,7 +601,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
return;
}
if (!user || !user.name) {
if (!user || !user.id) {
open?.({
type: "error",
message: "用户信息无效,请重新登录",
@@ -608,7 +614,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
open?.({
type: "progress",
message: "正在清洗数据,请稍候...",
undoableTimeout: 3000,
undoableTimeout: 3,
});
try {
@@ -616,8 +622,8 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
const endTime = dayjs(cleanEndTime).toISOString();
// 调用后端清洗接口
const response = await axios.post(
`${config.BACKEND_URL}/api/v1/composite/clean-scada?device_ids=all&start_time=${startTime}&end_time=${endTime}`
const response = await api.post(
`${config.BACKEND_URL}/api/v1/composite/clean-scada?device_ids=all&start_time=${startTime}&end_time=${endTime}`,
);
// 处理成功响应
@@ -1103,7 +1109,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
variant="caption"
sx={{
color: `${getStatusColor(
device.status.value
device.status.value,
)}.main`,
fontWeight: "bold",
fontSize: 16,
@@ -1134,7 +1140,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
/>
<Chip
label={`可靠度: ${getReliability(
device.reliability
device.reliability,
)}`}
size="small"
variant="outlined"
@@ -1156,7 +1162,7 @@ const SCADADeviceList: React.FC<SCADADeviceListProps> = ({
>
:{" "}
{getTransmissionFrequency(
device.transmission_frequency
device.transmission_frequency,
)}{" "}
</Typography>

View File

@@ -0,0 +1,291 @@
import { Title } from "@components/title";
import {
Dialog,
DialogContent,
DialogActions,
Button,
Select,
MenuItem,
FormControl,
InputLabel,
TextField,
Box,
Typography,
Fade,
IconButton,
} from "@mui/material";
import CloseIcon from "@mui/icons-material/Close";
import { useEffect, useState } from "react";
import { apiFetch } from "@/lib/apiFetch";
import { config, NETWORK_NAME } from "@/config/config";
interface ProjectSelectorProps {
open: boolean;
onSelect: (
projectId: string,
workspace: string,
networkName: string,
extent: number[],
) => void;
onClose?: () => void;
}
type ProjectOption = {
id: string;
label: string;
workspace: string;
networkName: string;
extent: number[];
description?: string | null;
status?: string | null;
projectRole?: string | null;
};
export const ProjectSelector: React.FC<ProjectSelectorProps> = ({
open,
onSelect,
onClose,
}) => {
const [projects, setProjects] = useState<ProjectOption[]>([]);
const [isLoading, setIsLoading] = useState(false);
const [loadError, setLoadError] = useState<string | null>(null);
const [projectId, setProjectId] = useState("");
const [projectIdError, setProjectIdError] = useState<string | null>(null);
const [workspace, setWorkspace] = useState(config.MAP_WORKSPACE);
const [networkName, setNetworkName] = useState(NETWORK_NAME || "tjwater");
const [extent, setExtent] = useState<number[]>(config.MAP_EXTENT);
const [customMode, setCustomMode] = useState(false);
useEffect(() => {
const fetchProjects = async () => {
setIsLoading(true);
setLoadError(null);
try {
const response = await apiFetch(
`${config.BACKEND_URL}/api/v1/meta/projects`,
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const mapped: ProjectOption[] = Array.isArray(data)
? data.map((item) => {
const bbox = Array.isArray(item.map_extent?.bbox)
? item.map_extent.bbox.map((value: number) => Number(value))
: null;
return {
id: item.project_id,
label: item.name || item.code || item.project_id,
workspace: item.gs_workspace || config.MAP_WORKSPACE,
networkName: item.code || NETWORK_NAME || config.MAP_WORKSPACE,
extent:
bbox && bbox.length === 4 ? bbox : config.MAP_EXTENT,
description: item.description,
status: item.status,
projectRole: item.project_role,
};
})
: [];
setProjects(mapped);
const savedProjectId = localStorage.getItem("active_project");
const initial =
(savedProjectId &&
mapped.find((project) => project.id === savedProjectId)) ||
mapped[0];
if (initial) {
setProjectId(initial.id);
setWorkspace(initial.workspace);
setNetworkName(initial.networkName);
setExtent(initial.extent);
setCustomMode(false);
} else {
setCustomMode(true);
}
} catch (error) {
console.error("Failed to load projects:", error);
setLoadError("项目列表加载失败,请使用自定义配置");
setCustomMode(true);
} finally {
setIsLoading(false);
}
};
fetchProjects();
}, []);
const handleConfirm = () => {
if (!projectId.trim()) {
setProjectIdError("项目 ID 不能为空");
return;
}
setProjectIdError(null);
onSelect(projectId.trim(), workspace, networkName, extent);
};
return (
<Dialog
open={open}
disableEscapeKeyDown={!onClose}
onClose={onClose ? onClose : undefined}
slotProps={{
paper: {
sx: {
borderRadius: 2,
padding: 2,
minWidth: 400,
background: "rgba(255, 255, 255, 0.95)",
backdropFilter: "blur(10px)",
position: "relative",
},
},
}}
slots={{ transition: Fade }}
transitionDuration={500}
>
{onClose && (
<IconButton
aria-label="close"
onClick={onClose}
sx={{
position: "absolute",
right: 8,
top: 8,
color: (theme) => theme.palette.grey[500],
}}
>
<CloseIcon />
</IconButton>
)}
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "center",
mb: 2,
}}
>
<Box sx={{ transform: "scale(1.5)", mb: 2, mt: 1 }}>
<Title />
</Box>
<Typography variant="subtitle1" color="text.secondary">
</Typography>
</Box>
<DialogContent
sx={{ display: "flex", flexDirection: "column", gap: 3, pt: 1 }}
>
{!customMode ? (
<FormControl fullWidth variant="outlined">
<InputLabel></InputLabel>
<Select
value={projectId}
label="项目"
onChange={(e) => {
const val = e.target.value;
if (val === "custom") {
setCustomMode(true);
setProjectIdError(null);
} else {
const p = projects.find((p) => p.id === val);
if (p) {
setProjectId(p.id);
setWorkspace(p.workspace);
setNetworkName(p.networkName);
setExtent(p.extent);
setProjectIdError(null);
}
}
}}
>
{projects.length === 0 && (
<MenuItem value="" disabled>
<Typography variant="body2" color="text.secondary">
{isLoading ? "正在加载项目..." : "暂无可用项目"}
</Typography>
</MenuItem>
)}
{projects.map((p) => (
<MenuItem key={p.id} value={p.id}>
<Box sx={{ display: "flex", flexDirection: "column" }}>
<Typography variant="body1">{p.label}</Typography>
<Typography variant="caption" color="text.secondary">
: {p.workspace} | : {p.networkName}
</Typography>
{(p.status || p.projectRole) && (
<Typography variant="caption" color="text.secondary">
{p.status ? `状态: ${p.status}` : ""}
{p.status && p.projectRole ? " | " : ""}
{p.projectRole ? `角色: ${p.projectRole}` : ""}
</Typography>
)}
</Box>
</MenuItem>
))}
<MenuItem value="custom">
<Typography variant="body1">...</Typography>
</MenuItem>
</Select>
{loadError && (
<Typography variant="caption" color="error">
{loadError}
</Typography>
)}
</FormControl>
) : (
<Box sx={{ display: "flex", flexDirection: "column", gap: 2 }}>
<TextField
label="项目 ID"
value={projectId}
onChange={(e) => {
setProjectId(e.target.value);
setProjectIdError(null);
}}
fullWidth
helperText={
projectIdError || "例如: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
}
error={Boolean(projectIdError)}
/>
<TextField
label="Geoserver 工作区"
value={workspace}
onChange={(e) => setWorkspace(e.target.value)}
fullWidth
helperText="例如: tjwater"
/>
<TextField
label="管网名称"
value={networkName}
onChange={(e) => setNetworkName(e.target.value)}
fullWidth
helperText="例如: tjwater"
/>
<Button
onClick={() => setCustomMode(false)}
size="small"
sx={{ alignSelf: "flex-start" }}
>
</Button>
</Box>
)}
</DialogContent>
<DialogActions sx={{ px: 3, pb: 2 }}>
<Button
onClick={handleConfirm}
variant="contained"
fullWidth
size="large"
sx={{
textTransform: "none",
borderRadius: 2,
fontWeight: "bold",
}}
>
</Button>
</DialogActions>
</Dialog>
);
};

View File

@@ -1,11 +1,10 @@
export const config = {
BACKEND_URL:
process.env.NEXT_PUBLIC_BACKEND_URL || "http://192.168.1.42:8000",
BACKEND_URL: process.env.NEXT_PUBLIC_BACKEND_URL || "http://127.0.0.1:8000",
MAP_URL: process.env.NEXT_PUBLIC_MAP_URL || "http://127.0.0.1:8080/geoserver",
MAP_WORKSPACE: process.env.NEXT_PUBLIC_MAP_WORKSPACE || "TJWater",
MAP_WORKSPACE: process.env.NEXT_PUBLIC_MAP_WORKSPACE || "tjwater",
MAP_EXTENT: process.env.NEXT_PUBLIC_MAP_EXTENT
? process.env.NEXT_PUBLIC_MAP_EXTENT.split(",").map(Number)
: [13508849, 3608035.75, 13555781, 3633812.75],
: [13508849, 3608036, 13555781, 3633813],
MAP_DEFAULT_STYLE: {
"stroke-width": 3,
"stroke-color": "rgba(51, 153, 204, 0.9)",
@@ -27,7 +26,20 @@ export const config = {
)
: ["junctions", "pipes", "valves", "reservoirs", "pumps", "tanks", "scada"],
};
export const NETWORK_NAME = process.env.NEXT_PUBLIC_NETWORK_NAME || "tjwater";
export let NETWORK_NAME = process.env.NEXT_PUBLIC_NETWORK_NAME || "tjwater";
export const setNetworkName = (name: string) => {
NETWORK_NAME = name;
};
export const setMapWorkspace = (workspace: string) => {
config.MAP_WORKSPACE = workspace;
};
export const setMapExtent = (extent: number[]) => {
config.MAP_EXTENT = extent;
};
export const MAPBOX_TOKEN =
process.env.NEXT_PUBLIC_MAPBOX_TOKEN ||
"pk.eyJ1IjoiemhpZnUiLCJhIjoiY205azNyNGY1MGkyZDJxcTJleDUwaHV1ZCJ9.wOmSdOnDDdre-mB1Lpy6Fg";

View File

@@ -0,0 +1,115 @@
"use client";
import React, { createContext, useContext, useEffect, useState } from "react";
import { useSession } from "next-auth/react";
import { config, NETWORK_NAME, setMapWorkspace, setNetworkName, setMapExtent } from "@/config/config";
import { ProjectSelector } from "@/components/project/ProjectSelector";
import { apiFetch } from "@/lib/apiFetch";
import { useProjectStore } from "@/store/projectStore";
interface ProjectContextType {
workspace: string;
networkName: string;
extent: number[];
}
const ProjectContext = createContext<ProjectContextType | undefined>(undefined);
export const ProjectProvider: React.FC<{ children: React.ReactNode }> = ({
children,
}) => {
const { status } = useSession();
const [isConfigured, setIsConfigured] = useState(false);
const setCurrentProjectId = useProjectStore(
(state) => state.setCurrentProjectId,
);
const [currentProject, setCurrentProject] = useState({
workspace: config.MAP_WORKSPACE,
networkName: NETWORK_NAME || "tjwater",
extent: config.MAP_EXTENT,
});
useEffect(() => {
// Check localStorage
const savedWorkspace = localStorage.getItem("NEXT_PUBLIC_MAP_WORKSPACE");
const savedNetwork = localStorage.getItem("NEXT_PUBLIC_NETWORK_NAME");
const savedExtent = localStorage.getItem("NEXT_PUBLIC_MAP_EXTENT");
const savedProjectId = localStorage.getItem("active_project");
// If we have saved config, use it.
if (savedWorkspace && savedNetwork) {
applyConfig(
savedProjectId || savedNetwork || savedWorkspace,
savedWorkspace,
savedNetwork,
savedExtent ? savedExtent.split(",").map(Number) : config.MAP_EXTENT,
);
}
}, []);
const applyConfig = async (
projectId: string,
ws: string,
net: string,
extent: number[],
) => {
const resolvedProjectId = projectId || net || ws;
setMapWorkspace(ws);
setNetworkName(net);
setMapExtent(extent);
localStorage.setItem("NEXT_PUBLIC_MAP_EXTENT", extent.join(","));
// Reset extent cache
localStorage.removeItem(`${ws}_map_view`);
setCurrentProject({ workspace: ws, networkName: net, extent: extent });
setCurrentProjectId(resolvedProjectId);
// Save to localStorage
localStorage.setItem("NEXT_PUBLIC_MAP_WORKSPACE", ws);
localStorage.setItem("NEXT_PUBLIC_NETWORK_NAME", net);
setIsConfigured(true);
try {
const response = await apiFetch(
`${config.BACKEND_URL}/openproject/?network=${net}`,
{
method: "POST",
},
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const data = await response.json();
const bbox = Array.isArray(data?.map_extent?.bbox)
? data.map_extent.bbox.map((value: number) => Number(value))
: null;
if (bbox && bbox.length === 4) {
setMapExtent(bbox);
localStorage.setItem("NEXT_PUBLIC_MAP_EXTENT", bbox.join(","));
localStorage.removeItem(`${ws}_map_view`);
setCurrentProject((prev) => ({ ...prev, extent: bbox }));
}
} catch (error) {
console.error("Failed to open project:", error);
}
};
// Only show selector if authenticated and not configured
if (status === "authenticated" && !isConfigured) {
return (
<ProjectSelector
open={true}
onSelect={(projectId, ws, net, extent) =>
applyConfig(projectId, ws, net, extent)
}
/>
);
}
return (
<ProjectContext.Provider value={currentProject}>
{children}
</ProjectContext.Provider>
);
};
export const useProject = () => useContext(ProjectContext);

34
src/lib/api.ts Normal file
View File

@@ -0,0 +1,34 @@
import axios from "axios";
import { config } from "@config/config";
import { useProjectStore } from "@/store/projectStore";
import { getAccessToken } from "@/lib/authToken";
export const API_URL = process.env.NEXT_PUBLIC_API_URL || config.BACKEND_URL;
export const api = axios.create({
baseURL: API_URL,
});
const isMetaProjectsRequest = (request: {
baseURL?: string;
url?: string;
}) => {
const url = `${request.baseURL ?? ""}${request.url ?? ""}`;
return url.includes("/api/v1/meta/projects");
};
api.interceptors.request.use(async (request) => {
const accessToken = await getAccessToken();
if (accessToken) {
request.headers = request.headers ?? {};
request.headers.Authorization = `Bearer ${accessToken}`;
}
const projectId = useProjectStore.getState().currentProjectId;
if (projectId && !isMetaProjectsRequest(request)) {
request.headers = request.headers ?? {};
request.headers["X-Project-Id"] = projectId;
}
return request;
});

28
src/lib/apiFetch.ts Normal file
View File

@@ -0,0 +1,28 @@
import { useProjectStore } from "@/store/projectStore";
import { getAccessToken } from "@/lib/authToken";
const resolveUrl = (input: RequestInfo | URL) => {
if (typeof input === "string") return input;
if (input instanceof URL) return input.toString();
if (input instanceof Request) return input.url;
return "";
};
const isMetaProjectsRequest = (input: RequestInfo | URL) =>
resolveUrl(input).includes("/api/v1/meta/projects");
export const apiFetch = async (
input: RequestInfo | URL,
init: RequestInit = {},
) => {
const projectId = useProjectStore.getState().currentProjectId;
const headers = new Headers(init.headers ?? {});
const accessToken = await getAccessToken();
if (accessToken) {
headers.set("Authorization", `Bearer ${accessToken}`);
}
if (projectId && !isMetaProjectsRequest(input)) {
headers.set("X-Project-Id", projectId);
}
return fetch(input, { ...init, headers });
};

51
src/lib/authToken.ts Normal file
View File

@@ -0,0 +1,51 @@
import { getSession } from "next-auth/react";
import { useAuthStore } from "@/store/authStore";
const decodeJwtPayload = (token: string) => {
const parts = token.split(".");
if (parts.length < 2) {
console.warn("Invalid JWT format.");
return null;
}
const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "=");
try {
const json =
typeof window !== "undefined"
? window.atob(padded)
: Buffer.from(padded, "base64").toString("utf-8");
return JSON.parse(json);
} catch (error) {
console.warn("Failed to decode JWT payload.", error);
return null;
}
};
const isTokenExpired = (token: string) => {
const payload = decodeJwtPayload(token);
if (!payload) {
return true;
}
if (typeof payload.exp !== "number") {
return false;
}
const now = Date.now();
return now >= payload.exp * 1000 - 30_000;
};
export const getAccessToken = async () => {
const { accessToken, setAccessToken } = useAuthStore.getState();
if (accessToken && !isTokenExpired(accessToken)) {
return accessToken;
}
if (accessToken) {
setAccessToken(null);
}
const session = await getSession();
const token = typeof session?.accessToken === "string" ? session.accessToken : null;
if (token && !isTokenExpired(token)) {
setAccessToken(token);
return token;
}
return null;
};

View File

@@ -1,7 +1,6 @@
"use client";
import dataProviderSimpleRest from "@refinedev/simple-rest";
import { api, API_URL } from "@/lib/api";
const API_URL = "https://api.fake-rest.refine.dev";
export const dataProvider = dataProviderSimpleRest(API_URL);
export const dataProvider = dataProviderSimpleRest(API_URL, api);

11
src/store/authStore.ts Normal file
View File

@@ -0,0 +1,11 @@
import { create } from "zustand";
interface AuthState {
accessToken: string | null;
setAccessToken: (token: string | null) => void;
}
export const useAuthStore = create<AuthState>((set) => ({
accessToken: null,
setAccessToken: (token) => set({ accessToken: token }),
}));

27
src/store/projectStore.ts Normal file
View File

@@ -0,0 +1,27 @@
import { create } from "zustand";
interface ProjectState {
currentProjectId: string | null;
setCurrentProjectId: (id: string | null) => void;
}
const getInitialProjectId = () => {
if (typeof window === "undefined") {
return null;
}
return localStorage.getItem("active_project");
};
export const useProjectStore = create<ProjectState>((set) => ({
currentProjectId: getInitialProjectId(),
setCurrentProjectId: (id) => {
if (typeof window !== "undefined") {
if (id) {
localStorage.setItem("active_project", id);
} else {
localStorage.removeItem("active_project");
}
}
set({ currentProjectId: id });
},
}));

25
src/types/next-auth.d.ts vendored Normal file
View File

@@ -0,0 +1,25 @@
import "next-auth";
import "next-auth/jwt";
declare module "next-auth" {
interface Session {
accessToken?: string;
user?: {
id?: string;
name?: string | null;
email?: string | null;
image?: string | null;
};
}
interface User {
id?: string;
}
}
declare module "next-auth/jwt" {
interface JWT {
sub?: string;
accessToken?: string;
}
}

View File

@@ -40,15 +40,15 @@ interface MapClickEvent {
// ========== 常量配置 ==========
/**
* GeoServer 服务配置
* GeoServer 服务配置获取函数
*/
const GEOSERVER_CONFIG = {
const getGeoserverConfig = () => ({
url: config.MAP_URL,
workspace: config.MAP_WORKSPACE,
layers: ["geo_pipes_mat", "geo_junctions_mat", "geo_valves"],
wfsVersion: "1.0.0",
outputFormat: "application/json",
} as const;
});
/**
* 地图交互配置
@@ -176,7 +176,7 @@ const convertRenderFeatureToFeature = (
* @returns WFS 查询 URL
*/
const buildWfsUrl = (layer: string, orFilter: string): string => {
const { url, workspace, wfsVersion, outputFormat } = GEOSERVER_CONFIG;
const { url, workspace, wfsVersion, outputFormat } = getGeoserverConfig();
const params = new URLSearchParams({
service: "WFS",
version: wfsVersion,
@@ -233,7 +233,7 @@ const queryFeaturesByIds = async (
try {
if (!layer) {
// 查询所有配置的图层
const promises = GEOSERVER_CONFIG.layers.map((layerName) =>
const promises = getGeoserverConfig().layers.map((layerName) =>
fetchFeaturesFromLayer(layerName, orFilter)
);

View File

@@ -0,0 +1,21 @@
const { parseColor } = require('./parseColor');
describe('parseColor', () => {
it('should parse hex color', () => {
expect(parseColor('#FF0000')).toEqual({ r: 255, g: 0, b: 0 });
expect(parseColor('00FF00')).toEqual({ r: 0, g: 255, b: 0 });
});
it('should parse rgb color', () => {
expect(parseColor('rgb(0, 0, 255)')).toEqual({ r: 0, g: 0, b: 255, a: 1 });
});
it('should parse rgba color', () => {
expect(parseColor('rgba(0, 0, 255, 0.5)')).toEqual({ r: 0, g: 0, b: 255, a: 0.5 });
});
it('should default alpha to 1 if not provided in rgba-like pattern', () => {
// The regex supports optional alpha
expect(parseColor('rgba(0, 0, 255)')).toEqual({ r: 0, g: 0, b: 255, a: 1 });
});
});

View File

@@ -16,18 +16,45 @@
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"jsx": "react-jsx",
"plugins": [
{
"name": "next"
}
],
"paths": {
"@*": [
"./src/*"
],
"@pages/*": [
"./pages/*"
],
"@app/*": [
"./src/app/*"
],
"@assets/*": [
"./src/assets/*"
],
"@components/*": [
"./src/components/*"
],
"@config/*": [
"./src/config/*"
],
"@contexts/*": [
"./src/contexts/*"
],
"@interfaces/*": [
"./src/interfaces/*"
],
"@libs/*": [
"./src/libs/*"
],
"@providers/*": [
"./src/providers/*"
],
"@utils/*": [
"./src/utils/*"
],
"@/*": [
"./src/*"
]
},
"incremental": true
@@ -36,7 +63,8 @@
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts"
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": [
"node_modules"