Compare commits
56
Commits
latest
..
18253f2fe0
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
18253f2fe0 | ||
|
|
02a8686222 | ||
|
|
50d823ca58 | ||
|
|
9f225374de | ||
|
|
9b16e4e0a5 | ||
|
|
810a39a1dc | ||
|
|
e49d21cd1b | ||
|
|
0a2ce81753 | ||
|
|
b8f2f70013 | ||
|
|
6f9c94a4dd | ||
|
|
9f7f5536d7 | ||
|
|
d33619d0d5 | ||
|
|
6a16ea44b2 | ||
|
|
e862e6c500 | ||
|
|
87824f3b3c | ||
|
|
18943314f8 | ||
|
|
c7947a7481 | ||
|
|
4b02118286 | ||
|
|
dc4e3de85e | ||
|
|
bb5d339dbe | ||
|
|
33615cdcfc | ||
|
|
d6dda51008 | ||
|
|
60c8fc4948 | ||
|
|
3de620a2ae | ||
|
|
8e07d580af | ||
|
|
9be0cd34cf | ||
|
|
f61be3685f | ||
|
|
78af7ecfb3 | ||
|
|
bf8e4fb040 | ||
|
|
67ba9c2ac6 | ||
|
|
21929b44fc | ||
|
|
24169bd277 | ||
|
|
a787327ca2 | ||
|
|
c676b55b70 | ||
|
|
322e8156ee | ||
|
|
1ec82971ca | ||
|
|
2d3fd353b4 | ||
|
|
4191f2e508 | ||
|
|
3fd152e033 | ||
|
|
f6361a9eca | ||
|
|
431cf38aaf | ||
|
|
220e641c0e | ||
|
|
ccfc78bb1c | ||
|
|
f90c5ab6bb | ||
|
|
67648587c5 | ||
|
|
42cac53319 | ||
|
|
c5f97da5c0 | ||
|
|
bf088f691b | ||
|
|
ceea6e7456 | ||
|
|
8338e11837 | ||
|
|
59e44eb1e8 | ||
|
|
cbad19e3bb | ||
|
|
41173d61c8 | ||
|
|
b58f075344 | ||
|
|
90a9bb62c6 | ||
|
|
a310522812 |
+1
-1
@@ -13,7 +13,7 @@ temp/
|
||||
data/
|
||||
# db_inp/
|
||||
inp/
|
||||
# .env
|
||||
.env
|
||||
*.pyc
|
||||
*.dump
|
||||
app/algorithms/health/model/my_survival_forest_model_quxi.joblib
|
||||
|
||||
@@ -45,7 +45,6 @@ METADATA_DB_PASSWORD="password"
|
||||
KEYCLOAK_PUBLIC_KEY="-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----"
|
||||
KEYCLOAK_ALGORITHM=RS256
|
||||
KEYCLOAK_AUDIENCE="account"
|
||||
KEYCLOAK_ACCESS_TOKEN_MAX_AGE_SECONDS=900
|
||||
|
||||
|
||||
# ============================================
|
||||
|
||||
@@ -1,263 +0,0 @@
|
||||
name: Server CI/CD
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- "v*"
|
||||
- "latest"
|
||||
workflow_dispatch: {}
|
||||
|
||||
jobs:
|
||||
docker-image:
|
||||
runs-on: ubuntu-22.04
|
||||
if: startsWith(github.ref, 'refs/tags/')
|
||||
permissions:
|
||||
contents: read
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: https://gitea.waternetwork.cn/actions/checkout@v4
|
||||
with:
|
||||
fetch-depth: 1
|
||||
|
||||
- name: Normalize image metadata
|
||||
env:
|
||||
RAW_REGISTRY_HOST: ${{ vars.REGISTRY_HOST }}
|
||||
RAW_REPOSITORY: ${{ github.repository }}
|
||||
RAW_REF_NAME: ${{ github.ref_name }}
|
||||
run: |
|
||||
RAW_REGISTRY_HOST="$(printf '%s' "${RAW_REGISTRY_HOST}" | sed 's/^[[:space:]]*//;s/[[:space:]]*$//')"
|
||||
|
||||
if [ -z "${RAW_REGISTRY_HOST}" ]; then
|
||||
echo "Missing required repository variable: REGISTRY_HOST"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
REGISTRY_HOST="${RAW_REGISTRY_HOST#http://}"
|
||||
REGISTRY_HOST="${REGISTRY_HOST#https://}"
|
||||
REGISTRY_HOST="${REGISTRY_HOST%/}"
|
||||
|
||||
if [ -z "${REGISTRY_HOST}" ]; then
|
||||
echo "Repository variable REGISTRY_HOST resolves to an empty host"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
REPOSITORY_PATH="${RAW_REPOSITORY#/}"
|
||||
IMAGE_OWNER="${REPOSITORY_PATH%%/*}"
|
||||
IMAGE_REPOSITORY_PATH="$(printf '%s' "${IMAGE_OWNER}/tjwater-backend" | tr '[:upper:]' '[:lower:]')"
|
||||
IMAGE_NAME="${REGISTRY_HOST}/${IMAGE_REPOSITORY_PATH}"
|
||||
IMAGE_TAG="${RAW_REF_NAME}"
|
||||
{
|
||||
echo "REGISTRY_HOST=${REGISTRY_HOST}"
|
||||
echo "REPOSITORY_PATH=${REPOSITORY_PATH}"
|
||||
echo "IMAGE_REPOSITORY_PATH=${IMAGE_REPOSITORY_PATH}"
|
||||
echo "IMAGE_NAME=${IMAGE_NAME}"
|
||||
echo "IMAGE_TAG=${IMAGE_TAG}"
|
||||
echo "IMAGE_REF=${IMAGE_NAME}:${IMAGE_TAG}"
|
||||
} >> "$GITHUB_ENV"
|
||||
|
||||
- name: Login to Gitea Container Registry
|
||||
env:
|
||||
REGISTRY_USERNAME: ${{ secrets.REGISTRY_USERNAME }}
|
||||
REGISTRY_PASSWORD: ${{ secrets.REGISTRY_PASSWORD }}
|
||||
GITEA_SERVER_URL: ${{ github.server_url }}
|
||||
run: |
|
||||
if [ -z "${REGISTRY_HOST:-}" ]; then
|
||||
echo "Missing resolved environment value: REGISTRY_HOST"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "${REGISTRY_USERNAME}" ]; then
|
||||
echo "Missing required repository secret: REGISTRY_USERNAME"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -z "${REGISTRY_PASSWORD}" ]; then
|
||||
echo "Missing required repository secret: REGISTRY_PASSWORD"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Registry username: ${REGISTRY_USERNAME}"
|
||||
echo "Image target: ${IMAGE_REF}"
|
||||
|
||||
API_SERVER_URL="${GITEA_SERVER_URL%/}"
|
||||
api_user="$(curl -fsS \
|
||||
-H "Authorization: token ${REGISTRY_PASSWORD}" \
|
||||
"${API_SERVER_URL}/api/v1/user" \
|
||||
| sed -n 's/.*"login"[[:space:]]*:[[:space:]]*"\([^"]*\)".*/\1/p' \
|
||||
| head -n 1 || true)"
|
||||
|
||||
if [ -n "${api_user}" ]; then
|
||||
echo "Registry token resolves to Gitea user: ${api_user}"
|
||||
else
|
||||
echo "Could not resolve Gitea user from REGISTRY_PASSWORD token; docker login may still use a password or a token without API access."
|
||||
fi
|
||||
|
||||
echo "Logging into registry host: ${REGISTRY_HOST}"
|
||||
echo "${REGISTRY_PASSWORD}" | docker login "$REGISTRY_HOST" \
|
||||
--username "${REGISTRY_USERNAME}" \
|
||||
--password-stdin
|
||||
|
||||
- name: Materialize runtime env file
|
||||
env:
|
||||
TJWATER_SERVER_ENV: ${{ secrets.TJWATER_SERVER_ENV }}
|
||||
run: |
|
||||
if [ -z "${TJWATER_SERVER_ENV}" ]; then
|
||||
echo "Missing required repository secret: TJWATER_SERVER_ENV"
|
||||
echo "Store the backend .env file content as a multiline Gitea repository secret named TJWATER_SERVER_ENV."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '%s\n' "${TJWATER_SERVER_ENV}" > .env
|
||||
chmod 600 .env
|
||||
|
||||
required_env_keys=(
|
||||
ENVIRONMENT
|
||||
NETWORK_NAME
|
||||
DB_NAME
|
||||
DB_HOST
|
||||
DB_PORT
|
||||
DB_USER
|
||||
DB_PASSWORD
|
||||
TIMESCALEDB_DB_NAME
|
||||
TIMESCALEDB_DB_HOST
|
||||
TIMESCALEDB_DB_PORT
|
||||
TIMESCALEDB_DB_USER
|
||||
TIMESCALEDB_DB_PASSWORD
|
||||
METADATA_DB_NAME
|
||||
METADATA_DB_HOST
|
||||
METADATA_DB_PORT
|
||||
METADATA_DB_USER
|
||||
METADATA_DB_PASSWORD
|
||||
DATABASE_ENCRYPTION_KEY
|
||||
)
|
||||
|
||||
missing_keys=()
|
||||
for key in "${required_env_keys[@]}"; do
|
||||
if ! grep -Eq "^[[:space:]]*(export[[:space:]]+)?${key}[[:space:]]*=" .env; then
|
||||
missing_keys+=("$key")
|
||||
fi
|
||||
done
|
||||
|
||||
if [ "${#missing_keys[@]}" -gt 0 ]; then
|
||||
echo "TJWATER_SERVER_ENV is missing required keys: ${missing_keys[*]}"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Validate workspace
|
||||
run: |
|
||||
if [ ! -f ./Dockerfile ]; then
|
||||
echo "Dockerfile not found in workspace. Repository checkout may have failed or produced an unexpected workspace."
|
||||
exit 1
|
||||
fi
|
||||
|
||||
- name: Build and Push Image
|
||||
run: |
|
||||
if [ -z "${IMAGE_NAME:-}" ] || [ -z "${IMAGE_TAG:-}" ]; then
|
||||
echo "Missing resolved image metadata: IMAGE_NAME or IMAGE_TAG"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
push_with_retry() {
|
||||
image_ref="$1"
|
||||
attempt=1
|
||||
max_attempts=3
|
||||
|
||||
while [ "$attempt" -le "$max_attempts" ]; do
|
||||
if docker push "$image_ref"; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
if [ "$attempt" -eq "$max_attempts" ]; then
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "Push failed for $image_ref (attempt $attempt/$max_attempts); retrying in 10s..."
|
||||
attempt=$((attempt + 1))
|
||||
sleep 10
|
||||
done
|
||||
}
|
||||
|
||||
if [ "${IMAGE_TAG}" = "latest" ]; then
|
||||
docker build \
|
||||
-f ./Dockerfile \
|
||||
-t "${IMAGE_NAME}:latest" \
|
||||
.
|
||||
push_with_retry "${IMAGE_NAME}:latest"
|
||||
else
|
||||
docker build \
|
||||
-f ./Dockerfile \
|
||||
-t "${IMAGE_NAME}:${IMAGE_TAG}" \
|
||||
-t "${IMAGE_NAME}:latest" \
|
||||
.
|
||||
push_with_retry "${IMAGE_NAME}:${IMAGE_TAG}"
|
||||
push_with_retry "${IMAGE_NAME}:latest"
|
||||
fi
|
||||
|
||||
- name: Notify Deploy Server
|
||||
run: |
|
||||
post_deploy_webhook() {
|
||||
label="$1"
|
||||
payload="$2"
|
||||
webhook_url="${{ vars.DEPLOY_WEBHOOK_URL }}"
|
||||
token="${{ secrets.DEPLOY_WEBHOOK_TOKEN }}"
|
||||
|
||||
webhook_url=$(echo "$webhook_url" | xargs)
|
||||
|
||||
if [ -z "$webhook_url" ]; then
|
||||
echo "Missing required repository variable: DEPLOY_WEBHOOK_URL"
|
||||
return 1
|
||||
fi
|
||||
|
||||
if [ -z "$token" ]; then
|
||||
echo "Missing required repository secret: DEPLOY_WEBHOOK_TOKEN"
|
||||
return 1
|
||||
fi
|
||||
|
||||
echo "[$label] Calling webhook: $webhook_url"
|
||||
|
||||
http_code=$(curl -sS -D /tmp/deploy_headers.txt -o /tmp/deploy_response.txt -w "%{http_code}" -X POST "$webhook_url" \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $token" \
|
||||
-d "$payload")
|
||||
|
||||
echo "[$label] webhook HTTP status: ${http_code}"
|
||||
if [ "$http_code" -ge 200 ] && [ "$http_code" -lt 300 ]; then
|
||||
return 0
|
||||
fi
|
||||
|
||||
echo "[$label] response headers:"
|
||||
cat /tmp/deploy_headers.txt
|
||||
echo "[$label] response body:"
|
||||
cat /tmp/deploy_response.txt
|
||||
return 1
|
||||
}
|
||||
|
||||
PRIMARY_PAYLOAD="{\"image\":\"${IMAGE_REF}\",\"tag\":\"${IMAGE_TAG}\",\"repo\":\"${REPOSITORY_PATH}\"}"
|
||||
FALLBACK_PAYLOAD="{\"image\":\"${IMAGE_REF}\",\"tag\":\"${IMAGE_TAG}\",\"repo\":\"${IMAGE_REPOSITORY_PATH}\"}"
|
||||
|
||||
echo "Deploy webhook target: ${{ vars.DEPLOY_WEBHOOK_URL }}"
|
||||
echo "Deploy payload(primary): image=${IMAGE_REF}, tag=${IMAGE_TAG}, repo=${REPOSITORY_PATH}"
|
||||
if post_deploy_webhook "primary" "$PRIMARY_PAYLOAD"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Primary webhook request failed, retrying with lowercase repo path..."
|
||||
echo "Deploy payload(fallback): image=${IMAGE_REF}, tag=${IMAGE_TAG}, repo=${IMAGE_REPOSITORY_PATH}"
|
||||
if post_deploy_webhook "fallback" "$FALLBACK_PAYLOAD"; then
|
||||
exit 0
|
||||
fi
|
||||
|
||||
echo "Deploy webhook failed after primary and fallback attempts."
|
||||
exit 1
|
||||
|
||||
deploy-fallback-log:
|
||||
runs-on: ubuntu-22.04
|
||||
needs: docker-image
|
||||
if: failure()
|
||||
steps:
|
||||
- name: Deployment not triggered
|
||||
run: echo "Image build/push failed, deployment webhook was not called."
|
||||
@@ -7,4 +7,3 @@ build/
|
||||
*.dump
|
||||
.vscode/
|
||||
app/algorithms/health/model/my_survival_forest_model_quxi.joblib
|
||||
inp/
|
||||
|
||||
@@ -1,38 +1,73 @@
|
||||
# Repository Guidelines
|
||||
|
||||
## Project Structure & Module Organization
|
||||
## Project Purpose
|
||||
|
||||
This repository contains the TJWater Python backend. Main application code lives in `app/`: API routes under `app/api`, authentication in `app/auth`, configuration in `app/core`, database and repository code in `app/infra`, domain models/schemas in `app/domain`, and business logic in `app/services` and `app/algorithms`.
|
||||
This repository is the customer-delivery edition of the TJWater backend. Treat it as a deployable delivery package, not as the primary internal development repository. Changes should be limited to customer-facing fixes, deployment compatibility, configuration templates, packaging, and delivery documentation.
|
||||
|
||||
Tests are under `tests/`, split into `tests/unit`, `tests/api`, and `tests/auth`. SQL and sample assets are stored in `resources/`; deployment files are in `Dockerfile`, `.gitea/workflows/package.yml`, and `infra/docker/docker-compose.yml`. Local data directories such as `db_inp/`, `temp/`, `data/`, and `.env` are ignored and should not be committed.
|
||||
Do not introduce internal-only experiments, debug utilities, local data, or source material that is not required for customer operation.
|
||||
|
||||
## Build, Test, and Development Commands
|
||||
## Source Encapsulation Requirement
|
||||
|
||||
Use the existing conda environment when available:
|
||||
Core backend source code must be encapsulated before delivery. The sensitive implementation areas include business services, native integrations, hydraulic/network algorithms, and EPANET-related logic, especially:
|
||||
|
||||
- `app/services`
|
||||
- `app/native`
|
||||
- `app/algorithms`
|
||||
- `app/infra/epanet`
|
||||
|
||||
Use the existing Cython packaging flow in `scripts/compile.py` for these areas. Do not ship uncompiled core `.py` files in the final customer package when compiled extension modules are expected. Keep public entry points, configuration loading, route wiring, and minimal package files readable only where required for runtime and operations.
|
||||
|
||||
Before removing source files with `--delete-source`, verify the build from a clean working tree or disposable copy. The delete mode is destructive by design.
|
||||
|
||||
## Workspace Structure
|
||||
|
||||
- `app/main.py` is the FastAPI entry point.
|
||||
- `app/api` contains HTTP route handlers.
|
||||
- `app/services` contains core business orchestration and must be protected in delivery builds.
|
||||
- `app/native`, `app/algorithms`, and `app/infra/epanet` contain specialized computation and integration code that must be protected in delivery builds.
|
||||
- `infra/` and `Dockerfile` contain deployment assets.
|
||||
- `scripts/` contains operational and packaging helpers.
|
||||
- `tests/` contains backend tests.
|
||||
|
||||
## Common Commands
|
||||
|
||||
Run commands from this repository root:
|
||||
|
||||
```bash
|
||||
conda run -n server python -m pytest tests/unit tests/auth -q
|
||||
conda run -n server uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
|
||||
docker build -t tjwater-server:local .
|
||||
docker compose -f infra/docker/docker-compose.yml config
|
||||
conda run -n server python -m pytest tests -q
|
||||
conda run -n server python scripts/run_server.py
|
||||
conda run -n server python scripts/compile.py
|
||||
```
|
||||
|
||||
`pytest` runs backend tests. `uvicorn` starts the FastAPI app locally. `docker build` verifies the container image. `docker compose config` validates compose syntax and variable expansion.
|
||||
Clean compiled extensions when needed:
|
||||
|
||||
## Coding Style & Naming Conventions
|
||||
```bash
|
||||
conda run -n server python scripts/compile.py --clean
|
||||
```
|
||||
|
||||
Use Python 3.12, four-space indentation, type hints for new public functions, and explicit imports. Keep API endpoint modules grouped by domain under `app/api/v1/endpoints`. Use `snake_case` for files, functions, and variables; `PascalCase` for classes and Pydantic models. Prefer existing repository/service patterns in `app/infra/db` and `app/services` over introducing new abstractions.
|
||||
Only use source deletion in a prepared delivery copy:
|
||||
|
||||
```bash
|
||||
conda run -n server python scripts/compile.py --delete-source
|
||||
```
|
||||
|
||||
## Change Policy
|
||||
|
||||
Keep changes scoped and conservative. Prefer compatibility patches, configuration adjustments, packaging fixes, and customer deployment hardening. If a change requires substantial business logic updates, make it first in the internal backend repository and then port the reviewed result here.
|
||||
|
||||
Do not weaken the encapsulation process to make debugging easier. If debugging requires readable source, do it in the internal repository or a non-delivery branch/copy.
|
||||
|
||||
## Testing Guidelines
|
||||
|
||||
The project uses `pytest`. Name test files `test_*.py` and test functions `test_*`. Keep unit tests isolated with fakes or monkeypatching from `tests/conftest.py`. Some existing tests depend on local data outside the repository; avoid adding new tests that require untracked files. For API changes, add or update tests in `tests/api`.
|
||||
Run the narrowest useful test command for the affected area. For delivery packaging changes, verify both:
|
||||
|
||||
## Commit & Pull Request Guidelines
|
||||
- tests still pass before packaging;
|
||||
- the packaged/compiled runtime can import and start the FastAPI app.
|
||||
|
||||
History uses a mix of Conventional Commit prefixes and concise Chinese messages, for example `feat(api): add Tianditu geocoding` or `fix(auth): validate project context`. Prefer `feat(scope): ...`, `fix(scope): ...`, or a clear Chinese summary.
|
||||
Do not add tests that depend on untracked customer data, local database dumps, or machine-specific files.
|
||||
|
||||
Pull requests should describe the behavior change, list verification commands, mention configuration or migration impacts, and link related issues. Include API examples or screenshots only when they clarify user-facing behavior.
|
||||
## Security & Delivery Rules
|
||||
|
||||
## Security & Configuration Tips
|
||||
Never commit `.env`, production credentials, customer data, logs, generated caches, `node_modules/`, database dumps, or temporary delivery archives. Use `.env.example` or deployment documentation for required configuration.
|
||||
|
||||
Do not commit `.env`, database dumps, generated caches, or local project data. Use `.env.example` as the configuration template. Secrets for CI/CD belong in Gitea repository secrets such as `REGISTRY_USERNAME`, `REGISTRY_PASSWORD`, and deploy webhook credentials.
|
||||
Review Docker and deployment files carefully before delivery. Customer packages should contain only the files needed to run, operate, and diagnose the deployed service.
|
||||
|
||||
@@ -13,29 +13,10 @@ TJWater metadata stores only business snapshots and authorization data:
|
||||
The backend does not accept passwords, does not issue local JWTs, and does not
|
||||
trust frontend-supplied user IDs.
|
||||
|
||||
## Fixed Project RBAC
|
||||
|
||||
Project roles are stored directly in
|
||||
`user_project_membership.project_role`; there is no separate role table or
|
||||
user-defined permission editor in this delivery.
|
||||
|
||||
| Role | Main access |
|
||||
| --- | --- |
|
||||
| `modeler` | Model upload/import, simulation, burst, risk, and optimization analysis |
|
||||
| `dispatcher` | SCADA cleaning, simulation and burst analysis |
|
||||
| `auditor` | Project read access and project-scoped audit logs |
|
||||
| `viewer` | WebGIS and read-only risk results |
|
||||
|
||||
Legacy `owner`, `admin`, and `member` values remain supported for existing
|
||||
records. The backend is the authorization boundary; the frontend uses
|
||||
`GET /api/v1/access/context` only to hide unavailable menus and guard routes.
|
||||
System admins receive environment, membership, and global-audit permissions,
|
||||
but still need a project membership for project business APIs.
|
||||
|
||||
## Login Snapshot Refresh
|
||||
|
||||
Every authenticated metadata-user resolution validates the Keycloak access token
|
||||
and reads `sub`, `preferred_username`, and `email` claims. The
|
||||
and reads `sub`, `preferred_username` or `username`, and `email` claims. The
|
||||
backend finds `users` by `keycloak_id = sub`, rejects inactive or missing users,
|
||||
then refreshes `username`, `email`, and `last_login_at`.
|
||||
|
||||
@@ -96,22 +77,14 @@ Apply metadata patches in order:
|
||||
|
||||
1. `resources/sql/004_metadata_auth_management.sql`
|
||||
2. `resources/sql/005_metadata_project_configuration.sql`
|
||||
3. `resources/sql/006_metadata_rbac_roles.sql`
|
||||
|
||||
`004` creates Keycloak-backed metadata users and project memberships. `005`
|
||||
creates project and project database routing tables with uniqueness, role/type,
|
||||
and pool-size constraints. `006` extends existing membership constraints with
|
||||
the fixed delivery roles.
|
||||
and pool-size constraints.
|
||||
|
||||
## Frontend System Management
|
||||
|
||||
`/system-admin` is shown only when `GET /api/v1/access/context` returns
|
||||
`environment.manage`. The page lets admins maintain metadata users, project
|
||||
members, projects, project database routing for `biz_data` and `iot_data`, and
|
||||
connection health checks. This replaces direct SQL editing for normal project
|
||||
onboarding.
|
||||
|
||||
Hydraulic model authoring is outside the Web application. Models are prepared
|
||||
in the desktop modeling client and uploaded/imported by an authorized modeler;
|
||||
the system administrator configures the project environment and database
|
||||
routing.
|
||||
`/system-admin` is shown only after `GET /api/v1/admin/me` confirms metadata
|
||||
admin access. The page lets admins maintain metadata users, project members,
|
||||
projects, project database routing for `biz_data` and `iot_data`, connection
|
||||
health checks. This replaces direct SQL editing for normal project onboarding.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Backend Naming Audit
|
||||
|
||||
DOC-003 audit for the internal `TJWaterServerBinary` backend.
|
||||
DOC-003 audit for the customer-delivery `TJWaterServerCustomer` backend.
|
||||
|
||||
## Scope
|
||||
|
||||
@@ -12,15 +12,14 @@ The backend is mounted only under `/api/v1` from `app/main.py`; the old no-prefi
|
||||
|
||||
These newer routes already follow the naming rule for public HTTP paths:
|
||||
|
||||
- Metadata/admin: `/api/v1/admin/projects`, `/api/v1/admin/users/sync`, `/api/v1/admin/projects/{project_id}/members`
|
||||
- Audit: `/api/v1/audit/logs`, `/api/v1/audit/logs/count`
|
||||
- Agent auth: `/api/v1/agent/auth/context`
|
||||
- Metadata: `/api/v1/meta/project`, `/api/v1/meta/projects`, `/api/v1/meta/db/health`
|
||||
- Business APIs: `/api/v1/burst-detection/detect`, `/api/v1/burst-location/locate`, `/api/v1/leakage/identify`
|
||||
- Time-series APIs: `/api/v1/scada/by-ids-time-range`, `/api/v1/scada/by-ids-field-time-range`, `/api/v1/composite/clean-scada`
|
||||
- Project data APIs: `/api/v1/scada-info`, `/api/v1/scheme-list`, `/api/v1/burst-locate-result`
|
||||
- Web integrations: `/api/v1/web-search`, `/api/v1/geocode`
|
||||
|
||||
Path template parameters such as `{project_id}`, `{user_id}`, `{device_id}`, `{scheme_name}`, and `{link_id}` intentionally remain `snake_case`.
|
||||
Path template parameters such as `{user_id}`, `{device_id}`, `{scheme_name}`, and `{link_id}` intentionally remain `snake_case`.
|
||||
|
||||
## Legacy URL Categories
|
||||
|
||||
@@ -62,7 +61,7 @@ These are likely safe only after confirming no caller uses them:
|
||||
|
||||
## Field Naming
|
||||
|
||||
Most public JSON, query, and SSE fields are already `snake_case`, including `project_id`, `user_id`, `scheme_name`, `scheme_type`, `start_time`, `end_time`, `device_ids`, `session_id`, and `request_id`.
|
||||
Most public JSON, query, and SSE fields are already `snake_case`, including `user_id`, `scheme_name`, `scheme_type`, `start_time`, `end_time`, `device_ids`, `session_id`, and `request_id`.
|
||||
|
||||
Known legacy exception:
|
||||
|
||||
@@ -72,6 +71,10 @@ Headers keep standard HTTP casing:
|
||||
|
||||
- `X-Project-Id`
|
||||
|
||||
## Internal vs Customer Difference
|
||||
|
||||
The customer backend retains local auth/user-management routes under `/api/v1/auth` and `/api/v1/users`; the internal backend has migrated to Keycloak/metadata admin routes. Treat those Customer-only auth routes as delivery compatibility surface, not a source for new internal API naming.
|
||||
|
||||
## Recommendation
|
||||
|
||||
Do not rename existing legacy routes in place. For each active legacy route, keep the new `kebab-case` alias as the documented path, keep the old route marked deprecated, migrate remaining Agent/customer/script callers, then remove only after a documented compatibility window.
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# tjwater-server Customer Image Packaging Notes
|
||||
|
||||
This repository is the customer-delivery backend package. Build delivery images from this repository root.
|
||||
|
||||
## Image Build
|
||||
|
||||
Build the customer backend image:
|
||||
|
||||
```bash
|
||||
docker build -t tjwater-server:latest .
|
||||
```
|
||||
|
||||
The `Dockerfile` already performs source encapsulation in the builder stage:
|
||||
|
||||
```bash
|
||||
python scripts/compile.py
|
||||
python scripts/compile.py --delete-source
|
||||
```
|
||||
|
||||
The compiled and source-deleted `app/` directory is then copied into the final runner stage. The source deletion happens inside the Docker builder layer only; it does not delete local workspace files.
|
||||
|
||||
## Encapsulation Scope
|
||||
|
||||
`scripts/compile.py` defaults to compiling these sensitive areas:
|
||||
|
||||
- `app/services`
|
||||
- `app/native/wndb`
|
||||
- `app/algorithms`
|
||||
- `app/infra/epanet/epanet.py`
|
||||
|
||||
These areas should not contain uncompiled `.py` source files in the delivered image. Public entry points, API route wiring, schemas, configuration, and operational files may remain readable when required for runtime.
|
||||
|
||||
## Verification
|
||||
|
||||
After building, verify the image tag:
|
||||
|
||||
```bash
|
||||
docker image ls tjwater-server
|
||||
```
|
||||
|
||||
Verify that core source files were removed and compiled extensions exist:
|
||||
|
||||
```bash
|
||||
docker run --rm --entrypoint sh tjwater-server:latest -c "\
|
||||
printf 'core_py_count='; \
|
||||
find /app/app/services /app/app/native/wndb /app/app/algorithms /app/app/infra/epanet/epanet.py -name '*.py' 2>/dev/null | wc -l; \
|
||||
printf 'core_so_count='; \
|
||||
find /app/app/services /app/app/native/wndb /app/app/algorithms /app/app/infra/epanet -name '*.so' 2>/dev/null | wc -l; \
|
||||
python -c 'import app.main; print(\"import_app_main=ok\")'"
|
||||
```
|
||||
|
||||
Expected delivery result:
|
||||
|
||||
```text
|
||||
core_py_count=0
|
||||
core_so_count=<non-zero>
|
||||
import_app_main=ok
|
||||
```
|
||||
|
||||
Warnings from third-party packages during import are not necessarily build failures. Treat non-zero exit codes, failed imports, or leftover core `.py` files as blockers.
|
||||
|
||||
## Export For Windows Delivery
|
||||
|
||||
Export the image tarball to the Windows desktop from WSL:
|
||||
|
||||
```bash
|
||||
docker save -o /mnt/c/Users/admin/Desktop/tjwater-server-latest.tar tjwater-server:latest
|
||||
```
|
||||
|
||||
Adjust the Windows username if needed. To find available desktop paths:
|
||||
|
||||
```bash
|
||||
find /mnt/c/Users -maxdepth 2 -type d \( -name Desktop -o -name 桌面 \) 2>/dev/null
|
||||
```
|
||||
|
||||
On the target machine, import the image with:
|
||||
|
||||
```bash
|
||||
docker load -i tjwater-server-latest.tar
|
||||
```
|
||||
|
||||
## Deployment Caution
|
||||
|
||||
The development `infra/docker/docker-compose.yml` bind-mounts local source:
|
||||
|
||||
```yaml
|
||||
volumes:
|
||||
- ../../app:/app/app
|
||||
- ../../resources:/app/resources
|
||||
```
|
||||
|
||||
Do not use that source mount for customer delivery of the encapsulated image. Mounting `../../app` over `/app/app` replaces the compiled code inside the image with local source files and defeats the encapsulation. For delivery compose files, use the built image directly and mount only required runtime data/config paths.
|
||||
|
||||
## Local Safety
|
||||
|
||||
Do not run this destructive command in the normal working tree:
|
||||
|
||||
```bash
|
||||
python scripts/compile.py --delete-source
|
||||
```
|
||||
|
||||
Only use `--delete-source` in Docker builder stages or in a disposable delivery copy. The normal delivery image build already handles this safely.
|
||||
+15
-3
@@ -1,4 +1,4 @@
|
||||
FROM condaforge/miniforge3:latest
|
||||
FROM condaforge/miniforge3:latest AS runtime-base
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
@@ -14,13 +14,25 @@ COPY requirements.txt .
|
||||
RUN pip install --no-cache-dir uv
|
||||
RUN uv pip install --system --no-cache-dir -r requirements.txt
|
||||
|
||||
FROM runtime-base AS builder
|
||||
|
||||
RUN mamba install -y c-compiler cxx-compiler && \
|
||||
mamba clean -afy
|
||||
|
||||
COPY app ./app
|
||||
COPY scripts ./scripts
|
||||
|
||||
RUN python scripts/compile.py && \
|
||||
python scripts/compile.py --delete-source
|
||||
|
||||
FROM runtime-base AS runner
|
||||
|
||||
# 将代码放入子目录 'app',将数据放入子目录 'db_inp'
|
||||
# 这样临时文件默认会生成在 /app 下,而代码在 /app/app 下,实现了分离
|
||||
COPY app ./app
|
||||
COPY --from=builder /app/app ./app
|
||||
RUN python -c "from pathlib import Path; from zipfile import ZipFile; model_dir = Path('app/algorithms/health/model'); zip_path = model_dir / 'my_survival_forest_model_quxi.zip'; joblib_name = 'my_survival_forest_model_quxi.joblib'; joblib_path = model_dir / joblib_name; assert zip_path.exists(), f'Model archive not found: {zip_path}'; archive = ZipFile(zip_path); archive.extract(joblib_name, model_dir); archive.close(); assert joblib_path.exists(), f'Model file not extracted: {joblib_path}'" && \
|
||||
rm -f app/algorithms/health/model/my_survival_forest_model_quxi.zip
|
||||
# COPY db_inp ./db_inp
|
||||
COPY .env .
|
||||
RUN mkdir -p db_inp temp data inp
|
||||
|
||||
# 设置 PYTHONPATH 以便 uvicorn 找到 app 模块
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# TJWaterServerBinary 内部后端
|
||||
# TJWaterServerCustomer 客户版后端
|
||||
|
||||
`TJWaterServerBinary` 是 TJWater 内部版 Python 后端,基于 FastAPI 提供认证、项目、管网、模拟、爆管、漏损、SCADA 和地图服务集成能力。该仓库用于内部开发和完整功能维护。
|
||||
`TJWaterServerCustomer` 是 TJWater 客户交付版 Python 后端。该仓库应被视为可部署交付包,只保留客户运行、配置、部署、诊断和交付说明所需内容。
|
||||
|
||||
## 技术栈
|
||||
|
||||
@@ -20,67 +20,88 @@ app/auth/ 认证和权限上下文
|
||||
app/core/ 配置、日志和基础设施初始化
|
||||
app/domain/ 领域模型和 Pydantic schema
|
||||
app/infra/ 数据库、缓存、EPANET 和外部集成
|
||||
app/services/ 业务服务编排
|
||||
app/algorithms/ 管网算法、模拟、爆管、漏损、清洗和健康分析
|
||||
app/native/ 本地管网数据读写与转换
|
||||
tests/ 后端测试
|
||||
resources/ SQL、模板和示例资源
|
||||
app/services/ 核心业务服务,交付镜像中必须封装
|
||||
app/algorithms/ 核心算法,交付镜像中必须封装
|
||||
app/native/ 本地管网数据读写与转换,交付镜像中必须封装
|
||||
scripts/compile.py Cython 封装脚本
|
||||
infra/docker/ Docker Compose 编排
|
||||
tests/ 后端测试
|
||||
```
|
||||
|
||||
## 本地开发
|
||||
|
||||
推荐使用已有 conda 环境:
|
||||
|
||||
```bash
|
||||
conda run -n server python -m pytest tests/unit tests/auth -q
|
||||
conda run -n server uvicorn app.main:app --host 0.0.0.0 --port 8000 --reload
|
||||
```
|
||||
|
||||
如需要进入环境:
|
||||
|
||||
```bash
|
||||
conda activate server
|
||||
```
|
||||
|
||||
## 常用命令
|
||||
|
||||
```bash
|
||||
conda run -n server python -m pytest tests -q
|
||||
conda run -n server python scripts/run_server.py
|
||||
docker build -t tjwater-server:local .
|
||||
docker compose -f infra/docker/docker-compose.yml config
|
||||
```
|
||||
|
||||
- `pytest`:运行自动化测试。
|
||||
- `scripts/run_server.py`:使用项目脚本启动服务。
|
||||
- `docker build`:构建后端镜像。
|
||||
- `docker compose config`:检查 compose 配置和变量展开。
|
||||
本地调试不要在正常工作树执行源码删除命令。
|
||||
|
||||
## 开发规范
|
||||
## 客户版镜像打包
|
||||
|
||||
- Python 文件、函数、变量、Pydantic 字段、JSON body 字段和 query 参数使用 `snake_case`。
|
||||
- Python 类和 Pydantic 模型使用 `PascalCase`。
|
||||
- 新 HTTP 路径使用 `kebab-case`,例如 `/api/v1/pressure-status/analyze`。
|
||||
- 优先复用现有 FastAPI/service/repository 边界。
|
||||
- 不要把临时数据、数据库 dump、日志或本地运行产物纳入提交。
|
||||
|
||||
## 测试与发布
|
||||
|
||||
提交前根据改动范围运行最小有效测试:
|
||||
交付镜像标签通常为:
|
||||
|
||||
```bash
|
||||
conda run -n server python -m pytest tests/unit tests/auth -q
|
||||
docker build -t tjwater-server:latest .
|
||||
```
|
||||
|
||||
发布镜像前建议运行:
|
||||
`Dockerfile` 会在 builder 阶段执行:
|
||||
|
||||
```bash
|
||||
docker build -t tjwater-server:local .
|
||||
python scripts/compile.py
|
||||
python scripts/compile.py --delete-source
|
||||
```
|
||||
|
||||
Gitea 包工作流位于 `.gitea/workflows/package.yml`,通常由 tag 触发构建、推送镜像并通知部署 webhook。
|
||||
源码删除只发生在 Docker 构建层内,不会删除本地工作树源码。详细封装、验证和 Windows 导出说明见:
|
||||
|
||||
```text
|
||||
DELIVERY_PACKAGING_NOTES.md
|
||||
```
|
||||
|
||||
## 封装范围
|
||||
|
||||
`scripts/compile.py` 默认封装:
|
||||
|
||||
- `app/services`
|
||||
- `app/native/wndb`
|
||||
- `app/algorithms`
|
||||
- `app/infra/epanet/epanet.py`
|
||||
|
||||
交付镜像中这些核心目录不应残留未编译的 `.py` 源码,应以 `.so` 扩展模块运行。
|
||||
|
||||
## 验证命令
|
||||
|
||||
构建后检查镜像:
|
||||
|
||||
```bash
|
||||
docker image ls tjwater-server
|
||||
```
|
||||
|
||||
检查核心源码是否已删除、FastAPI 入口是否可导入:
|
||||
|
||||
```bash
|
||||
docker run --rm --entrypoint sh tjwater-server:latest -c "\
|
||||
printf 'core_py_count='; \
|
||||
find /app/app/services /app/app/native/wndb /app/app/algorithms /app/app/infra/epanet/epanet.py -name '*.py' 2>/dev/null | wc -l; \
|
||||
printf 'core_so_count='; \
|
||||
find /app/app/services /app/app/native/wndb /app/app/algorithms /app/app/infra/epanet -name '*.so' 2>/dev/null | wc -l; \
|
||||
python -c 'import app.main; print(\"import_app_main=ok\")'"
|
||||
```
|
||||
|
||||
期望结果:
|
||||
|
||||
```text
|
||||
core_py_count=0
|
||||
core_so_count=<非零>
|
||||
import_app_main=ok
|
||||
```
|
||||
|
||||
## 部署注意
|
||||
|
||||
客户交付时不要把本地 `../../app` 挂载到容器 `/app/app`,否则会覆盖镜像内已封装代码。交付 compose 文件应使用构建好的镜像,只挂载必要的运行数据和配置。
|
||||
|
||||
## 安全规则
|
||||
|
||||
不要提交 `.env`、客户数据、数据库 dump、日志、生成缓存、`db_inp/`、`temp/`、`data/` 或本地密钥。CI/CD 凭据应放在 Gitea secrets 和仓库变量中。
|
||||
不要提交 `.env`、生产凭据、客户数据、数据库 dump、日志、生成缓存、临时交付压缩包或本地运行目录。客户版仓库不应加入内部实验、调试工具或非交付源码材料。
|
||||
|
||||
@@ -149,16 +149,14 @@ def valve_isolation_analysis(
|
||||
|
||||
must_close_valves.sort()
|
||||
optional_valves.sort()
|
||||
isolatable = bool(must_close_valves)
|
||||
|
||||
result = {
|
||||
"accident_elements": target_elements,
|
||||
"disabled_valves": disabled_valves,
|
||||
"affected_nodes": sorted(affected_nodes) if isolatable else [],
|
||||
"affected_node_count": len(affected_nodes),
|
||||
"affected_nodes": sorted(affected_nodes),
|
||||
"must_close_valves": must_close_valves,
|
||||
"optional_valves": optional_valves,
|
||||
"isolatable": isolatable,
|
||||
"isolatable": len(must_close_valves) > 0,
|
||||
}
|
||||
|
||||
if len(target_elements) == 1:
|
||||
|
||||
@@ -1,77 +1,14 @@
|
||||
from contextlib import contextmanager
|
||||
import fcntl
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
import psycopg
|
||||
|
||||
from app.algorithms.sensor import kmeans as kmeans_sensor
|
||||
from app.algorithms.sensor import sensitivity
|
||||
from app.native.wndb.s42_sensor_placement import create_sensor_placement
|
||||
from app.services.sensor_placement import (
|
||||
SensorPlacementConflictError,
|
||||
SensorPlacementValidationError,
|
||||
validate_sensor_placement_nodes,
|
||||
)
|
||||
from app.core.config import get_pgconn_string
|
||||
from app.services.tjnetwork import dump_inp
|
||||
|
||||
|
||||
def _sensor_inp_path(name: str) -> Path:
|
||||
if (
|
||||
not name
|
||||
or name in {".", ".."}
|
||||
or "/" in name
|
||||
or "\\" in name
|
||||
or "\x00" in name
|
||||
):
|
||||
raise SensorPlacementValidationError("管网名称不是有效的项目标识")
|
||||
return Path("db_inp") / f"{name}.db.inp"
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _sensor_inp_lock(name: str):
|
||||
inp_path = _sensor_inp_path(name)
|
||||
inp_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
lock_path = inp_path.with_suffix(".sensor.lock")
|
||||
with lock_path.open("w", encoding="utf-8") as lock_file:
|
||||
try:
|
||||
fcntl.flock(
|
||||
lock_file.fileno(),
|
||||
fcntl.LOCK_EX | fcntl.LOCK_NB,
|
||||
)
|
||||
except BlockingIOError as exc:
|
||||
raise SensorPlacementConflictError(
|
||||
"当前项目已有监测点优化任务正在运行,请稍后重试"
|
||||
) from exc
|
||||
try:
|
||||
yield inp_path
|
||||
finally:
|
||||
fcntl.flock(lock_file.fileno(), fcntl.LOCK_UN)
|
||||
|
||||
|
||||
def _create_validated_placement(
|
||||
name: str,
|
||||
*,
|
||||
scheme_name: str,
|
||||
min_diameter: int,
|
||||
username: str,
|
||||
sensor_location: list[str],
|
||||
) -> dict[str, Any]:
|
||||
validate_sensor_placement_nodes(name, sensor_location)
|
||||
return create_sensor_placement(
|
||||
name,
|
||||
scheme_name=scheme_name,
|
||||
min_diameter=min_diameter,
|
||||
username=username,
|
||||
sensor_location=sensor_location,
|
||||
)
|
||||
|
||||
|
||||
def pressure_sensor_placement_sensitivity(
|
||||
name: str,
|
||||
scheme_name: str,
|
||||
sensor_number: int,
|
||||
min_diameter: int,
|
||||
username: str,
|
||||
) -> dict[str, Any]:
|
||||
name: str, scheme_name: str, sensor_number: int, min_diameter: int, username: str
|
||||
) -> None:
|
||||
"""
|
||||
基于改进灵敏度法进行压力监测点优化布置
|
||||
:param name: 数据库名称
|
||||
@@ -79,32 +16,41 @@ def pressure_sensor_placement_sensitivity(
|
||||
:param sensor_number: 传感器数目
|
||||
:param min_diameter: 最小管径
|
||||
:param username: 用户名
|
||||
:return: 新建的监测点方案
|
||||
:return:
|
||||
"""
|
||||
with _sensor_inp_lock(name):
|
||||
sensor_location = sensitivity.get_ID(
|
||||
name=name,
|
||||
sensor_num=sensor_number,
|
||||
min_diameter=min_diameter,
|
||||
name=name, sensor_num=sensor_number, min_diameter=min_diameter
|
||||
)
|
||||
return _create_validated_placement(
|
||||
name,
|
||||
scheme_name=scheme_name,
|
||||
min_diameter=min_diameter,
|
||||
username=username,
|
||||
sensor_location=sensor_location,
|
||||
try:
|
||||
conn_string = get_pgconn_string(db_name=name)
|
||||
with psycopg.connect(conn_string) as conn:
|
||||
with conn.cursor() as cur:
|
||||
sql = """
|
||||
INSERT INTO sensor_placement (scheme_name, sensor_number, min_diameter, username, sensor_location)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
"""
|
||||
|
||||
cur.execute(
|
||||
sql,
|
||||
(
|
||||
scheme_name,
|
||||
sensor_number,
|
||||
min_diameter,
|
||||
username,
|
||||
sensor_location,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
print("方案信息存储成功!")
|
||||
except Exception as e:
|
||||
print(f"存储方案信息时出错:{e}")
|
||||
|
||||
|
||||
# 2025/08/21
|
||||
# 基于kmeans聚类法进行压力监测点优化布置
|
||||
def pressure_sensor_placement_kmeans(
|
||||
name: str,
|
||||
scheme_name: str,
|
||||
sensor_number: int,
|
||||
min_diameter: int,
|
||||
username: str,
|
||||
) -> dict[str, Any]:
|
||||
name: str, scheme_name: str, sensor_number: int, min_diameter: int, username: str
|
||||
) -> None:
|
||||
"""
|
||||
基于聚类法进行压力监测点优化布置
|
||||
:param name: 数据库名称(注意,此处数据库名称也是inp文件名称,inp文件与pg库名要一样)
|
||||
@@ -112,20 +58,34 @@ def pressure_sensor_placement_kmeans(
|
||||
:param sensor_number: 传感器数目
|
||||
:param min_diameter: 最小管径
|
||||
:param username: 用户名
|
||||
:return: 新建的监测点方案
|
||||
:return:
|
||||
"""
|
||||
# dump_inp
|
||||
with _sensor_inp_lock(name) as inp_path:
|
||||
dump_inp(name, str(inp_path), "2")
|
||||
inp_name = f"./db_inp/{name}.db.inp"
|
||||
dump_inp(name, inp_name, "2")
|
||||
sensor_location = kmeans_sensor.kmeans_sensor_placement(
|
||||
name=name,
|
||||
sensor_num=sensor_number,
|
||||
min_diameter=min_diameter,
|
||||
name=name, sensor_num=sensor_number, min_diameter=min_diameter
|
||||
)
|
||||
return _create_validated_placement(
|
||||
name,
|
||||
scheme_name=scheme_name,
|
||||
min_diameter=min_diameter,
|
||||
username=username,
|
||||
sensor_location=sensor_location,
|
||||
try:
|
||||
conn_string = get_pgconn_string(db_name=name)
|
||||
with psycopg.connect(conn_string) as conn:
|
||||
with conn.cursor() as cur:
|
||||
sql = """
|
||||
INSERT INTO sensor_placement (scheme_name, sensor_number, min_diameter, username, sensor_location)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
"""
|
||||
|
||||
cur.execute(
|
||||
sql,
|
||||
(
|
||||
scheme_name,
|
||||
sensor_number,
|
||||
min_diameter,
|
||||
username,
|
||||
sensor_location,
|
||||
),
|
||||
)
|
||||
conn.commit()
|
||||
print("方案信息存储成功!")
|
||||
except Exception as e:
|
||||
print(f"存储方案信息时出错:{e}")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,89 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from uuid import uuid4
|
||||
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ProblemDetails(BaseModel):
|
||||
"""RFC 9457 compatible error response used by the REST contract."""
|
||||
|
||||
type: str
|
||||
title: str
|
||||
status: int
|
||||
detail: str
|
||||
instance: str
|
||||
code: str
|
||||
trace_id: str
|
||||
errors: list[dict[str, Any]] = Field(default_factory=list)
|
||||
|
||||
|
||||
def _trace_id(request: Request) -> str:
|
||||
return request.headers.get("X-Request-Id") or str(uuid4())
|
||||
|
||||
|
||||
def _problem_response(
|
||||
request: Request,
|
||||
*,
|
||||
status_code: int,
|
||||
title: str,
|
||||
detail: str,
|
||||
code: str,
|
||||
errors: list[dict[str, Any]] | None = None,
|
||||
) -> JSONResponse:
|
||||
problem = ProblemDetails(
|
||||
type=f"https://tjwater.example/problems/{code.replace('_', '-')}",
|
||||
title=title,
|
||||
status=status_code,
|
||||
detail=detail,
|
||||
instance=request.url.path,
|
||||
code=code,
|
||||
trace_id=_trace_id(request),
|
||||
errors=errors or [],
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=status_code,
|
||||
content=problem.model_dump(mode="json"),
|
||||
media_type="application/problem+json",
|
||||
)
|
||||
|
||||
|
||||
def install_problem_details_handlers(app: FastAPI) -> None:
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error_handler(
|
||||
request: Request,
|
||||
exc: RequestValidationError,
|
||||
) -> JSONResponse:
|
||||
return _problem_response(
|
||||
request,
|
||||
status_code=422,
|
||||
title="Validation error",
|
||||
detail="Request validation failed",
|
||||
code="validation_error",
|
||||
errors=exc.errors(),
|
||||
)
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_error_handler(request: Request, exc: HTTPException) -> JSONResponse:
|
||||
detail = exc.detail if isinstance(exc.detail, str) else str(exc.detail)
|
||||
code_by_status = {
|
||||
401: "unauthenticated",
|
||||
403: "forbidden",
|
||||
404: "not_found",
|
||||
409: "conflict",
|
||||
422: "validation_error",
|
||||
503: "dependency_unavailable",
|
||||
}
|
||||
return _problem_response(
|
||||
request,
|
||||
status_code=exc.status_code,
|
||||
title=code_by_status.get(exc.status_code, "request_error")
|
||||
.replace("_", " ")
|
||||
.title(),
|
||||
detail=detail,
|
||||
code=code_by_status.get(exc.status_code, "request_error"),
|
||||
)
|
||||
@@ -1,39 +0,0 @@
|
||||
from fastapi import APIRouter, Depends, Header
|
||||
|
||||
from app.auth.metadata_dependencies import (
|
||||
get_current_metadata_user,
|
||||
get_metadata_repository,
|
||||
)
|
||||
from app.auth.permissions import resolve_permissions
|
||||
from app.auth.project_dependencies import resolve_project_context
|
||||
from app.domain.schemas.access import AccessContextResponse
|
||||
from app.infra.db.metadb.repositories.metadata_repository import MetadataRepository
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/access-context", response_model=AccessContextResponse)
|
||||
async def get_access_context(
|
||||
x_project_id: str | None = Header(default=None, alias="X-Project-Id"),
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> AccessContextResponse:
|
||||
project_context = (
|
||||
await resolve_project_context(x_project_id, current_user, metadata_repo)
|
||||
if x_project_id
|
||||
else None
|
||||
)
|
||||
permissions = resolve_permissions(
|
||||
project_role=project_context.project_role if project_context else None,
|
||||
system_role=current_user.role,
|
||||
is_superuser=current_user.is_superuser,
|
||||
)
|
||||
return AccessContextResponse(
|
||||
user_id=current_user.id,
|
||||
username=current_user.username,
|
||||
system_role=current_user.role,
|
||||
is_system_admin=current_user.is_superuser or current_user.role == "admin",
|
||||
project_id=project_context.project_id if project_context else None,
|
||||
project_role=project_context.project_role if project_context else None,
|
||||
permissions=sorted(permissions),
|
||||
)
|
||||
@@ -151,14 +151,14 @@ async def _upsert_and_audit_metadata_user(
|
||||
return MetadataUserResponse.model_validate(user)
|
||||
|
||||
|
||||
@router.get("/admin/users/me", response_model=MetadataUserResponse)
|
||||
@router.get("/me", response_model=MetadataUserResponse)
|
||||
async def get_metadata_admin_me(
|
||||
current_user=Depends(get_current_metadata_admin),
|
||||
) -> MetadataUserResponse:
|
||||
return MetadataUserResponse.model_validate(current_user)
|
||||
|
||||
|
||||
@router.post("/admin/user-syncs", response_model=MetadataUserResponse)
|
||||
@router.post("/users/sync", response_model=MetadataUserResponse)
|
||||
async def sync_metadata_user(
|
||||
payload: MetadataUserSyncRequest,
|
||||
current_user=Depends(get_current_metadata_admin),
|
||||
@@ -184,7 +184,7 @@ async def sync_metadata_user(
|
||||
|
||||
|
||||
|
||||
@router.post("/admin/user-syncs/batches", response_model=List[MetadataUserSyncResult])
|
||||
@router.post("/users/sync/batch", response_model=List[MetadataUserSyncResult])
|
||||
async def sync_metadata_users_batch(
|
||||
payload: MetadataUsersBatchSyncRequest,
|
||||
current_user=Depends(get_current_metadata_admin),
|
||||
@@ -228,7 +228,7 @@ async def sync_metadata_users_batch(
|
||||
return results
|
||||
|
||||
|
||||
@router.get("/admin/users", response_model=List[MetadataUserResponse])
|
||||
@router.get("/users", response_model=List[MetadataUserResponse])
|
||||
async def list_metadata_users(
|
||||
skip: int = Query(0, ge=0),
|
||||
limit: int = Query(100, ge=1, le=1000),
|
||||
@@ -239,7 +239,7 @@ async def list_metadata_users(
|
||||
return [MetadataUserResponse.model_validate(user) for user in users]
|
||||
|
||||
|
||||
@router.get("/admin/projects", response_model=List[AdminProjectResponse])
|
||||
@router.get("/projects", response_model=List[AdminProjectResponse])
|
||||
async def list_admin_projects(
|
||||
current_user=Depends(get_current_metadata_admin),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
@@ -249,7 +249,7 @@ async def list_admin_projects(
|
||||
|
||||
|
||||
@router.post(
|
||||
"/admin/projects",
|
||||
"/projects",
|
||||
response_model=AdminProjectResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
@@ -266,7 +266,6 @@ async def create_admin_project(
|
||||
gs_workspace=payload.gs_workspace,
|
||||
map_extent=payload.map_extent,
|
||||
status=payload.status,
|
||||
creator_user_id=current_user.id,
|
||||
)
|
||||
except IntegrityError as exc:
|
||||
raise HTTPException(
|
||||
@@ -293,7 +292,7 @@ async def create_admin_project(
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/admin/projects/{project_id}",
|
||||
"/projects/{project_id}",
|
||||
response_model=AdminProjectResponse,
|
||||
)
|
||||
async def update_admin_project(
|
||||
@@ -332,7 +331,7 @@ async def update_admin_project(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/admin/projects/{project_id}/databases",
|
||||
"/projects/{project_id}/databases",
|
||||
response_model=List[ProjectDatabaseResponse],
|
||||
)
|
||||
async def list_project_databases(
|
||||
@@ -348,7 +347,7 @@ async def list_project_databases(
|
||||
|
||||
|
||||
@router.put(
|
||||
"/admin/projects/{project_id}/databases",
|
||||
"/projects/{project_id}/databases",
|
||||
response_model=ProjectDatabaseResponse,
|
||||
)
|
||||
async def upsert_project_database(
|
||||
@@ -421,7 +420,7 @@ async def upsert_project_database(
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/admin/projects/{project_id}/databases/{db_role}",
|
||||
"/projects/{project_id}/databases/{db_role}",
|
||||
status_code=status.HTTP_204_NO_CONTENT,
|
||||
)
|
||||
async def delete_project_database(
|
||||
@@ -449,7 +448,7 @@ async def delete_project_database(
|
||||
|
||||
|
||||
@router.post(
|
||||
"/admin/projects/{project_id}/databases/{db_role}/health-checks",
|
||||
"/projects/{project_id}/databases/{db_role}/health",
|
||||
response_model=ProjectDatabaseHealthResponse,
|
||||
)
|
||||
async def check_project_database_health(
|
||||
@@ -504,7 +503,7 @@ async def check_project_database_health(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/admin/users/{user_id}", response_model=MetadataUserResponse)
|
||||
@router.get("/users/{user_id}", response_model=MetadataUserResponse)
|
||||
async def get_metadata_user(
|
||||
user_id: UUID = Path(...),
|
||||
current_user=Depends(get_current_metadata_admin),
|
||||
@@ -516,7 +515,7 @@ async def get_metadata_user(
|
||||
return MetadataUserResponse.model_validate(user)
|
||||
|
||||
|
||||
@router.patch("/admin/users/{user_id}", response_model=MetadataUserResponse)
|
||||
@router.patch("/users/{user_id}", response_model=MetadataUserResponse)
|
||||
async def update_metadata_user(
|
||||
payload: MetadataUserUpdateRequest,
|
||||
user_id: UUID = Path(...),
|
||||
@@ -549,7 +548,7 @@ async def update_metadata_user(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/admin/projects/{project_id}/members",
|
||||
"/projects/{project_id}/members",
|
||||
response_model=List[ProjectMemberResponse],
|
||||
)
|
||||
async def list_project_members(
|
||||
@@ -567,7 +566,7 @@ async def list_project_members(
|
||||
|
||||
|
||||
@router.post(
|
||||
"/admin/projects/{project_id}/members",
|
||||
"/projects/{project_id}/members",
|
||||
response_model=ProjectMemberResponse,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
@@ -622,7 +621,7 @@ async def add_project_member(
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/admin/projects/{project_id}/members/{user_id}",
|
||||
"/projects/{project_id}/members/{user_id}",
|
||||
response_model=ProjectMemberResponse,
|
||||
)
|
||||
async def update_project_member(
|
||||
@@ -668,7 +667,7 @@ async def update_project_member(
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/admin/projects/{project_id}/members/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
@router.delete("/projects/{project_id}/members/{user_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def remove_project_member(
|
||||
project_id: UUID = Path(...),
|
||||
user_id: UUID = Path(...),
|
||||
|
||||
@@ -9,7 +9,6 @@ from app.auth.project_dependencies import (
|
||||
ProjectContext,
|
||||
get_project_context,
|
||||
)
|
||||
from app.auth.permissions import permissions_for_context
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -23,11 +22,10 @@ class AgentAuthContextResponse(BaseModel):
|
||||
project_id: str
|
||||
network: str
|
||||
project_role: str
|
||||
permissions: list[str]
|
||||
token_expires_at: str | None = None
|
||||
|
||||
|
||||
@router.get("/agent-auth-context", response_model=AgentAuthContextResponse)
|
||||
@router.get("/agent/auth/context", response_model=AgentAuthContextResponse)
|
||||
async def get_agent_auth_context(
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
@@ -48,6 +46,5 @@ async def get_agent_auth_context(
|
||||
project_id=str(ctx.project_id),
|
||||
network=ctx.project_code,
|
||||
project_role=ctx.project_role,
|
||||
permissions=sorted(permissions_for_context(ctx)),
|
||||
token_expires_at=token_expires_at,
|
||||
)
|
||||
|
||||
@@ -1,52 +1,56 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
"""
|
||||
审计日志 API 接口
|
||||
|
||||
仅管理员可访问
|
||||
"""
|
||||
|
||||
from typing import List, Optional
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Request, status
|
||||
from pydantic import BaseModel
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, Depends, Query, Path
|
||||
from app.domain.schemas.audit import AuditLogResponse
|
||||
from app.infra.db.metadb.repositories.audit_repository import AuditRepository
|
||||
from app.auth.metadata_dependencies import (
|
||||
get_current_metadata_admin,
|
||||
get_current_metadata_user,
|
||||
)
|
||||
from app.core.audit import AuditAction, log_audit_event
|
||||
from app.domain.schemas.audit import AuditLogResponse
|
||||
from app.infra.db.metadb.database import get_metadata_session
|
||||
from app.infra.db.metadb.repositories.audit_repository import AuditRepository
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class SessionAuditEventRequest(BaseModel):
|
||||
event: Literal["login", "logout"]
|
||||
|
||||
|
||||
async def get_audit_repository(
|
||||
session: AsyncSession = Depends(get_metadata_session),
|
||||
) -> AuditRepository:
|
||||
"""获取审计日志仓储"""
|
||||
return AuditRepository(session)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/audit-logs",
|
||||
"/logs",
|
||||
summary="查询审计日志",
|
||||
description="查询审计日志(仅管理员)",
|
||||
response_model=list[AuditLogResponse],
|
||||
response_model=List[AuditLogResponse],
|
||||
)
|
||||
async def get_audit_logs(
|
||||
user_id: UUID | None = Query(None, description="按用户ID过滤"),
|
||||
project_id: UUID | None = Query(None, description="按项目ID过滤"),
|
||||
action: str | None = Query(None, description="按操作类型过滤"),
|
||||
resource_type: str | None = Query(None, description="按资源类型过滤"),
|
||||
start_time: datetime | None = Query(None, description="开始时间"),
|
||||
end_time: datetime | None = Query(None, description="结束时间"),
|
||||
user_id: Optional[UUID] = Query(None, description="按用户ID过滤"),
|
||||
project_id: Optional[UUID] = Query(None, description="按项目ID过滤"),
|
||||
action: Optional[str] = Query(None, description="按操作类型过滤"),
|
||||
resource_type: Optional[str] = Query(None, description="按资源类型过滤"),
|
||||
start_time: Optional[datetime] = Query(None, description="开始时间"),
|
||||
end_time: Optional[datetime] = Query(None, description="结束时间"),
|
||||
skip: int = Query(0, ge=0, description="跳过记录数"),
|
||||
limit: int = Query(100, ge=1, le=1000, description="限制记录数"),
|
||||
_current_user=Depends(get_current_metadata_admin),
|
||||
current_user=Depends(get_current_metadata_admin),
|
||||
audit_repo: AuditRepository = Depends(get_audit_repository),
|
||||
) -> list[AuditLogResponse]:
|
||||
return await audit_repo.get_logs(
|
||||
) -> List[AuditLogResponse]:
|
||||
"""
|
||||
查询审计日志
|
||||
|
||||
支持按用户、时间、操作类型等条件过滤,仅管理员可访问
|
||||
"""
|
||||
logs = await audit_repo.get_logs(
|
||||
user_id=user_id,
|
||||
project_id=project_id,
|
||||
action=action,
|
||||
@@ -56,23 +60,29 @@ async def get_audit_logs(
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
)
|
||||
return logs
|
||||
|
||||
|
||||
@router.get(
|
||||
"/audit-logs/count",
|
||||
"/logs/count",
|
||||
summary="获取审计日志总数",
|
||||
description="获取审计日志总数(仅管理员)",
|
||||
)
|
||||
async def get_audit_logs_count(
|
||||
user_id: UUID | None = Query(None, description="按用户ID过滤"),
|
||||
project_id: UUID | None = Query(None, description="按项目ID过滤"),
|
||||
action: str | None = Query(None, description="按操作类型过滤"),
|
||||
resource_type: str | None = Query(None, description="按资源类型过滤"),
|
||||
start_time: datetime | None = Query(None, description="开始时间"),
|
||||
end_time: datetime | None = Query(None, description="结束时间"),
|
||||
_current_user=Depends(get_current_metadata_admin),
|
||||
user_id: Optional[UUID] = Query(None, description="按用户ID过滤"),
|
||||
project_id: Optional[UUID] = Query(None, description="按项目ID过滤"),
|
||||
action: Optional[str] = Query(None, description="按操作类型过滤"),
|
||||
resource_type: Optional[str] = Query(None, description="按资源类型过滤"),
|
||||
start_time: Optional[datetime] = Query(None, description="开始时间"),
|
||||
end_time: Optional[datetime] = Query(None, description="结束时间"),
|
||||
current_user=Depends(get_current_metadata_admin),
|
||||
audit_repo: AuditRepository = Depends(get_audit_repository),
|
||||
) -> dict:
|
||||
"""
|
||||
获取审计日志总数
|
||||
|
||||
获取符合条件的审计日志的总数,仅管理员可访问
|
||||
"""
|
||||
count = await audit_repo.get_log_count(
|
||||
user_id=user_id,
|
||||
project_id=project_id,
|
||||
@@ -84,42 +94,27 @@ async def get_audit_logs_count(
|
||||
return {"count": count}
|
||||
|
||||
|
||||
@router.post("/audit-events", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def record_session_event(
|
||||
payload: SessionAuditEventRequest,
|
||||
request: Request,
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
session: AsyncSession = Depends(get_metadata_session),
|
||||
) -> None:
|
||||
await log_audit_event(
|
||||
action=AuditAction.LOGIN if payload.event == "login" else AuditAction.LOGOUT,
|
||||
user_id=current_user.id,
|
||||
resource_type="session",
|
||||
resource_id=str(current_user.keycloak_id),
|
||||
ip_address=request.client.host if request.client else None,
|
||||
request_method=request.method,
|
||||
request_path=request.url.path,
|
||||
response_status=status.HTTP_204_NO_CONTENT,
|
||||
session=session,
|
||||
)
|
||||
|
||||
|
||||
@router.get(
|
||||
"/audit-logs/mine",
|
||||
"/logs/my",
|
||||
summary="查询我的审计日志",
|
||||
description="查询当前用户的审计日志",
|
||||
response_model=list[AuditLogResponse],
|
||||
response_model=List[AuditLogResponse],
|
||||
)
|
||||
async def get_my_audit_logs(
|
||||
action: str | None = Query(None, description="按操作类型过滤"),
|
||||
start_time: datetime | None = Query(None, description="开始时间"),
|
||||
end_time: datetime | None = Query(None, description="结束时间"),
|
||||
action: Optional[str] = Query(None, description="按操作类型过滤"),
|
||||
start_time: Optional[datetime] = Query(None, description="开始时间"),
|
||||
end_time: Optional[datetime] = Query(None, description="结束时间"),
|
||||
skip: int = Query(0, ge=0, description="跳过记录数"),
|
||||
limit: int = Query(100, ge=1, le=1000, description="限制记录数"),
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
audit_repo: AuditRepository = Depends(get_audit_repository),
|
||||
) -> list[AuditLogResponse]:
|
||||
return await audit_repo.get_logs(
|
||||
) -> List[AuditLogResponse]:
|
||||
"""
|
||||
查询当前用户的审计日志
|
||||
|
||||
普通用户只能查看自己的操作记录
|
||||
"""
|
||||
logs = await audit_repo.get_logs(
|
||||
user_id=current_user.id,
|
||||
action=action,
|
||||
start_time=start_time,
|
||||
@@ -127,3 +122,4 @@ async def get_my_audit_logs(
|
||||
skip=skip,
|
||||
limit=limit,
|
||||
)
|
||||
return logs
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Body
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Path, Body
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.auth.keycloak_dependencies import get_current_keycloak_username
|
||||
from app.services.burst_detection import (
|
||||
get_burst_detection_scheme_detail,
|
||||
list_burst_detection_schemes,
|
||||
run_burst_detection,
|
||||
)
|
||||
|
||||
@@ -28,16 +30,6 @@ class BurstDetectionRequest(BaseModel):
|
||||
points_per_day: int = Field(1440, description="每天的数据点数")
|
||||
mu: int = Field(100, description="异常值检测的参数")
|
||||
iforest_params: dict[str, Any] | None = Field(None, description="隔离森林算法参数")
|
||||
target_time: datetime | None = Field(
|
||||
None,
|
||||
description="目标侦测时刻;为空时自动使用最近一个完整的监测时刻",
|
||||
)
|
||||
sampling_interval_minutes: int | None = Field(
|
||||
None,
|
||||
ge=1,
|
||||
le=1440,
|
||||
description="采样间隔(分钟);为空时根据压力 SCADA 传输频率自动推断",
|
||||
)
|
||||
scada_start: datetime | None = Field(None, description="SCADA数据起始时间")
|
||||
scada_end: datetime | None = Field(None, description="SCADA数据结束时间")
|
||||
sensor_nodes: list[str] | None = Field(None, description="传感器节点列表")
|
||||
@@ -48,7 +40,7 @@ class BurstDetectionRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post(
|
||||
"/burst-detections",
|
||||
"/detect/",
|
||||
summary="执行爆管检测",
|
||||
description="基于压力观测数据和其他参数执行爆管检测分析"
|
||||
)
|
||||
@@ -76,3 +68,64 @@ async def detect_burst(
|
||||
return run_burst_detection(**data.model_dump(), username=username)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/schemes/",
|
||||
summary="查询爆管检测方案列表",
|
||||
description="获取指定网络的所有爆管检测方案"
|
||||
)
|
||||
async def query_burst_detection_schemes(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
query_date: datetime | None = Query(None, description="查询日期(可选)"),
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
获取爆管检测方案列表。
|
||||
|
||||
查询指定网络的所有已配置的爆管检测方案,
|
||||
可按日期进行筛选。
|
||||
|
||||
Args:
|
||||
network: 管网名称(或数据库名称)
|
||||
query_date: 查询日期(可选)
|
||||
|
||||
Returns:
|
||||
爆管检测方案列表
|
||||
|
||||
Raises:
|
||||
HTTPException: 当查询失败时
|
||||
"""
|
||||
try:
|
||||
return list_burst_detection_schemes(network=network, query_date=query_date)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/schemes/{scheme_name}",
|
||||
summary="获取爆管检测方案详情",
|
||||
description="获取指定爆管检测方案的详细信息"
|
||||
)
|
||||
async def query_burst_detection_scheme_detail(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
scheme_name: str = Path(..., description="爆管检测方案名称"),
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
获取爆管检测方案详情。
|
||||
|
||||
查询指定爆管检测方案的完整配置和参数信息。
|
||||
|
||||
Args:
|
||||
network: 管网名称(或数据库名称)
|
||||
scheme_name: 爆管检测方案名称
|
||||
|
||||
Returns:
|
||||
包含方案详情的字典
|
||||
|
||||
Raises:
|
||||
HTTPException: 当查询失败时
|
||||
"""
|
||||
try:
|
||||
return get_burst_detection_scheme_detail(network=network, scheme_name=scheme_name)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
@@ -3,11 +3,13 @@ from datetime import datetime
|
||||
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Body
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Path, Body
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.auth.keycloak_dependencies import get_current_keycloak_username
|
||||
from app.services.burst_location import (
|
||||
get_burst_location_scheme_detail,
|
||||
list_burst_location_schemes,
|
||||
run_burst_location_by_network,
|
||||
)
|
||||
|
||||
@@ -38,7 +40,7 @@ class BurstLocationRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post(
|
||||
"/burst-locations",
|
||||
"/locate/",
|
||||
summary="执行爆管定位",
|
||||
description="基于压力和流量数据定位管网中的爆管位置"
|
||||
)
|
||||
@@ -66,3 +68,64 @@ async def locate_burst(
|
||||
return run_burst_location_by_network(**data.model_dump(), username=username)
|
||||
except (TypeError, ValueError) as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/schemes/",
|
||||
summary="查询爆管定位方案列表",
|
||||
description="获取指定网络的所有爆管定位方案"
|
||||
)
|
||||
async def query_burst_schemes(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
query_date: datetime | None = Query(None, description="查询日期(可选)")
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
获取爆管定位方案列表。
|
||||
|
||||
查询指定网络的所有已配置的爆管定位方案,
|
||||
可按日期进行筛选。
|
||||
|
||||
Args:
|
||||
network: 管网名称(或数据库名称)
|
||||
query_date: 查询日期(可选)
|
||||
|
||||
Returns:
|
||||
爆管定位方案列表
|
||||
|
||||
Raises:
|
||||
HTTPException: 当查询失败时
|
||||
"""
|
||||
try:
|
||||
return list_burst_location_schemes(network=network, query_date=query_date)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/schemes/{scheme_name}",
|
||||
summary="获取爆管定位方案详情",
|
||||
description="获取指定爆管定位方案的详细信息"
|
||||
)
|
||||
async def query_burst_scheme_detail(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
scheme_name: str = Path(..., description="爆管定位方案名称")
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
获取爆管定位方案详情。
|
||||
|
||||
查询指定爆管定位方案的完整配置和参数信息。
|
||||
|
||||
Args:
|
||||
network: 管网名称(或数据库名称)
|
||||
scheme_name: 爆管定位方案名称
|
||||
|
||||
Returns:
|
||||
包含方案详情的字典
|
||||
|
||||
Raises:
|
||||
HTTPException: 当查询失败时
|
||||
"""
|
||||
try:
|
||||
return get_burst_location_scheme_detail(network=network, scheme_name=scheme_name)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
@@ -3,7 +3,7 @@ from app.infra.cache.redis_client import redis_client
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.delete("/redis-keys/detail", summary="清除单个缓存键", description="根据键名清除单个Redis缓存")
|
||||
@router.post("/clearrediskey/", summary="清除单个缓存键", description="根据键名清除单个Redis缓存")
|
||||
async def fastapi_clear_redis_key(key: str = Query(..., description="缓存键名")):
|
||||
"""
|
||||
清除单个缓存键
|
||||
@@ -14,7 +14,7 @@ async def fastapi_clear_redis_key(key: str = Query(..., description="缓存键
|
||||
return True
|
||||
|
||||
|
||||
@router.delete("/redis-keys", summary="清除匹配的缓存键", description="根据模式清除匹配的Redis缓存键")
|
||||
@router.post("/clearrediskeys/", summary="清除匹配的缓存键", description="根据模式清除匹配的Redis缓存键")
|
||||
async def fastapi_clear_redis_keys(keys: str = Query(..., description="缓存键模式(支持通配符)")):
|
||||
"""
|
||||
清除匹配的缓存键
|
||||
@@ -29,7 +29,7 @@ async def fastapi_clear_redis_keys(keys: str = Query(..., description="缓存键
|
||||
return True
|
||||
|
||||
|
||||
@router.delete("/all-redis", summary="清除所有缓存", description="清空整个Redis数据库的所有缓存")
|
||||
@router.post("/clearallredis/", summary="清除所有缓存", description="清空整个Redis数据库的所有缓存")
|
||||
async def fastapi_clear_all_redis():
|
||||
"""
|
||||
清除所有缓存
|
||||
@@ -40,7 +40,7 @@ async def fastapi_clear_all_redis():
|
||||
return True
|
||||
|
||||
|
||||
@router.get("/redis", summary="查询缓存键列表", description="获取Redis中所有的缓存键")
|
||||
@router.get("/queryredis/", summary="查询缓存键列表", description="获取Redis中所有的缓存键")
|
||||
async def fastapi_query_redis():
|
||||
"""
|
||||
查询缓存键列表
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/control", summary="获取控制架构", description="获取网络中控制对象的架构定义")
|
||||
@router.get("/getcontrolschema/", summary="获取控制架构", description="获取网络中控制对象的架构定义")
|
||||
async def fastapi_get_control_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取控制架构。
|
||||
|
||||
@@ -21,7 +21,7 @@ async def fastapi_get_control_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_control_schema(network)
|
||||
|
||||
@router.get("/controls/properties", summary="获取控制属性", description="获取指定网络中的控制属性信息")
|
||||
@router.get("/getcontrolproperties/", summary="获取控制属性", description="获取指定网络中的控制属性信息")
|
||||
async def fastapi_get_control_properties(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, Any]:
|
||||
"""获取控制属性。
|
||||
|
||||
@@ -29,7 +29,7 @@ async def fastapi_get_control_properties(network: str = Query(..., description="
|
||||
"""
|
||||
return get_control(network)
|
||||
|
||||
@router.patch("/controls/properties", response_model=None, summary="设置控制属性", description="更新指定网络中的控制属性")
|
||||
@router.post("/setcontrolproperties/", response_model=None, summary="设置控制属性", description="更新指定网络中的控制属性")
|
||||
async def fastapi_set_control_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -41,7 +41,7 @@ async def fastapi_set_control_properties(
|
||||
props = await req.json()
|
||||
return set_control(network, ChangeSet(props))
|
||||
|
||||
@router.get("/rule-schemas", summary="获取规则架构", description="获取网络中规则对象的架构定义")
|
||||
@router.get("/getruleschema/", summary="获取规则架构", description="获取网络中规则对象的架构定义")
|
||||
async def fastapi_get_rule_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取规则架构。
|
||||
|
||||
@@ -49,7 +49,7 @@ async def fastapi_get_rule_schema(network: str = Query(..., description="管网
|
||||
"""
|
||||
return get_rule_schema(network)
|
||||
|
||||
@router.get("/rule-properties", summary="获取规则属性", description="获取指定网络中的规则属性信息")
|
||||
@router.get("/getruleproperties/", summary="获取规则属性", description="获取指定网络中的规则属性信息")
|
||||
async def fastapi_get_rule_properties(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, Any]:
|
||||
"""获取规则属性。
|
||||
|
||||
@@ -57,7 +57,7 @@ async def fastapi_get_rule_properties(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_rule(network)
|
||||
|
||||
@router.patch("/rule-properties", response_model=None, summary="设置规则属性", description="更新指定网络中的规则属性")
|
||||
@router.post("/setruleproperties/", response_model=None, summary="设置规则属性", description="更新指定网络中的规则属性")
|
||||
async def fastapi_set_rule_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/curve", summary="获取曲线架构", description="获取网络中曲线对象的架构定义")
|
||||
@router.get("/getcurveschema", summary="获取曲线架构", description="获取网络中曲线对象的架构定义")
|
||||
async def fastapi_get_curve_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取曲线架构。
|
||||
|
||||
@@ -22,7 +22,7 @@ async def fastapi_get_curve_schema(network: str = Query(..., description="管网
|
||||
"""
|
||||
return get_curve_schema(network)
|
||||
|
||||
@router.post("/curves", response_model=None, summary="添加曲线", description="在网络中添加一条新的曲线")
|
||||
@router.post("/addcurve/", response_model=None, summary="添加曲线", description="在网络中添加一条新的曲线")
|
||||
async def fastapi_add_curve(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
curve: str = Query(..., description="曲线ID"),
|
||||
@@ -38,7 +38,7 @@ async def fastapi_add_curve(
|
||||
} | props
|
||||
return add_curve(network, ChangeSet(ps))
|
||||
|
||||
@router.delete("/curves", response_model=None, summary="删除曲线", description="从网络中删除指定的曲线")
|
||||
@router.post("/deletecurve/", response_model=None, summary="删除曲线", description="从网络中删除指定的曲线")
|
||||
async def fastapi_delete_curve(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
curve: str = Query(..., description="曲线ID")
|
||||
@@ -50,7 +50,7 @@ async def fastapi_delete_curve(
|
||||
ps = {"id": curve}
|
||||
return delete_curve(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/curves/properties", summary="获取曲线属性", description="获取指定曲线的属性信息")
|
||||
@router.get("/getcurveproperties/", summary="获取曲线属性", description="获取指定曲线的属性信息")
|
||||
async def fastapi_get_curve_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
curve: str = Query(..., description="曲线ID")
|
||||
@@ -61,7 +61,7 @@ async def fastapi_get_curve_properties(
|
||||
"""
|
||||
return get_curve(network, curve)
|
||||
|
||||
@router.patch("/curves/properties", response_model=None, summary="设置曲线属性", description="更新指定曲线的属性")
|
||||
@router.post("/setcurveproperties/", response_model=None, summary="设置曲线属性", description="更新指定曲线的属性")
|
||||
async def fastapi_set_curve_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
curve: str = Query(..., description="曲线ID"),
|
||||
@@ -75,7 +75,7 @@ async def fastapi_set_curve_properties(
|
||||
ps = {"id": curve} | props
|
||||
return set_curve(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/curves", summary="获取所有曲线", description="获取网络中的所有曲线列表")
|
||||
@router.get("/getcurves/", summary="获取所有曲线", description="获取网络中的所有曲线列表")
|
||||
async def fastapi_get_curves(network: str = Query(..., description="管网名称(或数据库名称)")) -> list[str]:
|
||||
"""获取所有曲线。
|
||||
|
||||
@@ -83,7 +83,7 @@ async def fastapi_get_curves(network: str = Query(..., description="管网名称
|
||||
"""
|
||||
return get_curves(network)
|
||||
|
||||
@router.get("/curves/existence", summary="检查曲线存在性", description="检查指定的曲线是否存在")
|
||||
@router.get("/iscurve/", summary="检查曲线存在性", description="检查指定的曲线是否存在")
|
||||
async def fastapi_is_curve(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
curve: str = Query(..., description="曲线ID")
|
||||
|
||||
@@ -19,7 +19,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/time", summary="获取时间选项架构", description="获取网络中时间选项的架构定义")
|
||||
@router.get("/gettimeschema", summary="获取时间选项架构", description="获取网络中时间选项的架构定义")
|
||||
async def fastapi_get_time_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取时间选项架构。
|
||||
|
||||
@@ -27,7 +27,7 @@ async def fastapi_get_time_schema(network: str = Query(..., description="管网
|
||||
"""
|
||||
return get_time_schema(network)
|
||||
|
||||
@router.get("/network-options/time", summary="获取时间选项属性", description="获取指定网络中的时间选项属性信息")
|
||||
@router.get("/gettimeproperties/", summary="获取时间选项属性", description="获取指定网络中的时间选项属性信息")
|
||||
async def fastapi_get_time_properties(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, Any]:
|
||||
"""获取时间选项属性。
|
||||
|
||||
@@ -35,7 +35,7 @@ async def fastapi_get_time_properties(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_time(network)
|
||||
|
||||
@router.patch("/time-properties", response_model=None, summary="设置时间选项属性", description="更新指定网络中的时间选项属性")
|
||||
@router.post("/settimeproperties/", response_model=None, summary="设置时间选项属性", description="更新指定网络中的时间选项属性")
|
||||
async def fastapi_set_time_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -47,7 +47,7 @@ async def fastapi_set_time_properties(
|
||||
props = await req.json()
|
||||
return set_time(network, ChangeSet(props))
|
||||
|
||||
@router.get("/network-schemas/energy", summary="获取能耗选项架构", description="获取网络中能耗选项的架构定义")
|
||||
@router.get("/getenergyschema/", summary="获取能耗选项架构", description="获取网络中能耗选项的架构定义")
|
||||
async def fastapi_get_energy_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取能耗选项架构。
|
||||
|
||||
@@ -55,7 +55,7 @@ async def fastapi_get_energy_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_energy_schema(network)
|
||||
|
||||
@router.get("/network-options/energy", summary="获取能耗选项属性", description="获取指定网络中的能耗选项属性信息")
|
||||
@router.get("/getenergyproperties/", summary="获取能耗选项属性", description="获取指定网络中的能耗选项属性信息")
|
||||
async def fastapi_get_energy_properties(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, Any]:
|
||||
"""获取能耗选项属性。
|
||||
|
||||
@@ -63,7 +63,7 @@ async def fastapi_get_energy_properties(network: str = Query(..., description="
|
||||
"""
|
||||
return get_energy(network)
|
||||
|
||||
@router.patch("/energy-properties", response_model=None, summary="设置能耗选项属性", description="更新指定网络中的能耗选项属性")
|
||||
@router.post("/setenergyproperties/", response_model=None, summary="设置能耗选项属性", description="更新指定网络中的能耗选项属性")
|
||||
async def fastapi_set_energy_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -75,7 +75,7 @@ async def fastapi_set_energy_properties(
|
||||
props = await req.json()
|
||||
return set_energy(network, ChangeSet(props))
|
||||
|
||||
@router.get("/network-schemas/pump-energy", summary="获取泵能耗选项架构", description="获取网络中泵能耗选项的架构定义")
|
||||
@router.get("/getpumpenergyschema/", summary="获取泵能耗选项架构", description="获取网络中泵能耗选项的架构定义")
|
||||
async def fastapi_get_pump_energy_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取泵能耗选项架构。
|
||||
|
||||
@@ -83,7 +83,7 @@ async def fastapi_get_pump_energy_schema(network: str = Query(..., description="
|
||||
"""
|
||||
return get_pump_energy_schema(network)
|
||||
|
||||
@router.get("/network-options/pump-energy", summary="获取泵能耗属性", description="获取指定泵的能耗属性信息")
|
||||
@router.get("/getpumpenergyproperties//", summary="获取泵能耗属性", description="获取指定泵的能耗属性信息")
|
||||
async def fastapi_get_pump_energy_proeprties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="泵ID")
|
||||
@@ -94,7 +94,7 @@ async def fastapi_get_pump_energy_proeprties(
|
||||
"""
|
||||
return get_pump_energy(network, pump)
|
||||
|
||||
@router.patch("/network-options/pump-energy", response_model=None, summary="设置泵能耗属性", description="更新指定泵的能耗属性")
|
||||
@router.get("/setpumpenergyproperties//", response_model=None, summary="设置泵能耗属性", description="更新指定泵的能耗属性")
|
||||
async def fastapi_set_pump_energy_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="泵ID"),
|
||||
@@ -108,7 +108,7 @@ async def fastapi_set_pump_energy_properties(
|
||||
ps = {"id": pump} | props
|
||||
return set_pump_energy(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/network-schemas/option", summary="获取选项架构", description="获取网络中选项对象的架构定义")
|
||||
@router.get("/getoptionschema/", summary="获取选项架构", description="获取网络中选项对象的架构定义")
|
||||
async def fastapi_get_option_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取选项架构。
|
||||
|
||||
@@ -116,7 +116,7 @@ async def fastapi_get_option_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_option_v3_schema(network)
|
||||
|
||||
@router.get("/network-options", summary="获取选项属性", description="获取指定网络中的选项属性信息")
|
||||
@router.get("/getoptionproperties/", summary="获取选项属性", description="获取指定网络中的选项属性信息")
|
||||
async def fastapi_get_option_properties(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, Any]:
|
||||
"""获取选项属性。
|
||||
|
||||
@@ -124,7 +124,7 @@ async def fastapi_get_option_properties(network: str = Query(..., description="
|
||||
"""
|
||||
return get_option_v3(network)
|
||||
|
||||
@router.patch("/network-options", response_model=None, summary="设置选项属性", description="更新指定网络中的选项属性")
|
||||
@router.post("/setoptionproperties/", response_model=None, summary="设置选项属性", description="更新指定网络中的选项属性")
|
||||
async def fastapi_set_option_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/pattern", summary="获取模式架构", description="获取网络中模式对象的架构定义")
|
||||
@router.get("/getpatternschema", summary="获取模式架构", description="获取网络中模式对象的架构定义")
|
||||
async def fastapi_get_pattern_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取模式架构。
|
||||
|
||||
@@ -22,7 +22,7 @@ async def fastapi_get_pattern_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_pattern_schema(network)
|
||||
|
||||
@router.post("/patterns", response_model=None, summary="添加模式", description="在网络中添加一个新的模式")
|
||||
@router.post("/addpattern/", response_model=None, summary="添加模式", description="在网络中添加一个新的模式")
|
||||
async def fastapi_add_pattern(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pattern: str = Query(..., description="模式ID"),
|
||||
@@ -38,7 +38,7 @@ async def fastapi_add_pattern(
|
||||
} | props
|
||||
return add_pattern(network, ChangeSet(ps))
|
||||
|
||||
@router.delete("/patterns", response_model=None, summary="删除模式", description="从网络中删除指定的模式")
|
||||
@router.post("/deletepattern/", response_model=None, summary="删除模式", description="从网络中删除指定的模式")
|
||||
async def fastapi_delete_pattern(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pattern: str = Query(..., description="模式ID")
|
||||
@@ -50,7 +50,7 @@ async def fastapi_delete_pattern(
|
||||
ps = {"id": pattern}
|
||||
return delete_pattern(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/patterns/properties", summary="获取模式属性", description="获取指定模式的属性信息")
|
||||
@router.get("/getpatternproperties/", summary="获取模式属性", description="获取指定模式的属性信息")
|
||||
async def fastapi_get_pattern_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pattern: str = Query(..., description="模式ID")
|
||||
@@ -61,7 +61,7 @@ async def fastapi_get_pattern_properties(
|
||||
"""
|
||||
return get_pattern(network, pattern)
|
||||
|
||||
@router.patch("/patterns/properties", response_model=None, summary="设置模式属性", description="更新指定模式的属性")
|
||||
@router.post("/setpatternproperties/", response_model=None, summary="设置模式属性", description="更新指定模式的属性")
|
||||
async def fastapi_set_pattern_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pattern: str = Query(..., description="模式ID"),
|
||||
@@ -75,7 +75,7 @@ async def fastapi_set_pattern_properties(
|
||||
ps = {"id": pattern} | props
|
||||
return set_pattern(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/patterns/existence", summary="检查模式存在性", description="检查指定的模式是否存在")
|
||||
@router.get("/ispattern/", summary="检查模式存在性", description="检查指定的模式是否存在")
|
||||
async def fastapi_is_pattern(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pattern: str = Query(..., description="模式ID")
|
||||
@@ -86,7 +86,7 @@ async def fastapi_is_pattern(
|
||||
"""
|
||||
return is_pattern(network, pattern)
|
||||
|
||||
@router.get("/patterns", summary="获取所有模式", description="获取网络中的所有模式列表")
|
||||
@router.get("/getpatterns/", summary="获取所有模式", description="获取网络中的所有模式列表")
|
||||
async def fastapi_get_patterns(network: str = Query(..., description="管网名称(或数据库名称)")) -> list[str]:
|
||||
"""获取所有模式。
|
||||
|
||||
|
||||
@@ -32,7 +32,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/quality", summary="获取水质架构", description="获取网络中水质对象的架构定义")
|
||||
@router.get("/getqualityschema/", summary="获取水质架构", description="获取网络中水质对象的架构定义")
|
||||
async def fastapi_get_quality_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取水质架构。
|
||||
|
||||
@@ -40,7 +40,7 @@ async def fastapi_get_quality_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_quality_schema(network)
|
||||
|
||||
@router.get("/quality-configurations/properties", summary="获取水质属性", description="获取指定节点的水质属性信息")
|
||||
@router.get("/getqualityproperties/", summary="获取水质属性", description="获取指定节点的水质属性信息")
|
||||
async def fastapi_get_quality_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
node: str = Query(..., description="节点ID")
|
||||
@@ -51,7 +51,7 @@ async def fastapi_get_quality_properties(
|
||||
"""
|
||||
return get_quality(network, node)
|
||||
|
||||
@router.patch("/quality-configurations/properties", response_model=None, summary="设置水质属性", description="更新指定节点的水质属性")
|
||||
@router.post("/setqualityproperties/", response_model=None, summary="设置水质属性", description="更新指定节点的水质属性")
|
||||
async def fastapi_set_quality_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -63,7 +63,7 @@ async def fastapi_set_quality_properties(
|
||||
props = await req.json()
|
||||
return set_quality(network, ChangeSet(props))
|
||||
|
||||
@router.get("/network-schemas/emitter", summary="获取发射器架构", description="获取网络中发射器对象的架构定义")
|
||||
@router.get("/getemitterschema", summary="获取发射器架构", description="获取网络中发射器对象的架构定义")
|
||||
async def fastapi_get_emitter_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取发射器架构。
|
||||
|
||||
@@ -71,7 +71,7 @@ async def fastapi_get_emitter_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_emitter_schema(network)
|
||||
|
||||
@router.get("/emitters/properties", summary="获取发射器属性", description="获取指定连接点的发射器属性信息")
|
||||
@router.get("/getemitterproperties/", summary="获取发射器属性", description="获取指定连接点的发射器属性信息")
|
||||
async def fastapi_get_emitter_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="连接点ID")
|
||||
@@ -82,7 +82,7 @@ async def fastapi_get_emitter_properties(
|
||||
"""
|
||||
return get_emitter(network, junction)
|
||||
|
||||
@router.patch("/emitters/properties", response_model=None, summary="设置发射器属性", description="更新指定连接点的发射器属性")
|
||||
@router.post("/setemitterproperties/", response_model=None, summary="设置发射器属性", description="更新指定连接点的发射器属性")
|
||||
async def fastapi_set_emitter_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="连接点ID"),
|
||||
@@ -96,7 +96,7 @@ async def fastapi_set_emitter_properties(
|
||||
ps = {"junction": junction} | props
|
||||
return set_emitter(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/network-schemas/source", summary="获取水源架构", description="获取网络中水源对象的架构定义")
|
||||
@router.get("/getsourcechema/", summary="获取水源架构", description="获取网络中水源对象的架构定义")
|
||||
async def fastapi_get_source_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取水源架构。
|
||||
|
||||
@@ -104,7 +104,7 @@ async def fastapi_get_source_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_source_schema(network)
|
||||
|
||||
@router.get("/sources/detail", summary="获取水源属性", description="获取指定节点的水源属性信息")
|
||||
@router.get("/getsource/", summary="获取水源属性", description="获取指定节点的水源属性信息")
|
||||
async def fastapi_get_source(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
node: str = Query(..., description="节点ID")
|
||||
@@ -115,7 +115,7 @@ async def fastapi_get_source(
|
||||
"""
|
||||
return get_source(network, node)
|
||||
|
||||
@router.patch("/sources", response_model=None, summary="设置水源属性", description="更新指定节点的水源属性")
|
||||
@router.post("/setsource/", response_model=None, summary="设置水源属性", description="更新指定节点的水源属性")
|
||||
async def fastapi_set_source(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -127,7 +127,7 @@ async def fastapi_set_source(
|
||||
props = await req.json()
|
||||
return set_source(network, ChangeSet(props))
|
||||
|
||||
@router.post("/sources", response_model=None, summary="添加水源", description="在网络中添加一个新的水源")
|
||||
@router.post("/addsource/", response_model=None, summary="添加水源", description="在网络中添加一个新的水源")
|
||||
async def fastapi_add_source(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -139,7 +139,7 @@ async def fastapi_add_source(
|
||||
props = await req.json()
|
||||
return add_source(network, ChangeSet(props))
|
||||
|
||||
@router.delete("/sources", response_model=None, summary="删除水源", description="从网络中删除指定节点的水源")
|
||||
@router.post("/deletesource/", response_model=None, summary="删除水源", description="从网络中删除指定节点的水源")
|
||||
async def fastapi_delete_source(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
node: str = Query(..., description="节点ID")
|
||||
@@ -151,7 +151,7 @@ async def fastapi_delete_source(
|
||||
props = {"node": node}
|
||||
return delete_source(network, ChangeSet(props))
|
||||
|
||||
@router.get("/network-schemas/reaction", summary="获取反应架构", description="获取网络中反应对象的架构定义")
|
||||
@router.get("/getreactionschema/", summary="获取反应架构", description="获取网络中反应对象的架构定义")
|
||||
async def fastapi_get_reaction_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取反应架构。
|
||||
|
||||
@@ -159,7 +159,7 @@ async def fastapi_get_reaction_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_reaction_schema(network)
|
||||
|
||||
@router.get("/reactions/detail", summary="获取反应属性", description="获取指定网络中的反应属性信息")
|
||||
@router.get("/getreaction/", summary="获取反应属性", description="获取指定网络中的反应属性信息")
|
||||
async def fastapi_get_reaction(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, Any]:
|
||||
"""获取反应属性。
|
||||
|
||||
@@ -167,7 +167,7 @@ async def fastapi_get_reaction(network: str = Query(..., description="管网名
|
||||
"""
|
||||
return get_reaction(network)
|
||||
|
||||
@router.patch("/reactions", response_model=None, summary="设置反应属性", description="更新指定网络中的反应属性")
|
||||
@router.post("/setreaction/", response_model=None, summary="设置反应属性", description="更新指定网络中的反应属性")
|
||||
async def fastapi_set_reaction(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -179,7 +179,7 @@ async def fastapi_set_reaction(
|
||||
props = await req.json()
|
||||
return set_reaction(network, ChangeSet(props))
|
||||
|
||||
@router.get("/network-schemas/pipe-reaction", summary="获取管道反应架构", description="获取网络中管道反应对象的架构定义")
|
||||
@router.get("/getpipereactionschema/", summary="获取管道反应架构", description="获取网络中管道反应对象的架构定义")
|
||||
async def fastapi_get_pipe_reaction_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取管道反应架构。
|
||||
|
||||
@@ -187,7 +187,7 @@ async def fastapi_get_pipe_reaction_schema(network: str = Query(..., description
|
||||
"""
|
||||
return get_pipe_reaction_schema(network)
|
||||
|
||||
@router.get("/pipe-reactions/detail", summary="获取管道反应属性", description="获取指定管道的反应属性信息")
|
||||
@router.get("/getpipereaction/", summary="获取管道反应属性", description="获取指定管道的反应属性信息")
|
||||
async def fastapi_get_pipe_reaction(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID")
|
||||
@@ -198,7 +198,7 @@ async def fastapi_get_pipe_reaction(
|
||||
"""
|
||||
return get_pipe_reaction(network, pipe)
|
||||
|
||||
@router.patch("/pipe-reactions", response_model=None, summary="设置管道反应属性", description="更新指定管道的反应属性")
|
||||
@router.post("/setpipereaction/", response_model=None, summary="设置管道反应属性", description="更新指定管道的反应属性")
|
||||
async def fastapi_set_pipe_reaction(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -210,7 +210,7 @@ async def fastapi_set_pipe_reaction(
|
||||
props = await req.json()
|
||||
return set_pipe_reaction(network, ChangeSet(props))
|
||||
|
||||
@router.get("/network-schemas/tank-reaction", summary="获取水池反应架构", description="获取网络中水池反应对象的架构定义")
|
||||
@router.get("/gettankreactionschema/", summary="获取水池反应架构", description="获取网络中水池反应对象的架构定义")
|
||||
async def fastapi_get_tank_reaction_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取水池反应架构。
|
||||
|
||||
@@ -218,7 +218,7 @@ async def fastapi_get_tank_reaction_schema(network: str = Query(..., description
|
||||
"""
|
||||
return get_tank_reaction_schema(network)
|
||||
|
||||
@router.get("/tank-reactions/detail", summary="获取水池反应属性", description="获取指定水池的反应属性信息")
|
||||
@router.get("/gettankreaction/", summary="获取水池反应属性", description="获取指定水池的反应属性信息")
|
||||
async def fastapi_get_tank_reaction(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水池ID")
|
||||
@@ -229,7 +229,7 @@ async def fastapi_get_tank_reaction(
|
||||
"""
|
||||
return get_tank_reaction(network, tank)
|
||||
|
||||
@router.patch("/tank-reactions", response_model=None, summary="设置水池反应属性", description="更新指定水池的反应属性")
|
||||
@router.post("/settankreaction/", response_model=None, summary="设置水池反应属性", description="更新指定水池的反应属性")
|
||||
async def fastapi_set_tank_reaction(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -241,7 +241,7 @@ async def fastapi_set_tank_reaction(
|
||||
props = await req.json()
|
||||
return set_tank_reaction(network, ChangeSet(props))
|
||||
|
||||
@router.get("/network-schemas/mixing", summary="获取混合架构", description="获取网络中混合对象的架构定义")
|
||||
@router.get("/getmixingschema/", summary="获取混合架构", description="获取网络中混合对象的架构定义")
|
||||
async def fastapi_get_mixing_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取混合架构。
|
||||
|
||||
@@ -249,7 +249,7 @@ async def fastapi_get_mixing_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_mixing_schema(network)
|
||||
|
||||
@router.get("/mixing-configurations/detail", summary="获取混合属性", description="获取指定水池的混合属性信息")
|
||||
@router.get("/getmixing/", summary="获取混合属性", description="获取指定水池的混合属性信息")
|
||||
async def fastapi_get_mixing(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水池ID")
|
||||
@@ -260,7 +260,7 @@ async def fastapi_get_mixing(
|
||||
"""
|
||||
return get_mixing(network, tank)
|
||||
|
||||
@router.patch("/mixing-configurations", response_model=None, summary="设置混合属性", description="更新指定水池的混合属性")
|
||||
@router.post("/setmixing/", response_model=None, summary="设置混合属性", description="更新指定水池的混合属性")
|
||||
async def fastapi_set_mixing(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -272,7 +272,7 @@ async def fastapi_set_mixing(
|
||||
props = await req.json()
|
||||
return api.set_mixing(network, ChangeSet(props))
|
||||
|
||||
@router.post("/mixing-configurations", response_model=None, summary="添加混合", description="在网络中添加一个新的混合")
|
||||
@router.post("/addmixing/", response_model=None, summary="添加混合", description="在网络中添加一个新的混合")
|
||||
async def fastapi_add_mixing(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -284,7 +284,7 @@ async def fastapi_add_mixing(
|
||||
props = await req.json()
|
||||
return add_mixing(network, ChangeSet(props))
|
||||
|
||||
@router.delete("/mixing-configurations", response_model=None, summary="删除混合", description="从网络中删除指定的混合")
|
||||
@router.post("/deletemixing/", response_model=None, summary="删除混合", description="从网络中删除指定的混合")
|
||||
async def fastapi_delete_mixing(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
|
||||
@@ -24,7 +24,7 @@ import json
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/vertex", summary="获取图形元素架构", description="获取网络中图形元素对象的架构定义")
|
||||
@router.get("/getvertexschema/", summary="获取图形元素架构", description="获取网络中图形元素对象的架构定义")
|
||||
async def fastapi_get_vertex_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取图形元素架构。
|
||||
|
||||
@@ -32,7 +32,7 @@ async def fastapi_get_vertex_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_vertex_schema(network)
|
||||
|
||||
@router.get("/visual-elements/properties", summary="获取图形元素属性", description="获取指定图形元素的属性信息")
|
||||
@router.get("/getvertexproperties/", summary="获取图形元素属性", description="获取指定图形元素的属性信息")
|
||||
async def fastapi_get_vertex_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
link: str = Query(..., description="图形元素链接")
|
||||
@@ -43,7 +43,7 @@ async def fastapi_get_vertex_properties(
|
||||
"""
|
||||
return get_vertex(network, link)
|
||||
|
||||
@router.patch("/visual-elements/properties", response_model=None, summary="设置图形元素属性", description="更新指定图形元素的属性")
|
||||
@router.post("/setvertexproperties/", response_model=None, summary="设置图形元素属性", description="更新指定图形元素的属性")
|
||||
async def fastapi_set_vertex_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -55,7 +55,7 @@ async def fastapi_set_vertex_properties(
|
||||
props = await req.json()
|
||||
return set_vertex(network, ChangeSet(props))
|
||||
|
||||
@router.post("/visual-elements", response_model=None, summary="添加图形元素", description="在网络中添加一个新的图形元素")
|
||||
@router.post("/addvertex/", response_model=None, summary="添加图形元素", description="在网络中添加一个新的图形元素")
|
||||
async def fastapi_add_vertex(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -67,7 +67,7 @@ async def fastapi_add_vertex(
|
||||
props = await req.json()
|
||||
return add_vertex(network, ChangeSet(props))
|
||||
|
||||
@router.delete("/visual-elements", response_model=None, summary="删除图形元素", description="从网络中删除指定的图形元素")
|
||||
@router.post("/deletevertex/", response_model=None, summary="删除图形元素", description="从网络中删除指定的图形元素")
|
||||
async def fastapi_delete_vertex(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -79,7 +79,7 @@ async def fastapi_delete_vertex(
|
||||
props = await req.json()
|
||||
return delete_vertex(network, ChangeSet(props))
|
||||
|
||||
@router.get("/visual-elements/links", response_class=PlainTextResponse, summary="获取所有图形元素链接", description="获取网络中的所有图形元素链接列表")
|
||||
@router.get("/getallvertexlinks/", response_class=PlainTextResponse, summary="获取所有图形元素链接", description="获取网络中的所有图形元素链接列表")
|
||||
async def fastapi_get_all_vertex_links(network: str = Query(..., description="管网名称(或数据库名称)")) -> list[str]:
|
||||
"""获取所有图形元素链接。
|
||||
|
||||
@@ -87,7 +87,7 @@ async def fastapi_get_all_vertex_links(network: str = Query(..., description="
|
||||
"""
|
||||
return json.dumps(get_all_vertex_links(network))
|
||||
|
||||
@router.get("/all-vertices", response_class=PlainTextResponse, summary="获取所有图形元素", description="获取网络中的所有图形元素详细信息")
|
||||
@router.get("/getallvertices/", response_class=PlainTextResponse, summary="获取所有图形元素", description="获取网络中的所有图形元素详细信息")
|
||||
async def fastapi_get_all_vertices(network: str = Query(..., description="管网名称(或数据库名称)")) -> list[dict[str, Any]]:
|
||||
"""获取所有图形元素。
|
||||
|
||||
@@ -95,7 +95,7 @@ async def fastapi_get_all_vertices(network: str = Query(..., description="管网
|
||||
"""
|
||||
return json.dumps(get_all_vertices(network))
|
||||
|
||||
@router.get("/network-schemas/label", summary="获取标签架构", description="获取网络中标签对象的架构定义")
|
||||
@router.get("/getlabelschema/", summary="获取标签架构", description="获取网络中标签对象的架构定义")
|
||||
async def fastapi_get_label_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取标签架构。
|
||||
|
||||
@@ -103,7 +103,7 @@ async def fastapi_get_label_schema(network: str = Query(..., description="管网
|
||||
"""
|
||||
return get_label_schema(network)
|
||||
|
||||
@router.get("/labels/properties", summary="获取标签属性", description="获取指定坐标处的标签属性信息")
|
||||
@router.get("/getlabelproperties/", summary="获取标签属性", description="获取指定坐标处的标签属性信息")
|
||||
async def fastapi_get_label_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
x: float = Query(..., description="X坐标"),
|
||||
@@ -115,7 +115,7 @@ async def fastapi_get_label_properties(
|
||||
"""
|
||||
return get_label(network, x, y)
|
||||
|
||||
@router.patch("/labels/properties", response_model=None, summary="设置标签属性", description="更新指定标签的属性")
|
||||
@router.post("/setlabelproperties/", response_model=None, summary="设置标签属性", description="更新指定标签的属性")
|
||||
async def fastapi_set_label_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -127,7 +127,7 @@ async def fastapi_set_label_properties(
|
||||
props = await req.json()
|
||||
return set_label(network, ChangeSet(props))
|
||||
|
||||
@router.post("/labels", response_model=None, summary="添加标签", description="在网络中添加一个新的标签")
|
||||
@router.post("/addlabel/", response_model=None, summary="添加标签", description="在网络中添加一个新的标签")
|
||||
async def fastapi_add_label(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -139,7 +139,7 @@ async def fastapi_add_label(
|
||||
props = await req.json()
|
||||
return add_label(network, ChangeSet(props))
|
||||
|
||||
@router.delete("/labels", response_model=None, summary="删除标签", description="从网络中删除指定的标签")
|
||||
@router.post("/deletelabel/", response_model=None, summary="删除标签", description="从网络中删除指定的标签")
|
||||
async def fastapi_delete_label(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -151,7 +151,7 @@ async def fastapi_delete_label(
|
||||
props = await req.json()
|
||||
return delete_label(network, ChangeSet(props))
|
||||
|
||||
@router.get("/network-schemas/backdrop", summary="获取背景架构", description="获取网络中背景对象的架构定义")
|
||||
@router.get("/getbackdropschema/", summary="获取背景架构", description="获取网络中背景对象的架构定义")
|
||||
async def fastapi_get_backdrop_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""获取背景架构。
|
||||
|
||||
@@ -159,7 +159,7 @@ async def fastapi_get_backdrop_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_backdrop_schema(network)
|
||||
|
||||
@router.get("/backdrops/properties", summary="获取背景属性", description="获取指定网络的背景属性信息")
|
||||
@router.get("/getbackdropproperties/", summary="获取背景属性", description="获取指定网络的背景属性信息")
|
||||
async def fastapi_get_backdrop_properties(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, Any]:
|
||||
"""获取背景属性。
|
||||
|
||||
@@ -167,7 +167,7 @@ async def fastapi_get_backdrop_properties(network: str = Query(..., description=
|
||||
"""
|
||||
return get_backdrop(network)
|
||||
|
||||
@router.patch("/backdrops/properties", response_model=None, summary="设置背景属性", description="更新指定网络的背景属性")
|
||||
@router.post("/setbackdropproperties/", response_model=None, summary="设置背景属性", description="更新指定网络的背景属性")
|
||||
async def fastapi_set_backdrop_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
|
||||
@@ -11,7 +11,7 @@ from app.services.tjnetwork import (
|
||||
router = APIRouter()
|
||||
|
||||
@router.get(
|
||||
"/all-extension-data-keys",
|
||||
"/getallextensiondatakeys/",
|
||||
summary="获取所有扩展数据键",
|
||||
description="获取指定网络的所有扩展数据的键列表"
|
||||
)
|
||||
@@ -32,7 +32,7 @@ async def get_all_extension_data_keys_endpoint(
|
||||
return get_all_extension_data_keys(network)
|
||||
|
||||
@router.get(
|
||||
"/all-extension-datas",
|
||||
"/getallextensiondata/",
|
||||
summary="获取所有扩展数据",
|
||||
description="获取指定网络的所有扩展数据"
|
||||
)
|
||||
@@ -53,7 +53,7 @@ async def get_all_extension_data_endpoint(
|
||||
return get_all_extension_data(network)
|
||||
|
||||
@router.get(
|
||||
"/extension-datas",
|
||||
"/getextensiondata/",
|
||||
summary="获取指定扩展数据",
|
||||
description="获取指定网络中指定键的扩展数据值"
|
||||
)
|
||||
@@ -75,8 +75,8 @@ async def get_extension_data_endpoint(
|
||||
"""
|
||||
return get_extension_data(network, key)
|
||||
|
||||
@router.patch(
|
||||
"/extension-datas",
|
||||
@router.post(
|
||||
"/setextensiondata/",
|
||||
response_model=None,
|
||||
summary="设置扩展数据",
|
||||
description="设置指定网络中的扩展数据"
|
||||
|
||||
@@ -13,7 +13,7 @@ router = APIRouter()
|
||||
|
||||
|
||||
@router.post(
|
||||
"/geocoding-requests",
|
||||
"/tianditu/geocode",
|
||||
summary="Tianditu Geocoding",
|
||||
description="调用天地图地理编码服务,将结构化地址转换为经纬度",
|
||||
)
|
||||
|
||||
@@ -2,11 +2,13 @@ import os
|
||||
from typing import Any
|
||||
from datetime import datetime
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Body
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Path, Body
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
from app.auth.keycloak_dependencies import get_current_keycloak_username
|
||||
from app.services.leakage_identifier import (
|
||||
get_leakage_identify_scheme_detail,
|
||||
list_leakage_identify_schemes,
|
||||
run_leakage_identification,
|
||||
)
|
||||
|
||||
@@ -38,7 +40,7 @@ class LeakageIdentifyRequest(BaseModel):
|
||||
|
||||
|
||||
@router.post(
|
||||
"/leakage-identifications",
|
||||
"/identify/",
|
||||
summary="执行漏损识别",
|
||||
description="基于压力观测数据和遗传算法识别管网中的漏损位置和大小"
|
||||
)
|
||||
@@ -66,3 +68,66 @@ async def identify_leakage(
|
||||
return run_leakage_identification(**data.model_dump(), username=username)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/schemes/",
|
||||
summary="查询漏损识别方案列表",
|
||||
description="获取指定网络的所有漏损识别方案"
|
||||
)
|
||||
async def query_leakage_schemes(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
query_date: datetime | None = Query(None, description="查询日期(可选)")
|
||||
) -> list[dict[str, Any]]:
|
||||
"""
|
||||
获取漏损识别方案列表。
|
||||
|
||||
查询指定网络的所有已配置的漏损识别方案,
|
||||
可按日期进行筛选。
|
||||
|
||||
Args:
|
||||
network: 管网名称(或数据库名称)
|
||||
query_date: 查询日期(可选)
|
||||
|
||||
Returns:
|
||||
漏损识别方案列表
|
||||
|
||||
Raises:
|
||||
HTTPException: 当查询失败时
|
||||
"""
|
||||
try:
|
||||
return list_leakage_identify_schemes(network=network, query_date=query_date)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
|
||||
@router.get(
|
||||
"/schemes/{scheme_name}",
|
||||
summary="获取漏损识别方案详情",
|
||||
description="获取指定漏损识别方案的详细信息"
|
||||
)
|
||||
async def query_leakage_scheme_detail(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
scheme_name: str = Path(..., description="漏损识别方案名称")
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
获取漏损识别方案详情。
|
||||
|
||||
查询指定漏损识别方案的完整配置和参数信息。
|
||||
|
||||
Args:
|
||||
network: 管网名称(或数据库名称)
|
||||
scheme_name: 漏损识别方案名称
|
||||
|
||||
Returns:
|
||||
包含方案详情的字典
|
||||
|
||||
Raises:
|
||||
HTTPException: 当查询失败时
|
||||
"""
|
||||
try:
|
||||
return get_leakage_identify_scheme_detail(
|
||||
network=network, scheme_name=scheme_name
|
||||
)
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=400, detail=str(exc))
|
||||
|
||||
@@ -25,7 +25,7 @@ router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
@router.get("/projects/current/metadata", summary="获取项目元数据", description="获取当前项目的元数据和配置信息", response_model=ProjectMetaResponse)
|
||||
@router.get("/meta/project", summary="获取项目元数据", description="获取当前项目的元数据和配置信息", response_model=ProjectMetaResponse)
|
||||
async def get_project_metadata(
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
@@ -33,7 +33,7 @@ async def get_project_metadata(
|
||||
"""
|
||||
获取项目元数据
|
||||
|
||||
返回当前项目的完整元数据,包括项目基本信息和项目权限
|
||||
返回当前项目的完整元数据
|
||||
"""
|
||||
project = await metadata_repo.get_project_by_id(ctx.project_id)
|
||||
if not project:
|
||||
@@ -52,7 +52,7 @@ async def get_project_metadata(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/projects", summary="列出用户项目", description="获取当前用户有权限的所有项目列表", response_model=list[ProjectSummaryResponse])
|
||||
@router.get("/meta/projects", summary="列出用户项目", description="获取当前用户有权限的所有项目列表", response_model=list[ProjectSummaryResponse])
|
||||
async def list_user_projects(
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
@@ -88,7 +88,7 @@ async def list_user_projects(
|
||||
]
|
||||
|
||||
|
||||
@router.get("/projects/current/database-health", summary="检查数据库健康状态", description="检查项目数据库连接的健康状况")
|
||||
@router.get("/meta/db/health", summary="检查数据库健康状态", description="检查项目数据库连接的健康状况")
|
||||
async def project_db_health(
|
||||
pg_session: AsyncSession = Depends(get_project_pg_session),
|
||||
ts_conn: AsyncConnection = Depends(get_project_timescale_connection),
|
||||
|
||||
@@ -11,6 +11,7 @@ from app.services.tjnetwork import (
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/getjson/", summary="获取JSON示例", description="获取JSON格式响应示例")
|
||||
async def fastapi_get_json():
|
||||
"""
|
||||
获取JSON示例
|
||||
@@ -28,6 +29,7 @@ async def fastapi_get_json():
|
||||
|
||||
|
||||
@router.get("/sensor-placement-schemes", summary="获取所有传感器位置", description="获取网络中所有传感器的放置位置信息")
|
||||
@router.get("/getallsensorplacements/", summary="获取所有传感器位置(旧路径)", description="获取网络中所有传感器的放置位置信息", deprecated=True)
|
||||
async def fastapi_get_all_sensor_placements(network: str = Query(..., description="管网名称(或数据库名称)")) -> list[dict[Any, Any]]:
|
||||
"""
|
||||
获取所有传感器位置
|
||||
@@ -37,7 +39,7 @@ async def fastapi_get_all_sensor_placements(network: str = Query(..., descriptio
|
||||
return get_all_sensor_placements(network)
|
||||
|
||||
|
||||
@router.get("/burst-locations", summary="获取所有爆管定位结果", description="获取网络中所有爆管定位的分析结果")
|
||||
@router.get("/getallburstlocateresults/", summary="获取所有爆管定位结果", description="获取网络中所有爆管定位的分析结果")
|
||||
async def fastapi_get_all_burst_locate_results(network: str = Query(..., description="管网名称(或数据库名称)")) -> list[dict[Any, Any]]:
|
||||
"""
|
||||
获取所有爆管定位结果
|
||||
@@ -52,6 +54,7 @@ class Item(BaseModel):
|
||||
str_info: str
|
||||
|
||||
|
||||
@router.post("/test_dict/", summary="测试字典处理", description="测试处理字典类型数据")
|
||||
async def fastapi_test_dict(data: Item) -> dict[str, str]:
|
||||
"""
|
||||
测试字典处理
|
||||
|
||||
@@ -1,188 +0,0 @@
|
||||
from pathlib import Path
|
||||
from tempfile import NamedTemporaryFile
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from fastapi import (
|
||||
APIRouter,
|
||||
Depends,
|
||||
File,
|
||||
HTTPException,
|
||||
Path as ApiPath,
|
||||
Request,
|
||||
UploadFile,
|
||||
status,
|
||||
)
|
||||
|
||||
from app.auth.metadata_dependencies import (
|
||||
get_current_metadata_admin,
|
||||
get_metadata_repository,
|
||||
)
|
||||
from app.core.audit import AuditAction, log_audit_event
|
||||
from app.infra.db.metadb.repositories.metadata_repository import MetadataRepository
|
||||
from app.services.network_import import network_update
|
||||
from app.services.tjnetwork import run_inp
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
MAX_INP_FILE_BYTES = 50 * 1024 * 1024
|
||||
INP_SECTIONS = ("[TITLE]", "[JUNCTIONS]", "[RESERVOIRS]", "[TANKS]", "[PIPES]")
|
||||
|
||||
|
||||
async def _get_active_project(project_id: UUID, metadata_repo: MetadataRepository):
|
||||
project = await metadata_repo.get_project_by_id(project_id)
|
||||
if project is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Project not found",
|
||||
)
|
||||
if project.status != "active":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Project is not active",
|
||||
)
|
||||
return project
|
||||
|
||||
|
||||
def _validate_inp_bytes(content: bytes, filename: str) -> str:
|
||||
if Path(filename).suffix.lower() != ".inp":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Only .inp model files are accepted",
|
||||
)
|
||||
if not content:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="INP file is empty",
|
||||
)
|
||||
if len(content) > MAX_INP_FILE_BYTES:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_413_REQUEST_ENTITY_TOO_LARGE,
|
||||
detail="INP file exceeds the 50 MiB limit",
|
||||
)
|
||||
for encoding in ("utf-8-sig", "gb18030"):
|
||||
try:
|
||||
text = content.decode(encoding)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
else:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="INP file encoding is not supported",
|
||||
)
|
||||
upper_text = text.upper()
|
||||
if not any(section in upper_text for section in INP_SECTIONS):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Invalid INP file structure",
|
||||
)
|
||||
return text
|
||||
|
||||
|
||||
async def _read_upload(file: UploadFile) -> tuple[bytes, str]:
|
||||
filename = Path(file.filename or "").name
|
||||
content = await file.read(MAX_INP_FILE_BYTES + 1)
|
||||
_validate_inp_bytes(content, filename)
|
||||
return content, filename
|
||||
|
||||
|
||||
async def _audit_model_change(
|
||||
*,
|
||||
request: Request,
|
||||
current_user,
|
||||
metadata_repo: MetadataRepository,
|
||||
project_id: UUID,
|
||||
action: str,
|
||||
) -> None:
|
||||
await log_audit_event(
|
||||
action=AuditAction.UPDATE,
|
||||
user_id=current_user.id,
|
||||
project_id=project_id,
|
||||
resource_type="hydraulic_model",
|
||||
resource_id=action,
|
||||
request_data={"operation": action},
|
||||
ip_address=request.client.host if request.client else None,
|
||||
request_method=request.method,
|
||||
request_path=request.url.path,
|
||||
response_status=status.HTTP_200_OK,
|
||||
session=metadata_repo.session,
|
||||
)
|
||||
|
||||
|
||||
async def _run_uploaded_inp(content: bytes) -> str:
|
||||
target_dir = Path("inp")
|
||||
target_dir.mkdir(parents=True, exist_ok=True)
|
||||
model_name = f"admin_model_{uuid4().hex}"
|
||||
target_path = target_dir / f"{model_name}.inp"
|
||||
target_path.write_bytes(content)
|
||||
return run_inp(model_name)
|
||||
|
||||
|
||||
async def _update_from_inp(content: bytes) -> None:
|
||||
temp_path: Path | None = None
|
||||
try:
|
||||
with NamedTemporaryFile(suffix=".inp", delete=False) as temp_file:
|
||||
temp_file.write(content)
|
||||
temp_path = Path(temp_file.name)
|
||||
network_update(str(temp_path))
|
||||
finally:
|
||||
if temp_path is not None:
|
||||
temp_path.unlink(missing_ok=True)
|
||||
|
||||
|
||||
async def _apply_model_update(content: bytes) -> None:
|
||||
try:
|
||||
await _update_from_inp(content)
|
||||
except Exception as exc:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
detail=f"数据库操作失败: {exc}",
|
||||
) from exc
|
||||
|
||||
|
||||
@router.post(
|
||||
"/admin/projects/{project_id}/model-imports",
|
||||
summary="导入桌面端水力模型",
|
||||
)
|
||||
async def import_project_model(
|
||||
request: Request,
|
||||
project_id: UUID = ApiPath(...),
|
||||
file: UploadFile = File(..., description="桌面端导出的 INP 模型文件"),
|
||||
current_user=Depends(get_current_metadata_admin),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> dict:
|
||||
project = await _get_active_project(project_id, metadata_repo)
|
||||
content, filename = await _read_upload(file)
|
||||
result = await _run_uploaded_inp(content)
|
||||
await _audit_model_change(
|
||||
request=request,
|
||||
current_user=current_user,
|
||||
metadata_repo=metadata_repo,
|
||||
project_id=project.id,
|
||||
action="import",
|
||||
)
|
||||
return {"project_id": str(project.id), "filename": filename, "result": result}
|
||||
|
||||
|
||||
@router.patch(
|
||||
"/admin/projects/{project_id}/model-imports",
|
||||
summary="更新桌面端水力模型",
|
||||
)
|
||||
async def update_project_model(
|
||||
request: Request,
|
||||
project_id: UUID = ApiPath(...),
|
||||
file: UploadFile = File(..., description="桌面端导出的 INP 模型文件"),
|
||||
current_user=Depends(get_current_metadata_admin),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> dict:
|
||||
project = await _get_active_project(project_id, metadata_repo)
|
||||
content, filename = await _read_upload(file)
|
||||
await _apply_model_update(content)
|
||||
await _audit_model_change(
|
||||
request=request,
|
||||
current_user=current_user,
|
||||
metadata_repo=metadata_repo,
|
||||
project_id=project.id,
|
||||
action="update",
|
||||
)
|
||||
return {"project_id": str(project.id), "filename": filename, "updated": True}
|
||||
@@ -18,7 +18,7 @@ router = APIRouter()
|
||||
############################################################
|
||||
|
||||
@router.get(
|
||||
"/network-schemas/demand",
|
||||
"/getdemandschema",
|
||||
summary="获取需水量属性架构",
|
||||
description="获取指定水网中需水量(Demand)的属性架构定义"
|
||||
)
|
||||
@@ -32,7 +32,7 @@ async def fastapi_get_demand_schema(network: str = Query(..., description="管
|
||||
|
||||
|
||||
@router.get(
|
||||
"/demands/properties",
|
||||
"/getdemandproperties/",
|
||||
summary="获取需水量属性",
|
||||
description="获取指定水网中节点的需水量属性信息"
|
||||
)
|
||||
@@ -49,8 +49,8 @@ async def fastapi_get_demand_properties(
|
||||
|
||||
|
||||
# example: set_demand(p, ChangeSet({'junction': 'j1', 'demands': [{'demand': 10.0, 'pattern': None, 'category': 'x'}, {'demand': 20.0, 'pattern': None, 'category': None}]}))
|
||||
@router.patch(
|
||||
"/demands/properties",
|
||||
@router.post(
|
||||
"/setdemandproperties/",
|
||||
response_model=None,
|
||||
summary="设置需水量属性",
|
||||
description="设置指定水网中节点的需水量属性信息"
|
||||
@@ -72,8 +72,8 @@ async def fastapi_set_demand_properties(
|
||||
############################################################
|
||||
# water distribution 36.[Water Distribution]
|
||||
############################################################
|
||||
@router.post(
|
||||
"/demands/to-nodes",
|
||||
@router.get(
|
||||
"/calculatedemandtonodes/",
|
||||
summary="计算需水量到节点分配",
|
||||
description="将总需水量按指定方式分配到多个节点"
|
||||
)
|
||||
@@ -97,8 +97,8 @@ async def fastapi_calculate_demand_to_nodes(
|
||||
nodes = props["nodes"]
|
||||
return calculate_demand_to_nodes(network, demand, nodes)
|
||||
|
||||
@router.post(
|
||||
"/demands/to-region",
|
||||
@router.get(
|
||||
"/calculatedemandtoregion/",
|
||||
summary="计算需水量到区域分配",
|
||||
description="将总需水量按区域特征分配到该区域内的节点"
|
||||
)
|
||||
@@ -122,8 +122,8 @@ async def fastapi_calculate_demand_to_region(
|
||||
region = props["region"]
|
||||
return calculate_demand_to_region(network, demand, region)
|
||||
|
||||
@router.post(
|
||||
"/demands/to-network",
|
||||
@router.get(
|
||||
"/calculatedemandtonetwork/",
|
||||
summary="计算需水量到整网分配",
|
||||
description="将需水量均匀分配到整个水网的所有需水节点"
|
||||
)
|
||||
|
||||
@@ -45,7 +45,7 @@ router = APIRouter()
|
||||
############################################################
|
||||
|
||||
@router.get(
|
||||
"/nodes/existence",
|
||||
"/isnode/",
|
||||
summary="检查节点有效性",
|
||||
description="检查指定ID是否为水网中的有效节点"
|
||||
)
|
||||
@@ -57,7 +57,7 @@ async def fastapi_is_node(
|
||||
return is_node(network, node)
|
||||
|
||||
@router.get(
|
||||
"/junctions/existence",
|
||||
"/isjunction/",
|
||||
summary="检查是否为接点",
|
||||
description="检查指定ID是否为水网中的接点(需求点)"
|
||||
)
|
||||
@@ -69,7 +69,7 @@ async def fastapi_is_junction(
|
||||
return is_junction(network, node)
|
||||
|
||||
@router.get(
|
||||
"/reservoirs/existence",
|
||||
"/isreservoir/",
|
||||
summary="检查是否为水源",
|
||||
description="检查指定ID是否为水网中的水源(水库/河流)"
|
||||
)
|
||||
@@ -81,7 +81,7 @@ async def fastapi_is_reservoir(
|
||||
return is_reservoir(network, node)
|
||||
|
||||
@router.get(
|
||||
"/tanks/existence",
|
||||
"/istank/",
|
||||
summary="检查是否为蓄水池",
|
||||
description="检查指定ID是否为水网中的蓄水池"
|
||||
)
|
||||
@@ -93,7 +93,7 @@ async def fastapi_is_tank(
|
||||
return is_tank(network, node)
|
||||
|
||||
@router.get(
|
||||
"/links/existence",
|
||||
"/islink/",
|
||||
summary="检查管线有效性",
|
||||
description="检查指定ID是否为水网中的有效管线"
|
||||
)
|
||||
@@ -105,7 +105,7 @@ async def fastapi_is_link(
|
||||
return is_link(network, link)
|
||||
|
||||
@router.get(
|
||||
"/pipes/existence",
|
||||
"/ispipe/",
|
||||
summary="检查是否为管道",
|
||||
description="检查指定ID是否为水网中的管道"
|
||||
)
|
||||
@@ -117,7 +117,7 @@ async def fastapi_is_pipe(
|
||||
return is_pipe(network, link)
|
||||
|
||||
@router.get(
|
||||
"/pumps/existence",
|
||||
"/ispump/",
|
||||
summary="检查是否为泵",
|
||||
description="检查指定ID是否为水网中的泵"
|
||||
)
|
||||
@@ -129,7 +129,7 @@ async def fastapi_is_pump(
|
||||
return is_pump(network, link)
|
||||
|
||||
@router.get(
|
||||
"/valves/existence",
|
||||
"/isvalve/",
|
||||
summary="检查是否为阀门",
|
||||
description="检查指定ID是否为水网中的阀门"
|
||||
)
|
||||
@@ -141,7 +141,7 @@ async def fastapi_is_valve(
|
||||
return is_valve(network, link)
|
||||
|
||||
@router.get(
|
||||
"/node-types",
|
||||
"/getnodetype/",
|
||||
summary="获取节点类型",
|
||||
description="获取指定节点的类型(接点/水源/蓄水池)"
|
||||
)
|
||||
@@ -153,7 +153,7 @@ async def fastapi_get_node_type(
|
||||
return get_node_type(network, node)
|
||||
|
||||
@router.get(
|
||||
"/link-types",
|
||||
"/getlinktype/",
|
||||
summary="获取管线类型",
|
||||
description="获取指定管线的类型(管道/泵/阀门)"
|
||||
)
|
||||
@@ -165,7 +165,7 @@ async def fastapi_get_link_type(
|
||||
return get_link_type(network, link)
|
||||
|
||||
@router.get(
|
||||
"/element-types",
|
||||
"/getelementtype/",
|
||||
summary="获取元素类型",
|
||||
description="获取指定元素的类型(节点或管线)"
|
||||
)
|
||||
@@ -177,7 +177,7 @@ async def fastapi_get_element_type(
|
||||
return get_element_type(network, element)
|
||||
|
||||
@router.get(
|
||||
"/element-type-values",
|
||||
"/getelementtypevalue/",
|
||||
summary="获取元素类型值",
|
||||
description="获取指定元素的类型数值标识"
|
||||
)
|
||||
@@ -189,7 +189,7 @@ async def fastapi_get_element_type_value(
|
||||
return get_element_type_value(network, element)
|
||||
|
||||
@router.get(
|
||||
"/nodes",
|
||||
"/getnodes/",
|
||||
summary="获取所有节点",
|
||||
description="获取指定水网中的所有节点ID列表"
|
||||
)
|
||||
@@ -198,7 +198,7 @@ async def fastapi_get_nodes(network: str = Query(..., description="管网名称
|
||||
return get_nodes(network)
|
||||
|
||||
@router.get(
|
||||
"/links",
|
||||
"/getlinks/",
|
||||
summary="获取所有管线",
|
||||
description="获取指定水网中的所有管线ID列表"
|
||||
)
|
||||
@@ -207,7 +207,7 @@ async def fastapi_get_links(network: str = Query(..., description="管网名称
|
||||
return get_links(network)
|
||||
|
||||
@router.get(
|
||||
"/node-links",
|
||||
"/getnodelinks/",
|
||||
summary="获取节点的关联管线",
|
||||
description="获取指定节点连接的所有管线ID列表"
|
||||
)
|
||||
@@ -223,7 +223,7 @@ def get_node_links_endpoint(
|
||||
############################################################
|
||||
|
||||
@router.get(
|
||||
"/node-properties",
|
||||
"/getnodeproperties/",
|
||||
summary="获取节点属性",
|
||||
description="获取指定节点的所有属性信息"
|
||||
)
|
||||
@@ -235,7 +235,7 @@ async def fast_get_node_properties(
|
||||
return get_node_properties(network, node)
|
||||
|
||||
@router.get(
|
||||
"/link-properties",
|
||||
"/getlinkproperties/",
|
||||
summary="获取管线属性",
|
||||
description="获取指定管线的所有属性信息"
|
||||
)
|
||||
@@ -247,7 +247,7 @@ async def fast_get_link_properties(
|
||||
return get_link_properties(network, link)
|
||||
|
||||
@router.get(
|
||||
"/scada-properties",
|
||||
"/getscadaproperties/",
|
||||
summary="获取SCADA点属性",
|
||||
description="获取指定SCADA点的属性信息"
|
||||
)
|
||||
@@ -259,7 +259,7 @@ async def fast_get_scada_properties(
|
||||
return get_scada_info(network, scada)
|
||||
|
||||
@router.get(
|
||||
"/all-scada-properties",
|
||||
"/getallscadaproperties/",
|
||||
summary="获取所有SCADA点属性",
|
||||
description="获取指定水网中所有SCADA点的属性信息"
|
||||
)
|
||||
@@ -270,7 +270,7 @@ async def fast_get_all_scada_properties(
|
||||
return get_all_scada_info(network)
|
||||
|
||||
@router.get(
|
||||
"/element-properties-with-types",
|
||||
"/getelementpropertieswithtype/",
|
||||
summary="获取指定类型元素属性",
|
||||
description="获取指定类型的元素属性信息"
|
||||
)
|
||||
@@ -283,7 +283,7 @@ async def fast_get_element_properties_with_type(
|
||||
return get_element_properties_with_type(network, elementtype, element)
|
||||
|
||||
@router.get(
|
||||
"/element-properties",
|
||||
"/getelementproperties/",
|
||||
summary="获取元素属性",
|
||||
description="获取指定元素的属性信息"
|
||||
)
|
||||
@@ -299,7 +299,7 @@ async def fast_get_element_properties(
|
||||
############################################################
|
||||
|
||||
@router.get(
|
||||
"/title-schemas",
|
||||
"/gettitleschema/",
|
||||
summary="获取标题属性架构",
|
||||
description="获取指定水网的标题(标题)属性架构定义"
|
||||
)
|
||||
@@ -310,7 +310,7 @@ async def fast_get_title_schema(
|
||||
return get_title_schema(network)
|
||||
|
||||
@router.get(
|
||||
"/titles",
|
||||
"/gettitle/",
|
||||
summary="获取水网标题属性",
|
||||
description="获取指定水网的标题(Title)信息"
|
||||
)
|
||||
@@ -318,8 +318,8 @@ async def fast_get_title(network: str = Query(..., description="管网名称(
|
||||
"""获取水网的标题属性。"""
|
||||
return get_title(network)
|
||||
|
||||
@router.patch(
|
||||
"/titles",
|
||||
@router.get(
|
||||
"/settitle/",
|
||||
response_model=None,
|
||||
summary="设置水网标题属性",
|
||||
description="设置指定水网的标题(Title)信息"
|
||||
@@ -337,7 +337,7 @@ async def fastapi_set_title(
|
||||
############################################################
|
||||
|
||||
@router.get(
|
||||
"/status-schemas",
|
||||
"/getstatusschema",
|
||||
summary="获取状态属性架构",
|
||||
description="获取指定水网的状态(Status)属性架构定义"
|
||||
)
|
||||
@@ -348,7 +348,7 @@ async def fastapi_get_status_schema(
|
||||
return get_status_schema(network)
|
||||
|
||||
@router.get(
|
||||
"/status",
|
||||
"/getstatus/",
|
||||
summary="获取管线状态",
|
||||
description="获取指定管线的状态信息"
|
||||
)
|
||||
@@ -359,8 +359,8 @@ async def fastapi_get_status(
|
||||
"""获取管线的状态属性。"""
|
||||
return get_status(network, link)
|
||||
|
||||
@router.patch(
|
||||
"/status-properties",
|
||||
@router.post(
|
||||
"/setstatus/",
|
||||
response_model=None,
|
||||
summary="设置管线状态",
|
||||
description="设置指定管线的状态信息"
|
||||
@@ -379,8 +379,8 @@ async def fastapi_set_status_properties(
|
||||
# General Deletion
|
||||
############################################################
|
||||
|
||||
@router.delete(
|
||||
"/nodes",
|
||||
@router.post(
|
||||
"/deletenode/",
|
||||
response_model=None,
|
||||
summary="删除节点",
|
||||
description="删除指定的节点(接点/水源/蓄水池)"
|
||||
@@ -399,8 +399,8 @@ async def fastapi_delete_node(
|
||||
return delete_tank(network, ChangeSet(ps))
|
||||
return ChangeSet() # Should probably raise error or return empty
|
||||
|
||||
@router.delete(
|
||||
"/links",
|
||||
@router.post(
|
||||
"/deletelink/",
|
||||
response_model=None,
|
||||
summary="删除管线",
|
||||
description="删除指定的管线(管道/泵/阀门)"
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
from typing import Any
|
||||
|
||||
from fastapi import APIRouter, Query
|
||||
|
||||
from fastapi import APIRouter, Request, Depends, Query, Path, Body
|
||||
from typing import Any, List, Dict, Union
|
||||
from app.services.tjnetwork import (
|
||||
Any,
|
||||
get_all_scada_info,
|
||||
get_major_node_coords,
|
||||
get_major_pipe_nodes,
|
||||
get_network_in_extent,
|
||||
get_network_link_nodes,
|
||||
get_network_node_coords,
|
||||
get_node_coord,
|
||||
)
|
||||
from app.auth.metadata_dependencies import get_current_metadata_user
|
||||
from app.infra.cache.redis_client import redis_client, encode_datetime, decode_datetime
|
||||
import msgpack
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -31,7 +35,7 @@ router = APIRouter()
|
||||
# return set_coord(network, ChangeSet(props))
|
||||
|
||||
@router.get(
|
||||
"/node-coords",
|
||||
"/getnodecoord/",
|
||||
summary="获取节点坐标",
|
||||
description="获取指定节点的地理坐标(X, Y)"
|
||||
)
|
||||
@@ -44,7 +48,7 @@ async def fastapi_get_node_coord(
|
||||
|
||||
# Additional geometry queries found in main.py logic (implicit or explicit)
|
||||
@router.get(
|
||||
"/network-in-extents",
|
||||
"/getnetworkinextent/",
|
||||
summary="获取范围内的网络元素",
|
||||
description="获取指定地理范围内的网络节点和管线"
|
||||
)
|
||||
@@ -59,7 +63,34 @@ async def fastapi_get_network_in_extent(
|
||||
return get_network_in_extent(network, x1, y1, x2, y2)
|
||||
|
||||
@router.get(
|
||||
"/majornode-coords",
|
||||
"/getnetworkgeometries/",
|
||||
dependencies=[Depends(get_current_metadata_user)],
|
||||
summary="获取完整网络几何信息",
|
||||
description="获取整个水网的所有节点、管线和SCADA点的几何信息(需要身份验证)"
|
||||
)
|
||||
async def fastapi_get_network_geometries(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> dict[str, Any] | None:
|
||||
"""获取完整的网络几何信息,包括所有节点、管线和SCADA点。结果从缓存返回。"""
|
||||
cache_key = f"getnetworkgeometries_{network}"
|
||||
data = redis_client.get(cache_key)
|
||||
if data:
|
||||
loaded_dict = msgpack.unpackb(data, object_hook=decode_datetime)
|
||||
return loaded_dict
|
||||
|
||||
coords = get_network_node_coords(network)
|
||||
nodes = []
|
||||
for node_id, coord in coords.items():
|
||||
nodes.append(f"{node_id}:{coord['type']}:{coord['x']}:{coord['y']}")
|
||||
links = get_network_link_nodes(network)
|
||||
scadas = get_all_scada_info(network)
|
||||
|
||||
results = {"nodes": nodes, "links": links, "scadas": scadas}
|
||||
redis_client.set(cache_key, msgpack.packb(results, default=encode_datetime))
|
||||
return results
|
||||
|
||||
@router.get(
|
||||
"/getmajornodecoords/",
|
||||
summary="获取主要节点坐标",
|
||||
description="获取直径大于等于指定值的节点坐标"
|
||||
)
|
||||
@@ -71,7 +102,7 @@ async def fastapi_get_majornode_coords(
|
||||
return get_major_node_coords(network, diameter)
|
||||
|
||||
@router.get(
|
||||
"/major-pipe-nodes",
|
||||
"/getmajorpipenodes/",
|
||||
summary="获取主要管道节点",
|
||||
description="获取直径大于等于指定值的管道的节点ID"
|
||||
)
|
||||
@@ -83,7 +114,7 @@ async def fastapi_get_major_pipe_nodes(
|
||||
return get_major_pipe_nodes(network, diameter)
|
||||
|
||||
@router.get(
|
||||
"/network-link-nodes",
|
||||
"/getnetworklinknodes/",
|
||||
summary="获取网络管线节点",
|
||||
description="获取指定水网所有管线的起点和终点节点"
|
||||
)
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/junction", summary="获取节点架构", description="获取指定项目的节点属性架构和数据类型定义。")
|
||||
@router.get("/getjunctionschema", summary="获取节点架构", description="获取指定项目的节点属性架构和数据类型定义。")
|
||||
async def fast_get_junction_schema(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
@@ -27,7 +27,7 @@ async def fast_get_junction_schema(
|
||||
"""
|
||||
return get_junction_schema(network)
|
||||
|
||||
@router.post("/junctions", response_model=None, summary="添加节点", description="在供水网络中添加新的节点,指定节点ID和空间坐标。")
|
||||
@router.post("/addjunction/", response_model=None, summary="添加节点", description="在供水网络中添加新的节点,指定节点ID和空间坐标。")
|
||||
async def fastapi_add_junction(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID"),
|
||||
@@ -51,7 +51,7 @@ async def fastapi_add_junction(
|
||||
ps = {"id": junction, "x": x, "y": y, "elevation": z}
|
||||
return add_junction(network, ChangeSet(ps))
|
||||
|
||||
@router.delete("/junctions", response_model=None, summary="删除节点", description="从供水网络中删除指定的节点。")
|
||||
@router.post("/deletejunction/", response_model=None, summary="删除节点", description="从供水网络中删除指定的节点。")
|
||||
async def fastapi_delete_junction(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID")
|
||||
@@ -69,7 +69,7 @@ async def fastapi_delete_junction(
|
||||
ps = {"id": junction}
|
||||
return delete_junction(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/junctions/elevation", summary="获取节点标高", description="获取指定节点的标高(海拔高度)。")
|
||||
@router.get("/getjunctionelevation/", summary="获取节点标高", description="获取指定节点的标高(海拔高度)。")
|
||||
async def fastapi_get_junction_elevation(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID")
|
||||
@@ -87,7 +87,7 @@ async def fastapi_get_junction_elevation(
|
||||
ps = get_junction(network, junction)
|
||||
return ps["elevation"]
|
||||
|
||||
@router.get("/junctions/x", summary="获取节点 X 坐标", description="获取指定节点的 X 坐标值。")
|
||||
@router.get("/getjunctionx/", summary="获取节点 X 坐标", description="获取指定节点的 X 坐标值。")
|
||||
async def fastapi_get_junction_x(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID")
|
||||
@@ -105,7 +105,7 @@ async def fastapi_get_junction_x(
|
||||
ps = get_junction(network, junction)
|
||||
return ps["x"]
|
||||
|
||||
@router.get("/junctions/y", summary="获取节点 Y 坐标", description="获取指定节点的 Y 坐标值。")
|
||||
@router.get("/getjunctiony/", summary="获取节点 Y 坐标", description="获取指定节点的 Y 坐标值。")
|
||||
async def fastapi_get_junction_y(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID")
|
||||
@@ -123,7 +123,7 @@ async def fastapi_get_junction_y(
|
||||
ps = get_junction(network, junction)
|
||||
return ps["y"]
|
||||
|
||||
@router.get("/junctions/coord", summary="获取节点坐标", description="获取指定节点的 X 和 Y 坐标。")
|
||||
@router.get("/getjunctioncoord/", summary="获取节点坐标", description="获取指定节点的 X 和 Y 坐标。")
|
||||
async def fastapi_get_junction_coord(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID")
|
||||
@@ -142,7 +142,7 @@ async def fastapi_get_junction_coord(
|
||||
coord = {"x": ps["x"], "y": ps["y"]}
|
||||
return coord
|
||||
|
||||
@router.get("/junctions/demand", summary="获取节点需水量", description="获取指定节点的需水量。")
|
||||
@router.get("/getjunctiondemand/", summary="获取节点需水量", description="获取指定节点的需水量。")
|
||||
async def fastapi_get_junction_demand(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID")
|
||||
@@ -160,7 +160,7 @@ async def fastapi_get_junction_demand(
|
||||
ps = get_junction(network, junction)
|
||||
return ps["demand"]
|
||||
|
||||
@router.get("/junctions/pattern", summary="获取节点需水模式", description="获取指定节点的需水模式标识。")
|
||||
@router.get("/getjunctionpattern/", summary="获取节点需水模式", description="获取指定节点的需水模式标识。")
|
||||
async def fastapi_get_junction_pattern(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID")
|
||||
@@ -178,7 +178,7 @@ async def fastapi_get_junction_pattern(
|
||||
ps = get_junction(network, junction)
|
||||
return ps["pattern"]
|
||||
|
||||
@router.patch("/junctions/elevation", response_model=None, summary="设置节点标高", description="设置指定节点的标高值。")
|
||||
@router.post("/setjunctionelevation/", response_model=None, summary="设置节点标高", description="设置指定节点的标高值。")
|
||||
async def fastapi_set_junction_elevation(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID"),
|
||||
@@ -198,7 +198,7 @@ async def fastapi_set_junction_elevation(
|
||||
ps = {"id": junction, "elevation": elevation}
|
||||
return set_junction(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/junctions/x", response_model=None, summary="设置节点 X 坐标", description="设置指定节点的 X 坐标值。")
|
||||
@router.post("/setjunctionx/", response_model=None, summary="设置节点 X 坐标", description="设置指定节点的 X 坐标值。")
|
||||
async def fastapi_set_junction_x(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID"),
|
||||
@@ -218,7 +218,7 @@ async def fastapi_set_junction_x(
|
||||
ps = {"id": junction, "x": x}
|
||||
return set_junction(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/junctions/y", response_model=None, summary="设置节点 Y 坐标", description="设置指定节点的 Y 坐标值。")
|
||||
@router.post("/setjunctiony/", response_model=None, summary="设置节点 Y 坐标", description="设置指定节点的 Y 坐标值。")
|
||||
async def fastapi_set_junction_y(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID"),
|
||||
@@ -238,7 +238,7 @@ async def fastapi_set_junction_y(
|
||||
ps = {"id": junction, "y": y}
|
||||
return set_junction(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/junctions/coord", response_model=None, summary="设置节点坐标", description="设置指定节点的 X 和 Y 坐标。")
|
||||
@router.post("/setjunctioncoord/", response_model=None, summary="设置节点坐标", description="设置指定节点的 X 和 Y 坐标。")
|
||||
async def fastapi_set_junction_coord(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID"),
|
||||
@@ -260,7 +260,7 @@ async def fastapi_set_junction_coord(
|
||||
ps = {"id": junction, "x": x, "y": y}
|
||||
return set_junction(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/junctions/demand", response_model=None, summary="设置节点需水量", description="设置指定节点的需水量。")
|
||||
@router.post("/setjunctiondemand/", response_model=None, summary="设置节点需水量", description="设置指定节点的需水量。")
|
||||
async def fastapi_set_junction_demand(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID"),
|
||||
@@ -280,7 +280,7 @@ async def fastapi_set_junction_demand(
|
||||
ps = {"id": junction, "demand": demand}
|
||||
return set_junction(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/junctions/pattern", response_model=None, summary="设置节点需水模式", description="设置指定节点的需水模式标识。")
|
||||
@router.post("/setjunctionpattern/", response_model=None, summary="设置节点需水模式", description="设置指定节点的需水模式标识。")
|
||||
async def fastapi_set_junction_pattern(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID"),
|
||||
@@ -300,7 +300,7 @@ async def fastapi_set_junction_pattern(
|
||||
ps = {"id": junction, "pattern": pattern}
|
||||
return set_junction(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/junctions/properties", summary="获取节点属性", description="获取指定节点的所有属性信息。")
|
||||
@router.get("/getjunctionproperties/", summary="获取节点属性", description="获取指定节点的所有属性信息。")
|
||||
async def fastapi_get_junction_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID")
|
||||
@@ -317,7 +317,7 @@ async def fastapi_get_junction_properties(
|
||||
"""
|
||||
return get_junction(network, junction)
|
||||
|
||||
@router.get("/junctions", summary="获取所有节点属性", description="获取指定项目中所有节点的属性信息。")
|
||||
@router.get("/getalljunctionproperties/", summary="获取所有节点属性", description="获取指定项目中所有节点的属性信息。")
|
||||
async def fastapi_get_all_junction_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -337,7 +337,7 @@ async def fastapi_get_all_junction_properties(
|
||||
results = get_all_junctions(network)
|
||||
return results
|
||||
|
||||
@router.patch("/junctions/properties", response_model=None, summary="批量设置节点属性", description="批量设置指定节点的多个属性。")
|
||||
@router.post("/setjunctionproperties/", response_model=None, summary="批量设置节点属性", description="批量设置指定节点的多个属性。")
|
||||
async def fastapi_set_junction_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
junction: str = Query(..., description="节点 ID"),
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/pipe", summary="获取管道模式", description="获取管道对象的模式定义,包含所有可用字段及其类型")
|
||||
@router.get("/getpipeschema", summary="获取管道模式", description="获取管道对象的模式定义,包含所有可用字段及其类型")
|
||||
async def fastapi_get_pipe_schema(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
@@ -29,7 +29,7 @@ async def fastapi_get_pipe_schema(
|
||||
"""
|
||||
return get_pipe_schema(network)
|
||||
|
||||
@router.post("/pipes", response_model=None, summary="添加管道", description="向网络中添加新的管道,需要提供管道的基本参数如长度、管径、粗糙度等")
|
||||
@router.post("/addpipe/", response_model=None, summary="添加管道", description="向网络中添加新的管道,需要提供管道的基本参数如长度、管径、粗糙度等")
|
||||
async def fastapi_add_pipe(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道标识符"),
|
||||
@@ -70,7 +70,7 @@ async def fastapi_add_pipe(
|
||||
}
|
||||
return add_pipe(network, ChangeSet(ps))
|
||||
|
||||
@router.delete("/pipes", response_model=None, summary="删除管道", description="从网络中删除指定的管道")
|
||||
@router.post("/deletepipe/", response_model=None, summary="删除管道", description="从网络中删除指定的管道")
|
||||
async def fastapi_delete_pipe(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="要删除的管道ID")
|
||||
@@ -88,7 +88,7 @@ async def fastapi_delete_pipe(
|
||||
ps = {"id": pipe}
|
||||
return delete_pipe(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/pipes/node1", summary="获取管道起始节点", description="获取指定管道的起始节点ID")
|
||||
@router.get("/getpipenode1/", summary="获取管道起始节点", description="获取指定管道的起始节点ID")
|
||||
async def fastapi_get_pipe_node1(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID")
|
||||
@@ -106,7 +106,7 @@ async def fastapi_get_pipe_node1(
|
||||
ps = get_pipe(network, pipe)
|
||||
return ps["node1"]
|
||||
|
||||
@router.get("/pipes/node2", summary="获取管道终止节点", description="获取指定管道的终止节点ID")
|
||||
@router.get("/getpipenode2/", summary="获取管道终止节点", description="获取指定管道的终止节点ID")
|
||||
async def fastapi_get_pipe_node2(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID")
|
||||
@@ -124,7 +124,7 @@ async def fastapi_get_pipe_node2(
|
||||
ps = get_pipe(network, pipe)
|
||||
return ps["node2"]
|
||||
|
||||
@router.get("/pipes/length", summary="获取管道长度", description="获取指定管道的长度")
|
||||
@router.get("/getpipelength/", summary="获取管道长度", description="获取指定管道的长度")
|
||||
async def fastapi_get_pipe_length(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID")
|
||||
@@ -142,7 +142,7 @@ async def fastapi_get_pipe_length(
|
||||
ps = get_pipe(network, pipe)
|
||||
return ps["length"]
|
||||
|
||||
@router.get("/pipes/diameter", summary="获取管道管径", description="获取指定管道的管径")
|
||||
@router.get("/getpipediameter/", summary="获取管道管径", description="获取指定管道的管径")
|
||||
async def fastapi_get_pipe_diameter(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID")
|
||||
@@ -160,7 +160,7 @@ async def fastapi_get_pipe_diameter(
|
||||
ps = get_pipe(network, pipe)
|
||||
return ps["diameter"]
|
||||
|
||||
@router.get("/pipes/roughness", summary="获取管道粗糙度", description="获取指定管道的粗糙度")
|
||||
@router.get("/getpiperoughness/", summary="获取管道粗糙度", description="获取指定管道的粗糙度")
|
||||
async def fastapi_get_pipe_roughness(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID")
|
||||
@@ -178,7 +178,7 @@ async def fastapi_get_pipe_roughness(
|
||||
ps = get_pipe(network, pipe)
|
||||
return ps["roughness"]
|
||||
|
||||
@router.get("/pipes/minor-loss", summary="获取管道局部阻力系数", description="获取指定管道的局部阻力系数")
|
||||
@router.get("/getpipeminorloss/", summary="获取管道局部阻力系数", description="获取指定管道的局部阻力系数")
|
||||
async def fastapi_get_pipe_minor_loss(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID")
|
||||
@@ -196,7 +196,7 @@ async def fastapi_get_pipe_minor_loss(
|
||||
ps = get_pipe(network, pipe)
|
||||
return ps["minor_loss"]
|
||||
|
||||
@router.get("/pipes/status", summary="获取管道状态", description="获取指定管道的状态(开启或关闭)")
|
||||
@router.get("/getpipestatus/", summary="获取管道状态", description="获取指定管道的状态(开启或关闭)")
|
||||
async def fastapi_get_pipe_status(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID")
|
||||
@@ -214,7 +214,7 @@ async def fastapi_get_pipe_status(
|
||||
ps = get_pipe(network, pipe)
|
||||
return ps["status"]
|
||||
|
||||
@router.patch("/pipes/node1", response_model=None, summary="设置管道起始节点", description="设置指定管道的起始节点")
|
||||
@router.post("/setpipenode1/", response_model=None, summary="设置管道起始节点", description="设置指定管道的起始节点")
|
||||
async def fastapi_set_pipe_node1(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID"),
|
||||
@@ -234,7 +234,7 @@ async def fastapi_set_pipe_node1(
|
||||
ps = {"id": pipe, "node1": node1}
|
||||
return set_pipe(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/pipes/node2", response_model=None, summary="设置管道终止节点", description="设置指定管道的终止节点")
|
||||
@router.post("/setpipenode2/", response_model=None, summary="设置管道终止节点", description="设置指定管道的终止节点")
|
||||
async def fastapi_set_pipe_node2(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID"),
|
||||
@@ -254,7 +254,7 @@ async def fastapi_set_pipe_node2(
|
||||
ps = {"id": pipe, "node2": node2}
|
||||
return set_pipe(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/pipes/length", response_model=None, summary="设置管道长度", description="设置指定管道的长度")
|
||||
@router.post("/setpipelength/", response_model=None, summary="设置管道长度", description="设置指定管道的长度")
|
||||
async def fastapi_set_pipe_length(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID"),
|
||||
@@ -274,7 +274,7 @@ async def fastapi_set_pipe_length(
|
||||
ps = {"id": pipe, "length": length}
|
||||
return set_pipe(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/pipes/diameter", response_model=None, summary="设置管道管径", description="设置指定管道的管径")
|
||||
@router.post("/setpipediameter/", response_model=None, summary="设置管道管径", description="设置指定管道的管径")
|
||||
async def fastapi_set_pipe_diameter(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID"),
|
||||
@@ -294,7 +294,7 @@ async def fastapi_set_pipe_diameter(
|
||||
ps = {"id": pipe, "diameter": diameter}
|
||||
return set_pipe(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/pipes/roughness", response_model=None, summary="设置管道粗糙度", description="设置指定管道的粗糙度")
|
||||
@router.post("/setpiperoughness/", response_model=None, summary="设置管道粗糙度", description="设置指定管道的粗糙度")
|
||||
async def fastapi_set_pipe_roughness(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID"),
|
||||
@@ -314,7 +314,7 @@ async def fastapi_set_pipe_roughness(
|
||||
ps = {"id": pipe, "roughness": roughness}
|
||||
return set_pipe(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/pipes/minor-loss", response_model=None, summary="设置管道局部阻力系数", description="设置指定管道的局部阻力系数")
|
||||
@router.post("/setpipeminorloss/", response_model=None, summary="设置管道局部阻力系数", description="设置指定管道的局部阻力系数")
|
||||
async def fastapi_set_pipe_minor_loss(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID"),
|
||||
@@ -334,7 +334,7 @@ async def fastapi_set_pipe_minor_loss(
|
||||
ps = {"id": pipe, "minor_loss": minor_loss}
|
||||
return set_pipe(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/pipes/status", response_model=None, summary="设置管道状态", description="设置指定管道的状态(开启或关闭)")
|
||||
@router.post("/setpipestatus/", response_model=None, summary="设置管道状态", description="设置指定管道的状态(开启或关闭)")
|
||||
async def fastapi_set_pipe_status(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID"),
|
||||
@@ -354,7 +354,7 @@ async def fastapi_set_pipe_status(
|
||||
ps = {"id": pipe, "status": status}
|
||||
return set_pipe(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/pipes/properties", summary="获取管道属性", description="获取指定管道的所有属性信息")
|
||||
@router.get("/getpipeproperties/", summary="获取管道属性", description="获取指定管道的所有属性信息")
|
||||
async def fastapi_get_pipe_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID")
|
||||
@@ -371,7 +371,7 @@ async def fastapi_get_pipe_properties(
|
||||
"""
|
||||
return get_pipe(network, pipe)
|
||||
|
||||
@router.get("/pipes", summary="获取所有管道属性", description="获取网络中所有管道的属性信息列表")
|
||||
@router.get("/getallpipeproperties/", summary="获取所有管道属性", description="获取网络中所有管道的属性信息列表")
|
||||
async def fastapi_get_all_pipe_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -389,7 +389,7 @@ async def fastapi_get_all_pipe_properties(
|
||||
results = get_all_pipes(network)
|
||||
return results
|
||||
|
||||
@router.patch("/pipes/properties", response_model=None, summary="设置管道属性", description="批量设置指定管道的多个属性")
|
||||
@router.post("/setpipeproperties/", response_model=None, summary="设置管道属性", description="批量设置指定管道的多个属性")
|
||||
async def fastapi_set_pipe_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pipe: str = Query(..., description="管道ID"),
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/pump", summary="获取水泵模式", description="获取水泵对象的模式定义,包含所有可用字段及其类型")
|
||||
@router.get("/getpumpschema", summary="获取水泵模式", description="获取水泵对象的模式定义,包含所有可用字段及其类型")
|
||||
async def fastapi_get_pump_schema(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
@@ -28,7 +28,7 @@ async def fastapi_get_pump_schema(
|
||||
"""
|
||||
return get_pump_schema(network)
|
||||
|
||||
@router.post("/pumps", response_model=None, summary="添加水泵", description="向网络中添加新的水泵,需要提供水泵的基本参数如功率等")
|
||||
@router.post("/addpump/", response_model=None, summary="添加水泵", description="向网络中添加新的水泵,需要提供水泵的基本参数如功率等")
|
||||
async def fastapi_add_pump(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="水泵标识符"),
|
||||
@@ -52,7 +52,7 @@ async def fastapi_add_pump(
|
||||
ps = {"id": pump, "node1": node1, "node2": node2, "power": power}
|
||||
return add_pump(network, ChangeSet(ps))
|
||||
|
||||
@router.delete("/pumps", response_model=None, summary="删除水泵", description="从网络中删除指定的水泵")
|
||||
@router.post("/deletepump/", response_model=None, summary="删除水泵", description="从网络中删除指定的水泵")
|
||||
async def fastapi_delete_pump(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="要删除的水泵ID")
|
||||
@@ -70,7 +70,7 @@ async def fastapi_delete_pump(
|
||||
ps = {"id": pump}
|
||||
return delete_pump(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/pumps/node1", summary="获取水泵起始节点", description="获取指定水泵的起始节点ID")
|
||||
@router.get("/getpumpnode1/", summary="获取水泵起始节点", description="获取指定水泵的起始节点ID")
|
||||
async def fastapi_get_pump_node1(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="水泵ID")
|
||||
@@ -88,7 +88,7 @@ async def fastapi_get_pump_node1(
|
||||
ps = get_pump(network, pump)
|
||||
return ps["node1"]
|
||||
|
||||
@router.get("/pumps/node2", summary="获取水泵终止节点", description="获取指定水泵的终止节点ID")
|
||||
@router.get("/getpumpnode2/", summary="获取水泵终止节点", description="获取指定水泵的终止节点ID")
|
||||
async def fastapi_get_pump_node2(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="水泵ID")
|
||||
@@ -106,7 +106,7 @@ async def fastapi_get_pump_node2(
|
||||
ps = get_pump(network, pump)
|
||||
return ps["node2"]
|
||||
|
||||
@router.patch("/pumps/node1", response_model=None, summary="设置水泵起始节点", description="设置指定水泵的起始节点")
|
||||
@router.post("/setpumpnode1/", response_model=None, summary="设置水泵起始节点", description="设置指定水泵的起始节点")
|
||||
async def fastapi_set_pump_node1(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="水泵ID"),
|
||||
@@ -126,7 +126,7 @@ async def fastapi_set_pump_node1(
|
||||
ps = {"id": pump, "node1": node1}
|
||||
return set_pump(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/pumps/node2", response_model=None, summary="设置水泵终止节点", description="设置指定水泵的终止节点")
|
||||
@router.post("/setpumpnode2/", response_model=None, summary="设置水泵终止节点", description="设置指定水泵的终止节点")
|
||||
async def fastapi_set_pump_node2(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="水泵ID"),
|
||||
@@ -146,7 +146,7 @@ async def fastapi_set_pump_node2(
|
||||
ps = {"id": pump, "node2": node2}
|
||||
return set_pump(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/pumps/properties", summary="获取水泵属性", description="获取指定水泵的所有属性信息")
|
||||
@router.get("/getpumpproperties/", summary="获取水泵属性", description="获取指定水泵的所有属性信息")
|
||||
async def fastapi_get_pump_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="水泵ID")
|
||||
@@ -163,7 +163,7 @@ async def fastapi_get_pump_properties(
|
||||
"""
|
||||
return get_pump(network, pump)
|
||||
|
||||
@router.get("/pumps", summary="获取所有水泵属性", description="获取网络中所有水泵的属性信息列表")
|
||||
@router.get("/getallpumpproperties/", summary="获取所有水泵属性", description="获取网络中所有水泵的属性信息列表")
|
||||
async def fastapi_get_all_pump_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -181,7 +181,7 @@ async def fastapi_get_all_pump_properties(
|
||||
results = get_all_pumps(network)
|
||||
return results
|
||||
|
||||
@router.patch("/pumps/properties", response_model=None, summary="设置水泵属性", description="批量设置指定水泵的多个属性")
|
||||
@router.post("/setpumpproperties/", response_model=None, summary="设置水泵属性", description="批量设置指定水泵的多个属性")
|
||||
async def fastapi_set_pump_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
pump: str = Query(..., description="水泵ID"),
|
||||
|
||||
@@ -45,7 +45,7 @@ router = APIRouter()
|
||||
############################################################
|
||||
|
||||
@router.get(
|
||||
"/network-schemas/region",
|
||||
"/getregionschema/",
|
||||
summary="获取区域属性架构",
|
||||
description="获取指定水网的区域属性架构定义"
|
||||
)
|
||||
@@ -56,7 +56,7 @@ async def fastapi_get_region_schema(
|
||||
return get_region_schema(network)
|
||||
|
||||
@router.get(
|
||||
"/regions/detail",
|
||||
"/getregion/",
|
||||
summary="获取区域信息",
|
||||
description="获取指定ID的区域详细信息"
|
||||
)
|
||||
@@ -67,8 +67,8 @@ async def fastapi_get_region(
|
||||
"""获取区域的详细信息。"""
|
||||
return get_region(network, id)
|
||||
|
||||
@router.patch(
|
||||
"/regions",
|
||||
@router.post(
|
||||
"/setregion/",
|
||||
response_model=None,
|
||||
summary="设置区域属性",
|
||||
description="修改指定区域的属性信息"
|
||||
@@ -82,7 +82,7 @@ async def fastapi_set_region(
|
||||
return set_region(network, ChangeSet(props))
|
||||
|
||||
@router.post(
|
||||
"/regions",
|
||||
"/addregion/",
|
||||
response_model=None,
|
||||
summary="添加新区域",
|
||||
description="向水网添加一个新的区域"
|
||||
@@ -95,8 +95,8 @@ async def fastapi_add_region(
|
||||
props = await req.json()
|
||||
return add_region(network, ChangeSet(props))
|
||||
|
||||
@router.delete(
|
||||
"/regions",
|
||||
@router.post(
|
||||
"/deleteregion/",
|
||||
response_model=None,
|
||||
summary="删除区域",
|
||||
description="删除指定的区域"
|
||||
@@ -114,8 +114,8 @@ async def fastapi_delete_region(
|
||||
# district_metering_area 33
|
||||
############################################################
|
||||
|
||||
@router.post(
|
||||
"/district-metering-areas/for-region",
|
||||
@router.get(
|
||||
"/calculatedistrictmeteringareaforregion/",
|
||||
summary="计算区域内DMA分区",
|
||||
description="为指定区域计算区域计量(DMA)分区方案"
|
||||
)
|
||||
@@ -141,8 +141,8 @@ async def fastapi_calculate_district_metering_area_for_region(
|
||||
network, region, part_count, part_type
|
||||
)
|
||||
|
||||
@router.post(
|
||||
"/district-metering-areas/for-network",
|
||||
@router.get(
|
||||
"/calculatedistrictmeteringareafornetwork/",
|
||||
summary="计算整网DMA分区",
|
||||
description="为整个水网计算区域计量(DMA)分区方案"
|
||||
)
|
||||
@@ -165,7 +165,7 @@ async def fastapi_calculate_district_metering_area_for_network(
|
||||
return calculate_district_metering_area_for_network(network, part_count, part_type)
|
||||
|
||||
@router.get(
|
||||
"/network-schemas/district-metering-area",
|
||||
"/getdistrictmeteringareaschema/",
|
||||
summary="获取DMA属性架构",
|
||||
description="获取指定水网的区域计量(DMA)属性架构定义"
|
||||
)
|
||||
@@ -176,7 +176,7 @@ async def fastapi_get_district_metering_area_schema(
|
||||
return get_district_metering_area_schema(network)
|
||||
|
||||
@router.get(
|
||||
"/district-metering-areas/detail",
|
||||
"/getdistrictmeteringarea/",
|
||||
summary="获取DMA信息",
|
||||
description="获取指定ID的区域计量(DMA)详细信息"
|
||||
)
|
||||
@@ -187,8 +187,8 @@ async def fastapi_get_district_metering_area(
|
||||
"""获取DMA的详细信息。"""
|
||||
return get_district_metering_area(network, id)
|
||||
|
||||
@router.patch(
|
||||
"/district-metering-areas",
|
||||
@router.post(
|
||||
"/setdistrictmeteringarea/",
|
||||
response_model=None,
|
||||
summary="设置DMA属性",
|
||||
description="修改指定DMA的属性信息"
|
||||
@@ -202,7 +202,7 @@ async def fastapi_set_district_metering_area(
|
||||
return set_district_metering_area(network, ChangeSet(props))
|
||||
|
||||
@router.post(
|
||||
"/district-metering-areas",
|
||||
"/adddistrictmeteringarea/",
|
||||
response_model=None,
|
||||
summary="添加新DMA",
|
||||
description="向水网添加一个新的区域计量(DMA)"
|
||||
@@ -222,8 +222,8 @@ async def fastapi_add_district_metering_area(
|
||||
props["boundary"] = newBoundary
|
||||
return add_district_metering_area(network, ChangeSet(props))
|
||||
|
||||
@router.delete(
|
||||
"/district-metering-areas",
|
||||
@router.post(
|
||||
"/deletedistrictmeteringarea/",
|
||||
response_model=None,
|
||||
summary="删除DMA",
|
||||
description="删除指定的区域计量(DMA)"
|
||||
@@ -237,7 +237,7 @@ async def fastapi_delete_district_metering_area(
|
||||
return delete_district_metering_area(network, ChangeSet(props))
|
||||
|
||||
@router.get(
|
||||
"/district-metering-areas/ids",
|
||||
"/getalldistrictmeteringareaids/",
|
||||
summary="获取所有DMA ID",
|
||||
description="获取指定水网中所有DMA的ID列表"
|
||||
)
|
||||
@@ -248,7 +248,7 @@ async def fastapi_get_all_district_metering_area_ids(
|
||||
return get_all_district_metering_area_ids(network)
|
||||
|
||||
@router.get(
|
||||
"/district-metering-areas",
|
||||
"/getalldistrictmeteringareas/",
|
||||
summary="获取所有DMA",
|
||||
description="获取指定水网中所有DMA的详细信息"
|
||||
)
|
||||
@@ -259,7 +259,7 @@ async def getalldistrictmeteringareas(
|
||||
return get_all_district_metering_areas(network)
|
||||
|
||||
@router.post(
|
||||
"/district-metering-area-generation-runs",
|
||||
"/generatedistrictmeteringarea/",
|
||||
response_model=None,
|
||||
summary="生成DMA分区",
|
||||
description="根据参数自动生成水网的DMA分区方案"
|
||||
@@ -276,7 +276,7 @@ async def fastapi_generate_district_metering_area(
|
||||
)
|
||||
|
||||
@router.post(
|
||||
"/sub-district-metering-areas",
|
||||
"/generatesubdistrictmeteringarea/",
|
||||
response_model=None,
|
||||
summary="生成DMA子分区",
|
||||
description="为指定DMA生成子DMA分区"
|
||||
@@ -298,8 +298,8 @@ async def fastapi_generate_sub_district_metering_area(
|
||||
# service_area 34
|
||||
############################################################
|
||||
|
||||
@router.post(
|
||||
"/service-area-calculations",
|
||||
@router.get(
|
||||
"/calculateservicearea/",
|
||||
summary="计算服务区",
|
||||
description="计算指定水网的服务区分区,返回全部时间步结果"
|
||||
)
|
||||
@@ -310,7 +310,7 @@ async def fastapi_calculate_service_area(
|
||||
return calculate_service_area(network)
|
||||
|
||||
@router.get(
|
||||
"/network-schemas/service-area",
|
||||
"/getserviceareaschema/",
|
||||
summary="获取服务区属性架构",
|
||||
description="获取指定水网的服务区属性架构定义"
|
||||
)
|
||||
@@ -321,7 +321,7 @@ async def fastapi_get_service_area_schema(
|
||||
return get_service_area_schema(network)
|
||||
|
||||
@router.get(
|
||||
"/service-areas/detail",
|
||||
"/getservicearea/",
|
||||
summary="获取服务区信息",
|
||||
description="获取指定ID的服务区详细信息"
|
||||
)
|
||||
@@ -332,8 +332,8 @@ async def fastapi_get_service_area(
|
||||
"""获取服务区的详细信息。"""
|
||||
return get_service_area(network, id)
|
||||
|
||||
@router.patch(
|
||||
"/service-areas",
|
||||
@router.post(
|
||||
"/setservicearea/",
|
||||
response_model=None,
|
||||
summary="设置服务区属性",
|
||||
description="修改指定服务区的属性信息"
|
||||
@@ -347,7 +347,7 @@ async def fastapi_set_service_area(
|
||||
return set_service_area(network, ChangeSet(props))
|
||||
|
||||
@router.post(
|
||||
"/service-areas",
|
||||
"/addservicearea/",
|
||||
response_model=None,
|
||||
summary="添加新服务区",
|
||||
description="向水网添加一个新的服务区"
|
||||
@@ -360,8 +360,8 @@ async def fastapi_add_service_area(
|
||||
props = await req.json()
|
||||
return add_service_area(network, ChangeSet(props))
|
||||
|
||||
@router.delete(
|
||||
"/service-areas",
|
||||
@router.post(
|
||||
"/deleteservicearea/",
|
||||
response_model=None,
|
||||
summary="删除服务区",
|
||||
description="删除指定的服务区"
|
||||
@@ -375,7 +375,7 @@ async def fastapi_delete_service_area(
|
||||
return delete_service_area(network, ChangeSet(props))
|
||||
|
||||
@router.get(
|
||||
"/service-areas",
|
||||
"/getallserviceareas/",
|
||||
summary="获取所有服务区",
|
||||
description="获取指定水网中的所有服务区信息"
|
||||
)
|
||||
@@ -386,7 +386,7 @@ async def fastapi_get_all_service_areas(
|
||||
return get_all_service_areas(network)
|
||||
|
||||
@router.post(
|
||||
"/service-area-generation-runs",
|
||||
"/generateservicearea/",
|
||||
response_model=None,
|
||||
summary="生成服务区分区",
|
||||
description="根据参数自动生成水网的服务区分区"
|
||||
@@ -403,8 +403,8 @@ async def fastapi_generate_service_area(
|
||||
# virtual_district 35
|
||||
############################################################
|
||||
|
||||
@router.post(
|
||||
"/virtual-district-calculations",
|
||||
@router.get(
|
||||
"/calculatevirtualdistrict/",
|
||||
summary="计算虚拟分区",
|
||||
description="根据指定的压力监测节点作为中心节点计算虚拟分区方案"
|
||||
)
|
||||
@@ -416,7 +416,7 @@ async def fastapi_calculate_virtual_district(
|
||||
return calculate_virtual_district(network, centers)
|
||||
|
||||
@router.get(
|
||||
"/network-schemas/virtual-district",
|
||||
"/getvirtualdistrictschema/",
|
||||
summary="获取虚拟分区属性架构",
|
||||
description="获取指定水网的虚拟分区属性架构定义"
|
||||
)
|
||||
@@ -427,7 +427,7 @@ async def fastapi_get_virtual_district_schema(
|
||||
return get_virtual_district_schema(network)
|
||||
|
||||
@router.get(
|
||||
"/virtual-districts/detail",
|
||||
"/getvirtualdistrict/",
|
||||
summary="获取虚拟分区信息",
|
||||
description="获取指定ID的虚拟分区详细信息"
|
||||
)
|
||||
@@ -438,8 +438,8 @@ async def fastapi_get_virtual_district(
|
||||
"""获取虚拟分区的详细信息。"""
|
||||
return get_virtual_district(network, id)
|
||||
|
||||
@router.patch(
|
||||
"/virtual-districts",
|
||||
@router.post(
|
||||
"/setvirtualdistrict/",
|
||||
response_model=None,
|
||||
summary="设置虚拟分区属性",
|
||||
description="修改指定虚拟分区的属性信息"
|
||||
@@ -453,7 +453,7 @@ async def fastapi_set_virtual_district(
|
||||
return set_virtual_district(network, ChangeSet(props))
|
||||
|
||||
@router.post(
|
||||
"/virtual-districts",
|
||||
"/addvirtualdistrict/",
|
||||
response_model=None,
|
||||
summary="添加新虚拟分区",
|
||||
description="向水网添加一个新的虚拟分区"
|
||||
@@ -466,8 +466,8 @@ async def fastapi_add_virtual_district(
|
||||
props = await req.json()
|
||||
return add_virtual_district(network, ChangeSet(props))
|
||||
|
||||
@router.delete(
|
||||
"/virtual-districts",
|
||||
@router.post(
|
||||
"/deletevirtualdistrict/",
|
||||
response_model=None,
|
||||
summary="删除虚拟分区",
|
||||
description="删除指定的虚拟分区"
|
||||
@@ -481,7 +481,7 @@ async def fastapi_delete_virtual_district(
|
||||
return delete_virtual_district(network, ChangeSet(props))
|
||||
|
||||
@router.get(
|
||||
"/virtual-districts",
|
||||
"/getallvirtualdistrict/",
|
||||
summary="获取所有虚拟分区",
|
||||
description="获取指定水网中的所有虚拟分区信息"
|
||||
)
|
||||
@@ -492,7 +492,7 @@ async def fastapi_get_all_virtual_district(
|
||||
return get_all_virtual_districts(network)
|
||||
|
||||
@router.post(
|
||||
"/virtual-district-generation-runs",
|
||||
"/generatevirtualdistrict/",
|
||||
response_model=None,
|
||||
summary="生成虚拟分区",
|
||||
description="根据参数自动生成虚拟分区方案"
|
||||
@@ -506,8 +506,8 @@ async def fastapi_generate_virtual_district(
|
||||
props = await req.json()
|
||||
return generate_virtual_district(network, props["centers"], inflate_delta)
|
||||
|
||||
@router.post(
|
||||
"/district-metering-areas/for-nodes",
|
||||
@router.get(
|
||||
"/calculatedistrictmeteringareafornodes/",
|
||||
summary="计算节点DMA分区",
|
||||
description="为指定节点集计算区域计量(DMA)分区方案"
|
||||
)
|
||||
|
||||
@@ -14,7 +14,7 @@ from app.services.tjnetwork import (
|
||||
router = APIRouter()
|
||||
|
||||
@router.get(
|
||||
"/network-schemas/reservoir",
|
||||
"/getreservoirschema",
|
||||
summary="获取水库模式",
|
||||
description="获取指定供水网络中所有水库的模式/属性字段定义"
|
||||
)
|
||||
@@ -35,7 +35,7 @@ async def fast_get_reservoir_schema(
|
||||
return get_reservoir_schema(network)
|
||||
|
||||
@router.post(
|
||||
"/reservoirs",
|
||||
"/addreservoir/",
|
||||
response_model=None,
|
||||
summary="添加水库",
|
||||
description="在指定供水网络中添加新的水库/水源节点"
|
||||
@@ -65,8 +65,8 @@ async def fastapi_add_reservoir(
|
||||
ps = {"id": reservoir, "x": x, "y": y, "head": head}
|
||||
return add_reservoir(network, ChangeSet(ps))
|
||||
|
||||
@router.delete(
|
||||
"/reservoirs",
|
||||
@router.post(
|
||||
"/deletereservoir/",
|
||||
response_model=None,
|
||||
summary="删除水库",
|
||||
description="从指定供水网络中删除指定的水库/水源节点"
|
||||
@@ -91,7 +91,7 @@ async def fastapi_delete_reservoir(
|
||||
return delete_reservoir(network, ChangeSet(ps))
|
||||
|
||||
@router.get(
|
||||
"/reservoirs/head",
|
||||
"/getreservoirhead/",
|
||||
summary="获取水库水头",
|
||||
description="获取指定水库的供水水头/总水头值"
|
||||
)
|
||||
@@ -115,7 +115,7 @@ async def fastapi_get_reservoir_head(
|
||||
return ps["head"]
|
||||
|
||||
@router.get(
|
||||
"/reservoirs/pattern",
|
||||
"/getreservoirpattern/",
|
||||
summary="获取水库模式",
|
||||
description="获取指定水库的运行模式/供水模式"
|
||||
)
|
||||
@@ -139,7 +139,7 @@ async def fastapi_get_reservoir_pattern(
|
||||
return ps["pattern"]
|
||||
|
||||
@router.get(
|
||||
"/reservoirs/x",
|
||||
"/getreservoirx/",
|
||||
summary="获取水库X坐标",
|
||||
description="获取指定水库的X坐标位置"
|
||||
)
|
||||
@@ -163,7 +163,7 @@ async def fastapi_get_reservoir_x(
|
||||
return ps["x"]
|
||||
|
||||
@router.get(
|
||||
"/reservoirs/y",
|
||||
"/getreservoiry/",
|
||||
summary="获取水库Y坐标",
|
||||
description="获取指定水库的Y坐标位置"
|
||||
)
|
||||
@@ -187,7 +187,7 @@ async def fastapi_get_reservoir_y(
|
||||
return ps["y"]
|
||||
|
||||
@router.get(
|
||||
"/reservoirs/coord",
|
||||
"/getreservoircoord/",
|
||||
summary="获取水库坐标",
|
||||
description="获取指定水库的平面坐标(X和Y坐标)"
|
||||
)
|
||||
@@ -211,8 +211,8 @@ async def fastapi_get_reservoir_coord(
|
||||
coord = {"id": reservoir, "x": ps["x"], "y": ps["y"]}
|
||||
return coord
|
||||
|
||||
@router.patch(
|
||||
"/reservoirs/head",
|
||||
@router.post(
|
||||
"/setreservoirhead/",
|
||||
response_model=None,
|
||||
summary="设置水库水头",
|
||||
description="更新指定水库的供水水头/总水头值"
|
||||
@@ -238,8 +238,8 @@ async def fastapi_set_reservoir_head(
|
||||
ps = {"id": reservoir, "head": head}
|
||||
return set_reservoir(network, ChangeSet(ps))
|
||||
|
||||
@router.patch(
|
||||
"/reservoirs/pattern",
|
||||
@router.post(
|
||||
"/setreservoirpattern/",
|
||||
response_model=None,
|
||||
summary="设置水库模式",
|
||||
description="更新指定水库的运行模式/供水模式"
|
||||
@@ -265,8 +265,8 @@ async def fastapi_set_reservoir_pattern(
|
||||
ps = {"id": reservoir, "pattern": pattern}
|
||||
return set_reservoir(network, ChangeSet(ps))
|
||||
|
||||
@router.patch(
|
||||
"/reservoirs/x",
|
||||
@router.post(
|
||||
"/setreservoirx/",
|
||||
response_model=None,
|
||||
summary="设置水库X坐标",
|
||||
description="更新指定水库的X坐标位置"
|
||||
@@ -292,8 +292,8 @@ async def fastapi_set_reservoir_x(
|
||||
ps = {"id": reservoir, "x": x}
|
||||
return set_reservoir(network, ChangeSet(ps))
|
||||
|
||||
@router.patch(
|
||||
"/reservoirs/y",
|
||||
@router.post(
|
||||
"/setreservoiry/",
|
||||
response_model=None,
|
||||
summary="设置水库Y坐标",
|
||||
description="更新指定水库的Y坐标位置"
|
||||
@@ -319,8 +319,8 @@ async def fastapi_set_reservoir_y(
|
||||
ps = {"id": reservoir, "y": y}
|
||||
return set_reservoir(network, ChangeSet(ps))
|
||||
|
||||
@router.patch(
|
||||
"/reservoirs/coord",
|
||||
@router.post(
|
||||
"/setreservoircoord/",
|
||||
response_model=None,
|
||||
summary="设置水库坐标",
|
||||
description="更新指定水库的平面坐标(X和Y坐标)"
|
||||
@@ -349,7 +349,7 @@ async def fastapi_set_reservoir_coord(
|
||||
return set_reservoir(network, ChangeSet(ps))
|
||||
|
||||
@router.get(
|
||||
"/reservoirs/properties",
|
||||
"/getreservoirproperties/",
|
||||
summary="获取水库属性",
|
||||
description="获取指定水库的所有属性"
|
||||
)
|
||||
@@ -372,7 +372,7 @@ async def fastapi_get_reservoir_properties(
|
||||
return get_reservoir(network, reservoir)
|
||||
|
||||
@router.get(
|
||||
"/reservoirs",
|
||||
"/getallreservoirproperties/",
|
||||
summary="获取所有水库属性",
|
||||
description="获取指定供水网络中所有水库的属性"
|
||||
)
|
||||
@@ -393,8 +393,8 @@ async def fastapi_get_all_reservoir_properties(
|
||||
results = get_all_reservoirs(network)
|
||||
return results
|
||||
|
||||
@router.patch(
|
||||
"/reservoirs/properties",
|
||||
@router.post(
|
||||
"/setreservoirproperties/",
|
||||
response_model=None,
|
||||
summary="设置水库属性",
|
||||
description="批量更新指定水库的多个属性"
|
||||
|
||||
@@ -16,7 +16,7 @@ router = APIRouter()
|
||||
############################################################
|
||||
|
||||
@router.get(
|
||||
"/network-schemas/tag",
|
||||
"/gettagschema/",
|
||||
summary="获取标签属性架构",
|
||||
description="获取指定水网的标签(Tag)属性架构定义"
|
||||
)
|
||||
@@ -27,7 +27,7 @@ async def fastapi_get_tag_schema(
|
||||
return get_tag_schema(network)
|
||||
|
||||
@router.get(
|
||||
"/tags/detail",
|
||||
"/gettag/",
|
||||
summary="获取标签信息",
|
||||
description="获取指定类型和ID的标签信息"
|
||||
)
|
||||
@@ -40,7 +40,7 @@ async def fastapi_get_tag(
|
||||
return get_tag(network, t_type, id)
|
||||
|
||||
@router.get(
|
||||
"/tags",
|
||||
"/gettags/",
|
||||
summary="获取所有标签",
|
||||
description="获取指定水网中的所有标签信息"
|
||||
)
|
||||
@@ -51,8 +51,8 @@ async def fastapi_get_tags(
|
||||
tags = get_tags(network)
|
||||
return tags
|
||||
|
||||
@router.patch(
|
||||
"/tags",
|
||||
@router.post(
|
||||
"/settag/",
|
||||
response_model=None,
|
||||
summary="设置标签",
|
||||
description="为指定元素设置或修改标签信息"
|
||||
|
||||
@@ -13,7 +13,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/tank", summary="获取水箱模式", description="获取指定网络的水箱数据结构模式定义")
|
||||
@router.get("/gettankschema", summary="获取水箱模式", description="获取指定网络的水箱数据结构模式定义")
|
||||
async def fast_get_tank_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[str, Any]]:
|
||||
"""
|
||||
获取水箱的数据结构模式。
|
||||
@@ -26,7 +26,7 @@ async def fast_get_tank_schema(network: str = Query(..., description="管网名
|
||||
"""
|
||||
return get_tank_schema(network)
|
||||
|
||||
@router.post("/tanks", summary="新增水箱", description="向指定网络中新增一个水箱", response_model=None)
|
||||
@router.post("/addtank/", summary="新增水箱", description="向指定网络中新增一个水箱", response_model=None)
|
||||
async def fastapi_add_tank(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -70,7 +70,7 @@ async def fastapi_add_tank(
|
||||
}
|
||||
return add_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.delete("/tanks", summary="删除水箱", description="删除指定网络中的水箱", response_model=None)
|
||||
@router.post("/deletetank/", summary="删除水箱", description="删除指定网络中的水箱", response_model=None)
|
||||
async def fastapi_delete_tank(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -88,7 +88,7 @@ async def fastapi_delete_tank(
|
||||
ps = {"id": tank}
|
||||
return delete_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/tanks/elevation", summary="获取水箱标高", description="获取指定水箱的标高值")
|
||||
@router.get("/gettankelevation/", summary="获取水箱标高", description="获取指定水箱的标高值")
|
||||
async def fastapi_get_tank_elevation(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -106,7 +106,7 @@ async def fastapi_get_tank_elevation(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["elevation"]
|
||||
|
||||
@router.get("/tanks/init-level", summary="获取水箱初始水位", description="获取指定水箱的初始水位值")
|
||||
@router.get("/gettankinitlevel/", summary="获取水箱初始水位", description="获取指定水箱的初始水位值")
|
||||
async def fastapi_get_tank_init_level(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -124,7 +124,7 @@ async def fastapi_get_tank_init_level(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["init_level"]
|
||||
|
||||
@router.get("/tanks/min-level", summary="获取水箱最小水位", description="获取指定水箱的最小水位值")
|
||||
@router.get("/gettankminlevel/", summary="获取水箱最小水位", description="获取指定水箱的最小水位值")
|
||||
async def fastapi_get_tank_min_level(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -142,7 +142,7 @@ async def fastapi_get_tank_min_level(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["min_level"]
|
||||
|
||||
@router.get("/tanks/max-level", summary="获取水箱最大水位", description="获取指定水箱的最大水位值")
|
||||
@router.get("/gettankmaxlevel/", summary="获取水箱最大水位", description="获取指定水箱的最大水位值")
|
||||
async def fastapi_get_tank_max_level(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -160,7 +160,7 @@ async def fastapi_get_tank_max_level(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["max_level"]
|
||||
|
||||
@router.get("/tanks/diameter", summary="获取水箱直径", description="获取指定水箱的直径值")
|
||||
@router.get("/gettankdiameter/", summary="获取水箱直径", description="获取指定水箱的直径值")
|
||||
async def fastapi_get_tank_diameter(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -178,7 +178,7 @@ async def fastapi_get_tank_diameter(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["diameter"]
|
||||
|
||||
@router.get("/tanks/min-vol", summary="获取水箱最小体积", description="获取指定水箱的最小体积值")
|
||||
@router.get("/gettankminvol/", summary="获取水箱最小体积", description="获取指定水箱的最小体积值")
|
||||
async def fastapi_get_tank_min_vol(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -196,7 +196,7 @@ async def fastapi_get_tank_min_vol(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["min_vol"]
|
||||
|
||||
@router.get("/tanks/vol-curve", summary="获取水箱容积曲线", description="获取指定水箱的容积曲线标识")
|
||||
@router.get("/gettankvolcurve/", summary="获取水箱容积曲线", description="获取指定水箱的容积曲线标识")
|
||||
async def fastapi_get_tank_vol_curve(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -214,7 +214,7 @@ async def fastapi_get_tank_vol_curve(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["vol_curve"]
|
||||
|
||||
@router.get("/tanks/overflow", summary="获取水箱溢流口", description="获取指定水箱的溢流口配置")
|
||||
@router.get("/gettankoverflow/", summary="获取水箱溢流口", description="获取指定水箱的溢流口配置")
|
||||
async def fastapi_get_tank_overflow(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -232,7 +232,7 @@ async def fastapi_get_tank_overflow(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["overflow"]
|
||||
|
||||
@router.get("/tanks/x", summary="获取水箱X坐标", description="获取指定水箱的X坐标值")
|
||||
@router.get("/gettankx/", summary="获取水箱X坐标", description="获取指定水箱的X坐标值")
|
||||
async def fastapi_get_tank_x(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -250,7 +250,7 @@ async def fastapi_get_tank_x(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["x"]
|
||||
|
||||
@router.get("/tanks/y", summary="获取水箱Y坐标", description="获取指定水箱的Y坐标值")
|
||||
@router.get("/gettanky/", summary="获取水箱Y坐标", description="获取指定水箱的Y坐标值")
|
||||
async def fastapi_get_tank_y(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -268,7 +268,7 @@ async def fastapi_get_tank_y(
|
||||
ps = get_tank(network, tank)
|
||||
return ps["y"]
|
||||
|
||||
@router.get("/tanks/coord", summary="获取水箱坐标", description="获取指定水箱的X和Y坐标")
|
||||
@router.get("/gettankcoord/", summary="获取水箱坐标", description="获取指定水箱的X和Y坐标")
|
||||
async def fastapi_get_tank_coord(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -287,7 +287,7 @@ async def fastapi_get_tank_coord(
|
||||
coord = {"x": ps["x"], "y": ps["y"]}
|
||||
return coord
|
||||
|
||||
@router.patch("/tanks/elevation", summary="设置水箱标高", description="设置指定水箱的标高值", response_model=None)
|
||||
@router.post("/settankelevation/", summary="设置水箱标高", description="设置指定水箱的标高值", response_model=None)
|
||||
async def fastapi_set_tank_elevation(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -307,7 +307,7 @@ async def fastapi_set_tank_elevation(
|
||||
ps = {"id": tank, "elevation": elevation}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/init-level", summary="设置水箱初始水位", description="设置指定水箱的初始水位值", response_model=None)
|
||||
@router.post("/settankinitlevel/", summary="设置水箱初始水位", description="设置指定水箱的初始水位值", response_model=None)
|
||||
async def fastapi_set_tank_init_level(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -327,7 +327,7 @@ async def fastapi_set_tank_init_level(
|
||||
ps = {"id": tank, "init_level": init_level}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/min-level", summary="设置水箱最小水位", description="设置指定水箱的最小水位值", response_model=None)
|
||||
@router.post("/settankminlevel/", summary="设置水箱最小水位", description="设置指定水箱的最小水位值", response_model=None)
|
||||
async def fastapi_set_tank_min_level(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -347,7 +347,7 @@ async def fastapi_set_tank_min_level(
|
||||
ps = {"id": tank, "min_level": min_level}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/max-level", summary="设置水箱最大水位", description="设置指定水箱的最大水位值", response_model=None)
|
||||
@router.post("/settankmaxlevel/", summary="设置水箱最大水位", description="设置指定水箱的最大水位值", response_model=None)
|
||||
async def fastapi_set_tank_max_level(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -367,7 +367,7 @@ async def fastapi_set_tank_max_level(
|
||||
ps = {"id": tank, "max_level": max_level}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/diameter", summary="设置水箱直径", description="设置指定水箱的直径值", response_model=None)
|
||||
@router.post("/settankdiameter/", summary="设置水箱直径", description="设置指定水箱的直径值", response_model=None)
|
||||
async def fastapi_set_tank_diameter(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -387,7 +387,7 @@ async def fastapi_set_tank_diameter(
|
||||
ps = {"id": tank, "diameter": diameter}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/min-vol", summary="设置水箱最小体积", description="设置指定水箱的最小体积值", response_model=None)
|
||||
@router.post("/settankminvol/", summary="设置水箱最小体积", description="设置指定水箱的最小体积值", response_model=None)
|
||||
async def fastapi_set_tank_min_vol(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -407,7 +407,7 @@ async def fastapi_set_tank_min_vol(
|
||||
ps = {"id": tank, "min_vol": min_vol}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/vol-curve", summary="设置水箱容积曲线", description="设置指定水箱的容积曲线标识", response_model=None)
|
||||
@router.post("/settankvolcurve/", summary="设置水箱容积曲线", description="设置指定水箱的容积曲线标识", response_model=None)
|
||||
async def fastapi_set_tank_vol_curve(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -427,7 +427,7 @@ async def fastapi_set_tank_vol_curve(
|
||||
ps = {"id": tank, "vol_curve": vol_curve}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/overflow", summary="设置水箱溢流口", description="设置指定水箱的溢流口配置", response_model=None)
|
||||
@router.post("/settankoverflow/", summary="设置水箱溢流口", description="设置指定水箱的溢流口配置", response_model=None)
|
||||
async def fastapi_set_tank_overflow(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -447,7 +447,7 @@ async def fastapi_set_tank_overflow(
|
||||
ps = {"id": tank, "overflow": overflow}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/x", summary="设置水箱X坐标", description="设置指定水箱的X坐标值", response_model=None)
|
||||
@router.post("/settankx/", summary="设置水箱X坐标", description="设置指定水箱的X坐标值", response_model=None)
|
||||
async def fastapi_set_tank_x(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -467,7 +467,7 @@ async def fastapi_set_tank_x(
|
||||
ps = {"id": tank, "x": x}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/y", summary="设置水箱Y坐标", description="设置指定水箱的Y坐标值", response_model=None)
|
||||
@router.post("/settanky/", summary="设置水箱Y坐标", description="设置指定水箱的Y坐标值", response_model=None)
|
||||
async def fastapi_set_tank_y(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -487,7 +487,7 @@ async def fastapi_set_tank_y(
|
||||
ps = {"id": tank, "y": y}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.patch("/tanks/coord", summary="设置水箱坐标", description="设置指定水箱的X和Y坐标", response_model=None)
|
||||
@router.post("/settankcoord/", summary="设置水箱坐标", description="设置指定水箱的X和Y坐标", response_model=None)
|
||||
async def fastapi_set_tank_coord(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
@@ -509,7 +509,7 @@ async def fastapi_set_tank_coord(
|
||||
ps = {"id": tank, "x": x, "y": y}
|
||||
return set_tank(network, ChangeSet(ps))
|
||||
|
||||
@router.get("/tanks/properties", summary="获取水箱属性", description="获取指定水箱的所有属性")
|
||||
@router.get("/gettankproperties/", summary="获取水箱属性", description="获取指定水箱的所有属性")
|
||||
async def fastapi_get_tank_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID")
|
||||
@@ -526,7 +526,7 @@ async def fastapi_get_tank_properties(
|
||||
"""
|
||||
return get_tank(network, tank)
|
||||
|
||||
@router.get("/tanks", summary="获取所有水箱属性", description="获取指定网络中所有水箱的属性")
|
||||
@router.get("/getalltankproperties/", summary="获取所有水箱属性", description="获取指定网络中所有水箱的属性")
|
||||
async def fastapi_get_all_tank_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -544,7 +544,7 @@ async def fastapi_get_all_tank_properties(
|
||||
results = get_all_tanks(network)
|
||||
return results
|
||||
|
||||
@router.patch("/tanks/properties", summary="设置水箱属性", description="批量设置指定水箱的多个属性", response_model=None)
|
||||
@router.post("/settankproperties/", summary="设置水箱属性", description="批量设置指定水箱的多个属性", response_model=None)
|
||||
async def fastapi_set_tank_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
tank: str = Query(..., description="水箱ID"),
|
||||
|
||||
@@ -15,7 +15,7 @@ from app.services.tjnetwork import (
|
||||
router = APIRouter()
|
||||
|
||||
@router.get(
|
||||
"/network-schemas/valve",
|
||||
"/getvalveschema",
|
||||
summary="获取阀门架构",
|
||||
description="获取指定水网中所有阀门的架构和字段定义",
|
||||
)
|
||||
@@ -30,7 +30,7 @@ async def fastapi_get_valve_schema(
|
||||
return get_valve_schema(network)
|
||||
|
||||
@router.post(
|
||||
"/valves",
|
||||
"/addvalve/",
|
||||
response_model=None,
|
||||
summary="添加阀门",
|
||||
description="在指定的水网中添加新的阀门",
|
||||
@@ -62,8 +62,8 @@ async def fastapi_add_valve(
|
||||
|
||||
return add_valve(network, ChangeSet(ps))
|
||||
|
||||
@router.delete(
|
||||
"/valves",
|
||||
@router.post(
|
||||
"/deletevalve/",
|
||||
response_model=None,
|
||||
summary="删除阀门",
|
||||
description="从指定的水网中删除指定的阀门",
|
||||
@@ -81,7 +81,7 @@ async def fastapi_delete_valve(
|
||||
return delete_valve(network, ChangeSet(ps))
|
||||
|
||||
@router.get(
|
||||
"/valves/node1",
|
||||
"/getvalvenode1/",
|
||||
summary="获取阀门起点节点",
|
||||
description="获取指定阀门连接的起点节点ID",
|
||||
)
|
||||
@@ -98,7 +98,7 @@ async def fastapi_get_valve_node1(
|
||||
return ps["node1"]
|
||||
|
||||
@router.get(
|
||||
"/valves/node2",
|
||||
"/getvalvenode2/",
|
||||
summary="获取阀门终点节点",
|
||||
description="获取指定阀门连接的终点节点ID",
|
||||
)
|
||||
@@ -115,7 +115,7 @@ async def fastapi_get_valve_node2(
|
||||
return ps["node2"]
|
||||
|
||||
@router.get(
|
||||
"/valves/diameter",
|
||||
"/getvalvediameter/",
|
||||
summary="获取阀门直径",
|
||||
description="获取指定阀门的直径",
|
||||
)
|
||||
@@ -132,7 +132,7 @@ async def fastapi_get_valve_diameter(
|
||||
return ps["diameter"]
|
||||
|
||||
@router.get(
|
||||
"/valves/type",
|
||||
"/getvalvetype/",
|
||||
summary="获取阀门类型",
|
||||
description="获取指定阀门的类型",
|
||||
)
|
||||
@@ -149,7 +149,7 @@ async def fastapi_get_valve_type(
|
||||
return ps["type"]
|
||||
|
||||
@router.get(
|
||||
"/valves/setting",
|
||||
"/getvalvesetting/",
|
||||
summary="获取阀门开度",
|
||||
description="获取指定阀门的开度/设置值",
|
||||
)
|
||||
@@ -166,7 +166,7 @@ async def fastapi_get_valve_setting(
|
||||
return ps["setting"]
|
||||
|
||||
@router.get(
|
||||
"/valves/minor-loss",
|
||||
"/getvalveminorloss/",
|
||||
summary="获取阀门损失系数",
|
||||
description="获取指定阀门的损失系数",
|
||||
)
|
||||
@@ -182,8 +182,8 @@ async def fastapi_get_valve_minor_loss(
|
||||
ps = get_valve(network, valve)
|
||||
return ps["minor_loss"]
|
||||
|
||||
@router.patch(
|
||||
"/valves/node1",
|
||||
@router.post(
|
||||
"/setvalvenode1/",
|
||||
response_model=None,
|
||||
summary="设置阀门起点节点",
|
||||
description="设置指定阀门的起点节点",
|
||||
@@ -201,8 +201,8 @@ async def fastapi_set_valve_node1(
|
||||
ps = {"id": valve, "node1": node1}
|
||||
return set_valve(network, ChangeSet(ps))
|
||||
|
||||
@router.patch(
|
||||
"/valves/node2",
|
||||
@router.post(
|
||||
"/setvalvenode2/",
|
||||
response_model=None,
|
||||
summary="设置阀门终点节点",
|
||||
description="设置指定阀门的终点节点",
|
||||
@@ -220,8 +220,8 @@ async def fastapi_set_valve_node2(
|
||||
ps = {"id": valve, "node2": node2}
|
||||
return set_valve(network, ChangeSet(ps))
|
||||
|
||||
@router.patch(
|
||||
"/valves/diameter",
|
||||
@router.post(
|
||||
"/setvalvenodediameter/",
|
||||
response_model=None,
|
||||
summary="设置阀门直径",
|
||||
description="设置指定阀门的直径",
|
||||
@@ -239,8 +239,8 @@ async def fastapi_set_valve_diameter(
|
||||
ps = {"id": valve, "diameter": diameter}
|
||||
return set_valve(network, ChangeSet(ps))
|
||||
|
||||
@router.patch(
|
||||
"/valves/type",
|
||||
@router.post(
|
||||
"/setvalvetype/",
|
||||
response_model=None,
|
||||
summary="设置阀门类型",
|
||||
description="设置指定阀门的类型",
|
||||
@@ -258,8 +258,8 @@ async def fastapi_set_valve_type(
|
||||
ps = {"id": valve, "type": type}
|
||||
return set_valve(network, ChangeSet(ps))
|
||||
|
||||
@router.patch(
|
||||
"/valves/setting",
|
||||
@router.post(
|
||||
"/setvalvesetting/",
|
||||
response_model=None,
|
||||
summary="设置阀门开度",
|
||||
description="设置指定阀门的开度/设置值",
|
||||
@@ -278,7 +278,7 @@ async def fastapi_set_valve_setting(
|
||||
return set_valve(network, ChangeSet(ps))
|
||||
|
||||
@router.get(
|
||||
"/valves/properties",
|
||||
"/getvalveproperties/",
|
||||
summary="获取阀门所有属性",
|
||||
description="获取指定阀门的所有属性",
|
||||
)
|
||||
@@ -294,7 +294,7 @@ async def fastapi_get_valve_properties(
|
||||
return get_valve(network, valve)
|
||||
|
||||
@router.get(
|
||||
"/valves",
|
||||
"/getallvalveproperties/",
|
||||
summary="获取所有阀门属性",
|
||||
description="获取指定水网中所有阀门的属性",
|
||||
)
|
||||
@@ -311,8 +311,8 @@ async def fastapi_get_all_valve_properties(
|
||||
results = get_all_valves(network)
|
||||
return results
|
||||
|
||||
@router.patch(
|
||||
"/valves/properties",
|
||||
@router.post(
|
||||
"/setvalveproperties/",
|
||||
response_model=None,
|
||||
summary="批量设置阀门属性",
|
||||
description="批量设置指定阀门的多个属性",
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import json
|
||||
from fastapi import APIRouter, Request, HTTPException, Query, Path, Depends
|
||||
from fastapi import APIRouter, Request, HTTPException, Query, Path, Body, Depends
|
||||
from fastapi.responses import PlainTextResponse
|
||||
from typing import Any, Dict, List
|
||||
from app.infra.db.metadb.repositories.metadata_repository import MetadataRepository
|
||||
from app.auth.project_dependencies import get_metadata_repository
|
||||
from app.auth.permissions import (
|
||||
ENVIRONMENT_MANAGE,
|
||||
require_permission,
|
||||
)
|
||||
from app.domain.schemas.metadata import ProjectMetaResponse
|
||||
import app.services.project_info as project_info
|
||||
from app.infra.db.postgresql.database import get_database_instance as get_pg_db
|
||||
@@ -22,6 +18,7 @@ from app.services.tjnetwork import (
|
||||
open_project,
|
||||
close_project,
|
||||
copy_project,
|
||||
import_inp,
|
||||
export_inp,
|
||||
read_inp,
|
||||
dump_inp,
|
||||
@@ -45,7 +42,8 @@ inpDir = "data/" # Assuming data directory exists or is defined somewhere.
|
||||
router = APIRouter()
|
||||
lockedPrjs: Dict[str, str] = {}
|
||||
|
||||
@router.get("/projects/current", summary="获取项目信息", description="从数据库获取项目的详细信息,包括地图范围等。", response_model=ProjectMetaResponse)
|
||||
@router.get("/project-info", summary="获取项目信息", description="从数据库获取项目的详细信息,包括地图范围等。", response_model=ProjectMetaResponse)
|
||||
@router.get("/project_info/", summary="获取项目信息(旧路径)", description="从数据库获取项目的详细信息,包括地图范围等。", response_model=ProjectMetaResponse, deprecated=True)
|
||||
async def get_project_info_endpoint(
|
||||
network: str = Query(..., description="管网名称(或项目代码)"),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
@@ -58,6 +56,7 @@ async def get_project_info_endpoint(
|
||||
project_detail = await metadata_repo.get_project_detail_by_code(network)
|
||||
if not project_detail:
|
||||
raise HTTPException(status_code=404, detail=f"Project {network} not found")
|
||||
|
||||
return ProjectMetaResponse(
|
||||
project_id=project_detail.project_id,
|
||||
name=project_detail.name,
|
||||
@@ -66,10 +65,10 @@ async def get_project_info_endpoint(
|
||||
gs_workspace=project_detail.gs_workspace,
|
||||
map_extent=project_detail.map_extent,
|
||||
status=project_detail.status,
|
||||
project_role="viewer", # Default role for public access
|
||||
project_role="viewer",
|
||||
)
|
||||
|
||||
@router.get("/project-codes", summary="获取项目列表", description="获取服务器上所有可用的供水管网项目名称列表。")
|
||||
@router.get("/listprojects/", summary="获取项目列表", description="获取服务器上所有可用的供水管网项目名称列表。")
|
||||
async def list_projects_endpoint() -> list[str]:
|
||||
"""
|
||||
获取项目列表
|
||||
@@ -78,7 +77,7 @@ async def list_projects_endpoint() -> list[str]:
|
||||
"""
|
||||
return list_project()
|
||||
|
||||
@router.get("/projects/existence", summary="检查项目是否存在", description="检查指定名称的项目是否存在。")
|
||||
@router.get("/haveproject/", summary="检查项目是否存在", description="检查指定名称的项目是否存在。")
|
||||
async def have_project_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
):
|
||||
@@ -89,10 +88,9 @@ async def have_project_endpoint(
|
||||
"""
|
||||
return have_project(network)
|
||||
|
||||
@router.post("/projects", summary="创建新项目", description="创建一个新的供水管网项目。如果项目已存在,可能会覆盖或报错(取决于底层实现)。")
|
||||
@router.post("/createproject/", summary="创建新项目", description="创建一个新的供水管网项目。如果项目已存在,可能会覆盖或报错(取决于底层实现)。")
|
||||
async def create_project_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
_=Depends(require_permission(ENVIRONMENT_MANAGE)),
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
):
|
||||
"""
|
||||
创建新项目
|
||||
@@ -102,10 +100,9 @@ async def create_project_endpoint(
|
||||
create_project(network)
|
||||
return network
|
||||
|
||||
@router.delete("/projects", summary="删除项目", description="永久删除指定的供水管网项目。此操作不可恢复。")
|
||||
@router.post("/deleteproject/", summary="删除项目", description="永久删除指定的供水管网项目。此操作不可恢复。")
|
||||
async def delete_project_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
_=Depends(require_permission(ENVIRONMENT_MANAGE)),
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
):
|
||||
"""
|
||||
删除项目
|
||||
@@ -115,7 +112,7 @@ async def delete_project_endpoint(
|
||||
delete_project(network)
|
||||
return True
|
||||
|
||||
@router.get("/projects/current/status", summary="检查项目是否已打开", description="检查指定项目是否已被加载到内存中。")
|
||||
@router.get("/isprojectopen/", summary="检查项目是否已打开", description="检查指定项目是否已被加载到内存中。")
|
||||
async def is_project_open_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
):
|
||||
@@ -126,7 +123,8 @@ async def is_project_open_endpoint(
|
||||
"""
|
||||
return is_project_open(network)
|
||||
|
||||
@router.post("/projects/current", summary="打开项目", description="将指定项目加载到内存中,并初始化数据库连接池。")
|
||||
@router.post("/projects/open", summary="打开项目", description="将指定项目加载到内存中,并初始化数据库连接池。")
|
||||
@router.post("/openproject/", summary="打开项目(旧路径)", description="将指定项目加载到内存中,并初始化数据库连接池。", deprecated=True)
|
||||
async def open_project_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
):
|
||||
@@ -160,7 +158,7 @@ async def open_project_endpoint(
|
||||
|
||||
return network
|
||||
|
||||
@router.delete("/projects/current", summary="关闭项目", description="将指定项目从内存中卸载,释放资源。")
|
||||
@router.post("/closeproject/", summary="关闭项目", description="将指定项目从内存中卸载,释放资源。")
|
||||
async def close_project_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
):
|
||||
@@ -172,11 +170,10 @@ async def close_project_endpoint(
|
||||
close_project(network)
|
||||
return True
|
||||
|
||||
@router.post("/project-copies", summary="复制项目", description="将现有项目复制为新项目。")
|
||||
@router.post("/copyproject/", summary="复制项目", description="将现有项目复制为新项目。")
|
||||
async def copy_project_endpoint(
|
||||
source: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
target: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
_=Depends(require_permission(ENVIRONMENT_MANAGE)),
|
||||
target: str = Query(..., description="管网名称(或数据库名称)")
|
||||
):
|
||||
"""
|
||||
复制项目
|
||||
@@ -187,7 +184,25 @@ async def copy_project_endpoint(
|
||||
copy_project(source, target)
|
||||
return True
|
||||
|
||||
@router.get("/projects/current/exports/change-set", response_model=None, summary="导出项目为 ChangeSet", description="导出项目的变更集 (ChangeSet),包含顶点、SCADA 元素、DMA、SA、VD 等信息。")
|
||||
@router.post("/importinp/", summary="导入 INP 文件内容", description="将 INP 格式的文本内容导入到指定项目中。")
|
||||
async def import_inp_endpoint(
|
||||
req: Request,
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
):
|
||||
"""
|
||||
导入 INP 文件内容
|
||||
|
||||
- **network**: 管网名称(或数据库名称)
|
||||
- **req**: 请求体,需包含 `{"inp": "..."}` 结构
|
||||
"""
|
||||
jo_root = await req.json()
|
||||
inp_text = jo_root["inp"]
|
||||
ps = {"inp": inp_text}
|
||||
ret = import_inp(network, ChangeSet(ps))
|
||||
print(ret)
|
||||
return ret
|
||||
|
||||
@router.get("/exportinp/", response_model=None, summary="导出项目为 ChangeSet", description="导出项目的变更集 (ChangeSet),包含顶点、SCADA 元素、DMA、SA、VD 等信息。")
|
||||
async def export_inp_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
version: str = Query(..., description="版本号 (通常用于增量更新)")
|
||||
@@ -220,7 +235,7 @@ async def export_inp_endpoint(
|
||||
|
||||
return cs
|
||||
|
||||
@router.post("/projects/current/imports", summary="读取 INP 文件到项目", description="从服务器文件系统中读取指定的 INP 文件并加载到项目中。")
|
||||
@router.post("/readinp/", summary="读取 INP 文件到项目", description="从服务器文件系统中读取指定的 INP 文件并加载到项目中。")
|
||||
async def read_inp_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
inp: str = Query(..., description="INP 文件名 (不包含路径)")
|
||||
@@ -234,7 +249,7 @@ async def read_inp_endpoint(
|
||||
read_inp(network, inp)
|
||||
return True
|
||||
|
||||
@router.post("/projects/current/exports/inp", summary="导出项目到 INP 文件", description="将项目当前状态保存为 INP 文件到服务器文件系统。")
|
||||
@router.get("/dumpinp/", summary="导出项目到 INP 文件", description="将项目当前状态保存为 INP 文件到服务器文件系统。")
|
||||
async def dump_inp_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
inp: str = Query(..., description="目标文件名")
|
||||
@@ -248,7 +263,7 @@ async def dump_inp_endpoint(
|
||||
dump_inp(network, inp)
|
||||
return True
|
||||
|
||||
@router.get("/projects/current/lock", summary="检查项目是否被锁定", description="检查指定项目是否处于锁定状态。")
|
||||
@router.get("/isprojectlocked/", summary="检查项目是否被锁定", description="检查指定项目是否处于锁定状态。")
|
||||
async def is_project_locked_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -260,7 +275,7 @@ async def is_project_locked_endpoint(
|
||||
"""
|
||||
return network in lockedPrjs.keys()
|
||||
|
||||
@router.get("/projects/current/lock/ownership", summary="检查项目是否被当前用户锁定", description="检查指定项目是否被当前访问地址 (IP) 锁定。")
|
||||
@router.get("/isprojectlockedbyme/", summary="检查项目是否被当前用户锁定", description="检查指定项目是否被当前客户端 (IP) 锁定。")
|
||||
async def is_project_locked_by_me_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -276,7 +291,7 @@ async def is_project_locked_by_me_endpoint(
|
||||
# 0 successfully locked
|
||||
# 1 already locked by you
|
||||
# 2 locked by others
|
||||
@router.post("/projects/current/lock", summary="锁定项目", description="锁定指定项目以防止并发修改。")
|
||||
@router.post("/lockproject/", summary="锁定项目", description="锁定指定项目以防止并发修改。")
|
||||
async def lock_project_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -299,7 +314,7 @@ async def lock_project_endpoint(
|
||||
else:
|
||||
return 2
|
||||
|
||||
@router.delete("/projects/current/lock", summary="解锁项目", description="释放对项目的锁定。")
|
||||
@router.post("/unlockproject/", summary="解锁项目", description="释放对项目的锁定。")
|
||||
def unlock_project_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -317,7 +332,27 @@ def unlock_project_endpoint(
|
||||
|
||||
return False
|
||||
|
||||
@router.get("/projects/current/files/inp", status_code=status.HTTP_200_OK, summary="下载 INP 文件", description="从服务器数据目录下载指定的 INP 文件。")
|
||||
# inp file operations
|
||||
@router.post("/uploadinp/", status_code=status.HTTP_200_OK, summary="上传 INP 文件", description="上传 INP 文件到服务器数据目录。")
|
||||
async def fastapi_upload_inp(
|
||||
afile: bytes = Body(..., description="文件二进制内容"),
|
||||
name: str = Query(..., description="保存的文件名")
|
||||
):
|
||||
"""
|
||||
上传 INP 文件
|
||||
|
||||
- **afile**: 文件内容
|
||||
- **name**: 文件名
|
||||
"""
|
||||
if not os.path.exists(inpDir):
|
||||
os.makedirs(inpDir, exist_ok=True)
|
||||
|
||||
filePath = inpDir + str(name)
|
||||
with open(filePath, "wb") as f:
|
||||
f.write(afile)
|
||||
return True
|
||||
|
||||
@router.get("/downloadinp/", status_code=status.HTTP_200_OK, summary="下载 INP 文件", description="从服务器数据目录下载指定的 INP 文件。")
|
||||
async def fastapi_download_inp(
|
||||
name: str = Query(..., description="文件名"),
|
||||
response: Response = None
|
||||
@@ -337,7 +372,7 @@ async def fastapi_download_inp(
|
||||
return True
|
||||
|
||||
# DingZQ, 2024-12-28, convert v3 to v2
|
||||
@router.post("/project-conversions", response_model=None, summary="转换 INP V3 为 V2", description="将 EPANET 3.0 格式的 INP 内容转换为 2.x 格式。")
|
||||
@router.get("/convertv3tov2/", response_model=None, summary="转换 INP V3 为 V2", description="将 EPANET 3.0 格式的 INP 内容转换为 2.x 格式。")
|
||||
async def fastapi_convert_v3_to_v2(
|
||||
req: Request
|
||||
) -> ChangeSet:
|
||||
@@ -371,6 +406,7 @@ async def fastapi_convert_v3_to_v2(
|
||||
|
||||
return cs
|
||||
|
||||
@router.post("/readinp/", summary="读取 INP 文件到项目", description="从服务器文件系统中读取指定的 INP 文件并加载到项目中。")
|
||||
async def read_inp_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
inp: str = Query(..., description="INP 文件名 (不包含路径)")
|
||||
@@ -384,6 +420,7 @@ async def read_inp_endpoint(
|
||||
read_inp(network, inp)
|
||||
return True
|
||||
|
||||
@router.get("/dumpinp/", summary="导出项目到 INP 文件", description="将项目当前状态保存为 INP 文件到服务器文件系统。")
|
||||
async def dump_inp_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
inp: str = Query(..., description="目标文件名")
|
||||
@@ -397,6 +434,7 @@ async def dump_inp_endpoint(
|
||||
dump_inp(network, inp)
|
||||
return True
|
||||
|
||||
@router.get("/isprojectlocked/", summary="检查项目是否被锁定", description="检查指定项目是否处于锁定状态。")
|
||||
async def is_project_locked_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -408,6 +446,7 @@ async def is_project_locked_endpoint(
|
||||
"""
|
||||
return network in lockedPrjs.keys()
|
||||
|
||||
@router.get("/isprojectlockedbyme/", summary="检查项目是否被当前用户锁定", description="检查指定项目是否被当前客户端 (IP) 锁定。")
|
||||
async def is_project_locked_by_me_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -423,6 +462,7 @@ async def is_project_locked_by_me_endpoint(
|
||||
# 0 successfully locked
|
||||
# 1 already locked by you
|
||||
# 2 locked by others
|
||||
@router.post("/lockproject/", summary="锁定项目", description="锁定指定项目以防止并发修改。")
|
||||
async def lock_project_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -445,6 +485,7 @@ async def lock_project_endpoint(
|
||||
else:
|
||||
return 2
|
||||
|
||||
@router.post("/unlockproject/", summary="解锁项目", description="释放对项目的锁定。")
|
||||
def unlock_project_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -462,6 +503,27 @@ def unlock_project_endpoint(
|
||||
|
||||
return False
|
||||
|
||||
# inp file operations
|
||||
@router.post("/uploadinp/", status_code=status.HTTP_200_OK, summary="上传 INP 文件", description="上传 INP 文件到服务器数据目录。")
|
||||
async def fastapi_upload_inp(
|
||||
afile: bytes = Body(..., description="文件二进制内容"),
|
||||
name: str = Query(..., description="保存的文件名")
|
||||
):
|
||||
"""
|
||||
上传 INP 文件
|
||||
|
||||
- **afile**: 文件内容
|
||||
- **name**: 文件名
|
||||
"""
|
||||
if not os.path.exists(inpDir):
|
||||
os.makedirs(inpDir, exist_ok=True)
|
||||
|
||||
filePath = inpDir + str(name)
|
||||
with open(filePath, "wb") as f:
|
||||
f.write(afile)
|
||||
return True
|
||||
|
||||
@router.get("/downloadinp/", status_code=status.HTTP_200_OK, summary="下载 INP 文件", description="从服务器数据目录下载指定的 INP 文件。")
|
||||
async def fastapi_download_inp(
|
||||
name: str = Query(..., description="文件名"),
|
||||
response: Response = None
|
||||
@@ -481,6 +543,7 @@ async def fastapi_download_inp(
|
||||
return True
|
||||
|
||||
# DingZQ, 2024-12-28, convert v3 to v2
|
||||
@router.get("/convertv3tov2/", response_model=None, summary="转换 INP V3 为 V2", description="将 EPANET 3.0 格式的 INP 内容转换为 2.x 格式。")
|
||||
async def fastapi_convert_v3_to_v2(
|
||||
req: Request
|
||||
) -> ChangeSet:
|
||||
|
||||
@@ -15,7 +15,7 @@ async def get_database_connection(
|
||||
yield conn
|
||||
|
||||
|
||||
@router.get("/scada-info/database-view", summary="获取SCADA信息", description="使用连接池查询所有SCADA信息")
|
||||
@router.get("/scada-info", summary="获取SCADA信息", description="使用连接池查询所有SCADA信息")
|
||||
async def get_scada_info_with_connection(
|
||||
conn: AsyncConnection = Depends(get_database_connection),
|
||||
):
|
||||
@@ -33,7 +33,7 @@ async def get_scada_info_with_connection(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/schemes/list-with-connection", summary="获取方案列表", description="使用连接池查询所有方案信息")
|
||||
@router.get("/scheme-list", summary="获取方案列表", description="使用连接池查询所有方案信息")
|
||||
async def get_scheme_list_with_connection(
|
||||
conn: AsyncConnection = Depends(get_database_connection),
|
||||
):
|
||||
@@ -49,7 +49,7 @@ async def get_scheme_list_with_connection(
|
||||
raise HTTPException(status_code=500, detail=f"查询方案信息时发生错误: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/burst-locations/database-view", summary="获取爆管定位结果", description="使用连接池查询所有爆管定位结果")
|
||||
@router.get("/burst-locate-result", summary="获取爆管定位结果", description="使用连接池查询所有爆管定位结果")
|
||||
async def get_burst_locate_result_with_connection(
|
||||
conn: AsyncConnection = Depends(get_database_connection),
|
||||
):
|
||||
@@ -67,7 +67,7 @@ async def get_burst_locate_result_with_connection(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/burst-locations/{burst_incident}", summary="按事件查询爆管定位结果", description="根据爆管事件ID查询对应的爆管定位结果")
|
||||
@router.get("/burst-locate-result/{burst_incident}", summary="按事件查询爆管定位结果", description="根据爆管事件ID查询对应的爆管定位结果")
|
||||
async def get_burst_locate_result_by_incident(
|
||||
burst_incident: str = Path(..., description="爆管事件ID"),
|
||||
conn: AsyncConnection = Depends(get_database_connection),
|
||||
|
||||
@@ -11,7 +11,7 @@ from app.services.tjnetwork import (
|
||||
router = APIRouter()
|
||||
|
||||
@router.get(
|
||||
"/pipes/risk-probability-now",
|
||||
"/getpiperiskprobabilitynow/",
|
||||
summary="获取管道当前风险概率",
|
||||
description="获取指定管道当前时刻的风险概率值"
|
||||
)
|
||||
@@ -35,7 +35,7 @@ async def fastapi_get_pipe_risk_probability_now(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/pipes/risk-probability",
|
||||
"/getpiperiskprobability/",
|
||||
summary="获取管道风险概率历史",
|
||||
description="获取指定管道的风险概率历史数据"
|
||||
)
|
||||
@@ -59,7 +59,7 @@ async def fastapi_get_pipe_risk_probability(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/pipes-risk-probabilities",
|
||||
"/getpipesriskprobability/",
|
||||
summary="批量获取多条管道风险概率",
|
||||
description="批量获取多条管道的风险概率值"
|
||||
)
|
||||
@@ -84,7 +84,7 @@ async def fastapi_get_pipes_risk_probability(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/network-pipe-risk-probability-nows",
|
||||
"/getnetworkpiperiskprobabilitynow/",
|
||||
summary="获取整个网络的管道风险概率",
|
||||
description="获取指定网络中所有管道的当前风险概率值"
|
||||
)
|
||||
@@ -106,7 +106,7 @@ async def fastapi_get_network_pipe_risk_probability_now(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/pipes/risk-probability-geometries",
|
||||
"/getpiperiskprobabilitygeometries/",
|
||||
summary="获取管道风险几何信息",
|
||||
description="获取指定网络中管道的风险相关几何数据"
|
||||
)
|
||||
|
||||
@@ -31,6 +31,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/getscadaproperties/", summary="获取SCADA属性", tags=["SCADA基础"])
|
||||
async def fast_get_scada_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
scada: str = Query(..., description="SCADA设备ID")
|
||||
@@ -49,6 +50,7 @@ async def fast_get_scada_properties(
|
||||
"""
|
||||
return get_scada_info(network, scada)
|
||||
|
||||
@router.get("/getallscadaproperties/", summary="获取所有SCADA属性", tags=["SCADA基础"])
|
||||
async def fast_get_all_scada_properties(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -70,7 +72,7 @@ async def fast_get_all_scada_properties(
|
||||
# scada_device 设备管理
|
||||
############################################################
|
||||
|
||||
@router.get("/network-schemas/scada-device", summary="获取SCADA设备架构", tags=["SCADA设备"])
|
||||
@router.get("/getscadadeviceschema/", summary="获取SCADA设备架构", tags=["SCADA设备"])
|
||||
async def fastapi_get_scada_device_schema(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
@@ -87,7 +89,7 @@ async def fastapi_get_scada_device_schema(
|
||||
"""
|
||||
return get_scada_device_schema(network)
|
||||
|
||||
@router.get("/scada-devices/detail", summary="获取SCADA设备", tags=["SCADA设备"])
|
||||
@router.get("/getscadadevice/", summary="获取SCADA设备", tags=["SCADA设备"])
|
||||
async def fastapi_get_scada_device(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
id: str = Query(..., description="SCADA设备ID")
|
||||
@@ -106,7 +108,7 @@ async def fastapi_get_scada_device(
|
||||
"""
|
||||
return get_scada_device(network, id)
|
||||
|
||||
@router.patch("/scada-devices", response_model=None, summary="更新SCADA设备", tags=["SCADA设备"])
|
||||
@router.post("/setscadadevice/", response_model=None, summary="更新SCADA设备", tags=["SCADA设备"])
|
||||
async def fastapi_set_scada_device(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -126,7 +128,7 @@ async def fastapi_set_scada_device(
|
||||
props = await req.json()
|
||||
return set_scada_device(network, ChangeSet(props))
|
||||
|
||||
@router.post("/scada-devices", response_model=None, summary="添加SCADA设备", tags=["SCADA设备"])
|
||||
@router.post("/addscadadevice/", response_model=None, summary="添加SCADA设备", tags=["SCADA设备"])
|
||||
async def fastapi_add_scada_device(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -146,7 +148,7 @@ async def fastapi_add_scada_device(
|
||||
props = await req.json()
|
||||
return add_scada_device(network, ChangeSet(props))
|
||||
|
||||
@router.delete("/scada-devices", response_model=None, summary="删除SCADA设备", tags=["SCADA设备"])
|
||||
@router.post("/deletescadadevice/", response_model=None, summary="删除SCADA设备", tags=["SCADA设备"])
|
||||
async def fastapi_delete_scada_device(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -166,7 +168,7 @@ async def fastapi_delete_scada_device(
|
||||
props = await req.json()
|
||||
return delete_scada_device(network, ChangeSet(props))
|
||||
|
||||
@router.post("/scada-device-cleaning-runs", response_model=None, summary="清空SCADA设备表", tags=["SCADA设备"])
|
||||
@router.post("/cleanscadadevice/", response_model=None, summary="清空SCADA设备表", tags=["SCADA设备"])
|
||||
async def fastapi_clean_scada_device(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> ChangeSet:
|
||||
@@ -183,7 +185,7 @@ async def fastapi_clean_scada_device(
|
||||
"""
|
||||
return clean_scada_device(network)
|
||||
|
||||
@router.get("/scada-devices/ids", summary="获取所有SCADA设备ID", tags=["SCADA设备"])
|
||||
@router.get("/getallscadadeviceids/", summary="获取所有SCADA设备ID", tags=["SCADA设备"])
|
||||
async def fastapi_get_all_scada_device_ids(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> list[str]:
|
||||
@@ -198,7 +200,7 @@ async def fastapi_get_all_scada_device_ids(
|
||||
"""
|
||||
return get_all_scada_device_ids(network)
|
||||
|
||||
@router.get("/scada-devices", summary="获取所有SCADA设备", tags=["SCADA设备"])
|
||||
@router.get("/getallscadadevices/", summary="获取所有SCADA设备", tags=["SCADA设备"])
|
||||
async def fastapi_get_all_scada_devices(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -218,7 +220,7 @@ async def fastapi_get_all_scada_devices(
|
||||
# scada_device_data 设备数据管理
|
||||
############################################################
|
||||
|
||||
@router.get("/network-schemas/scada-device-data", summary="获取SCADA设备数据架构", tags=["SCADA设备数据"])
|
||||
@router.get("/getscadadevicedataschema/", summary="获取SCADA设备数据架构", tags=["SCADA设备数据"])
|
||||
async def fastapi_get_scada_device_data_schema(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
@@ -235,7 +237,7 @@ async def fastapi_get_scada_device_data_schema(
|
||||
"""
|
||||
return get_scada_device_data_schema(network)
|
||||
|
||||
@router.get("/scada-device-datas/detail", summary="获取SCADA设备数据", tags=["SCADA设备数据"])
|
||||
@router.get("/getscadadevicedata/", summary="获取SCADA设备数据", tags=["SCADA设备数据"])
|
||||
async def fastapi_get_scada_device_data(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
device_id: str = Query(..., description="SCADA设备ID")
|
||||
@@ -254,7 +256,7 @@ async def fastapi_get_scada_device_data(
|
||||
"""
|
||||
return get_scada_device_data(network, device_id)
|
||||
|
||||
@router.patch("/scada-device-datas", response_model=None, summary="更新SCADA设备数据", tags=["SCADA设备数据"])
|
||||
@router.post("/setscadadevicedata/", response_model=None, summary="更新SCADA设备数据", tags=["SCADA设备数据"])
|
||||
async def fastapi_set_scada_device_data(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -274,7 +276,7 @@ async def fastapi_set_scada_device_data(
|
||||
props = await req.json()
|
||||
return set_scada_device_data(network, ChangeSet(props))
|
||||
|
||||
@router.post("/scada-device-datas", response_model=None, summary="添加SCADA设备数据", tags=["SCADA设备数据"])
|
||||
@router.post("/addscadadevicedata/", response_model=None, summary="添加SCADA设备数据", tags=["SCADA设备数据"])
|
||||
async def fastapi_add_scada_device_data(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -294,7 +296,7 @@ async def fastapi_add_scada_device_data(
|
||||
props = await req.json()
|
||||
return add_scada_device_data(network, ChangeSet(props))
|
||||
|
||||
@router.delete("/scada-device-datas", response_model=None, summary="删除SCADA设备数据", tags=["SCADA设备数据"])
|
||||
@router.post("/deletescadadevicedata/", response_model=None, summary="删除SCADA设备数据", tags=["SCADA设备数据"])
|
||||
async def fastapi_delete_scada_device_data(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -314,7 +316,7 @@ async def fastapi_delete_scada_device_data(
|
||||
props = await req.json()
|
||||
return delete_scada_device_data(network, ChangeSet(props))
|
||||
|
||||
@router.post("/scada-device-data-cleaning-runs", response_model=None, summary="清空SCADA设备数据表", tags=["SCADA设备数据"])
|
||||
@router.post("/cleanscadadevicedata/", response_model=None, summary="清空SCADA设备数据表", tags=["SCADA设备数据"])
|
||||
async def fastapi_clean_scada_device_data(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> ChangeSet:
|
||||
@@ -336,7 +338,7 @@ async def fastapi_clean_scada_device_data(
|
||||
# scada_element SCADA元素映射
|
||||
############################################################
|
||||
|
||||
@router.get("/network-schemas/scada-element", summary="获取SCADA元素架构", tags=["SCADA元素映射"])
|
||||
@router.get("/getscadaelementschema/", summary="获取SCADA元素架构", tags=["SCADA元素映射"])
|
||||
async def fastapi_get_scada_element_schema(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
@@ -353,7 +355,7 @@ async def fastapi_get_scada_element_schema(
|
||||
"""
|
||||
return get_scada_element_schema(network)
|
||||
|
||||
@router.get("/scada-elements", summary="获取所有SCADA元素映射", tags=["SCADA元素映射"])
|
||||
@router.get("/getscadaelements/", summary="获取所有SCADA元素映射", tags=["SCADA元素映射"])
|
||||
async def fastapi_get_scada_elements(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> list[dict[str, Any]]:
|
||||
@@ -370,7 +372,7 @@ async def fastapi_get_scada_elements(
|
||||
"""
|
||||
return get_all_scada_elements(network)
|
||||
|
||||
@router.get("/scada-elements/detail", summary="获取单个SCADA元素映射", tags=["SCADA元素映射"])
|
||||
@router.get("/getscadaelement/", summary="获取单个SCADA元素映射", tags=["SCADA元素映射"])
|
||||
async def fastapi_get_scada_element(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
id: str = Query(..., description="SCADA元素映射ID")
|
||||
@@ -389,7 +391,7 @@ async def fastapi_get_scada_element(
|
||||
"""
|
||||
return get_scada_element(network, id)
|
||||
|
||||
@router.patch("/scada-elements", response_model=None, summary="更新SCADA元素映射", tags=["SCADA元素映射"])
|
||||
@router.post("/setscadaelement/", response_model=None, summary="更新SCADA元素映射", tags=["SCADA元素映射"])
|
||||
async def fastapi_set_scada_element(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -409,7 +411,7 @@ async def fastapi_set_scada_element(
|
||||
props = await req.json()
|
||||
return set_scada_element(network, ChangeSet(props))
|
||||
|
||||
@router.post("/scada-elements", response_model=None, summary="添加SCADA元素映射", tags=["SCADA元素映射"])
|
||||
@router.post("/addscadaelement/", response_model=None, summary="添加SCADA元素映射", tags=["SCADA元素映射"])
|
||||
async def fastapi_add_scada_element(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -429,7 +431,7 @@ async def fastapi_add_scada_element(
|
||||
props = await req.json()
|
||||
return add_scada_element(network, ChangeSet(props))
|
||||
|
||||
@router.delete("/scada-elements", response_model=None, summary="删除SCADA元素映射", tags=["SCADA元素映射"])
|
||||
@router.post("/deletescadaelement/", response_model=None, summary="删除SCADA元素映射", tags=["SCADA元素映射"])
|
||||
async def fastapi_delete_scada_element(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -449,7 +451,7 @@ async def fastapi_delete_scada_element(
|
||||
props = await req.json()
|
||||
return delete_scada_element(network, ChangeSet(props))
|
||||
|
||||
@router.post("/scada-element-cleaning-runs", response_model=None, summary="清空SCADA元素映射表", tags=["SCADA元素映射"])
|
||||
@router.post("/cleanscadaelement/", response_model=None, summary="清空SCADA元素映射表", tags=["SCADA元素映射"])
|
||||
async def fastapi_clean_scada_element(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> ChangeSet:
|
||||
@@ -471,7 +473,7 @@ async def fastapi_clean_scada_element(
|
||||
# scada_info SCADA信息
|
||||
############################################################
|
||||
|
||||
@router.get("/scada-info-schemas", summary="获取SCADA信息架构", tags=["SCADA信息"])
|
||||
@router.get("/getscadainfoschema/", summary="获取SCADA信息架构", tags=["SCADA信息"])
|
||||
async def fastapi_get_scada_info_schema(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> dict[str, dict[str, Any]]:
|
||||
@@ -488,7 +490,7 @@ async def fastapi_get_scada_info_schema(
|
||||
"""
|
||||
return get_scada_info_schema(network)
|
||||
|
||||
@router.get("/scada-info/detail", summary="获取SCADA信息", tags=["SCADA信息"])
|
||||
@router.get("/getscadainfo/", summary="获取SCADA信息", tags=["SCADA信息"])
|
||||
async def fastapi_get_scada_info(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
id: str = Query(..., description="SCADA信息ID")
|
||||
@@ -507,7 +509,7 @@ async def fastapi_get_scada_info(
|
||||
"""
|
||||
return get_scada_info(network, id)
|
||||
|
||||
@router.get("/scada-info", summary="获取所有SCADA信息", tags=["SCADA信息"])
|
||||
@router.get("/getallscadainfo/", summary="获取所有SCADA信息", tags=["SCADA信息"])
|
||||
async def fastapi_get_all_scada_info(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)")
|
||||
) -> list[dict[str, Any]]:
|
||||
|
||||
@@ -1,13 +1,10 @@
|
||||
from datetime import datetime
|
||||
from fastapi import APIRouter, HTTPException, Path, Query
|
||||
from typing import Any
|
||||
from fastapi import APIRouter, Query
|
||||
from typing import Any, List, Dict
|
||||
from app.services.tjnetwork import get_scheme_schema, get_scheme, get_all_schemes
|
||||
from app.services.scheme_management import query_scheme_detail
|
||||
from app.services.time_api import extract_date
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/network-schemas/scheme", summary="获取方案模式", description="获取指定网络的方案模式定义")
|
||||
@router.get("/getschemeschema/", summary="获取方案模式", description="获取指定网络的方案模式定义")
|
||||
async def fastapi_get_scheme_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[Any, Any]]:
|
||||
"""
|
||||
获取方案模式定义
|
||||
@@ -16,7 +13,7 @@ async def fastapi_get_scheme_schema(network: str = Query(..., description="管
|
||||
"""
|
||||
return get_scheme_schema(network)
|
||||
|
||||
@router.get("/schemes/detail", summary="获取单个方案", description="根据名称获取指定的方案信息")
|
||||
@router.get("/getscheme/", summary="获取单个方案", description="根据名称获取指定的方案信息")
|
||||
async def fastapi_get_scheme(network: str = Query(..., description="管网名称(或数据库名称)"), schema_name: str = Query(..., description="方案名称")) -> dict[Any, Any]:
|
||||
"""
|
||||
获取单个方案详情
|
||||
@@ -26,35 +23,11 @@ async def fastapi_get_scheme(network: str = Query(..., description="管网名称
|
||||
return get_scheme(network, schema_name)
|
||||
|
||||
@router.get("/schemes", summary="获取所有方案", description="获取指定网络的所有方案信息")
|
||||
async def fastapi_get_all_schemes(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
scheme_type: str | None = Query(None, description="方案类型;为空时返回全部类型"),
|
||||
query_date: datetime | None = Query(None, description="查询日期(可选)"),
|
||||
) -> list[dict[Any, Any]]:
|
||||
@router.get("/getallschemes/", summary="获取所有方案(旧路径)", description="获取指定网络的所有方案信息", deprecated=True)
|
||||
async def fastapi_get_all_schemes(network: str = Query(..., description="管网名称(或数据库名称)")) -> list[dict[Any, Any]]:
|
||||
"""
|
||||
获取所有方案列表
|
||||
|
||||
返回指定网络中所有可用的方案
|
||||
"""
|
||||
parsed_date = (
|
||||
extract_date(query_date, field_name="query_date")
|
||||
if query_date is not None
|
||||
else None
|
||||
)
|
||||
return get_all_schemes(network, scheme_type=scheme_type, query_date=parsed_date)
|
||||
|
||||
|
||||
@router.get("/schemes/{scheme_name}", summary="获取方案详情", description="按方案类型获取指定方案详情")
|
||||
async def fastapi_get_scheme_detail(
|
||||
scheme_name: str = Path(..., description="方案名称"),
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
scheme_type: str | None = Query(None, description="方案类型;为空时返回通用方案详情"),
|
||||
) -> dict[Any, Any]:
|
||||
result = query_scheme_detail(
|
||||
name=network,
|
||||
scheme_name=scheme_name,
|
||||
scheme_type=scheme_type,
|
||||
)
|
||||
if not result:
|
||||
raise HTTPException(status_code=404, detail=f"Scheme {scheme_name} not found")
|
||||
return result
|
||||
return get_all_schemes(network)
|
||||
|
||||
@@ -1,265 +0,0 @@
|
||||
import logging
|
||||
from typing import Any
|
||||
from urllib.parse import quote
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Path, Query, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app.algorithms.sensor import (
|
||||
pressure_sensor_placement_kmeans,
|
||||
pressure_sensor_placement_sensitivity,
|
||||
)
|
||||
from app.auth.metadata_dependencies import get_current_metadata_user
|
||||
from app.auth.project_dependencies import ProjectContext, get_project_context
|
||||
from app.domain.schemas.sensor_placement import (
|
||||
SensorPointResponse,
|
||||
SensorPlacementExportRequest,
|
||||
SensorPlacementOptimizeRequest,
|
||||
SensorPlacementSchemeResponse,
|
||||
SensorPlacementUpdateRequest,
|
||||
)
|
||||
from app.services.sensor_placement import (
|
||||
SensorPlacementConflictError,
|
||||
SensorPlacementNotFoundError,
|
||||
SensorPlacementValidationError,
|
||||
build_sensor_placement_workbook,
|
||||
can_edit_sensor_placement,
|
||||
get_sensor_placement_candidate,
|
||||
get_sensor_placement_scheme,
|
||||
update_sensor_placement_scheme,
|
||||
)
|
||||
|
||||
router = APIRouter()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def _project_network(network: str, project_context: ProjectContext) -> str:
|
||||
if network != project_context.project_code:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="请求的管网不属于当前项目",
|
||||
)
|
||||
return project_context.project_code
|
||||
|
||||
|
||||
def _can_modify_project(project_context: ProjectContext) -> bool:
|
||||
return project_context.project_role == "member"
|
||||
|
||||
|
||||
def _require_project_write(
|
||||
project_context: ProjectContext,
|
||||
) -> None:
|
||||
if not _can_modify_project(project_context):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="当前项目角色为只读,不能修改监测点方案",
|
||||
)
|
||||
|
||||
|
||||
def _service_http_error(exc: Exception) -> HTTPException:
|
||||
if isinstance(exc, SensorPlacementNotFoundError):
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=str(exc),
|
||||
)
|
||||
if isinstance(exc, SensorPlacementConflictError):
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail=str(exc),
|
||||
)
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=str(exc),
|
||||
)
|
||||
|
||||
|
||||
def _get_scheme_response(
|
||||
network: str,
|
||||
scheme_id: int,
|
||||
current_user: Any,
|
||||
project_context: ProjectContext,
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
scheme = get_sensor_placement_scheme(network, scheme_id)
|
||||
return {
|
||||
**scheme,
|
||||
"can_edit": (
|
||||
_can_modify_project(project_context)
|
||||
and can_edit_sensor_placement(current_user, scheme)
|
||||
),
|
||||
}
|
||||
except (
|
||||
SensorPlacementNotFoundError,
|
||||
SensorPlacementValidationError,
|
||||
) as exc:
|
||||
raise _service_http_error(exc) from exc
|
||||
|
||||
|
||||
@router.get(
|
||||
"/sensor-placement-candidates/{node_id}",
|
||||
response_model=SensorPointResponse,
|
||||
summary="获取监测点候选节点详情",
|
||||
)
|
||||
async def get_sensor_placement_candidate_detail(
|
||||
node_id: str = Path(..., min_length=1, max_length=32),
|
||||
project_context: ProjectContext = Depends(get_project_context),
|
||||
) -> dict[str, Any]:
|
||||
try:
|
||||
return await run_in_threadpool(
|
||||
get_sensor_placement_candidate,
|
||||
project_context.project_code,
|
||||
node_id,
|
||||
)
|
||||
except SensorPlacementValidationError as exc:
|
||||
raise _service_http_error(exc) from exc
|
||||
|
||||
|
||||
@router.post(
|
||||
"/sensor-placement-optimization-runs",
|
||||
response_model=SensorPlacementSchemeResponse,
|
||||
summary="创建并返回监测点优化方案",
|
||||
)
|
||||
async def optimize_sensor_placement_scheme(
|
||||
payload: SensorPlacementOptimizeRequest,
|
||||
project_context: ProjectContext = Depends(get_project_context),
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
) -> dict[str, Any]:
|
||||
network = _project_network(payload.network, project_context)
|
||||
_require_project_write(project_context)
|
||||
optimizer = (
|
||||
pressure_sensor_placement_sensitivity
|
||||
if payload.method == "sensitivity"
|
||||
else pressure_sensor_placement_kmeans
|
||||
)
|
||||
try:
|
||||
created = await run_in_threadpool(
|
||||
optimizer,
|
||||
name=network,
|
||||
scheme_name=payload.scheme_name,
|
||||
sensor_number=payload.sensor_count,
|
||||
min_diameter=payload.min_diameter,
|
||||
username=current_user.username,
|
||||
)
|
||||
scheme = get_sensor_placement_scheme(network, int(created["id"]))
|
||||
return {**scheme, "can_edit": True}
|
||||
except (
|
||||
SensorPlacementConflictError,
|
||||
SensorPlacementValidationError,
|
||||
ValueError,
|
||||
) as exc:
|
||||
raise _service_http_error(exc) from exc
|
||||
except Exception as exc:
|
||||
logger.exception("Sensor placement optimization failed")
|
||||
raise HTTPException(
|
||||
status_code=500,
|
||||
detail="监测点优化失败,请稍后重试",
|
||||
) from exc
|
||||
|
||||
|
||||
@router.get(
|
||||
"/sensor-placement-schemes/{scheme_id}",
|
||||
response_model=SensorPlacementSchemeResponse,
|
||||
summary="获取监测点方案详情",
|
||||
)
|
||||
async def get_sensor_placement_scheme_detail(
|
||||
scheme_id: int,
|
||||
network: str = Query(..., min_length=1),
|
||||
project_context: ProjectContext = Depends(get_project_context),
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
) -> dict[str, Any]:
|
||||
return _get_scheme_response(
|
||||
_project_network(network, project_context),
|
||||
scheme_id,
|
||||
current_user,
|
||||
project_context,
|
||||
)
|
||||
|
||||
|
||||
@router.put(
|
||||
"/sensor-placement-schemes/{scheme_id}",
|
||||
response_model=SensorPlacementSchemeResponse,
|
||||
summary="覆盖保存监测点方案",
|
||||
)
|
||||
async def overwrite_sensor_placement_scheme(
|
||||
scheme_id: int,
|
||||
payload: SensorPlacementUpdateRequest,
|
||||
network: str = Query(..., min_length=1),
|
||||
project_context: ProjectContext = Depends(get_project_context),
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
) -> dict[str, Any]:
|
||||
network = _project_network(network, project_context)
|
||||
_require_project_write(project_context)
|
||||
scheme = _get_scheme_response(
|
||||
network,
|
||||
scheme_id,
|
||||
current_user,
|
||||
project_context,
|
||||
)
|
||||
if not scheme["can_edit"]:
|
||||
raise HTTPException(status_code=403, detail="无权修改该监测点方案")
|
||||
|
||||
try:
|
||||
updated = update_sensor_placement_scheme(
|
||||
network,
|
||||
scheme_id,
|
||||
expected_sensor_location=payload.expected_sensor_location,
|
||||
sensor_location=payload.sensor_location,
|
||||
)
|
||||
return {**updated, "can_edit": True}
|
||||
except (
|
||||
SensorPlacementConflictError,
|
||||
SensorPlacementNotFoundError,
|
||||
SensorPlacementValidationError,
|
||||
) as exc:
|
||||
raise _service_http_error(exc) from exc
|
||||
|
||||
|
||||
@router.post(
|
||||
"/sensor-placement-schemes/{scheme_id}/exports/excel",
|
||||
summary="导出监测点工程清单",
|
||||
)
|
||||
async def export_sensor_placement_excel(
|
||||
scheme_id: int,
|
||||
payload: SensorPlacementExportRequest,
|
||||
network: str = Query(..., min_length=1),
|
||||
project_context: ProjectContext = Depends(get_project_context),
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
) -> StreamingResponse:
|
||||
network = _project_network(network, project_context)
|
||||
scheme = _get_scheme_response(
|
||||
network,
|
||||
scheme_id,
|
||||
current_user,
|
||||
project_context,
|
||||
)
|
||||
if (
|
||||
payload.sensor_location != scheme["sensor_location"]
|
||||
and not scheme["can_edit"]
|
||||
):
|
||||
raise HTTPException(status_code=403, detail="无权导出该方案的未保存草稿")
|
||||
|
||||
try:
|
||||
workbook = await run_in_threadpool(
|
||||
build_sensor_placement_workbook,
|
||||
network=network,
|
||||
scheme=scheme,
|
||||
sensor_location=payload.sensor_location,
|
||||
adjustment_status=payload.adjustment_status,
|
||||
)
|
||||
except SensorPlacementValidationError as exc:
|
||||
raise _service_http_error(exc) from exc
|
||||
|
||||
filename = f"{scheme['scheme_name']}_监测点清单.xlsx"
|
||||
encoded_filename = quote(filename)
|
||||
return StreamingResponse(
|
||||
workbook,
|
||||
media_type=(
|
||||
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
),
|
||||
headers={
|
||||
"Content-Disposition": (
|
||||
f"attachment; filename*=UTF-8''{encoded_filename}"
|
||||
)
|
||||
},
|
||||
)
|
||||
@@ -1,8 +1,10 @@
|
||||
from typing import Any, List, Optional
|
||||
from datetime import datetime, timedelta
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
import threading
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Path, Body
|
||||
from fastapi import APIRouter, Depends, HTTPException, File, UploadFile, Query, Path, Body
|
||||
from fastapi.responses import PlainTextResponse
|
||||
from app.auth.keycloak_dependencies import get_current_keycloak_username
|
||||
import app.services.simulation as simulation
|
||||
@@ -27,6 +29,7 @@ from app.algorithms.sensor import (
|
||||
pressure_sensor_placement_kmeans,
|
||||
)
|
||||
|
||||
from app.services.network_import import network_update
|
||||
from app.services.simulation_ops import (
|
||||
project_management,
|
||||
scheduling_simulation,
|
||||
@@ -139,7 +142,7 @@ def run_simulation_manually_by_date(
|
||||
|
||||
|
||||
# 必须用这个PlainTextResponse,不然每个key都有引号
|
||||
@router.post("/project-runs", response_class=PlainTextResponse, summary="运行项目模拟", description="基于指定的管网项目运行标准水力模拟,返回纯文本格式的模拟报告。")
|
||||
@router.get("/runproject/", response_class=PlainTextResponse, summary="运行项目模拟", description="基于指定的管网项目运行标准水力模拟,返回纯文本格式的模拟报告。")
|
||||
async def run_project_endpoint(network: str = Query(..., description="管网名称(或数据库名称)")) -> str:
|
||||
"""
|
||||
运行项目模拟
|
||||
@@ -155,7 +158,7 @@ async def run_project_endpoint(network: str = Query(..., description="管网名
|
||||
# output 和 report
|
||||
# output 是 json
|
||||
# report 是 text
|
||||
@router.post("/project-return-dict-runs", summary="运行项目模拟(返回字典)", description="基于指定的管网项目运行标准水力模拟,返回JSON格式的字典,包含输出数据和报告文本。")
|
||||
@router.get("/runprojectreturndict/", summary="运行项目模拟(返回字典)", description="基于指定的管网项目运行标准水力模拟,返回JSON格式的字典,包含输出数据和报告文本。")
|
||||
async def run_project_return_dict_endpoint(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, Any]:
|
||||
"""
|
||||
运行项目模拟(返回字典)
|
||||
@@ -172,7 +175,7 @@ async def run_project_return_dict_endpoint(network: str = Query(..., description
|
||||
|
||||
|
||||
# put in inp folder, name without extension
|
||||
@router.post("/inp-runs", summary="运行INP文件", description="运行指定INP文件格式的管网模型进行水力模拟。INP文件应该放在inp文件夹中,参数为文件名不含扩展名。")
|
||||
@router.get("/runinp/", summary="运行INP文件", description="运行指定INP文件格式的管网模型进行水力模拟。INP文件应该放在inp文件夹中,参数为文件名不含扩展名。")
|
||||
async def run_inp_endpoint(network: str = Query(..., description="inp文件名(不含扩展名)")) -> str:
|
||||
"""
|
||||
运行INP文件
|
||||
@@ -185,7 +188,7 @@ async def run_inp_endpoint(network: str = Query(..., description="inp文件名
|
||||
|
||||
|
||||
# path is absolute path
|
||||
@router.get("/outputs", summary="导出模拟输出", description="导出指定路径的模拟输出文件内容。参数应为绝对路径。")
|
||||
@router.get("/dumpoutput/", summary="导出模拟输出", description="导出指定路径的模拟输出文件内容。参数应为绝对路径。")
|
||||
async def dump_output_endpoint(output: str = Query(..., description="模拟输出文件的绝对路径")) -> str:
|
||||
"""
|
||||
导出模拟输出
|
||||
@@ -198,7 +201,8 @@ async def dump_output_endpoint(output: str = Query(..., description="模拟输
|
||||
|
||||
|
||||
# Analysis Endpoints
|
||||
@router.post("/burst-analyses", summary="爆管分析(高级)", description="高级版本的爆管分析,支持在指定时间点修改泵控制模式和阀门开度,以分析这些改变对爆管影响的作用。支持固定泵和变速泵的独立控制。")
|
||||
@router.get("/burst-analysis", summary="爆管分析(高级)", description="高级版本的爆管分析,支持在指定时间点修改泵控制模式和阀门开度,以分析这些改变对爆管影响的作用。支持固定泵和变速泵的独立控制。")
|
||||
@router.get("/burst_analysis/", summary="爆管分析(高级,旧路径)", description="高级版本的爆管分析,支持在指定时间点修改泵控制模式和阀门开度,以分析这些改变对爆管影响的作用。支持固定泵和变速泵的独立控制。", deprecated=True)
|
||||
async def fastapi_burst_analysis(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
modify_pattern_start_time: str = Query(..., description="模式修改开始时间(ISO 8601格式)"),
|
||||
@@ -232,7 +236,7 @@ async def fastapi_burst_analysis(
|
||||
return "success"
|
||||
|
||||
|
||||
@router.post("/valve-closure-analyses", response_class=PlainTextResponse, summary="阀门关闭分析(高级)", description="高级版本的阀门关闭分析,支持同时关闭多个阀门,并在指定持续时间内进行模拟。返回纯文本格式的分析结果。")
|
||||
@router.get("/valve_close_analysis/", response_class=PlainTextResponse, summary="阀门关闭分析(高级)", description="高级版本的阀门关闭分析,支持同时关闭多个阀门,并在指定持续时间内进行模拟。返回纯文本格式的分析结果。")
|
||||
async def fastapi_valve_close_analysis(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
start_time: str = Query(..., description="阀门关闭开始时间(ISO 8601格式)"),
|
||||
@@ -261,7 +265,8 @@ async def fastapi_valve_close_analysis(
|
||||
return result or "success"
|
||||
|
||||
|
||||
@router.post("/valve-isolation-analyses", summary="阀门隔离分析", description="分析当发生突发事件时,通过关闭指定阀门进行隔离,确定哪些阀门必须关闭、哪些可选关闭,以及隔离的可行性。")
|
||||
@router.get("/valve-isolation-analysis", summary="阀门隔离分析", description="分析当发生突发事件时,通过关闭指定阀门进行隔离,确定哪些阀门必须关闭、哪些可选关闭,以及隔离的可行性。")
|
||||
@router.get("/valve_isolation_analysis/", summary="阀门隔离分析(旧路径)", description="分析当发生突发事件时,通过关闭指定阀门进行隔离,确定哪些阀门必须关闭、哪些可选关闭,以及隔离的可行性。", deprecated=True)
|
||||
async def valve_isolation_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
accident_element: List[str] = Query(..., description="发生事故的管段/节点ID列表"),
|
||||
@@ -277,8 +282,7 @@ async def valve_isolation_endpoint(
|
||||
返回隔离方案,包括:
|
||||
- must_close_valves: 必须关闭的阀门列表
|
||||
- optional_valves: 可选关闭的阀门列表
|
||||
- affected_nodes: 受影响的节点列表;不可隔离时为空列表
|
||||
- affected_node_count: 受影响的节点总数
|
||||
- affected_nodes: 受影响的节点列表
|
||||
- isolatable: 是否可以有效隔离
|
||||
"""
|
||||
# result = {
|
||||
@@ -302,7 +306,8 @@ async def valve_isolation_endpoint(
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/flushing-analyses", response_class=PlainTextResponse, summary="冲洗分析(高级)", description="高级版本的冲洗分析,支持同时开启多个阀门进行冲洗,指定排污节点,并设置固定的冲洗流量。返回纯文本格式的分析结果。")
|
||||
@router.get("/flushing-analysis", response_class=PlainTextResponse, summary="冲洗分析(高级)", description="高级版本的冲洗分析,支持同时开启多个阀门进行冲洗,指定排污节点,并设置固定的冲洗流量。返回纯文本格式的分析结果。")
|
||||
@router.get("/flushing_analysis/", response_class=PlainTextResponse, summary="冲洗分析(高级,旧路径)", description="高级版本的冲洗分析,支持同时开启多个阀门进行冲洗,指定排污节点,并设置固定的冲洗流量。返回纯文本格式的分析结果。", deprecated=True)
|
||||
async def fastapi_flushing_analysis(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
start_time: str = Query(..., description="冲洗开始时间(ISO 8601格式)"),
|
||||
@@ -344,7 +349,8 @@ async def fastapi_flushing_analysis(
|
||||
return result or "success"
|
||||
|
||||
|
||||
@router.post("/contaminant-simulations", response_class=PlainTextResponse, summary="污染物模拟", description="对管网中的污染物扩散进行模拟,评估污染源对管网的影响范围和浓度分布。支持指定污染源位置、污染浓度和扩散模式。")
|
||||
@router.get("/contaminant-simulation", response_class=PlainTextResponse, summary="污染物模拟", description="对管网中的污染物扩散进行模拟,评估污染源对管网的影响范围和浓度分布。支持指定污染源位置、污染浓度和扩散模式。")
|
||||
@router.get("/contaminant_simulation/", response_class=PlainTextResponse, summary="污染物模拟(旧路径)", description="对管网中的污染物扩散进行模拟,评估污染源对管网的影响范围和浓度分布。支持指定污染源位置、污染浓度和扩散模式。", deprecated=True)
|
||||
async def fastapi_contaminant_simulation(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
start_time: str = Query(..., description="污染开始时间(ISO 8601格式)"),
|
||||
@@ -381,7 +387,7 @@ async def fastapi_contaminant_simulation(
|
||||
return result or "success"
|
||||
|
||||
|
||||
@router.post("/water-age-analyses", response_class=PlainTextResponse, summary="水龄分析(高级)", description="高级版本的水龄分析,在指定时间点进行分析,支持自定义模拟持续时间。返回纯文本格式的分析结果。")
|
||||
@router.get("/age_analysis/", response_class=PlainTextResponse, summary="水龄分析(高级)", description="高级版本的水龄分析,在指定时间点进行分析,支持自定义模拟持续时间。返回纯文本格式的分析结果。")
|
||||
async def fastapi_age_analysis(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
start_time: str = Query(..., description="分析开始时间(ISO 8601格式)"),
|
||||
@@ -405,7 +411,7 @@ async def fastapi_age_analysis(
|
||||
# return scheduling_analysis(network)
|
||||
|
||||
|
||||
@router.post("/pressure-regulation-calculations", summary="压力调节(基础)", description="对管网的压力进行调节分析,通过控制泵的运行来维持目标节点的目标压力。此为基础版本。")
|
||||
@router.get("/pressureregulation/", summary="压力调节(基础)", description="对管网的压力进行调节分析,通过控制泵的运行来维持目标节点的目标压力。此为基础版本。")
|
||||
async def pressure_regulation_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
target_node: str = Query(..., description="目标节点ID"),
|
||||
@@ -423,7 +429,7 @@ async def pressure_regulation_endpoint(
|
||||
return pressure_regulation(network, target_node, target_pressure)
|
||||
|
||||
|
||||
@router.post("/pressure-regulation-analyses", summary="压力调节(高级)", description="高级版本的压力调节分析,通过JSON请求体提供详细的控制参数,包括固定泵和变速泵的独立控制、水箱初始水位等。")
|
||||
@router.post("/pressure_regulation/", summary="压力调节(高级)", description="高级版本的压力调节分析,通过JSON请求体提供详细的控制参数,包括固定泵和变速泵的独立控制、水箱初始水位等。")
|
||||
async def fastapi_pressure_regulation(data: PressureRegulation = Body(..., description="压力调节控制参数")) -> str:
|
||||
"""
|
||||
压力调节(高级版本)
|
||||
@@ -461,7 +467,7 @@ async def fastapi_pressure_regulation(data: PressureRegulation = Body(..., descr
|
||||
return "success"
|
||||
|
||||
|
||||
@router.post("/project-managements", summary="项目管理(高级)", description="高级版本的项目管理,通过JSON请求体提供详细的控制参数,包括泵控制策略、水箱初始水位和区域需水量控制。")
|
||||
@router.post("/project_management/", summary="项目管理(高级)", description="高级版本的项目管理,通过JSON请求体提供详细的控制参数,包括泵控制策略、水箱初始水位和区域需水量控制。")
|
||||
async def fastapi_project_management(data: ProjectManagement = Body(..., description="项目管理控制参数")) -> str:
|
||||
"""
|
||||
项目管理(高级版本)
|
||||
@@ -490,7 +496,7 @@ async def fastapi_project_management(data: ProjectManagement = Body(..., descrip
|
||||
# return daily_scheduling_analysis(network)
|
||||
|
||||
|
||||
@router.post("/scheduling-analyses", summary="排程分析", description="对管网的供水排程进行分析,优化泵的运行时间和出水流量,平衡水厂出水、水箱进出水,满足用户需求。")
|
||||
@router.post("/scheduling_analysis/", summary="排程分析", description="对管网的供水排程进行分析,优化泵的运行时间和出水流量,平衡水厂出水、水箱进出水,满足用户需求。")
|
||||
async def fastapi_scheduling_analysis(data: SchedulingAnalysis = Body(..., description="排程分析参数")) -> str:
|
||||
"""
|
||||
排程分析
|
||||
@@ -516,7 +522,7 @@ async def fastapi_scheduling_analysis(data: SchedulingAnalysis = Body(..., descr
|
||||
)
|
||||
|
||||
|
||||
@router.post("/daily-scheduling-analyses", summary="日排程分析", description="对管网的每日供水排程进行分析,优化水库、水厂、水箱和用户需求的协调,制定合理的每日排程方案。")
|
||||
@router.post("/daily_scheduling_analysis/", summary="日排程分析", description="对管网的每日供水排程进行分析,优化水库、水厂、水箱和用户需求的协调,制定合理的每日排程方案。")
|
||||
async def fastapi_daily_scheduling_analysis(data: DailySchedulingAnalysis = Body(..., description="日排程分析参数")) -> str:
|
||||
"""
|
||||
日排程分析
|
||||
@@ -543,12 +549,52 @@ async def fastapi_daily_scheduling_analysis(data: DailySchedulingAnalysis = Body
|
||||
)
|
||||
|
||||
|
||||
@router.post("/network_project/", summary="导入网络项目", description="通过上传INP格式的管网文件导入新的网络项目。系统将自动处理文件并执行模拟。")
|
||||
async def fastapi_network_project(file: UploadFile = File(..., description="INP格式的管网文件")) -> str:
|
||||
"""
|
||||
导入网络项目
|
||||
|
||||
- **file**: 上传的INP格式管网文件
|
||||
|
||||
系统将上传的文件保存到inp文件夹并执行模拟。
|
||||
"""
|
||||
temp_file_dir = "./inp/"
|
||||
if not os.path.exists(temp_file_dir):
|
||||
os.mkdir(temp_file_dir)
|
||||
temp_file_name = f'network_project_{datetime.now().strftime("%Y%m%d")}'
|
||||
temp_file_path = f"{temp_file_dir}{temp_file_name}.inp"
|
||||
with open(temp_file_path, "wb") as buffer:
|
||||
shutil.copyfileobj(file.file, buffer)
|
||||
return run_inp(temp_file_name)
|
||||
|
||||
|
||||
@router.post("/network_update/", summary="管网更新(高级)", description="通过上传更新文件对管网进行高级的更新操作。系统将处理更新文件并应用到数据库。")
|
||||
async def fastapi_network_update(file: UploadFile = File(..., description="包含管网更新信息的文件")) -> str:
|
||||
"""
|
||||
管网更新(高级版本)
|
||||
|
||||
- **file**: 包含管网更新信息的文件
|
||||
|
||||
系统将处理上传的文件并应用管网更新。
|
||||
"""
|
||||
default_folder = "./"
|
||||
temp_file_name = f'network_update_{datetime.now().strftime("%Y%m%d")}'
|
||||
temp_file_path = os.path.join(default_folder, temp_file_name)
|
||||
try:
|
||||
with open(temp_file_path, "wb") as buffer:
|
||||
shutil.copyfileobj(file.file, buffer)
|
||||
network_update(temp_file_path)
|
||||
return json.dumps({"message": "管网更新成功"})
|
||||
except Exception as exc:
|
||||
raise HTTPException(status_code=500, detail=f"数据库操作失败: {exc}")
|
||||
|
||||
|
||||
# @router.get("/pumpfailure/")
|
||||
# async def pump_failure_endpoint(network: str, pump_id: str, time: str):
|
||||
# return pump_failure(network, pump_id, time)
|
||||
|
||||
|
||||
@router.post("/pump-failure-events", summary="泵故障管理", description="记录和管理泵的故障状态,包括故障发生时间和受影响的泵列表。系统将记录故障日志并更新泵状态。")
|
||||
@router.post("/pump_failure/", summary="泵故障管理", description="记录和管理泵的故障状态,包括故障发生时间和受影响的泵列表。系统将记录故障日志并更新泵状态。")
|
||||
async def fastapi_pump_failure(data: PumpFailureState = Body(..., description="泵故障状态信息")) -> str:
|
||||
"""
|
||||
泵故障管理
|
||||
@@ -592,7 +638,7 @@ async def fastapi_pump_failure(data: PumpFailureState = Body(..., description="
|
||||
return json.dumps("SUCCESS")
|
||||
|
||||
|
||||
@router.post("/pressure-sensor-placement-sensitivity-calculations", summary="压力传感器放置-灵敏度分析(基础)", description="基于灵敏度分析方法,为指定管网项目确定最优的压力传感器放置位置。此为基础版本。")
|
||||
@router.get("/pressuresensorplacementsensitivity/", summary="压力传感器放置-灵敏度分析(基础)", description="基于灵敏度分析方法,为指定管网项目确定最优的压力传感器放置位置。此为基础版本。")
|
||||
async def pressure_sensor_placement_sensitivity_endpoint(
|
||||
name: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
scheme_name: str = Query(..., description="放置方案名称"),
|
||||
@@ -616,7 +662,7 @@ async def pressure_sensor_placement_sensitivity_endpoint(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/pressure-sensor-placement-sensitivities", summary="压力传感器放置-灵敏度分析(高级)", description="高级版本的压力传感器放置分析,通过JSON请求体提供详细参数。基于灵敏度分析方法确定最优放置位置。")
|
||||
@router.post("/pressure_sensor_placement_sensitivity/", summary="压力传感器放置-灵敏度分析(高级)", description="高级版本的压力传感器放置分析,通过JSON请求体提供详细参数。基于灵敏度分析方法确定最优放置位置。")
|
||||
async def fastapi_pressure_sensor_placement_sensitivity(
|
||||
data: PressureSensorPlacement = Body(..., description="传感器放置分析参数"),
|
||||
) -> None:
|
||||
@@ -642,7 +688,7 @@ async def fastapi_pressure_sensor_placement_sensitivity(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/pressure-sensor-placement-kmeans-calculations", summary="压力传感器放置-KMeans聚类分析(基础)", description="基于KMeans聚类算法,为指定管网项目确定压力传感器的最优放置位置。此为基础版本。")
|
||||
@router.get("/pressuresensorplacementkmeans/", summary="压力传感器放置-KMeans聚类分析(基础)", description="基于KMeans聚类算法,为指定管网项目确定压力传感器的最优放置位置。此为基础版本。")
|
||||
async def pressure_sensor_placement_kmeans_endpoint(
|
||||
name: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
scheme_name: str = Query(..., description="放置方案名称"),
|
||||
@@ -666,7 +712,7 @@ async def pressure_sensor_placement_kmeans_endpoint(
|
||||
)
|
||||
|
||||
|
||||
@router.post("/pressure-sensor-placement-kmeans", summary="压力传感器放置-KMeans聚类分析(高级)", description="高级版本的压力传感器放置分析,通过JSON请求体提供详细参数。基于KMeans聚类算法确定最优放置位置。")
|
||||
@router.post("/pressure_sensor_placement_kmeans/", summary="压力传感器放置-KMeans聚类分析(高级)", description="高级版本的压力传感器放置分析,通过JSON请求体提供详细参数。基于KMeans聚类算法确定最优放置位置。")
|
||||
async def fastapi_pressure_sensor_placement_kmeans(
|
||||
data: PressureSensorPlacement = Body(..., description="传感器放置分析参数"),
|
||||
) -> None:
|
||||
@@ -693,6 +739,7 @@ async def fastapi_pressure_sensor_placement_kmeans(
|
||||
|
||||
|
||||
@router.post("/sensor-placement-schemes", summary="传感器放置方案创建", description="创建新的传感器放置方案,支持灵敏度分析和KMeans聚类两种方法。根据指定的方法自动计算最优的传感器放置位置。")
|
||||
@router.post("/sensorplacementscheme/create", summary="传感器放置方案创建(旧路径)", description="创建新的传感器放置方案,支持灵敏度分析和KMeans聚类两种方法。根据指定的方法自动计算最优的传感器放置位置。", deprecated=True)
|
||||
async def fastapi_pressure_sensor_placement(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
scheme_name: str = Query(..., description="放置方案名称"),
|
||||
@@ -740,7 +787,8 @@ async def fastapi_pressure_sensor_placement(
|
||||
return "success"
|
||||
|
||||
|
||||
@router.post("/simulation-runs", summary="手动运行日期指定模拟", description="根据指定的开始时间和持续时间,手动运行水力模拟。开始时间必须是显式带时区的 ISO 8601 / RFC3339 时间。")
|
||||
@router.post("/simulations/run-by-date", summary="手动运行日期指定模拟", description="根据指定的开始时间和持续时间,手动运行水力模拟。开始时间必须是显式带时区的 ISO 8601 / RFC3339 时间。")
|
||||
@router.post("/runsimulationmanuallybydate/", summary="手动运行日期指定模拟(旧路径)", description="根据指定的开始时间和持续时间,手动运行水力模拟。开始时间必须是显式带时区的 ISO 8601 / RFC3339 时间。", deprecated=True)
|
||||
async def fastapi_run_simulation_manually_by_date(
|
||||
data: RunSimulationManuallyByDate = Body(..., description="模拟运行参数"),
|
||||
) -> dict[str, str]:
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from fastapi import APIRouter, Depends, Request, Query
|
||||
from app.auth.permissions import SIMULATION_RUN, require_permission
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from app.services.tjnetwork import (
|
||||
ChangeSet,
|
||||
get_current_operation,
|
||||
@@ -23,7 +22,7 @@ from app.services.tjnetwork import (
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.get("/current-operation-ids", summary="获取当前操作ID", description="获取网络当前的操作ID")
|
||||
@router.get("/getcurrentoperationid/", summary="获取当前操作ID", description="获取网络当前的操作ID")
|
||||
async def get_current_operation_id_endpoint(network: str = Query(..., description="管网名称(或数据库名称)")) -> int:
|
||||
"""
|
||||
获取当前操作ID
|
||||
@@ -32,7 +31,7 @@ async def get_current_operation_id_endpoint(network: str = Query(..., descriptio
|
||||
"""
|
||||
return get_current_operation(network)
|
||||
|
||||
@router.post("/undos", summary="撤销操作", description="撤销网络上最后的一个操作")
|
||||
@router.post("/undo/", summary="撤销操作", description="撤销网络上最后的一个操作")
|
||||
async def undo_endpoint(network: str = Query(..., description="管网名称(或数据库名称)")):
|
||||
"""
|
||||
撤销操作
|
||||
@@ -41,7 +40,7 @@ async def undo_endpoint(network: str = Query(..., description="管网名称(
|
||||
"""
|
||||
return execute_undo(network)
|
||||
|
||||
@router.post("/redos", summary="重做操作", description="重做网络上被撤销的操作")
|
||||
@router.post("/redo/", summary="重做操作", description="重做网络上被撤销的操作")
|
||||
async def redo_endpoint(network: str = Query(..., description="管网名称(或数据库名称)")):
|
||||
"""
|
||||
重做操作
|
||||
@@ -50,7 +49,7 @@ async def redo_endpoint(network: str = Query(..., description="管网名称(
|
||||
"""
|
||||
return execute_redo(network)
|
||||
|
||||
@router.get("/snapshots", summary="获取快照列表", description="获取网络中的所有快照")
|
||||
@router.get("/getsnapshots/", summary="获取快照列表", description="获取网络中的所有快照")
|
||||
async def list_snapshot_endpoint(network: str = Query(..., description="管网名称(或数据库名称)")) -> list[tuple[int, str]]:
|
||||
"""
|
||||
获取快照列表
|
||||
@@ -59,7 +58,7 @@ async def list_snapshot_endpoint(network: str = Query(..., description="管网
|
||||
"""
|
||||
return list_snapshot(network)
|
||||
|
||||
@router.get("/snapshots/existence", summary="检查快照是否存在", description="检查指定标签的快照是否存在")
|
||||
@router.get("/havesnapshot/", summary="检查快照是否存在", description="检查指定标签的快照是否存在")
|
||||
async def have_snapshot_endpoint(network: str = Query(..., description="管网名称(或数据库名称)"), tag: str = Query(..., description="快照标签")) -> bool:
|
||||
"""
|
||||
检查快照是否存在
|
||||
@@ -68,7 +67,7 @@ async def have_snapshot_endpoint(network: str = Query(..., description="管网
|
||||
"""
|
||||
return have_snapshot(network, tag)
|
||||
|
||||
@router.get("/snapshot-for-operations", summary="检查操作快照是否存在", description="检查指定操作ID的快照是否存在")
|
||||
@router.get("/havesnapshotforoperation/", summary="检查操作快照是否存在", description="检查指定操作ID的快照是否存在")
|
||||
async def have_snapshot_for_operation_endpoint(network: str = Query(..., description="管网名称(或数据库名称)"), operation: int = Query(..., description="操作ID")) -> bool:
|
||||
"""
|
||||
检查操作快照是否存在
|
||||
@@ -77,7 +76,7 @@ async def have_snapshot_for_operation_endpoint(network: str = Query(..., descrip
|
||||
"""
|
||||
return have_snapshot_for_operation(network, operation)
|
||||
|
||||
@router.get("/snapshot-for-current-operations", summary="检查当前操作快照是否存在", description="检查当前操作的快照是否存在")
|
||||
@router.get("/havesnapshotforcurrentoperation/", summary="检查当前操作快照是否存在", description="检查当前操作的快照是否存在")
|
||||
async def have_snapshot_for_current_operation_endpoint(network: str = Query(..., description="管网名称(或数据库名称)")) -> bool:
|
||||
"""
|
||||
检查当前操作快照是否存在
|
||||
@@ -86,7 +85,7 @@ async def have_snapshot_for_current_operation_endpoint(network: str = Query(...,
|
||||
"""
|
||||
return have_snapshot_for_current_operation(network)
|
||||
|
||||
@router.post("/snapshot-for-operations", summary="为操作创建快照", description="为指定的操作创建快照")
|
||||
@router.post("/takesnapshotforoperation/", summary="为操作创建快照", description="为指定的操作创建快照")
|
||||
async def take_snapshot_for_operation_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
operation: int = Query(..., description="操作ID"),
|
||||
@@ -99,7 +98,7 @@ async def take_snapshot_for_operation_endpoint(
|
||||
"""
|
||||
return take_snapshot_for_operation(network, operation, tag)
|
||||
|
||||
@router.post("/snapshot-for-current-operations", summary="为当前操作创建快照", description="为当前操作创建快照")
|
||||
@router.post("/takesnapshotforcurrentoperation", summary="为当前操作创建快照", description="为当前操作创建快照")
|
||||
async def take_snapshot_for_current_operation_endpoint(network: str = Query(..., description="管网名称(或数据库名称)"), tag: str = Query(..., description="快照标签")) -> None:
|
||||
"""
|
||||
为当前操作创建快照
|
||||
@@ -108,7 +107,17 @@ async def take_snapshot_for_current_operation_endpoint(network: str = Query(...,
|
||||
"""
|
||||
return take_snapshot_for_current_operation(network, tag)
|
||||
|
||||
@router.post("/snapshots", summary="创建快照", description="为网络创建一个快照")
|
||||
# 兼容旧拼写: takenapshotforcurrentoperation
|
||||
@router.post("/takenapshotforcurrentoperation", summary="为当前操作创建快照(兼容模式)", description="为当前操作创建快照(兼容旧的API路径)")
|
||||
async def take_snapshot_for_current_operation_legacy_endpoint(network: str = Query(..., description="管网名称(或数据库名称)"), tag: str = Query(..., description="快照标签")) -> None:
|
||||
"""
|
||||
为当前操作创建快照(兼容模式)
|
||||
|
||||
兼容旧的API路径,为网络当前操作创建一个快照
|
||||
"""
|
||||
return take_snapshot_for_current_operation(network, tag)
|
||||
|
||||
@router.post("/takesnapshot/", summary="创建快照", description="为网络创建一个快照")
|
||||
async def take_snapshot_endpoint(network: str = Query(..., description="管网名称(或数据库名称)"), tag: str = Query(..., description="快照标签")) -> None:
|
||||
"""
|
||||
创建快照
|
||||
@@ -117,7 +126,7 @@ async def take_snapshot_endpoint(network: str = Query(..., description="管网
|
||||
"""
|
||||
return take_snapshot(network, tag)
|
||||
|
||||
@router.patch("/snapshots", summary="选择快照", description="选择并恢复到指定的快照", response_model=None)
|
||||
@router.post("/picksnapshot/", summary="选择快照", description="选择并恢复到指定的快照", response_model=None)
|
||||
async def pick_snapshot_endpoint(network: str = Query(..., description="管网名称(或数据库名称)"), tag: str = Query(..., description="快照标签"), discard: bool = Query(False, description="是否丢弃当前更改")) -> ChangeSet:
|
||||
"""
|
||||
选择快照
|
||||
@@ -126,7 +135,7 @@ async def pick_snapshot_endpoint(network: str = Query(..., description="管网
|
||||
"""
|
||||
return pick_snapshot(network, tag, discard)
|
||||
|
||||
@router.patch("/operations", summary="选择操作", description="选择并恢复到指定的操作", response_model=None)
|
||||
@router.post("/pickoperation/", summary="选择操作", description="选择并恢复到指定的操作", response_model=None)
|
||||
async def pick_operation_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
operation: int = Query(..., description="操作ID"),
|
||||
@@ -139,12 +148,8 @@ async def pick_operation_endpoint(
|
||||
"""
|
||||
return pick_operation(network, operation, discard)
|
||||
|
||||
@router.post("/with-servers", summary="与服务器同步", description="将网络与服务器同步到指定操作", response_model=None)
|
||||
async def sync_with_server_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
operation: int = Query(..., description="目标操作ID"),
|
||||
_=Depends(require_permission(SIMULATION_RUN)),
|
||||
) -> ChangeSet:
|
||||
@router.get("/syncwithserver/", summary="与服务器同步", description="将网络与服务器同步到指定操作", response_model=None)
|
||||
async def sync_with_server_endpoint(network: str = Query(..., description="管网名称(或数据库名称)"), operation: int = Query(..., description="目标操作ID")) -> ChangeSet:
|
||||
"""
|
||||
与服务器同步
|
||||
|
||||
@@ -152,7 +157,7 @@ async def sync_with_server_endpoint(
|
||||
"""
|
||||
return sync_with_server(network, operation)
|
||||
|
||||
@router.post("/network-command-batches", summary="执行批量命令", description="执行多个网络操作命令", response_model=None)
|
||||
@router.post("/batch/", summary="执行批量命令", description="执行多个网络操作命令", response_model=None)
|
||||
async def execute_batch_commands_endpoint(network: str = Query(..., description="管网名称(或数据库名称)"), req: Request = None) -> ChangeSet:
|
||||
"""
|
||||
执行批量命令
|
||||
@@ -165,7 +170,7 @@ async def execute_batch_commands_endpoint(network: str = Query(..., description=
|
||||
rcs = execute_batch_commands(network, cs)
|
||||
return rcs
|
||||
|
||||
@router.post("/network-command-batches/compressed", summary="执行压缩批量命令", description="执行压缩的批量命令", response_model=None)
|
||||
@router.post("/compressedbatch/", summary="执行压缩批量命令", description="执行压缩的批量命令", response_model=None)
|
||||
async def execute_compressed_batch_commands_endpoint(
|
||||
network: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
req: Request = None
|
||||
@@ -180,7 +185,7 @@ async def execute_compressed_batch_commands_endpoint(
|
||||
cs.operations = jo_root["operations"]
|
||||
return execute_batch_command(network, cs)
|
||||
|
||||
@router.get("/restore-operations", summary="获取恢复操作ID", description="获取网络的恢复操作ID")
|
||||
@router.get("/getrestoreoperation/", summary="获取恢复操作ID", description="获取网络的恢复操作ID")
|
||||
async def get_restore_operation_endpoint(network: str = Query(..., description="管网名称(或数据库名称)")) -> int:
|
||||
"""
|
||||
获取恢复操作ID
|
||||
@@ -189,7 +194,7 @@ async def get_restore_operation_endpoint(network: str = Query(..., description="
|
||||
"""
|
||||
return get_restore_operation(network)
|
||||
|
||||
@router.patch("/restore-operations", summary="设置恢复操作ID", description="设置网络的恢复操作ID")
|
||||
@router.post("/setrestoreoperation/", summary="设置恢复操作ID", description="设置网络的恢复操作ID")
|
||||
async def set_restore_operation_endpoint(network: str = Query(..., description="管网名称(或数据库名称)"), operation: int = Query(..., description="操作ID")) -> None:
|
||||
"""
|
||||
设置恢复操作ID
|
||||
|
||||
@@ -8,7 +8,7 @@ from .dependencies import get_timescale_connection, get_postgres_connection
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.get("/timeseries/views/scada-simulations", summary="获取SCADA关联的模拟数据")
|
||||
@router.get("/composite/scada-simulation", summary="获取SCADA关联的模拟数据")
|
||||
async def get_scada_associated_simulation_data(
|
||||
start_time: datetime = Query(..., description="查询开始时间"),
|
||||
end_time: datetime = Query(..., description="查询结束时间"),
|
||||
@@ -73,7 +73,7 @@ async def get_scada_associated_simulation_data(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/timeseries/views/element-simulations", summary="获取管网元素的模拟数据")
|
||||
@router.get("/composite/element-simulation", summary="获取管网元素的模拟数据")
|
||||
async def get_feature_simulation_data(
|
||||
start_time: datetime = Query(..., description="查询开始时间"),
|
||||
end_time: datetime = Query(..., description="查询结束时间"),
|
||||
@@ -143,7 +143,7 @@ async def get_feature_simulation_data(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/timeseries/views/element-scada-readings", summary="获取管网元素关联的SCADA监测数据")
|
||||
@router.get("/composite/element-scada", summary="获取管网元素关联的SCADA监测数据")
|
||||
async def get_element_associated_scada_data(
|
||||
element_id: str = Query(..., description="管网元素ID(管道或节点)"),
|
||||
start_time: datetime = Query(..., description="查询开始时间"),
|
||||
@@ -185,7 +185,7 @@ async def get_element_associated_scada_data(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/timeseries/scada-cleaning-runs", summary="清洗SCADA监测数据")
|
||||
@router.post("/composite/clean-scada", summary="清洗SCADA监测数据")
|
||||
async def clean_scada_data(
|
||||
device_ids: str = Query(..., description="设备ID列表或 'all' 表示清洗所有设备"),
|
||||
start_time: datetime = Query(..., description="清洗数据的开始时间"),
|
||||
@@ -228,7 +228,7 @@ async def clean_scada_data(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/pipeline-health-predictions", summary="预测管道健康状况")
|
||||
@router.get("/composite/pipeline-health-prediction", summary="预测管道健康状况")
|
||||
async def predict_pipeline_health(
|
||||
query_time: datetime = Query(..., description="查询时间"),
|
||||
network_name: str = Query(..., description="管网名称(或数据库名称)"),
|
||||
|
||||
@@ -13,7 +13,7 @@ TIME_RANGE_START_DESC = f"时间范围开始时间。{TIME_WITH_TZ_DESC}"
|
||||
TIME_RANGE_END_DESC = f"时间范围结束时间。{TIME_WITH_TZ_DESC}"
|
||||
|
||||
|
||||
@router.post("/timeseries/realtime/links/batches", status_code=201, summary="批量插入实时管道数据")
|
||||
@router.post("/realtime/links/batch", status_code=201, summary="批量插入实时管道数据")
|
||||
async def insert_realtime_links(
|
||||
data: List[dict] = Body(..., description="管道数据列表,每项包含管道ID、时间戳等信息"),
|
||||
conn: AsyncConnection = Depends(get_timescale_connection)
|
||||
@@ -34,7 +34,7 @@ async def insert_realtime_links(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/timeseries/realtime/links",
|
||||
"/realtime/links",
|
||||
summary="查询实时管道数据",
|
||||
description="按时间范围查询实时管道数据。start_time 和 end_time 必须显式带时区;允许传 UTC+8,服务端会先归一化为 UTC 再执行查询。",
|
||||
)
|
||||
@@ -60,7 +60,7 @@ async def get_realtime_links(
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/timeseries/realtime/links",
|
||||
"/realtime/links",
|
||||
summary="删除实时管道数据",
|
||||
description="按时间范围删除实时管道数据。start_time 和 end_time 必须显式带时区;允许传 UTC+8,服务端按请求中的绝对时间删除对应 UTC 数据。",
|
||||
)
|
||||
@@ -85,7 +85,7 @@ async def delete_realtime_links(
|
||||
return {"message": "Deleted successfully"}
|
||||
|
||||
|
||||
@router.patch("/timeseries/realtime/links/{link_id}/field", summary="更新实时管道字段")
|
||||
@router.patch("/realtime/links/{link_id}/field", summary="更新实时管道字段")
|
||||
async def update_realtime_link_field(
|
||||
link_id: str = Path(..., description="管道ID"),
|
||||
time: datetime = Query(..., description=f"要更新记录的时间戳。{TIME_WITH_TZ_DESC}"),
|
||||
@@ -117,7 +117,7 @@ async def update_realtime_link_field(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/timeseries/realtime/nodes/batches", status_code=201, summary="批量插入实时节点数据")
|
||||
@router.post("/realtime/nodes/batch", status_code=201, summary="批量插入实时节点数据")
|
||||
async def insert_realtime_nodes(
|
||||
data: List[dict] = Body(..., description="节点数据列表,每项包含节点ID、时间戳等信息"),
|
||||
conn: AsyncConnection = Depends(get_timescale_connection)
|
||||
@@ -138,7 +138,7 @@ async def insert_realtime_nodes(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/timeseries/realtime/nodes",
|
||||
"/realtime/nodes",
|
||||
summary="查询实时节点数据",
|
||||
description="按时间范围查询实时节点数据。start_time 和 end_time 必须显式带时区;允许传 UTC+8,服务端会先归一化为 UTC 再执行查询。",
|
||||
)
|
||||
@@ -164,7 +164,7 @@ async def get_realtime_nodes(
|
||||
|
||||
|
||||
@router.delete(
|
||||
"/timeseries/realtime/nodes",
|
||||
"/realtime/nodes",
|
||||
summary="删除实时节点数据",
|
||||
description="按时间范围删除实时节点数据。start_time 和 end_time 必须显式带时区;允许传 UTC+8,服务端按请求中的绝对时间删除对应 UTC 数据。",
|
||||
)
|
||||
@@ -191,7 +191,7 @@ async def delete_realtime_nodes(
|
||||
|
||||
|
||||
|
||||
@router.post("/timeseries/realtime/simulation-results", status_code=201, summary="存储实时模拟结果")
|
||||
@router.post("/realtime/simulation/store", status_code=201, summary="存储实时模拟结果")
|
||||
async def store_realtime_simulation_result(
|
||||
node_result_list: List[dict] = Body(..., description="节点模拟结果列表"),
|
||||
link_result_list: List[dict] = Body(..., description="管道模拟结果列表"),
|
||||
@@ -218,7 +218,7 @@ async def store_realtime_simulation_result(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/timeseries/realtime/records",
|
||||
"/realtime/query/by-time-property",
|
||||
summary="按时间和属性查询实时数据",
|
||||
description="查询指定时间点的实时属性值。query_time 必须显式带时区;允许传 UTC+8,服务端会先归一化为 UTC 再执行查询。",
|
||||
)
|
||||
@@ -254,7 +254,7 @@ async def query_realtime_records_by_time_property(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/timeseries/realtime/simulation-results",
|
||||
"/realtime/query/by-id-time",
|
||||
summary="按ID和时间查询实时模拟数据",
|
||||
description="查询指定元素在某一时间点的实时模拟结果。query_time 必须显式带时区;允许传 UTC+8,服务端会先归一化为 UTC 再执行查询。",
|
||||
)
|
||||
|
||||
@@ -9,7 +9,7 @@ from .dependencies import get_timescale_connection
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/timeseries/scada-readings/batches", status_code=201, summary="批量插入SCADA监测数据")
|
||||
@router.post("/scada/batch", status_code=201, summary="批量插入SCADA监测数据")
|
||||
async def insert_scada_data(
|
||||
data: List[dict] = Body(..., description="SCADA设备监测数据列表"),
|
||||
conn: AsyncConnection = Depends(get_timescale_connection),
|
||||
@@ -29,7 +29,7 @@ async def insert_scada_data(
|
||||
return {"message": f"Inserted {len(data)} records"}
|
||||
|
||||
|
||||
@router.get("/timeseries/scada-readings", summary="按设备ID和时间范围查询SCADA数据")
|
||||
@router.get("/scada/by-ids-time-range", summary="按设备ID和时间范围查询SCADA数据")
|
||||
async def get_scada_by_ids_time_range(
|
||||
start_time: datetime = Query(..., description="查询开始时间"),
|
||||
end_time: datetime = Query(..., description="查询结束时间"),
|
||||
@@ -60,7 +60,7 @@ async def get_scada_by_ids_time_range(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/timeseries/scada-readings/fields", summary="按设备ID、字段和时间范围查询SCADA数据"
|
||||
"/scada/by-ids-field-time-range", summary="按设备ID、字段和时间范围查询SCADA数据"
|
||||
)
|
||||
async def get_scada_field_by_ids_time_range(
|
||||
start_time: datetime = Query(..., description="查询开始时间"),
|
||||
@@ -101,7 +101,7 @@ async def get_scada_field_by_ids_time_range(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.patch("/timeseries/scada-readings/{device_id}/field", summary="更新SCADA设备字段")
|
||||
@router.patch("/scada/{device_id}/field", summary="更新SCADA设备字段")
|
||||
async def update_scada_field(
|
||||
device_id: str = Path(..., description="设备ID"),
|
||||
time: datetime = Query(..., description="更新数据的时间戳"),
|
||||
@@ -133,7 +133,7 @@ async def update_scada_field(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/timeseries/scada-readings", summary="按设备ID和时间范围删除SCADA数据")
|
||||
@router.delete("/scada/by-id-time-range", summary="按设备ID和时间范围删除SCADA数据")
|
||||
async def delete_scada_data(
|
||||
device_id: str = Query(..., description="设备ID"),
|
||||
start_time: datetime = Query(..., description="删除开始时间"),
|
||||
|
||||
@@ -9,7 +9,7 @@ from .dependencies import get_timescale_connection
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
@router.post("/timeseries/schemes/links/batches", status_code=201, summary="批量插入方案管道数据")
|
||||
@router.post("/scheme/links/batch", status_code=201, summary="批量插入方案管道数据")
|
||||
async def insert_scheme_links(
|
||||
data: List[dict] = Body(..., description="方案管道数据列表"),
|
||||
conn: AsyncConnection = Depends(get_timescale_connection),
|
||||
@@ -29,7 +29,7 @@ async def insert_scheme_links(
|
||||
return {"message": f"Inserted {len(data)} records"}
|
||||
|
||||
|
||||
@router.get("/timeseries/schemes/links", summary="查询方案管道数据")
|
||||
@router.get("/scheme/links", summary="查询方案管道数据")
|
||||
async def get_scheme_links(
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
scheme_name: str = Query(..., description="方案名称"),
|
||||
@@ -56,7 +56,7 @@ async def get_scheme_links(
|
||||
)
|
||||
|
||||
|
||||
@router.get("/timeseries/schemes/links/{link_id}/field", summary="查询方案管道字段数据")
|
||||
@router.get("/scheme/links/{link_id}/field", summary="查询方案管道字段数据")
|
||||
async def get_scheme_link_field(
|
||||
link_id: str = Path(..., description="管道ID"),
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
@@ -93,7 +93,7 @@ async def get_scheme_link_field(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.patch("/timeseries/schemes/links/{link_id}/field", summary="更新方案管道字段")
|
||||
@router.patch("/scheme/links/{link_id}/field", summary="更新方案管道字段")
|
||||
async def update_scheme_link_field(
|
||||
link_id: str = Path(..., description="管道ID"),
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
@@ -131,7 +131,7 @@ async def update_scheme_link_field(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/timeseries/schemes/links", summary="删除方案管道数据")
|
||||
@router.delete("/scheme/links", summary="删除方案管道数据")
|
||||
async def delete_scheme_links(
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
scheme_name: str = Query(..., description="方案名称"),
|
||||
@@ -159,7 +159,7 @@ async def delete_scheme_links(
|
||||
return {"message": "Deleted successfully"}
|
||||
|
||||
|
||||
@router.post("/timeseries/schemes/nodes/batches", status_code=201, summary="批量插入方案节点数据")
|
||||
@router.post("/scheme/nodes/batch", status_code=201, summary="批量插入方案节点数据")
|
||||
async def insert_scheme_nodes(
|
||||
data: List[dict] = Body(..., description="方案节点数据列表"),
|
||||
conn: AsyncConnection = Depends(get_timescale_connection),
|
||||
@@ -179,7 +179,7 @@ async def insert_scheme_nodes(
|
||||
return {"message": f"Inserted {len(data)} records"}
|
||||
|
||||
|
||||
@router.get("/timeseries/schemes/nodes/{node_id}/field", summary="查询方案节点字段数据")
|
||||
@router.get("/scheme/nodes/{node_id}/field", summary="查询方案节点字段数据")
|
||||
async def get_scheme_node_field(
|
||||
node_id: str = Path(..., description="节点ID"),
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
@@ -216,7 +216,7 @@ async def get_scheme_node_field(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.patch("/timeseries/schemes/nodes/{node_id}/field", summary="更新方案节点字段")
|
||||
@router.patch("/scheme/nodes/{node_id}/field", summary="更新方案节点字段")
|
||||
async def update_scheme_node_field(
|
||||
node_id: str = Path(..., description="节点ID"),
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
@@ -254,7 +254,7 @@ async def update_scheme_node_field(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/timeseries/schemes/nodes", summary="删除方案节点数据")
|
||||
@router.delete("/scheme/nodes", summary="删除方案节点数据")
|
||||
async def delete_scheme_nodes(
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
scheme_name: str = Query(..., description="方案名称"),
|
||||
@@ -282,7 +282,7 @@ async def delete_scheme_nodes(
|
||||
return {"message": "Deleted successfully"}
|
||||
|
||||
|
||||
@router.post("/timeseries/schemes/simulation-results", status_code=201, summary="存储方案模拟结果")
|
||||
@router.post("/scheme/simulation/store", status_code=201, summary="存储方案模拟结果")
|
||||
async def store_scheme_simulation_result(
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
scheme_name: str = Query(..., description="方案名称"),
|
||||
@@ -318,7 +318,7 @@ async def store_scheme_simulation_result(
|
||||
|
||||
|
||||
@router.get(
|
||||
"/timeseries/schemes/records", summary="按方案、时间和属性查询数据"
|
||||
"/scheme/query/by-scheme-time-property", summary="按方案、时间和属性查询数据"
|
||||
)
|
||||
async def query_scheme_records_by_scheme_time_property(
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
@@ -355,7 +355,7 @@ async def query_scheme_records_by_scheme_time_property(
|
||||
raise HTTPException(status_code=400, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/timeseries/schemes/simulation-results", summary="按ID和时间查询方案模拟数据")
|
||||
@router.get("/scheme/query/by-id-time", summary="按ID和时间查询方案模拟数据")
|
||||
async def query_scheme_simulation_by_id_time(
|
||||
scheme_type: str = Query(..., description="方案类型"),
|
||||
scheme_name: str = Query(..., description="方案名称"),
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
from fastapi import APIRouter, Request, Query
|
||||
from typing import Any, List, Dict, Union
|
||||
from app.services.tjnetwork import Any, get_all_users, get_user, get_user_schema
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
###########################################################
|
||||
# user 39
|
||||
###########################################################
|
||||
|
||||
@router.get("/getuserschema/", summary="获取用户模式", description="获取指定网络的用户模式定义")
|
||||
async def fastapi_get_user_schema(network: str = Query(..., description="管网名称(或数据库名称)")) -> dict[str, dict[Any, Any]]:
|
||||
"""
|
||||
获取用户模式定义
|
||||
|
||||
返回指定网络的用户模式结构定义
|
||||
"""
|
||||
return get_user_schema(network)
|
||||
|
||||
@router.get("/getuser/", summary="获取单个用户", description="获取指定网络中的单个用户信息")
|
||||
async def fastapi_get_user(network: str = Query(..., description="管网名称(或数据库名称)"), user_name: str = Query(..., description="用户名")) -> dict[Any, Any]:
|
||||
"""
|
||||
获取用户信息
|
||||
|
||||
返回指定网络中指定用户名的详细信息
|
||||
"""
|
||||
return get_user(network, user_name)
|
||||
|
||||
@router.get("/getallusers/", summary="获取所有用户", description="获取指定网络的所有用户列表")
|
||||
async def fastapi_get_all_users(network: str = Query(..., description="管网名称(或数据库名称)")) -> list[dict[Any, Any]]:
|
||||
"""
|
||||
获取所有用户列表
|
||||
|
||||
返回指定网络中所有用户的信息
|
||||
"""
|
||||
return get_all_users(network)
|
||||
@@ -13,7 +13,7 @@ router = APIRouter()
|
||||
|
||||
|
||||
@router.post(
|
||||
"/web-searches",
|
||||
"/web-search",
|
||||
summary="Web Search",
|
||||
description="调用 Bocha Web Search API 获取实时网页搜索结果",
|
||||
)
|
||||
|
||||
@@ -1,391 +0,0 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import re
|
||||
from collections.abc import Iterable
|
||||
from copy import copy
|
||||
from functools import wraps
|
||||
from typing import Any, Generic, TypeVar, get_args, get_origin
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.routing import APIRoute
|
||||
from pydantic import BaseModel, JsonValue, create_model
|
||||
from starlette.responses import Response
|
||||
|
||||
from app.api.problem_details import ProblemDetails
|
||||
from app.api.v1.router import api_router as handler_api_router
|
||||
from app.auth.metadata_dependencies import get_current_metadata_user
|
||||
from app.auth.project_dependencies import ProjectContext, get_project_context
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class Page(BaseModel, Generic[T]):
|
||||
items: list[T]
|
||||
total: int
|
||||
limit: int
|
||||
offset: int
|
||||
|
||||
|
||||
_NAME_IS_NETWORK = {
|
||||
"pressure_sensor_placement_sensitivity_endpoint",
|
||||
"pressure_sensor_placement_kmeans_endpoint",
|
||||
}
|
||||
_DERIVE_USERNAME = {
|
||||
"pressure_sensor_placement_sensitivity_endpoint": "username",
|
||||
"pressure_sensor_placement_kmeans_endpoint": "username",
|
||||
"fastapi_pressure_sensor_placement": "user_name",
|
||||
}
|
||||
_PUBLIC_PARAMETER_RENAMES = {
|
||||
"burst_ID": "burst_id",
|
||||
"drainage_node_ID": "drainage_node_id",
|
||||
}
|
||||
_MODEL_NAME_IS_NETWORK = {"RunSimulationManuallyByDate"}
|
||||
_MODEL_USERNAME_FROM_AUTH: set[str] = set()
|
||||
|
||||
|
||||
def _clean_name(name: str) -> str:
|
||||
for prefix in ("fastapi_", "fast_"):
|
||||
if name.startswith(prefix):
|
||||
name = name[len(prefix) :]
|
||||
break
|
||||
if name.endswith("_endpoint"):
|
||||
name = name[: -len("_endpoint")]
|
||||
return name
|
||||
|
||||
|
||||
def _rest_body_model(annotation):
|
||||
if not inspect.isclass(annotation) or not issubclass(annotation, BaseModel):
|
||||
return None
|
||||
project_fields = {
|
||||
name
|
||||
for name in ("network", "network_name")
|
||||
if name in annotation.model_fields
|
||||
}
|
||||
if annotation.__name__ in _MODEL_NAME_IS_NETWORK and "name" in annotation.model_fields:
|
||||
project_fields.add("name")
|
||||
username_fields = (
|
||||
{
|
||||
name
|
||||
for name in ("username", "user_name")
|
||||
if name in annotation.model_fields
|
||||
}
|
||||
if annotation.__name__ in _MODEL_USERNAME_FROM_AUTH
|
||||
else set()
|
||||
)
|
||||
excluded_fields = project_fields | username_fields
|
||||
if not excluded_fields:
|
||||
return None
|
||||
|
||||
public_fields = {
|
||||
name: (field.annotation, copy(field))
|
||||
for name, field in annotation.model_fields.items()
|
||||
if name not in excluded_fields
|
||||
}
|
||||
public_model = create_model(
|
||||
f"{annotation.__name__}Rest",
|
||||
__module__=annotation.__module__,
|
||||
**public_fields,
|
||||
)
|
||||
return annotation, public_model, project_fields, username_fields
|
||||
|
||||
|
||||
def _with_header_project_context(endpoint, route_name: str):
|
||||
signature = inspect.signature(endpoint)
|
||||
network_parameters = [
|
||||
name for name in ("network", "network_name") if name in signature.parameters
|
||||
]
|
||||
if route_name in _NAME_IS_NETWORK and "name" in signature.parameters:
|
||||
network_parameters.append("name")
|
||||
username_parameter = _DERIVE_USERNAME.get(route_name)
|
||||
parameter_renames = {
|
||||
internal: public
|
||||
for internal, public in _PUBLIC_PARAMETER_RENAMES.items()
|
||||
if internal in signature.parameters
|
||||
}
|
||||
body_models = {
|
||||
name: body_model
|
||||
for name, parameter in signature.parameters.items()
|
||||
if (body_model := _rest_body_model(parameter.annotation)) is not None
|
||||
}
|
||||
model_has_username = any(model[3] for model in body_models.values())
|
||||
if (
|
||||
not network_parameters
|
||||
and not username_parameter
|
||||
and not parameter_renames
|
||||
and not body_models
|
||||
):
|
||||
return endpoint
|
||||
|
||||
existing_context_parameter = next(
|
||||
(
|
||||
name
|
||||
for name, parameter in signature.parameters.items()
|
||||
if parameter.annotation is ProjectContext
|
||||
),
|
||||
None,
|
||||
)
|
||||
injected_context_name = existing_context_parameter or "_rest_project_context"
|
||||
injected_user_name = "_rest_current_user"
|
||||
|
||||
@wraps(endpoint)
|
||||
async def wrapper(*args, **kwargs):
|
||||
project_context = kwargs.get(injected_context_name)
|
||||
if not isinstance(project_context, ProjectContext):
|
||||
raise RuntimeError("REST project context was not resolved")
|
||||
if not existing_context_parameter:
|
||||
kwargs.pop(injected_context_name, None)
|
||||
for parameter_name in network_parameters:
|
||||
kwargs[parameter_name] = project_context.project_code
|
||||
if username_parameter:
|
||||
kwargs[username_parameter] = kwargs[injected_user_name].username
|
||||
kwargs.pop(injected_user_name, None)
|
||||
for internal_name, public_name in parameter_renames.items():
|
||||
kwargs[internal_name] = kwargs.pop(public_name)
|
||||
for parameter_name, (
|
||||
original_model,
|
||||
_public_model,
|
||||
project_fields,
|
||||
username_fields,
|
||||
) in body_models.items():
|
||||
data = kwargs[parameter_name].model_dump()
|
||||
data.update(
|
||||
{field_name: project_context.project_code for field_name in project_fields}
|
||||
)
|
||||
if username_fields:
|
||||
current_user = kwargs[injected_user_name]
|
||||
data.update(
|
||||
{field_name: current_user.username for field_name in username_fields}
|
||||
)
|
||||
kwargs[parameter_name] = original_model.model_validate(data)
|
||||
if model_has_username:
|
||||
kwargs.pop(injected_user_name, None)
|
||||
result = endpoint(*args, **kwargs)
|
||||
if inspect.isawaitable(result):
|
||||
return await result
|
||||
return result
|
||||
|
||||
parameters = []
|
||||
for name, parameter in signature.parameters.items():
|
||||
if name in network_parameters or name == username_parameter:
|
||||
continue
|
||||
public_name = parameter_renames.get(name, name)
|
||||
if public_name != name:
|
||||
default = copy(parameter.default)
|
||||
default.alias = public_name
|
||||
default.validation_alias = public_name
|
||||
default.serialization_alias = public_name
|
||||
parameter = parameter.replace(name=public_name, default=default)
|
||||
if name in body_models:
|
||||
parameter = parameter.replace(annotation=body_models[name][1])
|
||||
parameters.append(parameter)
|
||||
if not existing_context_parameter:
|
||||
parameters.append(
|
||||
inspect.Parameter(
|
||||
injected_context_name,
|
||||
kind=inspect.Parameter.KEYWORD_ONLY,
|
||||
annotation=ProjectContext,
|
||||
default=Depends(get_project_context),
|
||||
)
|
||||
)
|
||||
if username_parameter or model_has_username:
|
||||
parameters.append(
|
||||
inspect.Parameter(
|
||||
injected_user_name,
|
||||
kind=inspect.Parameter.KEYWORD_ONLY,
|
||||
default=Depends(get_current_metadata_user),
|
||||
)
|
||||
)
|
||||
wrapper.__signature__ = signature.replace(parameters=parameters)
|
||||
return wrapper
|
||||
|
||||
|
||||
def _with_pagination(endpoint):
|
||||
signature = inspect.signature(endpoint)
|
||||
handler_limit_parameter = "limit" if "limit" in signature.parameters else None
|
||||
handler_offset_parameter = next(
|
||||
(
|
||||
parameter_name
|
||||
for parameter_name in ("offset", "skip")
|
||||
if parameter_name in signature.parameters
|
||||
),
|
||||
None,
|
||||
)
|
||||
handler_handles_pagination = bool(
|
||||
handler_limit_parameter or handler_offset_parameter
|
||||
)
|
||||
|
||||
@wraps(endpoint)
|
||||
async def wrapper(*args, **kwargs):
|
||||
if handler_handles_pagination:
|
||||
limit = kwargs.get(handler_limit_parameter, 0)
|
||||
offset = kwargs.get(handler_offset_parameter, 0)
|
||||
else:
|
||||
limit = kwargs.pop("_rest_limit")
|
||||
offset = kwargs.pop("_rest_offset")
|
||||
result = endpoint(*args, **kwargs)
|
||||
if inspect.isawaitable(result):
|
||||
result = await result
|
||||
if not isinstance(result, list):
|
||||
return result
|
||||
if handler_handles_pagination:
|
||||
return Page(
|
||||
items=result,
|
||||
total=offset + len(result),
|
||||
limit=limit or len(result),
|
||||
offset=offset,
|
||||
)
|
||||
return Page(
|
||||
items=result[offset : offset + limit],
|
||||
total=len(result),
|
||||
limit=limit,
|
||||
offset=offset,
|
||||
)
|
||||
|
||||
parameters = list(signature.parameters.values())
|
||||
if not handler_handles_pagination:
|
||||
parameters.extend(
|
||||
[
|
||||
inspect.Parameter(
|
||||
"_rest_limit",
|
||||
kind=inspect.Parameter.KEYWORD_ONLY,
|
||||
annotation=int,
|
||||
default=Query(100, ge=1, le=1000, alias="limit"),
|
||||
),
|
||||
inspect.Parameter(
|
||||
"_rest_offset",
|
||||
kind=inspect.Parameter.KEYWORD_ONLY,
|
||||
annotation=int,
|
||||
default=Query(0, ge=0, alias="offset"),
|
||||
),
|
||||
]
|
||||
)
|
||||
wrapper.__signature__ = signature.replace(parameters=parameters)
|
||||
return wrapper
|
||||
|
||||
|
||||
def _with_jsonable_response(endpoint):
|
||||
"""Normalize untyped handler results before JsonValue validation."""
|
||||
|
||||
@wraps(endpoint)
|
||||
async def wrapper(*args, **kwargs):
|
||||
result = endpoint(*args, **kwargs)
|
||||
if inspect.isawaitable(result):
|
||||
result = await result
|
||||
if isinstance(result, Response):
|
||||
return result
|
||||
return jsonable_encoder(result)
|
||||
|
||||
return wrapper
|
||||
|
||||
|
||||
def _adapt_route(route: APIRoute) -> APIRoute:
|
||||
methods = route.methods or set()
|
||||
if len(methods) != 1:
|
||||
raise RuntimeError(
|
||||
f"REST route {route.name!r} must declare exactly one HTTP method"
|
||||
)
|
||||
method = next(iter(methods))
|
||||
responses = dict(route.responses or {})
|
||||
for status_code, description in (
|
||||
(401, "Authentication required"),
|
||||
(403, "Insufficient permission"),
|
||||
(404, "Resource not found"),
|
||||
(409, "Resource conflict"),
|
||||
(422, "Validation error"),
|
||||
(503, "Dependency unavailable"),
|
||||
):
|
||||
responses.setdefault(
|
||||
status_code,
|
||||
{"model": ProblemDetails, "description": description},
|
||||
)
|
||||
|
||||
endpoint = _with_header_project_context(route.endpoint, route.name)
|
||||
response_model = route.response_model
|
||||
has_untyped_response = response_model is None
|
||||
if has_untyped_response:
|
||||
endpoint = _with_jsonable_response(endpoint)
|
||||
if get_origin(response_model) is list:
|
||||
item_type = get_args(response_model)[0] if get_args(response_model) else JsonValue
|
||||
response_model = Page[item_type]
|
||||
endpoint = _with_pagination(endpoint)
|
||||
|
||||
clean_name = _clean_name(route.name)
|
||||
creates_resource = clean_name.startswith(
|
||||
("add_", "create_", "copy_", "import_", "insert_", "store_", "take_", "upload_")
|
||||
) or route.name == "fastapi_pressure_sensor_placement"
|
||||
status_code = (
|
||||
204
|
||||
if method == "DELETE"
|
||||
else 201
|
||||
if method == "POST" and creates_resource
|
||||
else route.status_code
|
||||
)
|
||||
if status_code == 204:
|
||||
response_model = None
|
||||
elif response_model is None:
|
||||
response_model = JsonValue
|
||||
|
||||
return APIRoute(
|
||||
path=route.path,
|
||||
endpoint=endpoint,
|
||||
response_model=response_model,
|
||||
status_code=status_code,
|
||||
tags=route.tags,
|
||||
dependencies=route.dependencies,
|
||||
summary=route.summary,
|
||||
description=route.description,
|
||||
response_description=route.response_description,
|
||||
responses=responses,
|
||||
deprecated=False,
|
||||
name=route.name,
|
||||
methods={method},
|
||||
operation_id=f"{method.lower()}_{re.sub(r'[^a-z0-9]+', '_', route.path).strip('_')}",
|
||||
response_model_include=route.response_model_include,
|
||||
response_model_exclude=route.response_model_exclude,
|
||||
response_model_by_alias=route.response_model_by_alias,
|
||||
response_model_exclude_unset=route.response_model_exclude_unset,
|
||||
response_model_exclude_defaults=route.response_model_exclude_defaults,
|
||||
response_model_exclude_none=route.response_model_exclude_none,
|
||||
include_in_schema=route.include_in_schema,
|
||||
response_class=route.response_class,
|
||||
callbacks=route.callbacks,
|
||||
openapi_extra=route.openapi_extra,
|
||||
)
|
||||
|
||||
|
||||
def build_rest_router(routes: Iterable[Any]) -> APIRouter:
|
||||
router = APIRouter()
|
||||
seen: dict[tuple[str, str], APIRoute] = {}
|
||||
operation_ids: set[str] = set()
|
||||
|
||||
for route in routes:
|
||||
if not isinstance(route, APIRoute):
|
||||
continue
|
||||
|
||||
methods = route.methods or set()
|
||||
if len(methods) != 1:
|
||||
raise RuntimeError(
|
||||
f"REST route {route.name!r} must declare exactly one HTTP method"
|
||||
)
|
||||
method = next(iter(methods))
|
||||
key = (method, route.path)
|
||||
if key in seen:
|
||||
previous = seen[key]
|
||||
raise RuntimeError(
|
||||
"REST route collision for "
|
||||
f"{method} {route.path}: {previous.name!r} and {route.name!r}."
|
||||
)
|
||||
|
||||
adapted = _adapt_route(route)
|
||||
if adapted.operation_id in operation_ids:
|
||||
adapted.operation_id = f"{adapted.operation_id}_{route.name}"
|
||||
seen[key] = route
|
||||
operation_ids.add(adapted.operation_id or "")
|
||||
router.routes.append(adapted)
|
||||
|
||||
return router
|
||||
|
||||
|
||||
api_router = build_rest_router(handler_api_router.routes)
|
||||
+86
-200
@@ -1,230 +1,116 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
|
||||
from fastapi import APIRouter
|
||||
from app.api.v1.endpoints import (
|
||||
access,
|
||||
admin_metadata,
|
||||
agent_auth,
|
||||
audit,
|
||||
project,
|
||||
simulation,
|
||||
scada,
|
||||
extension,
|
||||
snapshots,
|
||||
users,
|
||||
schemes,
|
||||
misc,
|
||||
risk,
|
||||
cache,
|
||||
leakage,
|
||||
burst_detection,
|
||||
burst_location,
|
||||
cache,
|
||||
extension,
|
||||
geocoding,
|
||||
leakage,
|
||||
audit, # 新增:审计日志
|
||||
meta,
|
||||
misc,
|
||||
model_import,
|
||||
project,
|
||||
project_data,
|
||||
risk,
|
||||
scada,
|
||||
schemes,
|
||||
sensor_placement,
|
||||
simulation,
|
||||
snapshots,
|
||||
web_search,
|
||||
geocoding,
|
||||
)
|
||||
from app.api.v1.endpoints.network import (
|
||||
general,
|
||||
junctions,
|
||||
reservoirs,
|
||||
tanks,
|
||||
pipes,
|
||||
pumps,
|
||||
valves,
|
||||
tags,
|
||||
demands,
|
||||
geometry,
|
||||
regions,
|
||||
)
|
||||
from app.api.v1.endpoints.components import (
|
||||
controls,
|
||||
curves,
|
||||
options,
|
||||
patterns,
|
||||
controls,
|
||||
options,
|
||||
quality,
|
||||
visuals,
|
||||
)
|
||||
from app.api.v1.endpoints.network import (
|
||||
demands,
|
||||
general,
|
||||
geometry,
|
||||
junctions,
|
||||
pipes,
|
||||
pumps,
|
||||
regions,
|
||||
reservoirs,
|
||||
tags,
|
||||
tanks,
|
||||
valves,
|
||||
)
|
||||
|
||||
from app.api.v1.endpoints import project_data
|
||||
from app.api.v1.endpoints.timeseries import (
|
||||
composite as ts_composite,
|
||||
realtime as ts_realtime,
|
||||
scada as ts_scada,
|
||||
scheme as ts_scheme,
|
||||
)
|
||||
from app.auth.permissions import (
|
||||
BURST_RUN,
|
||||
OPTIMIZATION_RUN,
|
||||
RISK_RUN,
|
||||
SCADA_CLEAN,
|
||||
SCADA_VIEW,
|
||||
SIMULATION_RUN,
|
||||
SIMULATION_VIEW,
|
||||
WEBGIS_EDIT,
|
||||
WEBGIS_VIEW,
|
||||
require_method_permission,
|
||||
require_permission,
|
||||
scada as ts_scada,
|
||||
composite as ts_composite,
|
||||
)
|
||||
|
||||
api_router = APIRouter()
|
||||
|
||||
webgis_access = Depends(
|
||||
require_method_permission(
|
||||
read_permission=WEBGIS_VIEW,
|
||||
write_permission=WEBGIS_EDIT,
|
||||
)
|
||||
)
|
||||
scada_access = Depends(
|
||||
require_method_permission(
|
||||
read_permission=SCADA_VIEW,
|
||||
write_permission=SCADA_CLEAN,
|
||||
)
|
||||
)
|
||||
simulation_access = Depends(
|
||||
require_method_permission(
|
||||
read_permission=SIMULATION_VIEW,
|
||||
write_permission=SIMULATION_RUN,
|
||||
)
|
||||
)
|
||||
|
||||
webgis_view_access = Depends(require_permission(WEBGIS_VIEW))
|
||||
simulation_run_access = Depends(require_permission(SIMULATION_RUN))
|
||||
burst_run_access = Depends(require_permission(BURST_RUN))
|
||||
risk_run_access = Depends(require_permission(RISK_RUN))
|
||||
optimization_run_access = Depends(require_permission(OPTIMIZATION_RUN))
|
||||
|
||||
# Core services
|
||||
api_router.include_router(access.router, tags=["Access Control"])
|
||||
# Core Services
|
||||
api_router.include_router(agent_auth.router, tags=["Agent Auth"])
|
||||
api_router.include_router(
|
||||
admin_metadata.router,
|
||||
tags=["Metadata Admin"],
|
||||
admin_metadata.router, prefix="/admin", tags=["Metadata Admin"]
|
||||
)
|
||||
api_router.include_router(model_import.router, tags=["Model Administration"])
|
||||
api_router.include_router(audit.router, tags=["Audit Logs"])
|
||||
api_router.include_router(audit.router, prefix="/audit", tags=["Audit Logs"]) # 新增
|
||||
api_router.include_router(meta.router, tags=["Metadata"])
|
||||
api_router.include_router(project.router, tags=["Project"])
|
||||
|
||||
# Network Elements (Node/Link Types)
|
||||
api_router.include_router(general.router, tags=["Network General"])
|
||||
api_router.include_router(junctions.router, tags=["Junctions"])
|
||||
api_router.include_router(reservoirs.router, tags=["Reservoirs"])
|
||||
api_router.include_router(tanks.router, tags=["Tanks"])
|
||||
api_router.include_router(pipes.router, tags=["Pipes"])
|
||||
api_router.include_router(pumps.router, tags=["Pumps"])
|
||||
api_router.include_router(valves.router, tags=["Valves"])
|
||||
|
||||
# Network Features
|
||||
api_router.include_router(tags.router, tags=["Tags"])
|
||||
api_router.include_router(demands.router, tags=["Demands"])
|
||||
api_router.include_router(geometry.router, tags=["Geometry & Coordinates"])
|
||||
api_router.include_router(regions.router, tags=["Regions & DMAs"])
|
||||
|
||||
# Components & Controls
|
||||
api_router.include_router(curves.router, tags=["Curves"])
|
||||
api_router.include_router(patterns.router, tags=["Patterns"])
|
||||
api_router.include_router(controls.router, tags=["Controls & Rules"])
|
||||
api_router.include_router(options.router, tags=["Options"])
|
||||
api_router.include_router(quality.router, tags=["Quality"])
|
||||
api_router.include_router(visuals.router, tags=["Visuals"])
|
||||
|
||||
# Simulation & Data
|
||||
api_router.include_router(simulation.router, tags=["Simulation Control"])
|
||||
api_router.include_router(scada.router)
|
||||
api_router.include_router(snapshots.router, tags=["Snapshots"])
|
||||
api_router.include_router(users.router, tags=["Users"])
|
||||
api_router.include_router(schemes.router, tags=["Schemes"])
|
||||
api_router.include_router(misc.router, tags=["Misc"])
|
||||
api_router.include_router(risk.router, tags=["Risk"])
|
||||
api_router.include_router(cache.router, tags=["Cache"])
|
||||
api_router.include_router(web_search.router, tags=["Web Search"])
|
||||
api_router.include_router(geocoding.router, tags=["Geocoding"])
|
||||
api_router.include_router(leakage.router, prefix="/leakage", tags=["Leakage"])
|
||||
api_router.include_router(
|
||||
project.router,
|
||||
tags=["Project"],
|
||||
dependencies=[webgis_access],
|
||||
burst_detection.router, prefix="/burst-detection", tags=["Burst Detection"]
|
||||
)
|
||||
api_router.include_router(
|
||||
burst_location.router, prefix="/burst-location", tags=["Burst Location"]
|
||||
)
|
||||
|
||||
# WebGIS data
|
||||
for endpoint_router, tag in (
|
||||
(general.router, "Network General"),
|
||||
(junctions.router, "Junctions"),
|
||||
(reservoirs.router, "Reservoirs"),
|
||||
(tanks.router, "Tanks"),
|
||||
(pipes.router, "Pipes"),
|
||||
(pumps.router, "Pumps"),
|
||||
(valves.router, "Valves"),
|
||||
(tags.router, "Tags"),
|
||||
(demands.router, "Demands"),
|
||||
(geometry.router, "Geometry & Coordinates"),
|
||||
(regions.router, "Regions & DMAs"),
|
||||
(curves.router, "Curves"),
|
||||
(patterns.router, "Patterns"),
|
||||
(controls.router, "Controls & Rules"),
|
||||
(options.router, "Options"),
|
||||
(quality.router, "Quality"),
|
||||
(visuals.router, "Visuals"),
|
||||
):
|
||||
api_router.include_router(
|
||||
endpoint_router,
|
||||
tags=[tag],
|
||||
dependencies=[webgis_access],
|
||||
)
|
||||
# TimescaleDB Data Access
|
||||
api_router.include_router(ts_realtime.router, tags=["TimescaleDB - Realtime"])
|
||||
api_router.include_router(ts_scheme.router, tags=["TimescaleDB - Scheme"])
|
||||
api_router.include_router(ts_scada.router, tags=["TimescaleDB - SCADA"])
|
||||
api_router.include_router(ts_composite.router, tags=["TimescaleDB - Composite"])
|
||||
|
||||
# Simulation and analysis
|
||||
api_router.include_router(
|
||||
simulation.router,
|
||||
tags=["Simulation Control"],
|
||||
dependencies=[simulation_run_access],
|
||||
)
|
||||
api_router.include_router(scada.router, dependencies=[scada_access])
|
||||
api_router.include_router(
|
||||
sensor_placement.router,
|
||||
tags=["Sensor Placement"],
|
||||
dependencies=[optimization_run_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
snapshots.router,
|
||||
tags=["Snapshots"],
|
||||
dependencies=[simulation_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
schemes.router,
|
||||
tags=["Schemes"],
|
||||
dependencies=[simulation_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
misc.router,
|
||||
tags=["Misc"],
|
||||
dependencies=[webgis_view_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
risk.router,
|
||||
tags=["Risk"],
|
||||
dependencies=[risk_run_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
cache.router,
|
||||
tags=["Cache"],
|
||||
dependencies=[simulation_run_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
web_search.router,
|
||||
tags=["Web Search"],
|
||||
dependencies=[webgis_view_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
geocoding.router,
|
||||
tags=["Geocoding"],
|
||||
dependencies=[webgis_view_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
leakage.router,
|
||||
tags=["Leakage"],
|
||||
dependencies=[burst_run_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
burst_detection.router,
|
||||
tags=["Burst Detection"],
|
||||
dependencies=[burst_run_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
burst_location.router,
|
||||
tags=["Burst Location"],
|
||||
dependencies=[burst_run_access],
|
||||
)
|
||||
# Project Data (PostgreSQL)
|
||||
api_router.include_router(project_data.router, tags=["Project Data"])
|
||||
|
||||
# TimescaleDB data
|
||||
for endpoint_router, tag in (
|
||||
(ts_realtime.router, "TimescaleDB - Realtime"),
|
||||
(ts_scheme.router, "TimescaleDB - Scheme"),
|
||||
):
|
||||
api_router.include_router(
|
||||
endpoint_router,
|
||||
tags=[tag],
|
||||
dependencies=[simulation_access],
|
||||
)
|
||||
|
||||
for endpoint_router, tag in (
|
||||
(ts_scada.router, "TimescaleDB - SCADA"),
|
||||
(ts_composite.router, "TimescaleDB - Composite"),
|
||||
):
|
||||
api_router.include_router(
|
||||
endpoint_router,
|
||||
tags=[tag],
|
||||
dependencies=[scada_access],
|
||||
)
|
||||
|
||||
api_router.include_router(
|
||||
project_data.router,
|
||||
tags=["Project Data"],
|
||||
dependencies=[webgis_view_access],
|
||||
)
|
||||
api_router.include_router(
|
||||
extension.router,
|
||||
tags=["Extension"],
|
||||
dependencies=[webgis_access],
|
||||
)
|
||||
# Extension
|
||||
api_router.include_router(extension.router, tags=["Extension"])
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import time
|
||||
# import logging
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
@@ -23,22 +23,12 @@ def _decode_keycloak_token(token: str) -> dict:
|
||||
|
||||
key = settings.KEYCLOAK_PUBLIC_KEY.replace("\\n", "\n")
|
||||
|
||||
payload = jwt.decode(
|
||||
return jwt.decode(
|
||||
token,
|
||||
key,
|
||||
algorithms=[settings.KEYCLOAK_ALGORITHM],
|
||||
audience=settings.KEYCLOAK_AUDIENCE or None,
|
||||
)
|
||||
if settings.KEYCLOAK_ACCESS_TOKEN_MAX_AGE_SECONDS <= 0:
|
||||
return payload
|
||||
|
||||
issued_at = payload.get("iat")
|
||||
if not isinstance(issued_at, (int, float)) or (
|
||||
time.time() >= issued_at + settings.KEYCLOAK_ACCESS_TOKEN_MAX_AGE_SECONDS
|
||||
):
|
||||
raise JWTError("Keycloak access token is older than the allowed maximum age")
|
||||
|
||||
return payload
|
||||
|
||||
|
||||
async def get_current_keycloak_payload(
|
||||
@@ -83,18 +73,14 @@ async def get_current_keycloak_sub(
|
||||
) from exc
|
||||
|
||||
|
||||
def get_keycloak_preferred_username(payload: dict) -> str:
|
||||
username = payload.get("preferred_username")
|
||||
if not username:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Missing preferred_username claim",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return str(username)
|
||||
|
||||
|
||||
async def get_current_keycloak_username(
|
||||
payload: dict = Depends(get_current_keycloak_payload),
|
||||
) -> str:
|
||||
return get_keycloak_preferred_username(payload)
|
||||
username = payload.get("preferred_username") or payload.get("username")
|
||||
if not username:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Missing username claim",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
return str(username)
|
||||
|
||||
@@ -6,10 +6,7 @@ from fastapi import Depends, HTTPException, status
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.auth.keycloak_dependencies import (
|
||||
get_current_keycloak_payload,
|
||||
get_keycloak_preferred_username,
|
||||
)
|
||||
from app.auth.keycloak_dependencies import get_current_keycloak_payload
|
||||
from app.infra.db.metadb.database import get_metadata_session
|
||||
from app.infra.db.metadb.repositories.metadata_repository import MetadataRepository
|
||||
|
||||
@@ -41,6 +38,11 @@ def _keycloak_sub_from_payload(payload: dict) -> UUID:
|
||||
) from exc
|
||||
|
||||
|
||||
def _username_from_payload(payload: dict) -> str | None:
|
||||
username = payload.get("preferred_username") or payload.get("username")
|
||||
return str(username) if username else None
|
||||
|
||||
|
||||
def _email_from_payload(payload: dict) -> str | None:
|
||||
email = payload.get("email")
|
||||
return str(email) if email else None
|
||||
@@ -51,7 +53,6 @@ async def get_current_metadata_user(
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
):
|
||||
keycloak_sub = _keycloak_sub_from_payload(keycloak_payload)
|
||||
username = get_keycloak_preferred_username(keycloak_payload)
|
||||
try:
|
||||
user = await metadata_repo.get_user_by_keycloak_id(keycloak_sub)
|
||||
except SQLAlchemyError as exc:
|
||||
@@ -61,7 +62,7 @@ async def get_current_metadata_user(
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Metadata database is unavailable",
|
||||
detail=f"Metadata database error: {exc}",
|
||||
) from exc
|
||||
if not user or not user.is_active:
|
||||
raise HTTPException(
|
||||
@@ -70,7 +71,7 @@ async def get_current_metadata_user(
|
||||
try:
|
||||
user = await metadata_repo.refresh_user_keycloak_snapshot(
|
||||
user,
|
||||
username=username,
|
||||
username=_username_from_payload(keycloak_payload),
|
||||
email=_email_from_payload(keycloak_payload),
|
||||
)
|
||||
except SQLAlchemyError as exc:
|
||||
@@ -80,7 +81,7 @@ async def get_current_metadata_user(
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Metadata database is unavailable",
|
||||
detail=f"Metadata database error: {exc}",
|
||||
) from exc
|
||||
return user
|
||||
|
||||
|
||||
@@ -1,162 +0,0 @@
|
||||
from collections.abc import Awaitable, Callable
|
||||
from typing import Any
|
||||
|
||||
from fastapi import Depends, HTTPException, Request, status
|
||||
|
||||
from app.auth.project_dependencies import ProjectContext, get_project_context
|
||||
|
||||
WEBGIS_VIEW = "webgis.view"
|
||||
WEBGIS_EDIT = "webgis.edit"
|
||||
SCADA_VIEW = "scada.view"
|
||||
SCADA_CLEAN = "scada.clean"
|
||||
SIMULATION_VIEW = "simulation.view"
|
||||
SIMULATION_RUN = "simulation.run"
|
||||
BURST_VIEW = "burst.view"
|
||||
BURST_RUN = "burst.run"
|
||||
RISK_VIEW = "risk.view"
|
||||
RISK_RUN = "risk.run"
|
||||
OPTIMIZATION_VIEW = "optimization.view"
|
||||
OPTIMIZATION_RUN = "optimization.run"
|
||||
MODEL_IMPORT = "model.import"
|
||||
AUDIT_VIEW = "audit.view"
|
||||
ENVIRONMENT_MANAGE = "environment.manage"
|
||||
MEMBERSHIP_MANAGE = "membership.manage"
|
||||
|
||||
PROJECT_MEMBER_PERMISSIONS = frozenset(
|
||||
{
|
||||
WEBGIS_VIEW,
|
||||
WEBGIS_EDIT,
|
||||
SCADA_VIEW,
|
||||
SCADA_CLEAN,
|
||||
SIMULATION_VIEW,
|
||||
SIMULATION_RUN,
|
||||
BURST_VIEW,
|
||||
BURST_RUN,
|
||||
RISK_VIEW,
|
||||
RISK_RUN,
|
||||
OPTIMIZATION_VIEW,
|
||||
OPTIMIZATION_RUN,
|
||||
}
|
||||
)
|
||||
|
||||
PROJECT_VIEWER_PERMISSIONS = frozenset(
|
||||
{
|
||||
WEBGIS_VIEW,
|
||||
SCADA_VIEW,
|
||||
SIMULATION_VIEW,
|
||||
}
|
||||
)
|
||||
|
||||
SYSTEM_ADMIN_PERMISSIONS = frozenset(
|
||||
{
|
||||
MODEL_IMPORT,
|
||||
AUDIT_VIEW,
|
||||
ENVIRONMENT_MANAGE,
|
||||
MEMBERSHIP_MANAGE,
|
||||
}
|
||||
)
|
||||
|
||||
PROJECT_ROLE_PERMISSIONS: dict[str, frozenset[str]] = {
|
||||
"member": PROJECT_MEMBER_PERMISSIONS,
|
||||
"viewer": PROJECT_VIEWER_PERMISSIONS,
|
||||
}
|
||||
|
||||
|
||||
def resolve_permissions(
|
||||
*,
|
||||
project_role: str | None,
|
||||
system_role: str,
|
||||
is_superuser: bool,
|
||||
) -> frozenset[str]:
|
||||
permissions = set(PROJECT_ROLE_PERMISSIONS.get(project_role or "", frozenset()))
|
||||
if is_superuser or system_role == "admin":
|
||||
permissions.update(SYSTEM_ADMIN_PERMISSIONS)
|
||||
return frozenset(permissions)
|
||||
|
||||
|
||||
def permissions_for_context(ctx: ProjectContext) -> frozenset[str]:
|
||||
return resolve_permissions(
|
||||
project_role=ctx.project_role,
|
||||
system_role=ctx.system_role,
|
||||
is_superuser=ctx.is_superuser,
|
||||
)
|
||||
|
||||
|
||||
def _permission_denied(permission: str) -> HTTPException:
|
||||
return HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail={
|
||||
"code": "permission_denied",
|
||||
"permission": permission,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def _enforce_project_scope(request: Request, ctx: ProjectContext) -> None:
|
||||
requested_network = (
|
||||
request.path_params.get("network")
|
||||
or request.query_params.get("network")
|
||||
)
|
||||
if not requested_network:
|
||||
content_type = request.headers.get("content-type", "")
|
||||
if content_type.startswith("application/json"):
|
||||
try:
|
||||
payload = await request.json()
|
||||
except (ValueError, RuntimeError):
|
||||
payload = None
|
||||
if isinstance(payload, dict):
|
||||
requested_network = payload.get("network")
|
||||
|
||||
if requested_network and str(requested_network) != ctx.project_code:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail={
|
||||
"code": "project_scope_denied",
|
||||
"project_id": str(ctx.project_id),
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def require_permission(
|
||||
permission: str,
|
||||
) -> Callable[..., Awaitable[ProjectContext]]:
|
||||
async def dependency(
|
||||
request: Request,
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
) -> ProjectContext:
|
||||
if permission not in permissions_for_context(ctx):
|
||||
raise _permission_denied(permission)
|
||||
await _enforce_project_scope(request, ctx)
|
||||
return ctx
|
||||
|
||||
return dependency
|
||||
|
||||
|
||||
def require_method_permission(
|
||||
*,
|
||||
read_permission: str,
|
||||
write_permission: str,
|
||||
) -> Callable[..., Awaitable[ProjectContext]]:
|
||||
async def dependency(
|
||||
request: Request,
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
) -> ProjectContext:
|
||||
permission = (
|
||||
read_permission
|
||||
if request.method.upper() in {"GET", "HEAD", "OPTIONS"}
|
||||
else write_permission
|
||||
)
|
||||
if permission not in permissions_for_context(ctx):
|
||||
raise _permission_denied(permission)
|
||||
await _enforce_project_scope(request, ctx)
|
||||
return ctx
|
||||
|
||||
return dependency
|
||||
|
||||
|
||||
def has_permission(user: Any, project_role: str | None, permission: str) -> bool:
|
||||
return permission in resolve_permissions(
|
||||
project_role=project_role,
|
||||
system_role=str(getattr(user, "role", "user")),
|
||||
is_superuser=bool(getattr(user, "is_superuser", False)),
|
||||
)
|
||||
@@ -1,21 +1,18 @@
|
||||
import logging
|
||||
from collections.abc import AsyncGenerator
|
||||
from dataclasses import dataclass
|
||||
from typing import AsyncGenerator
|
||||
from uuid import UUID
|
||||
|
||||
import logging
|
||||
from fastapi import Depends, Header, HTTPException, status
|
||||
from psycopg import AsyncConnection
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.auth.metadata_dependencies import get_current_metadata_user
|
||||
from app.auth.keycloak_dependencies import get_current_keycloak_sub
|
||||
from app.core.config import settings
|
||||
from app.infra.db.dynamic_manager import project_connection_manager
|
||||
from app.infra.db.metadb.database import get_metadata_session
|
||||
from app.infra.db.metadb.repositories.metadata_repository import (
|
||||
MetadataRepository,
|
||||
ProjectDbRouting,
|
||||
)
|
||||
from app.infra.db.metadb.repositories.metadata_repository import MetadataRepository
|
||||
|
||||
DB_ROLE_BIZ_DATA = "biz_data"
|
||||
DB_ROLE_IOT_DATA = "iot_data"
|
||||
@@ -31,8 +28,6 @@ class ProjectContext:
|
||||
project_code: str
|
||||
user_id: UUID
|
||||
project_role: str
|
||||
system_role: str = "user"
|
||||
is_superuser: bool = False
|
||||
|
||||
|
||||
async def get_metadata_repository(
|
||||
@@ -41,10 +36,10 @@ async def get_metadata_repository(
|
||||
return MetadataRepository(session)
|
||||
|
||||
|
||||
async def resolve_project_context(
|
||||
x_project_id: str,
|
||||
current_user,
|
||||
metadata_repo: MetadataRepository,
|
||||
async def get_project_context(
|
||||
x_project_id: str = Header(..., alias="X-Project-Id"),
|
||||
keycloak_sub: UUID = Depends(get_current_keycloak_sub),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> ProjectContext:
|
||||
try:
|
||||
project_uuid = UUID(x_project_id)
|
||||
@@ -64,9 +59,17 @@ async def resolve_project_context(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="Project is not active"
|
||||
)
|
||||
|
||||
membership_role = await metadata_repo.get_membership_role(
|
||||
project_uuid, current_user.id
|
||||
user = await metadata_repo.get_user_by_keycloak_id(keycloak_sub)
|
||||
if not user:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="User not registered"
|
||||
)
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="Inactive user"
|
||||
)
|
||||
|
||||
membership_role = await metadata_repo.get_membership_role(project_uuid, user.id)
|
||||
if not membership_role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN, detail="No access to project"
|
||||
@@ -78,70 +81,43 @@ async def resolve_project_context(
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Metadata database is unavailable",
|
||||
detail=f"Metadata database error: {exc}",
|
||||
) from exc
|
||||
|
||||
return ProjectContext(
|
||||
project_id=project.id,
|
||||
project_code=project.code,
|
||||
user_id=current_user.id,
|
||||
user_id=user.id,
|
||||
project_role=membership_role,
|
||||
system_role=current_user.role,
|
||||
is_superuser=current_user.is_superuser,
|
||||
)
|
||||
|
||||
|
||||
async def get_project_context(
|
||||
x_project_id: str = Header(..., alias="X-Project-Id"),
|
||||
current_user=Depends(get_current_metadata_user),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> ProjectContext:
|
||||
return await resolve_project_context(x_project_id, current_user, metadata_repo)
|
||||
|
||||
|
||||
async def _get_project_routing(
|
||||
metadata_repo: MetadataRepository,
|
||||
project_id: UUID,
|
||||
db_role: str,
|
||||
expected_db_type: str,
|
||||
database_label: str,
|
||||
) -> ProjectDbRouting:
|
||||
try:
|
||||
routing = await metadata_repo.get_project_db_routing(project_id, db_role)
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Invalid project %s routing DSN configuration",
|
||||
database_label,
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project {database_label} routing DSN is invalid: {exc}",
|
||||
) from exc
|
||||
|
||||
if not routing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project {database_label} not configured",
|
||||
)
|
||||
if routing.db_type != expected_db_type:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project {database_label} type mismatch",
|
||||
)
|
||||
return routing
|
||||
|
||||
|
||||
async def get_project_pg_session(
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> AsyncGenerator[AsyncSession, None]:
|
||||
routing = await _get_project_routing(
|
||||
metadata_repo,
|
||||
ctx.project_id,
|
||||
DB_ROLE_BIZ_DATA,
|
||||
DB_TYPE_POSTGRES,
|
||||
"PostgreSQL",
|
||||
try:
|
||||
routing = await metadata_repo.get_project_db_routing(
|
||||
ctx.project_id, DB_ROLE_BIZ_DATA
|
||||
)
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Invalid project PostgreSQL routing DSN configuration",
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project PostgreSQL routing DSN is invalid: {exc}",
|
||||
) from exc
|
||||
if not routing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project PostgreSQL not configured",
|
||||
)
|
||||
if routing.db_type != DB_TYPE_POSTGRES:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project PostgreSQL type mismatch",
|
||||
)
|
||||
|
||||
pool_min_size = routing.pool_min_size or settings.PROJECT_PG_POOL_SIZE
|
||||
@@ -161,12 +137,28 @@ async def get_project_pg_connection(
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> AsyncGenerator[AsyncConnection, None]:
|
||||
routing = await _get_project_routing(
|
||||
metadata_repo,
|
||||
ctx.project_id,
|
||||
DB_ROLE_BIZ_DATA,
|
||||
DB_TYPE_POSTGRES,
|
||||
"PostgreSQL",
|
||||
try:
|
||||
routing = await metadata_repo.get_project_db_routing(
|
||||
ctx.project_id, DB_ROLE_BIZ_DATA
|
||||
)
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Invalid project PostgreSQL routing DSN configuration",
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project PostgreSQL routing DSN is invalid: {exc}",
|
||||
) from exc
|
||||
if not routing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project PostgreSQL not configured",
|
||||
)
|
||||
if routing.db_type != DB_TYPE_POSTGRES:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project PostgreSQL type mismatch",
|
||||
)
|
||||
|
||||
pool_min_size = routing.pool_min_size or settings.PROJECT_PG_POOL_SIZE
|
||||
@@ -186,12 +178,28 @@ async def get_project_timescale_connection(
|
||||
ctx: ProjectContext = Depends(get_project_context),
|
||||
metadata_repo: MetadataRepository = Depends(get_metadata_repository),
|
||||
) -> AsyncGenerator[AsyncConnection, None]:
|
||||
routing = await _get_project_routing(
|
||||
metadata_repo,
|
||||
ctx.project_id,
|
||||
DB_ROLE_IOT_DATA,
|
||||
DB_TYPE_TIMESCALE,
|
||||
"TimescaleDB",
|
||||
try:
|
||||
routing = await metadata_repo.get_project_db_routing(
|
||||
ctx.project_id, DB_ROLE_IOT_DATA
|
||||
)
|
||||
except ValueError as exc:
|
||||
logger.error(
|
||||
"Invalid project TimescaleDB routing DSN configuration",
|
||||
exc_info=True,
|
||||
)
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail=f"Project TimescaleDB routing DSN is invalid: {exc}",
|
||||
) from exc
|
||||
if not routing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project TimescaleDB not configured",
|
||||
)
|
||||
if routing.db_type != DB_TYPE_TIMESCALE:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
|
||||
detail="Project TimescaleDB type mismatch",
|
||||
)
|
||||
|
||||
pool_min_size = routing.pool_min_size or settings.PROJECT_TS_POOL_MIN_SIZE
|
||||
|
||||
+1
-6
@@ -8,6 +8,7 @@ class Settings(BaseSettings):
|
||||
PROJECT_NAME: str = "TJWater Server"
|
||||
ENVIRONMENT: str = "production"
|
||||
API_V1_STR: str = "/api/v1"
|
||||
|
||||
NETWORK_NAME: str = "default_network"
|
||||
|
||||
# 敏感配置加密密钥 (Fernet)
|
||||
@@ -26,11 +27,6 @@ class Settings(BaseSettings):
|
||||
TIMESCALEDB_DB_PORT: str = "5433"
|
||||
TIMESCALEDB_DB_USER: str = "postgres"
|
||||
TIMESCALEDB_DB_PASSWORD: str = "password"
|
||||
# InfluxDB
|
||||
INFLUXDB_URL: str = "http://localhost:8086"
|
||||
INFLUXDB_TOKEN: str = "token"
|
||||
INFLUXDB_ORG: str = "org"
|
||||
INFLUXDB_BUCKET: str = "bucket"
|
||||
|
||||
# Metadata Database Config (PostgreSQL)
|
||||
METADATA_DB_NAME: str = "system_hub"
|
||||
@@ -53,7 +49,6 @@ class Settings(BaseSettings):
|
||||
KEYCLOAK_PUBLIC_KEY: str = ""
|
||||
KEYCLOAK_ALGORITHM: str = "RS256"
|
||||
KEYCLOAK_AUDIENCE: str = ""
|
||||
KEYCLOAK_ACCESS_TOKEN_MAX_AGE_SECONDS: int = 900
|
||||
|
||||
# Bocha Web Search API
|
||||
BOCHA_API_KEY: str = ""
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
"""
|
||||
This module is reserved for future implementation of advanced cryptographic operations.
|
||||
|
||||
Current basic encryption (Fernet) and password hashing are implemented in `app.core.encryption` and `app.core.security`.
|
||||
Current Fernet encryption helpers are implemented in `app.core.encryption`.
|
||||
Login credentials are owned by Keycloak; this backend does not hash or store
|
||||
local passwords.
|
||||
Future expansion may include:
|
||||
- Asymmetric encryption (RSA/ECC) for secure communication
|
||||
- Key management and rotation services
|
||||
|
||||
@@ -1,13 +0,0 @@
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class AccessContextResponse(BaseModel):
|
||||
user_id: UUID
|
||||
username: str
|
||||
system_role: str
|
||||
is_system_admin: bool
|
||||
project_id: UUID | None = None
|
||||
project_role: str | None = None
|
||||
permissions: list[str]
|
||||
@@ -5,8 +5,8 @@ from uuid import UUID
|
||||
from pydantic import BaseModel, ConfigDict, Field, model_validator
|
||||
|
||||
|
||||
BusinessRole = Literal["admin", "user"]
|
||||
ProjectRole = Literal["member", "viewer"]
|
||||
BusinessRole = Literal["admin", "user", "operator", "viewer"]
|
||||
ProjectRole = Literal["owner", "admin", "member", "viewer"]
|
||||
ProjectStatus = Literal["active", "inactive", "archived"]
|
||||
ProjectDbRole = Literal["biz_data", "iot_data"]
|
||||
|
||||
|
||||
@@ -1,92 +0,0 @@
|
||||
from datetime import datetime
|
||||
from typing import Literal
|
||||
|
||||
from pydantic import BaseModel, Field, field_validator
|
||||
|
||||
|
||||
AdjustmentStatus = Literal["current", "original", "added", "replaced"]
|
||||
|
||||
|
||||
def _normalize_location_ids(value: list[str]) -> list[str]:
|
||||
normalized = [str(item).strip() for item in value]
|
||||
if any(not item for item in normalized):
|
||||
raise ValueError("sensor locations cannot contain blank node IDs")
|
||||
if len(set(normalized)) != len(normalized):
|
||||
raise ValueError("sensor locations cannot contain duplicate node IDs")
|
||||
return normalized
|
||||
|
||||
|
||||
class SensorPlacementOptimizeRequest(BaseModel):
|
||||
network: str = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=63,
|
||||
pattern=r"^[^/\\\x00]+$",
|
||||
)
|
||||
scheme_name: str = Field(..., min_length=1, max_length=32)
|
||||
sensor_type: Literal["pressure"]
|
||||
method: Literal["sensitivity", "kmeans"]
|
||||
sensor_count: int = Field(..., gt=0, le=200)
|
||||
min_diameter: int = Field(default=0, ge=0)
|
||||
|
||||
@field_validator("network")
|
||||
@classmethod
|
||||
def validate_network(cls, value: str) -> str:
|
||||
normalized = value.strip()
|
||||
if normalized in {".", ".."}:
|
||||
raise ValueError("network must be a project identifier")
|
||||
return normalized
|
||||
|
||||
|
||||
class SensorPlacementUpdateRequest(BaseModel):
|
||||
expected_sensor_location: list[str] = Field(
|
||||
...,
|
||||
min_length=1,
|
||||
max_length=200,
|
||||
)
|
||||
sensor_location: list[str] = Field(..., min_length=1, max_length=200)
|
||||
|
||||
@field_validator("expected_sensor_location", "sensor_location")
|
||||
@classmethod
|
||||
def validate_locations(cls, value: list[str]) -> list[str]:
|
||||
return _normalize_location_ids(value)
|
||||
|
||||
|
||||
class SensorPlacementExportRequest(BaseModel):
|
||||
sensor_location: list[str] = Field(..., min_length=1, max_length=200)
|
||||
adjustment_status: dict[str, AdjustmentStatus] = Field(
|
||||
default_factory=dict,
|
||||
max_length=200,
|
||||
)
|
||||
|
||||
@field_validator("sensor_location")
|
||||
@classmethod
|
||||
def validate_locations(cls, value: list[str]) -> list[str]:
|
||||
return _normalize_location_ids(value)
|
||||
|
||||
|
||||
class SensorPointResponse(BaseModel):
|
||||
node_id: str
|
||||
max_pipe_diameter: float | None = Field(
|
||||
...,
|
||||
description="节点关联管道的最大管径,单位:毫米",
|
||||
)
|
||||
project_x: float
|
||||
project_y: float
|
||||
map_x: float
|
||||
map_y: float
|
||||
longitude: float
|
||||
latitude: float
|
||||
elevation: float
|
||||
|
||||
|
||||
class SensorPlacementSchemeResponse(BaseModel):
|
||||
id: int
|
||||
scheme_name: str
|
||||
sensor_number: int
|
||||
min_diameter: int
|
||||
username: str
|
||||
create_time: datetime
|
||||
sensor_location: list[str]
|
||||
sensor_points: list[SensorPointResponse]
|
||||
can_edit: bool = False
|
||||
@@ -58,8 +58,6 @@ class AuditMiddleware(BaseHTTPMiddleware):
|
||||
"/meta/projects",
|
||||
"/api/v1/openproject/",
|
||||
"/openproject/",
|
||||
"/api/v1/audit/session-events",
|
||||
"/audit/session-events",
|
||||
}
|
||||
EXCLUDED_PATH_PREFIXES = (
|
||||
)
|
||||
@@ -82,9 +80,27 @@ class AuditMiddleware(BaseHTTPMiddleware):
|
||||
request_data = None
|
||||
if should_capture_body:
|
||||
try:
|
||||
# 注意:读取 body 后需要重新设置,避免影响后续处理
|
||||
original_receive = request._receive
|
||||
body = await request.body()
|
||||
if body:
|
||||
request_data = json.loads(body.decode())
|
||||
|
||||
# 重新构造请求以供后续使用:仅回放一次,后续回落原始 receive
|
||||
body_sent = False
|
||||
|
||||
async def receive():
|
||||
nonlocal body_sent
|
||||
if not body_sent:
|
||||
body_sent = True
|
||||
return {
|
||||
"type": "http.request",
|
||||
"body": body,
|
||||
"more_body": False,
|
||||
}
|
||||
return await original_receive()
|
||||
|
||||
request._receive = receive
|
||||
except Exception as e:
|
||||
logger.warning(f"Failed to read request body for audit: {e}")
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,6 +0,0 @@
|
||||
# influxdb数据库连接信息
|
||||
url = "http://127.0.0.1:8086" # 替换为你的InfluxDB实例地址
|
||||
token = "kMPX2V5HsbzPpUT2B9HPBu1sTG1Emf-lPlT2UjxYnGAuocpXq_f_0lK4HHs-TbbKyjsZpICkMsyXG_V2D7P7yQ==" # 替换为你的InfluxDB Token
|
||||
# _ENCODED_TOKEN = "eEdETTVSWnFSSkF1ekFHUy1vdFhVZEMyTkZkWTc1cUpBalJMcUFCNHA1V2NJSUFsSVVwT3BUOF95QTE2QU9IbUpXZXJ3UV8wOGd3Yjg0c3k0MmpuWlE9PQ=="
|
||||
# token = base64.b64decode(_ENCODED_TOKEN).decode("utf-8")
|
||||
org = "TJWATERORG" # 替换为你的Organization名称
|
||||
@@ -1,33 +0,0 @@
|
||||
from influxdb_client import InfluxDBClient, Point, WriteOptions
|
||||
from influxdb_client.client.query_api import QueryApi
|
||||
import influxdb_info
|
||||
|
||||
# 配置 InfluxDB 连接
|
||||
url = influxdb_info.url
|
||||
token = influxdb_info.token
|
||||
org = influxdb_info.org
|
||||
bucket = "SCADA_data"
|
||||
|
||||
# 创建 InfluxDB 客户端
|
||||
client = InfluxDBClient(url=url, token=token, org=org)
|
||||
|
||||
# 创建查询 API 对象
|
||||
query_api = client.query_api()
|
||||
|
||||
# 构建查询语句
|
||||
query = f'''
|
||||
from(bucket: "{bucket}")
|
||||
|> range(start: -1h)
|
||||
'''
|
||||
|
||||
# 执行查询
|
||||
result = query_api.query(query)
|
||||
print(result)
|
||||
|
||||
# 处理查询结果
|
||||
for table in result:
|
||||
for record in table.records:
|
||||
print(f"Time: {record.get_time()}, Value: {record.get_value()}, Measurement: {record.get_measurement()}, Field: {record.get_field()}")
|
||||
|
||||
# 关闭客户端连接
|
||||
client.close()
|
||||
@@ -211,7 +211,6 @@ class MetadataRepository:
|
||||
gs_workspace: str,
|
||||
map_extent: dict | None,
|
||||
status: str,
|
||||
creator_user_id: UUID | None = None,
|
||||
) -> models.Project:
|
||||
project = models.Project(
|
||||
id=uuid4(),
|
||||
@@ -225,15 +224,6 @@ class MetadataRepository:
|
||||
updated_at=_utcnow(),
|
||||
)
|
||||
self.session.add(project)
|
||||
if creator_user_id is not None:
|
||||
self.session.add(
|
||||
models.UserProjectMembership(
|
||||
id=uuid4(),
|
||||
user_id=creator_user_id,
|
||||
project_id=project.id,
|
||||
project_role="member",
|
||||
)
|
||||
)
|
||||
await self.session.commit()
|
||||
await self.session.refresh(project)
|
||||
return project
|
||||
@@ -493,7 +483,7 @@ class MetadataRepository:
|
||||
gs_workspace=project.gs_workspace,
|
||||
map_extent=project.map_extent,
|
||||
status=project.status,
|
||||
project_role="member",
|
||||
project_role="owner",
|
||||
)
|
||||
for project in result.scalars().all()
|
||||
]
|
||||
|
||||
@@ -169,38 +169,6 @@ class InternalQueries:
|
||||
else:
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def query_latest_scada_time(
|
||||
device_ids: List[str],
|
||||
before_time: str | datetime | None = None,
|
||||
db_name: str = None,
|
||||
max_retries: int = 3,
|
||||
) -> datetime | None:
|
||||
"""Return the latest SCADA timestamp for the selected devices."""
|
||||
before_dt = (
|
||||
parse_utc_time(before_time, field_name="before_time")
|
||||
if before_time is not None
|
||||
else None
|
||||
)
|
||||
for attempt in range(max_retries):
|
||||
try:
|
||||
conn_string = (
|
||||
get_timescaledb_pgconn_string(db_name=db_name)
|
||||
if db_name
|
||||
else get_timescaledb_pgconn_string()
|
||||
)
|
||||
with psycopg.Connection.connect(conn_string) as conn:
|
||||
return ScadaRepository.get_latest_scada_time_sync(
|
||||
conn,
|
||||
device_ids,
|
||||
before_dt,
|
||||
)
|
||||
except Exception:
|
||||
if attempt < max_retries - 1:
|
||||
time.sleep(1)
|
||||
else:
|
||||
raise
|
||||
|
||||
@staticmethod
|
||||
def query_realtime_simulation_by_ids_timerange(
|
||||
element_ids: List[str],
|
||||
|
||||
@@ -54,27 +54,6 @@ class ScadaRepository:
|
||||
)
|
||||
return cur.fetchall()
|
||||
|
||||
@staticmethod
|
||||
def get_latest_scada_time_sync(
|
||||
conn: Connection,
|
||||
device_ids: List[str],
|
||||
before_time: datetime | None = None,
|
||||
) -> datetime | None:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
if before_time is None:
|
||||
cur.execute(
|
||||
"SELECT max(time) AS time FROM scada.scada_data WHERE device_id = ANY(%s)",
|
||||
(device_ids,),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"SELECT max(time) AS time FROM scada.scada_data "
|
||||
"WHERE device_id = ANY(%s) AND time <= %s",
|
||||
(device_ids, before_time),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
return row["time"] if row else None
|
||||
|
||||
@staticmethod
|
||||
async def get_scada_field_by_id_time_range(
|
||||
conn: AsyncConnection,
|
||||
|
||||
+1
-4
@@ -6,8 +6,7 @@ import logging
|
||||
from datetime import datetime
|
||||
|
||||
import app.services.project_info as project_info
|
||||
from app.api.problem_details import install_problem_details_handlers
|
||||
from app.api.v1.rest_router import api_router
|
||||
from app.api.v1.router import api_router
|
||||
from app.infra.db.timescaledb.database import db as tsdb
|
||||
from app.infra.db.postgresql.database import db as pgdb
|
||||
from app.infra.db.dynamic_manager import project_connection_manager
|
||||
@@ -65,13 +64,11 @@ app = FastAPI(
|
||||
docs_url=None if is_production else "/docs",
|
||||
redoc_url=None if is_production else "/redoc",
|
||||
openapi_url=None if is_production else "/openapi.json",
|
||||
redirect_slashes=False,
|
||||
)
|
||||
|
||||
|
||||
# Include Routers
|
||||
app.include_router(api_router, prefix="/api/v1")
|
||||
install_problem_details_handlers(app)
|
||||
# Legcy Routers without version prefix
|
||||
# app.include_router(api_router)
|
||||
|
||||
|
||||
@@ -320,11 +320,7 @@ from .s23_options_util import (
|
||||
from .s23_options_util import get_option_v3_schema, get_option_v3
|
||||
from .batch_api import set_option_v3_ex
|
||||
|
||||
from .s24_coordinates import (
|
||||
get_links_in_extent,
|
||||
get_node_coord,
|
||||
get_nodes_in_extent,
|
||||
)
|
||||
from .s24_coordinates import get_node_coord, get_nodes_in_extent, get_links_in_extent
|
||||
|
||||
from .s25_vertices import (
|
||||
get_vertex_schema,
|
||||
@@ -460,6 +456,8 @@ from .s36_wda_cal import (
|
||||
# -----------------------------------------------------------------------------
|
||||
from .s38_scada_info import get_scada_info_schema, get_scada_info, get_all_scada_info
|
||||
|
||||
from .s39_user import get_user_schema, get_user, get_all_users
|
||||
|
||||
from .s40_schema import get_scheme_schema, get_scheme, get_all_schemes
|
||||
|
||||
from .s41_pipe_risk_probability import (
|
||||
@@ -470,11 +468,6 @@ from .s41_pipe_risk_probability import (
|
||||
get_pipe_risk_probability_geometries,
|
||||
)
|
||||
|
||||
from .s42_sensor_placement import (
|
||||
get_all_sensor_placements,
|
||||
get_sensor_placement,
|
||||
get_sensor_placement_nodes,
|
||||
update_sensor_placement,
|
||||
)
|
||||
from .s42_sensor_placement import get_all_sensor_placements
|
||||
|
||||
from .s43_burst_locate_result import get_all_burst_locate_results
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
from .database import *
|
||||
from .s0_base import *
|
||||
|
||||
class User(object):
|
||||
def __init__(self, input: dict[str, Any]) -> None:
|
||||
self.type = 'user'
|
||||
self.id = str(input['user_id'])
|
||||
self.name = str(input['username'])
|
||||
self.password = str(input['password'])
|
||||
|
||||
def as_dict(self) -> dict[str, Any]:
|
||||
return { 'type': self.type, 'id': self.id, 'name': self.name, 'password': self.password }
|
||||
|
||||
def as_id_dict(self) -> dict[str, Any]:
|
||||
return { 'type': self.type, 'id': self.id }
|
||||
|
||||
|
||||
def get_user_schema(name: str) -> dict[str, dict[Any, Any]]:
|
||||
return { 'id' : {'type': 'str' , 'optional': False , 'readonly': True },
|
||||
'name' : {'type': 'str' , 'optional': False , 'readonly': False},
|
||||
'password' : {'type': 'str' , 'optional': False , 'readonly': False} }
|
||||
|
||||
def get_user(name: str, user_name: str) -> dict[Any, Any]:
|
||||
t = try_read(name, f"select * from users where username = '{user_name}'")
|
||||
if t == None:
|
||||
return {}
|
||||
|
||||
d = {}
|
||||
d['id'] = str(t['user_id'])
|
||||
d['name'] = str(t['username'])
|
||||
# d['password'] = str(t['password'])
|
||||
|
||||
return d
|
||||
|
||||
def get_all_users(name: str) -> list[dict[Any, Any]]:
|
||||
return read_all(name, "select * from users")
|
||||
|
||||
@@ -1,124 +1,7 @@
|
||||
from typing import Any
|
||||
from .database import *
|
||||
from .s0_base import *
|
||||
from .s42_sensor_placement import *
|
||||
import json
|
||||
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from .connection import project_connection
|
||||
from .database import read_all
|
||||
|
||||
|
||||
def get_all_sensor_placements(name: str) -> list[dict[str, Any]]:
|
||||
def get_all_sensor_placements(name: str) -> list[dict[Any, Any]]:
|
||||
return read_all(name, "select * from sensor_placement")
|
||||
|
||||
|
||||
def create_sensor_placement(
|
||||
name: str,
|
||||
*,
|
||||
scheme_name: str,
|
||||
min_diameter: int,
|
||||
username: str,
|
||||
sensor_location: list[str],
|
||||
) -> dict[str, Any]:
|
||||
with project_connection(name) as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
INSERT INTO sensor_placement (
|
||||
scheme_name,
|
||||
sensor_number,
|
||||
min_diameter,
|
||||
username,
|
||||
sensor_location
|
||||
)
|
||||
VALUES (%s, %s, %s, %s, %s)
|
||||
RETURNING *
|
||||
""",
|
||||
(
|
||||
scheme_name,
|
||||
len(sensor_location),
|
||||
min_diameter,
|
||||
username,
|
||||
sensor_location,
|
||||
),
|
||||
)
|
||||
created = cur.fetchone()
|
||||
if created is None:
|
||||
raise RuntimeError("监测点方案写入失败")
|
||||
return dict(created)
|
||||
|
||||
|
||||
def get_sensor_placement(name: str, scheme_id: int) -> dict[str, Any] | None:
|
||||
with project_connection(name) as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"SELECT * FROM sensor_placement WHERE id = %s",
|
||||
(scheme_id,),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
|
||||
def get_sensor_placement_nodes(
|
||||
name: str,
|
||||
node_ids: list[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
if not node_ids:
|
||||
return []
|
||||
with project_connection(name) as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
WITH incident_pipe_diameters AS (
|
||||
SELECT node_id, MAX(diameter) AS max_pipe_diameter
|
||||
FROM (
|
||||
SELECT node1 AS node_id, diameter
|
||||
FROM pipes
|
||||
WHERE node1 = ANY(%s)
|
||||
UNION ALL
|
||||
SELECT node2 AS node_id, diameter
|
||||
FROM pipes
|
||||
WHERE node2 = ANY(%s)
|
||||
) AS incident_pipes
|
||||
GROUP BY node_id
|
||||
)
|
||||
SELECT DISTINCT ON (gj.id)
|
||||
gj.id AS node_id,
|
||||
ipd.max_pipe_diameter,
|
||||
gj.elevation,
|
||||
ST_X(c.coord) AS project_x,
|
||||
ST_Y(c.coord) AS project_y,
|
||||
ST_X(gj.geom) AS map_x,
|
||||
ST_Y(gj.geom) AS map_y
|
||||
FROM geo_junctions_mat AS gj
|
||||
JOIN coordinates AS c ON c.node = gj.id
|
||||
LEFT JOIN incident_pipe_diameters AS ipd ON ipd.node_id = gj.id
|
||||
WHERE gj.id = ANY(%s)
|
||||
ORDER BY gj.id
|
||||
""",
|
||||
(node_ids, node_ids, node_ids),
|
||||
)
|
||||
return list(cur.fetchall())
|
||||
|
||||
|
||||
def update_sensor_placement(
|
||||
name: str,
|
||||
scheme_id: int,
|
||||
*,
|
||||
expected_sensor_location: list[str],
|
||||
sensor_location: list[str],
|
||||
) -> dict[str, Any] | None:
|
||||
with project_connection(name) as conn:
|
||||
with conn.cursor(row_factory=dict_row) as cur:
|
||||
cur.execute(
|
||||
"""
|
||||
UPDATE sensor_placement
|
||||
SET sensor_location = %s, sensor_number = %s
|
||||
WHERE id = %s AND sensor_location = %s
|
||||
RETURNING *
|
||||
""",
|
||||
(
|
||||
sensor_location,
|
||||
len(sensor_location),
|
||||
scheme_id,
|
||||
expected_sensor_location,
|
||||
),
|
||||
)
|
||||
return cur.fetchone()
|
||||
|
||||
+29
-363
@@ -1,10 +1,8 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from collections import Counter
|
||||
from datetime import datetime, timedelta
|
||||
from datetime import datetime
|
||||
from typing import Any
|
||||
|
||||
import numpy as np
|
||||
import pandas as pd
|
||||
|
||||
from app.algorithms.burst_detection.burst_detector import BurstDetector
|
||||
@@ -19,15 +17,6 @@ from app.services.tjnetwork import get_all_scada_info
|
||||
from app.services.time_api import extract_date, parse_utc_time, utc_now
|
||||
|
||||
|
||||
TARGET_DAY_COUNT = 15
|
||||
DEFAULT_SAMPLE_INTERVAL_MINUTES = 15
|
||||
TARGET_MU = 1
|
||||
TARGET_N_ESTIMATORS = 50
|
||||
TARGET_RANDOM_STATE = 42
|
||||
TARGET_SCORE_THRESHOLD = -0.04
|
||||
MIN_COMPLETE_SENSORS = 5
|
||||
|
||||
|
||||
def run_burst_detection(
|
||||
*,
|
||||
network: str,
|
||||
@@ -42,8 +31,6 @@ def run_burst_detection(
|
||||
points_per_day: int = 1440,
|
||||
mu: int = 100,
|
||||
iforest_params: dict[str, Any] | None = None,
|
||||
target_time: datetime | str | None = None,
|
||||
sampling_interval_minutes: int | None = None,
|
||||
scada_start: datetime | str | None = None,
|
||||
scada_end: datetime | str | None = None,
|
||||
sensor_nodes: list[str] | None = None,
|
||||
@@ -55,8 +42,7 @@ def run_burst_detection(
|
||||
"""
|
||||
运行爆管侦测服务入口。
|
||||
|
||||
调用方式三选一:
|
||||
- 不传数据时间窗,自动侦测最近完整时刻;可用 `target_time` 回放历史时刻
|
||||
调用方式二选一:
|
||||
- 直接传 `observed_pressure_data`
|
||||
- 或传 `scada_start/scada_end` 让后端自动查询 SCADA 压力数据
|
||||
|
||||
@@ -88,65 +74,8 @@ def run_burst_detection(
|
||||
else None
|
||||
)
|
||||
use_scada_source = scada_start is not None or scada_end is not None
|
||||
use_target_mode = (
|
||||
observed_pressure_data is None
|
||||
and not use_scada_source
|
||||
and data_source != "simulation"
|
||||
) or target_time is not None
|
||||
|
||||
resolved_target_time: datetime | None = None
|
||||
requested_target_time: datetime | None = None
|
||||
excluded_sensors: list[dict[str, str]] = []
|
||||
daily_times: list[datetime] | None = None
|
||||
resolved_sampling_interval_minutes: int | None = None
|
||||
|
||||
if use_target_mode:
|
||||
if observed_pressure_data is not None or use_scada_source:
|
||||
raise ValueError(
|
||||
"target_time 不能与 observed_pressure_data 或 scada_start/scada_end 同时使用。"
|
||||
)
|
||||
scada_sensor_nodes = (
|
||||
selected_sensor_nodes
|
||||
if selected_sensor_nodes is not None
|
||||
else _get_pressure_sensor_nodes(network)
|
||||
)
|
||||
requested_target_time = (
|
||||
_to_datetime(target_time) if target_time is not None else None
|
||||
)
|
||||
resolved_sampling_interval_minutes = _resolve_sampling_interval_minutes(
|
||||
network=network,
|
||||
sensor_nodes=scada_sensor_nodes,
|
||||
requested_interval=sampling_interval_minutes,
|
||||
)
|
||||
target_points_per_day = 1440 // resolved_sampling_interval_minutes
|
||||
(
|
||||
observed_input,
|
||||
resolved_target_time,
|
||||
excluded_sensors,
|
||||
) = _build_target_pressure_from_scada(
|
||||
network=network,
|
||||
sensor_nodes=scada_sensor_nodes,
|
||||
requested_target_time=requested_target_time,
|
||||
sampling_interval_minutes=resolved_sampling_interval_minutes,
|
||||
points_per_day=target_points_per_day,
|
||||
)
|
||||
selected_sensor_nodes = list(observed_input.columns)
|
||||
observed_source = (
|
||||
"latest_monitoring" if target_time is None else "historical_monitoring"
|
||||
)
|
||||
points_per_day = target_points_per_day
|
||||
mu = TARGET_MU
|
||||
iforest_params = {
|
||||
"n_estimators": TARGET_N_ESTIMATORS,
|
||||
"random_state": TARGET_RANDOM_STATE,
|
||||
"contamination": "auto",
|
||||
}
|
||||
daily_times = [
|
||||
resolved_target_time - timedelta(days=offset)
|
||||
for offset in range(TARGET_DAY_COUNT - 1, -1, -1)
|
||||
]
|
||||
|
||||
elif use_scada_source:
|
||||
if use_scada_source:
|
||||
scada_sensor_nodes = (
|
||||
selected_sensor_nodes
|
||||
if selected_sensor_nodes is not None
|
||||
@@ -192,16 +121,7 @@ def run_burst_detection(
|
||||
sensor_nodes=selected_sensor_nodes,
|
||||
)
|
||||
resolved_sensor_nodes = list(result_df.attrs.get("sensor_nodes", []))
|
||||
rows = _serialize_result_rows(
|
||||
result_df,
|
||||
daily_times=daily_times,
|
||||
target_only=use_target_mode,
|
||||
)
|
||||
summary = _build_detection_summary(
|
||||
result_df,
|
||||
daily_times=daily_times,
|
||||
target_only=use_target_mode,
|
||||
)
|
||||
rows = _serialize_result_rows(result_df)
|
||||
payload: dict[str, Any] = {
|
||||
"network": network,
|
||||
"sensor_nodes": resolved_sensor_nodes,
|
||||
@@ -210,17 +130,7 @@ def run_burst_detection(
|
||||
"points_per_day": int(result_df.attrs.get("points_per_day", points_per_day)),
|
||||
"day_count": int(result_df.attrs.get("day_count", len(result_df))),
|
||||
"rows": rows,
|
||||
"summary": summary,
|
||||
"algorithm_params": {
|
||||
"mu": mu,
|
||||
"points_per_day": points_per_day,
|
||||
"iforest_params": detector.iforest_params,
|
||||
**(
|
||||
{"score_threshold": TARGET_SCORE_THRESHOLD}
|
||||
if use_target_mode
|
||||
else {}
|
||||
),
|
||||
},
|
||||
"summary": _build_detection_summary(result_df),
|
||||
}
|
||||
if data_source == "simulation":
|
||||
payload["data_source"] = "simulation"
|
||||
@@ -231,50 +141,7 @@ def run_burst_detection(
|
||||
else:
|
||||
payload["data_source"] = "monitoring"
|
||||
|
||||
if (
|
||||
use_target_mode
|
||||
and resolved_target_time is not None
|
||||
and resolved_sampling_interval_minutes is not None
|
||||
):
|
||||
sample_start = resolved_target_time - timedelta(
|
||||
days=TARGET_DAY_COUNT,
|
||||
minutes=-resolved_sampling_interval_minutes,
|
||||
)
|
||||
payload.update(
|
||||
{
|
||||
"requested_target_time": (
|
||||
requested_target_time.isoformat()
|
||||
if requested_target_time is not None
|
||||
else None
|
||||
),
|
||||
"target_time": resolved_target_time.isoformat(),
|
||||
"reference_window": {
|
||||
"start": (resolved_target_time - timedelta(days=14)).isoformat(),
|
||||
"end": (resolved_target_time - timedelta(days=1)).isoformat(),
|
||||
"day_count": 14,
|
||||
},
|
||||
"sampling_interval_minutes": resolved_sampling_interval_minutes,
|
||||
"daily_scores": [
|
||||
{
|
||||
"timestamp": row["Timestamp"],
|
||||
"role": row["Role"],
|
||||
"score": row["Score"],
|
||||
"raw_prediction": row["Prediction"],
|
||||
}
|
||||
for row in rows
|
||||
],
|
||||
"data_quality": {
|
||||
"included_sensors": resolved_sensor_nodes,
|
||||
"excluded_sensors": excluded_sensors,
|
||||
"minimum_required_sensors": MIN_COMPLETE_SENSORS,
|
||||
},
|
||||
"scada_window": {
|
||||
"start": sample_start.isoformat(),
|
||||
"end": resolved_target_time.isoformat(),
|
||||
},
|
||||
}
|
||||
)
|
||||
elif use_scada_source:
|
||||
if use_scada_source:
|
||||
payload["scada_window"] = {
|
||||
"start": _to_datetime(scada_start).isoformat(),
|
||||
"end": _to_datetime(scada_end).isoformat(),
|
||||
@@ -427,49 +294,22 @@ def _store_burst_detection_scheme(
|
||||
)
|
||||
|
||||
|
||||
def _serialize_result_rows(
|
||||
result_df: pd.DataFrame,
|
||||
*,
|
||||
daily_times: list[datetime] | None = None,
|
||||
target_only: bool = False,
|
||||
) -> list[dict[str, Any]]:
|
||||
def _serialize_result_rows(result_df: pd.DataFrame) -> list[dict[str, Any]]:
|
||||
rows: list[dict[str, Any]] = []
|
||||
raw_rows = result_df.to_dict(orient="records")
|
||||
for index, row in enumerate(raw_rows):
|
||||
is_target = index == len(raw_rows) - 1
|
||||
is_burst = bool(row["IsBurst"])
|
||||
if target_only:
|
||||
is_burst = is_target and float(row["Score"]) <= TARGET_SCORE_THRESHOLD
|
||||
for row in result_df.to_dict(orient="records"):
|
||||
rows.append(
|
||||
{
|
||||
"Day": int(row["Day"]),
|
||||
"Score": float(row["Score"]),
|
||||
"Prediction": int(row["Prediction"]),
|
||||
"IsBurst": is_burst,
|
||||
**(
|
||||
{
|
||||
"Timestamp": daily_times[index].isoformat(),
|
||||
"Role": "target" if is_target else "reference",
|
||||
}
|
||||
if daily_times is not None
|
||||
else {}
|
||||
),
|
||||
"IsBurst": bool(row["IsBurst"]),
|
||||
}
|
||||
)
|
||||
return rows
|
||||
|
||||
|
||||
def _build_detection_summary(
|
||||
result_df: pd.DataFrame,
|
||||
*,
|
||||
daily_times: list[datetime] | None = None,
|
||||
target_only: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
rows = _serialize_result_rows(
|
||||
result_df,
|
||||
daily_times=daily_times,
|
||||
target_only=target_only,
|
||||
)
|
||||
def _build_detection_summary(result_df: pd.DataFrame) -> dict[str, Any]:
|
||||
rows = _serialize_result_rows(result_df)
|
||||
if not rows:
|
||||
raise ValueError("爆管侦测结果为空。")
|
||||
|
||||
@@ -478,7 +318,7 @@ def _build_detection_summary(
|
||||
latest_row = rows[-1]
|
||||
anomaly_days = [row["Day"] for row in rows if row["IsBurst"]]
|
||||
|
||||
summary = {
|
||||
return {
|
||||
"burst_detected": bool(latest_row["IsBurst"]),
|
||||
"latest_day": latest_row,
|
||||
"most_anomalous_day": int(result_df.iloc[most_anomalous_index]["Day"]),
|
||||
@@ -486,18 +326,6 @@ def _build_detection_summary(
|
||||
"anomaly_day_count": len(anomaly_days),
|
||||
"latest_sensor_rankings": _build_latest_sensor_rankings(result_df),
|
||||
}
|
||||
if target_only:
|
||||
target_score = float(latest_row["Score"])
|
||||
summary.update(
|
||||
{
|
||||
"target_score": target_score,
|
||||
"score_threshold": TARGET_SCORE_THRESHOLD,
|
||||
"target_rank": int(result_df["Score"].rank(method="min").iloc[-1]),
|
||||
"target_time": latest_row.get("Timestamp"),
|
||||
"reference_day_count": TARGET_DAY_COUNT - 1,
|
||||
}
|
||||
)
|
||||
return summary
|
||||
|
||||
|
||||
def _build_latest_sensor_rankings(result_df: pd.DataFrame) -> list[dict[str, Any]]:
|
||||
@@ -506,192 +334,18 @@ def _build_latest_sensor_rankings(result_df: pd.DataFrame) -> list[dict[str, Any
|
||||
if feature_matrix is None or len(sensor_nodes) == 0:
|
||||
return []
|
||||
|
||||
latest_values = np.asarray(feature_matrix[-1], dtype=float)
|
||||
history = np.asarray(feature_matrix[:-1], dtype=float)
|
||||
history_means = history.mean(axis=0)
|
||||
history_stds = history.std(axis=0)
|
||||
safe_stds = np.where(history_stds > 1e-9, history_stds, 1e-9)
|
||||
deviations = (latest_values - history_means) / safe_stds
|
||||
latest_values = feature_matrix[-1]
|
||||
ranking = sorted(
|
||||
zip(
|
||||
sensor_nodes,
|
||||
latest_values,
|
||||
history_means,
|
||||
history_stds,
|
||||
deviations,
|
||||
strict=False,
|
||||
),
|
||||
key=lambda item: item[4],
|
||||
zip(sensor_nodes, latest_values, strict=False),
|
||||
key=lambda item: item[1],
|
||||
)
|
||||
return [
|
||||
{
|
||||
"sensor_node": sensor_id,
|
||||
"latest_high_frequency_value": float(value),
|
||||
"historical_mean": float(history_mean),
|
||||
"historical_std": float(history_std),
|
||||
"standardized_deviation": float(deviation),
|
||||
}
|
||||
for sensor_id, value, history_mean, history_std, deviation in ranking[
|
||||
: min(10, len(ranking))
|
||||
for sensor_id, value in ranking[: min(10, len(ranking))]
|
||||
]
|
||||
]
|
||||
|
||||
|
||||
def _build_target_pressure_from_scada(
|
||||
*,
|
||||
network: str,
|
||||
sensor_nodes: list[str],
|
||||
requested_target_time: datetime | None,
|
||||
sampling_interval_minutes: int,
|
||||
points_per_day: int,
|
||||
) -> tuple[pd.DataFrame, datetime, list[dict[str, str]]]:
|
||||
node_query_id = _get_pressure_sensor_mapping(network)
|
||||
mapped_nodes = [node for node in sensor_nodes if node in node_query_id]
|
||||
excluded_without_mapping = [
|
||||
{"sensor_node": node, "reason": "missing_api_query_id"}
|
||||
for node in sensor_nodes
|
||||
if node not in node_query_id
|
||||
]
|
||||
if len(mapped_nodes) < MIN_COMPLETE_SENSORS:
|
||||
raise ValueError(
|
||||
f"可查询的压力测点少于 {MIN_COMPLETE_SENSORS} 个,无法执行爆管侦测。"
|
||||
)
|
||||
|
||||
query_ids = [node_query_id[node] for node in mapped_nodes]
|
||||
candidate_before = requested_target_time
|
||||
last_excluded: list[dict[str, str]] = excluded_without_mapping
|
||||
|
||||
for _ in range(4):
|
||||
resolved_target = InternalQueries.query_latest_scada_time(
|
||||
db_name=network,
|
||||
device_ids=query_ids,
|
||||
before_time=candidate_before,
|
||||
)
|
||||
if resolved_target is None:
|
||||
break
|
||||
|
||||
sample_start = resolved_target - timedelta(
|
||||
days=TARGET_DAY_COUNT,
|
||||
minutes=-sampling_interval_minutes,
|
||||
)
|
||||
expected_index = pd.date_range(
|
||||
start=sample_start,
|
||||
end=resolved_target,
|
||||
freq=f"{sampling_interval_minutes}min",
|
||||
)
|
||||
scada_data = InternalQueries.query_scada_by_ids_timerange(
|
||||
db_name=network,
|
||||
device_ids=query_ids,
|
||||
start_time=sample_start,
|
||||
end_time=resolved_target,
|
||||
)
|
||||
|
||||
complete_columns: dict[str, pd.Series] = {}
|
||||
excluded = list(excluded_without_mapping)
|
||||
for node_id in mapped_nodes:
|
||||
query_id = node_query_id[node_id]
|
||||
records = scada_data.get(query_id, [])
|
||||
if not records:
|
||||
excluded.append({"sensor_node": node_id, "reason": "no_data"})
|
||||
continue
|
||||
|
||||
record_frame = pd.DataFrame.from_records(records)
|
||||
record_frame["time"] = pd.to_datetime(record_frame["time"], utc=True)
|
||||
record_frame["value"] = pd.to_numeric(
|
||||
record_frame["value"], errors="coerce"
|
||||
)
|
||||
series = (
|
||||
record_frame.drop_duplicates(subset="time", keep="last")
|
||||
.set_index("time")["value"]
|
||||
.reindex(expected_index)
|
||||
)
|
||||
if len(series) != TARGET_DAY_COUNT * points_per_day:
|
||||
excluded.append(
|
||||
{"sensor_node": node_id, "reason": "unexpected_sample_count"}
|
||||
)
|
||||
continue
|
||||
if series.isna().any():
|
||||
excluded.append(
|
||||
{"sensor_node": node_id, "reason": "missing_or_invalid_samples"}
|
||||
)
|
||||
continue
|
||||
complete_columns[node_id] = series
|
||||
|
||||
if len(complete_columns) >= MIN_COMPLETE_SENSORS:
|
||||
observation_df = pd.DataFrame(complete_columns, index=expected_index)
|
||||
return observation_df, resolved_target, excluded
|
||||
|
||||
last_excluded = excluded
|
||||
candidate_before = resolved_target - timedelta(microseconds=1)
|
||||
|
||||
excluded_preview = ", ".join(
|
||||
item["sensor_node"] for item in last_excluded[:10]
|
||||
)
|
||||
raise ValueError(
|
||||
f"最近数据中完整压力测点少于 {MIN_COMPLETE_SENSORS} 个;"
|
||||
f"请检查 15 天数据完整性。排除测点: {excluded_preview or '无'}"
|
||||
)
|
||||
|
||||
|
||||
def _resolve_sampling_interval_minutes(
|
||||
*,
|
||||
network: str,
|
||||
sensor_nodes: list[str],
|
||||
requested_interval: int | None,
|
||||
) -> int:
|
||||
if requested_interval is not None:
|
||||
interval = int(requested_interval)
|
||||
else:
|
||||
selected_nodes = set(sensor_nodes)
|
||||
inferred_intervals = [
|
||||
parsed
|
||||
for item in get_all_scada_info(network)
|
||||
if str(item.get("type", "")).lower() == "pressure"
|
||||
and str(item.get("associated_element_id", "")) in selected_nodes
|
||||
and (
|
||||
parsed := _parse_sampling_interval_minutes(
|
||||
item.get("transmission_frequency")
|
||||
)
|
||||
)
|
||||
is not None
|
||||
]
|
||||
interval = (
|
||||
Counter(inferred_intervals).most_common(1)[0][0]
|
||||
if inferred_intervals
|
||||
else DEFAULT_SAMPLE_INTERVAL_MINUTES
|
||||
)
|
||||
|
||||
if interval <= 0 or 1440 % interval != 0:
|
||||
raise ValueError("采样间隔必须是能整除 1440 分钟的正整数。")
|
||||
return interval
|
||||
|
||||
|
||||
def _parse_sampling_interval_minutes(value: Any) -> int | None:
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, (int, float)):
|
||||
minutes = float(value)
|
||||
else:
|
||||
try:
|
||||
minutes = pd.to_timedelta(str(value)).total_seconds() / 60
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
rounded = round(minutes)
|
||||
if minutes <= 0 or abs(minutes - rounded) > 1e-6:
|
||||
return None
|
||||
return int(rounded)
|
||||
|
||||
|
||||
def _get_pressure_sensor_mapping(network: str) -> dict[str, str]:
|
||||
node_query_id: dict[str, str] = {}
|
||||
for item in get_all_scada_info(network):
|
||||
if str(item.get("type", "")).lower() != "pressure":
|
||||
continue
|
||||
node_id = item.get("associated_element_id")
|
||||
query_id = item.get("api_query_id")
|
||||
if node_id and query_id is not None:
|
||||
node_query_id[str(node_id)] = str(query_id)
|
||||
return node_query_id
|
||||
|
||||
|
||||
def _get_pressure_sensor_nodes(network: str) -> list[str]:
|
||||
@@ -723,7 +377,19 @@ def _build_observed_pressure_from_scada(
|
||||
if start_dt >= end_dt:
|
||||
raise ValueError("SCADA 时间窗非法:scada_start 必须早于 scada_end。")
|
||||
|
||||
node_query_id = _get_pressure_sensor_mapping(network)
|
||||
node_query_id: dict[str, str] = {}
|
||||
for item in get_all_scada_info(network):
|
||||
if str(item.get("type", "")).lower() != "pressure":
|
||||
continue
|
||||
node_id = item.get("associated_element_id")
|
||||
query_id = item.get("api_query_id")
|
||||
if (
|
||||
isinstance(node_id, str)
|
||||
and node_id
|
||||
and isinstance(query_id, str)
|
||||
and query_id
|
||||
):
|
||||
node_query_id[node_id] = query_id
|
||||
|
||||
missing_nodes = [node_id for node_id in sensor_nodes if node_id not in node_query_id]
|
||||
if missing_nodes:
|
||||
|
||||
@@ -476,7 +476,7 @@ def _get_simulation_scheme_burst_ids(
|
||||
) -> list[str]:
|
||||
if not scheme_name:
|
||||
return []
|
||||
rows = query_scheme_list(network, scheme_type=scheme_type) or []
|
||||
rows = query_scheme_list(network) or []
|
||||
for row in rows:
|
||||
if len(row) < 7:
|
||||
continue
|
||||
|
||||
@@ -23,8 +23,8 @@ non_realtime_region_patterns = {} # 基于source_outflow_region进行区分
|
||||
realtime_region_pipe_flow_and_demand_id = {} # 基于source_outflow_region搜索该分区中的实时pipe_flow和demand的api_query_id,后续用region的流量 - 实时流量计的流量
|
||||
realtime_region_pipe_flow_and_demand_patterns = {} # 基于source_outflow_region搜索该分区中的实时pipe_flow和demand的associated_pattern,后续用region的流量 - 实时流量计的流量
|
||||
# ---------------------------------------------------------
|
||||
# influxdb_api.py中的全局变量
|
||||
# 全局变量,用于存储不同类型的realtime api_query_id
|
||||
# 历史数据访问相关全局变量
|
||||
# 全局变量,用于存储不同类型的 realtime api_query_id
|
||||
reservoir_liquid_level_realtime_ids = []
|
||||
tank_liquid_level_realtime_ids = []
|
||||
fixed_pump_realtime_ids = []
|
||||
|
||||
@@ -11,6 +11,53 @@ from app.core.config import get_pgconn_string
|
||||
from app.services.time_api import parse_utc_time
|
||||
|
||||
|
||||
# 2025/03/23
|
||||
def create_user(name: str, username: str, password: str):
|
||||
"""
|
||||
创建用户
|
||||
:param name: 数据库名称
|
||||
:param username: 用户名
|
||||
:param password: 密码
|
||||
:return:
|
||||
"""
|
||||
try:
|
||||
# 动态替换数据库名称
|
||||
conn_string = get_pgconn_string(db_name=name)
|
||||
# 连接到 PostgreSQL 数据库(这里是数据库 "bb")
|
||||
with psycopg.connect(conn_string) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute(
|
||||
"INSERT INTO users (username, password) VALUES (%s, %s)",
|
||||
(username, password),
|
||||
)
|
||||
# 提交事务
|
||||
conn.commit()
|
||||
print("新用户创建成功!")
|
||||
except Exception as e:
|
||||
print(f"创建用户出错:{e}")
|
||||
|
||||
|
||||
# 2025/03/23
|
||||
def delete_user(name: str, username: str):
|
||||
"""
|
||||
删除用户
|
||||
:param name: 数据库名称
|
||||
:param username: 用户名
|
||||
:return:
|
||||
"""
|
||||
try:
|
||||
# 动态替换数据库名称
|
||||
conn_string = get_pgconn_string(db_name=name)
|
||||
# 连接到 PostgreSQL 数据库(这里是数据库 "bb")
|
||||
with psycopg.connect(conn_string) as conn:
|
||||
with conn.cursor() as cur:
|
||||
cur.execute("DELETE FROM users WHERE username = %s", (username,))
|
||||
conn.commit()
|
||||
print(f"用户 {username} 删除成功!")
|
||||
except Exception as e:
|
||||
print(f"删除用户出错:{e}")
|
||||
|
||||
|
||||
# 2025/03/23
|
||||
def scheme_name_exists(name: str, scheme_name: str) -> bool:
|
||||
"""
|
||||
@@ -51,8 +98,8 @@ def store_scheme_info(
|
||||
:param name: 数据库名称
|
||||
:param scheme_name: 方案名称
|
||||
:param scheme_type: 方案类型
|
||||
:param username: MetaDB 中的用户名快照
|
||||
:param scheme_start_time: 带时区的方案起始时间;写入前统一转换为 UTC
|
||||
:param username: 用户名(需在 users 表中已存在)
|
||||
:param scheme_start_time: 方案起始时间(字符串)
|
||||
:param scheme_detail: 方案详情(字典,会转换为 JSON)
|
||||
:return:
|
||||
"""
|
||||
@@ -107,16 +154,10 @@ def delete_scheme_info(name: str, scheme_name: str) -> None:
|
||||
|
||||
|
||||
# 2025/03/23
|
||||
def query_scheme_list(
|
||||
name: str,
|
||||
scheme_type: str | None = None,
|
||||
query_date: date | None = None,
|
||||
) -> list:
|
||||
def query_scheme_list(name: str) -> list:
|
||||
"""
|
||||
查询pg数据库中的scheme_list,按照 create_time 降序排列,离现在时间最近的记录排在最前面
|
||||
:param name: 项目名称(数据库名称)
|
||||
:param scheme_type: 方案类型;为空时返回全部类型
|
||||
:param query_date: 查询日期;为空时不按日期过滤
|
||||
:return: 返回查询结果的所有行
|
||||
"""
|
||||
try:
|
||||
@@ -125,37 +166,7 @@ def query_scheme_list(
|
||||
# 连接到 PostgreSQL 数据库(这里是数据库 "bb")
|
||||
with psycopg.connect(conn_string) as conn:
|
||||
with conn.cursor() as cur:
|
||||
if scheme_type and query_date is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM scheme_list
|
||||
WHERE scheme_type = %s AND DATE(create_time) = %s
|
||||
ORDER BY create_time DESC
|
||||
""",
|
||||
(scheme_type, query_date),
|
||||
)
|
||||
elif scheme_type:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM scheme_list
|
||||
WHERE scheme_type = %s
|
||||
ORDER BY create_time DESC
|
||||
""",
|
||||
(scheme_type,),
|
||||
)
|
||||
elif query_date is not None:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT *
|
||||
FROM scheme_list
|
||||
WHERE DATE(create_time) = %s
|
||||
ORDER BY create_time DESC
|
||||
""",
|
||||
(query_date,),
|
||||
)
|
||||
else:
|
||||
# 按 create_time 降序排列
|
||||
cur.execute("SELECT * FROM scheme_list ORDER BY create_time DESC")
|
||||
rows = cur.fetchall()
|
||||
return rows
|
||||
@@ -164,85 +175,6 @@ def query_scheme_list(
|
||||
print(f"查询错误:{e}")
|
||||
|
||||
|
||||
def _filter_scheme_detail_scope(
|
||||
result: dict,
|
||||
name: str,
|
||||
scheme_type: str | None = None,
|
||||
) -> dict:
|
||||
if not result:
|
||||
return {}
|
||||
if scheme_type and result.get("scheme_type") != scheme_type:
|
||||
return {}
|
||||
network = result.get("network")
|
||||
if network not in (None, name):
|
||||
return {}
|
||||
return result
|
||||
|
||||
|
||||
def query_scheme_detail(
|
||||
name: str,
|
||||
scheme_name: str,
|
||||
scheme_type: str | None = None,
|
||||
) -> dict:
|
||||
if scheme_type == "dma_leak_identification":
|
||||
return _filter_scheme_detail_scope(
|
||||
query_leakage_identify_scheme_detail(name, scheme_name),
|
||||
name,
|
||||
scheme_type,
|
||||
)
|
||||
if scheme_type == "burst_detection":
|
||||
return _filter_scheme_detail_scope(
|
||||
query_burst_detection_scheme_detail(name, scheme_name),
|
||||
name,
|
||||
scheme_type,
|
||||
)
|
||||
if scheme_type == "burst_location":
|
||||
return _filter_scheme_detail_scope(
|
||||
query_burst_location_scheme_detail(name, scheme_name),
|
||||
name,
|
||||
scheme_type,
|
||||
)
|
||||
|
||||
conn_string = get_pgconn_string(db_name=name)
|
||||
with psycopg.connect(conn_string) as conn:
|
||||
with conn.cursor() as cur:
|
||||
if scheme_type:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT scheme_id, scheme_name, scheme_type, username, create_time, scheme_start_time, scheme_detail
|
||||
FROM public.scheme_list
|
||||
WHERE scheme_name = %s AND scheme_type = %s
|
||||
LIMIT 1
|
||||
""",
|
||||
(scheme_name, scheme_type),
|
||||
)
|
||||
else:
|
||||
cur.execute(
|
||||
"""
|
||||
SELECT scheme_id, scheme_name, scheme_type, username, create_time, scheme_start_time, scheme_detail
|
||||
FROM public.scheme_list
|
||||
WHERE scheme_name = %s
|
||||
LIMIT 1
|
||||
""",
|
||||
(scheme_name,),
|
||||
)
|
||||
row = cur.fetchone()
|
||||
if row is None:
|
||||
return {}
|
||||
detail = row[6] if isinstance(row[6], dict) else {}
|
||||
return _filter_scheme_detail_scope({
|
||||
"scheme_id": row[0],
|
||||
"scheme_name": row[1],
|
||||
"scheme_type": row[2],
|
||||
"username": row[3],
|
||||
"create_time": row[4],
|
||||
"scheme_start_time": row[5],
|
||||
"scheme_detail": detail,
|
||||
"network": detail.get("network"),
|
||||
"result_payload": detail.get("result_payload", {}),
|
||||
}, name, scheme_type)
|
||||
|
||||
|
||||
def store_leakage_identify_result(
|
||||
name: str,
|
||||
scheme_name: str,
|
||||
|
||||
@@ -1,271 +0,0 @@
|
||||
from datetime import datetime
|
||||
from io import BytesIO
|
||||
from typing import Any
|
||||
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Font, PatternFill
|
||||
from openpyxl.worksheet.worksheet import Worksheet
|
||||
from openpyxl.utils import get_column_letter
|
||||
from pyproj import Transformer
|
||||
|
||||
from app.native import wndb
|
||||
|
||||
|
||||
class SensorPlacementNotFoundError(LookupError):
|
||||
pass
|
||||
|
||||
|
||||
class SensorPlacementValidationError(ValueError):
|
||||
pass
|
||||
|
||||
|
||||
class SensorPlacementConflictError(RuntimeError):
|
||||
pass
|
||||
|
||||
|
||||
_to_wgs84 = Transformer.from_crs("EPSG:3857", "EPSG:4326", always_xy=True)
|
||||
_STATUS_LABELS = {
|
||||
"current": "当前方案",
|
||||
"original": "原方案",
|
||||
"added": "新增",
|
||||
"replaced": "替换",
|
||||
}
|
||||
_COORDINATE_DESCRIPTION = (
|
||||
"工程 X/Y: 项目地方坐标系;地图 X/Y: EPSG:3857;经纬度: WGS84"
|
||||
)
|
||||
_LIST_HEADERS = (
|
||||
"序号",
|
||||
"节点 ID",
|
||||
"经度",
|
||||
"纬度",
|
||||
"工程 X",
|
||||
"工程 Y",
|
||||
"地图 X",
|
||||
"地图 Y",
|
||||
"高程",
|
||||
"调整状态",
|
||||
)
|
||||
_LIST_COLUMN_WIDTHS = (8, 20, 16, 16, 18, 18, 18, 18, 14, 14)
|
||||
|
||||
|
||||
def _normalize_locations(sensor_location: list[str]) -> list[str]:
|
||||
normalized = [str(node_id).strip() for node_id in sensor_location]
|
||||
if not normalized or any(not node_id for node_id in normalized):
|
||||
raise SensorPlacementValidationError("监测点列表不能为空")
|
||||
if len(set(normalized)) != len(normalized):
|
||||
raise SensorPlacementValidationError("监测点列表不能包含重复节点")
|
||||
return normalized
|
||||
|
||||
|
||||
def _sensor_points(
|
||||
network: str,
|
||||
sensor_location: list[str],
|
||||
) -> list[dict[str, Any]]:
|
||||
nodes = wndb.get_sensor_placement_nodes(network, sensor_location)
|
||||
by_id = {str(node["node_id"]): node for node in nodes}
|
||||
missing = [node_id for node_id in sensor_location if node_id not in by_id]
|
||||
if missing:
|
||||
raise SensorPlacementValidationError(
|
||||
f"以下节点不存在或不是 junction: {', '.join(missing)}"
|
||||
)
|
||||
|
||||
points: list[dict[str, Any]] = []
|
||||
for node_id in sensor_location:
|
||||
node = by_id[node_id]
|
||||
project_x = float(node["project_x"])
|
||||
project_y = float(node["project_y"])
|
||||
map_x = float(node["map_x"])
|
||||
map_y = float(node["map_y"])
|
||||
longitude, latitude = _to_wgs84.transform(map_x, map_y)
|
||||
points.append(
|
||||
{
|
||||
"node_id": node_id,
|
||||
"max_pipe_diameter": (
|
||||
float(node["max_pipe_diameter"])
|
||||
if node["max_pipe_diameter"] is not None
|
||||
else None
|
||||
),
|
||||
"project_x": project_x,
|
||||
"project_y": project_y,
|
||||
"map_x": map_x,
|
||||
"map_y": map_y,
|
||||
"longitude": float(longitude),
|
||||
"latitude": float(latitude),
|
||||
"elevation": float(node["elevation"]),
|
||||
}
|
||||
)
|
||||
return points
|
||||
|
||||
|
||||
def get_sensor_placement_candidate(
|
||||
network: str,
|
||||
node_id: str,
|
||||
) -> dict[str, Any]:
|
||||
"""Return the authoritative editable point data for one junction."""
|
||||
|
||||
return _sensor_points(network, _normalize_locations([node_id]))[0]
|
||||
|
||||
|
||||
def validate_sensor_placement_nodes(
|
||||
network: str,
|
||||
sensor_location: list[str],
|
||||
) -> None:
|
||||
_sensor_points(network, _normalize_locations(sensor_location))
|
||||
|
||||
|
||||
def get_sensor_placement_scheme(network: str, scheme_id: int) -> dict[str, Any]:
|
||||
scheme = wndb.get_sensor_placement(network, scheme_id)
|
||||
if scheme is None:
|
||||
raise SensorPlacementNotFoundError("监测点方案不存在")
|
||||
|
||||
locations = [str(item) for item in (scheme.get("sensor_location") or [])]
|
||||
return {
|
||||
**scheme,
|
||||
"sensor_number": len(locations),
|
||||
"sensor_location": locations,
|
||||
"sensor_points": _sensor_points(network, locations),
|
||||
}
|
||||
|
||||
|
||||
def update_sensor_placement_scheme(
|
||||
network: str,
|
||||
scheme_id: int,
|
||||
*,
|
||||
expected_sensor_location: list[str],
|
||||
sensor_location: list[str],
|
||||
) -> dict[str, Any]:
|
||||
expected = _normalize_locations(expected_sensor_location)
|
||||
next_locations = _normalize_locations(sensor_location)
|
||||
_sensor_points(network, next_locations)
|
||||
|
||||
updated = wndb.update_sensor_placement(
|
||||
network,
|
||||
scheme_id,
|
||||
expected_sensor_location=expected,
|
||||
sensor_location=next_locations,
|
||||
)
|
||||
if updated is None:
|
||||
if wndb.get_sensor_placement(network, scheme_id) is None:
|
||||
raise SensorPlacementNotFoundError("监测点方案不存在")
|
||||
raise SensorPlacementConflictError("方案已被其他用户修改,请重新加载")
|
||||
return get_sensor_placement_scheme(network, scheme_id)
|
||||
|
||||
|
||||
def can_edit_sensor_placement(user: Any, scheme: dict[str, Any]) -> bool:
|
||||
return bool(
|
||||
getattr(user, "is_superuser", False)
|
||||
or getattr(user, "role", None) == "admin"
|
||||
or getattr(user, "username", None) == scheme.get("username")
|
||||
)
|
||||
|
||||
|
||||
def _safe_excel_text(value: Any) -> str:
|
||||
text = "" if value is None else str(value)
|
||||
if text.startswith(("=", "+", "-", "@")):
|
||||
return f"'{text}"
|
||||
return text
|
||||
|
||||
|
||||
def _populate_info_sheet(
|
||||
sheet: Worksheet,
|
||||
*,
|
||||
network: str,
|
||||
scheme: dict[str, Any],
|
||||
location_count: int,
|
||||
is_draft: bool,
|
||||
) -> None:
|
||||
created_at = scheme["create_time"]
|
||||
if isinstance(created_at, datetime):
|
||||
created_at = created_at.isoformat(timespec="minutes")
|
||||
|
||||
rows = [
|
||||
("项目", network),
|
||||
("方案名称", scheme["scheme_name"]),
|
||||
("监测点数量", location_count),
|
||||
("最小管径", scheme["min_diameter"]),
|
||||
("创建人", scheme["username"]),
|
||||
("创建时间", created_at),
|
||||
("导出时间", datetime.now().astimezone().isoformat(timespec="minutes")),
|
||||
("文档状态", "未保存草稿" if is_draft else "当前方案"),
|
||||
("坐标说明", _COORDINATE_DESCRIPTION),
|
||||
]
|
||||
for row_index, (label, value) in enumerate(rows, start=1):
|
||||
sheet.cell(row=row_index, column=1, value=label)
|
||||
safe_value = _safe_excel_text(value) if isinstance(value, str) else value
|
||||
sheet.cell(row=row_index, column=2, value=safe_value)
|
||||
sheet.column_dimensions["A"].width = 18
|
||||
sheet.column_dimensions["B"].width = 64
|
||||
|
||||
|
||||
def _populate_list_sheet(
|
||||
sheet: Worksheet,
|
||||
*,
|
||||
points: list[dict[str, Any]],
|
||||
adjustment_status: dict[str, str],
|
||||
) -> None:
|
||||
sheet.append(_LIST_HEADERS)
|
||||
for index, point in enumerate(points, start=1):
|
||||
status = adjustment_status.get(point["node_id"], "current")
|
||||
sheet.append(
|
||||
[
|
||||
index,
|
||||
_safe_excel_text(point["node_id"]),
|
||||
point["longitude"],
|
||||
point["latitude"],
|
||||
point["project_x"],
|
||||
point["project_y"],
|
||||
point["map_x"],
|
||||
point["map_y"],
|
||||
point["elevation"],
|
||||
_STATUS_LABELS.get(status, "当前方案"),
|
||||
]
|
||||
)
|
||||
|
||||
header_fill = PatternFill("solid", fgColor="257DD4")
|
||||
for cell in sheet[1]:
|
||||
cell.fill = header_fill
|
||||
cell.font = Font(color="FFFFFF", bold=True)
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
sheet.freeze_panes = "A2"
|
||||
sheet.auto_filter.ref = sheet.dimensions
|
||||
for index, width in enumerate(_LIST_COLUMN_WIDTHS, start=1):
|
||||
sheet.column_dimensions[get_column_letter(index)].width = width
|
||||
for row in sheet.iter_rows(min_row=2):
|
||||
row[0].alignment = Alignment(horizontal="center")
|
||||
for cell in row[2:9]:
|
||||
cell.number_format = "0.000000"
|
||||
|
||||
|
||||
def build_sensor_placement_workbook(
|
||||
*,
|
||||
network: str,
|
||||
scheme: dict[str, Any],
|
||||
sensor_location: list[str],
|
||||
adjustment_status: dict[str, str],
|
||||
) -> BytesIO:
|
||||
locations = _normalize_locations(sensor_location)
|
||||
points = _sensor_points(network, locations)
|
||||
is_draft = locations != list(scheme["sensor_location"])
|
||||
|
||||
workbook = Workbook()
|
||||
info_sheet = workbook.active
|
||||
info_sheet.title = "方案信息"
|
||||
_populate_info_sheet(
|
||||
info_sheet,
|
||||
network=network,
|
||||
scheme=scheme,
|
||||
location_count=len(locations),
|
||||
is_draft=is_draft,
|
||||
)
|
||||
|
||||
list_sheet = workbook.create_sheet("监测点清单")
|
||||
_populate_list_sheet(
|
||||
list_sheet,
|
||||
points=points,
|
||||
adjustment_status=adjustment_status,
|
||||
)
|
||||
|
||||
output = BytesIO()
|
||||
workbook.save(output)
|
||||
output.seek(0)
|
||||
return output
|
||||
@@ -28,7 +28,6 @@ import pytz
|
||||
import requests
|
||||
import time
|
||||
from typing import Optional, Tuple
|
||||
import app.infra.db.influxdb.api as influxdb_api
|
||||
import typing
|
||||
import psycopg
|
||||
import logging
|
||||
|
||||
+17
-27
@@ -1290,6 +1290,19 @@ def get_scada_info(name: str, id: str) -> dict[str, Any]:
|
||||
def get_all_scada_info(name: str) -> list[dict[str, Any]]:
|
||||
return api.get_all_scada_info(name)
|
||||
|
||||
# DingZQ 2025-03-27
|
||||
############################################################
|
||||
# 39 users
|
||||
############################################################
|
||||
def get_user_schema(name: str) -> dict[str, dict[str, Any]]:
|
||||
return api.get_user_schema(name)
|
||||
|
||||
def get_user(name: str, user_name: str) -> dict[str, Any]:
|
||||
return api.get_user(name, user_name=user_name)
|
||||
|
||||
def get_all_users(name: str) -> list[dict[str, Any]]:
|
||||
return api.get_all_users(name)
|
||||
|
||||
############################################################
|
||||
# scheme 40
|
||||
############################################################
|
||||
@@ -1299,35 +1312,9 @@ def get_scheme_schema(name: str) -> dict[str, dict[str, Any]]:
|
||||
def get_scheme(name: str, schema_name: str) -> dict[str, Any]:
|
||||
return api.get_scheme(name, schema_name)
|
||||
|
||||
def get_all_schemes(
|
||||
name: str,
|
||||
scheme_type: str | None = None,
|
||||
query_date: Any | None = None,
|
||||
) -> list[dict[str, Any]]:
|
||||
if scheme_type is None and query_date is None:
|
||||
def get_all_schemes(name: str) -> list[dict[str, Any]]:
|
||||
return api.get_all_schemes(name)
|
||||
|
||||
from app.services.scheme_management import query_scheme_list
|
||||
|
||||
rows = query_scheme_list(name, scheme_type=scheme_type, query_date=query_date) or []
|
||||
columns = [
|
||||
"scheme_id",
|
||||
"scheme_name",
|
||||
"scheme_type",
|
||||
"username",
|
||||
"create_time",
|
||||
"scheme_start_time",
|
||||
"scheme_detail",
|
||||
]
|
||||
result = []
|
||||
for row in rows:
|
||||
item = dict(zip(columns, row, strict=False))
|
||||
detail = item.get("scheme_detail")
|
||||
if isinstance(detail, dict) and detail.get("network") not in (None, name):
|
||||
continue
|
||||
result.append(item)
|
||||
return result
|
||||
|
||||
############################################################
|
||||
# pipe_risk_probability 41
|
||||
############################################################
|
||||
@@ -1357,3 +1344,6 @@ def get_all_sensor_placements(name: str) -> list[dict[Any, Any]]:
|
||||
############################################################
|
||||
def get_all_burst_locate_results(name: str) -> list[dict[Any, Any]]:
|
||||
return api.get_all_burst_locate_results(name)
|
||||
|
||||
|
||||
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
{
|
||||
"contract_version": "1.0.0",
|
||||
"contracts": {
|
||||
"server": {
|
||||
"file": "server-v1.openapi.json",
|
||||
"sha256": "b003a57c9b8c1a041b644363ef58afb8bfcede1fe076ce48a190d2a1ac915e3f"
|
||||
}
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,22 +0,0 @@
|
||||
# TJWater REST API v1
|
||||
|
||||
This contract is the public API contract for coordinated TJWater
|
||||
Server, Agent, Frontend, and CLI releases.
|
||||
|
||||
- Paths use lowercase kebab-case, have no trailing slash, and identify
|
||||
resources rather than handler actions.
|
||||
- JSON fields, query parameters, and path parameter names use snake_case.
|
||||
- Project-scoped requests use `X-Project-Id`; `network` query parameters
|
||||
are not part of the public contract.
|
||||
- `GET` is read-only. Synchronous analysis and simulation requests use
|
||||
`POST` and clients must not retry them automatically.
|
||||
- JSON errors use `application/problem+json`.
|
||||
- The static OpenAPI file and `contracts/manifest.json` are release
|
||||
artifacts even when production runtime documentation is disabled.
|
||||
|
||||
Generate and validate the contract with:
|
||||
|
||||
```bash
|
||||
conda run -n server python scripts/export_openapi.py
|
||||
conda run -n server python scripts/check_openapi.py
|
||||
```
|
||||
@@ -1,270 +0,0 @@
|
||||
# 监测点灵敏度算法优化说明
|
||||
|
||||
本文记录压力监测点布置算法的改造方案、数学含义、复杂度变化和本地验证结果。实现位于 `app/algorithms/sensor/sensitivity.py`,对外兼容入口仍为 `get_ID(name, sensor_num, min_diameter)`。
|
||||
|
||||
## 改造目标
|
||||
|
||||
原算法根据节点压力对管道粗糙度变化的灵敏度,以及节点到全网的水力距离,给每个候选节点评分。空间聚类用于限制监测点过度集中。业务评分可以写成:
|
||||
|
||||
$$
|
||||
score_i = sensitivity_i \times \sum_j distance(i, j)
|
||||
$$
|
||||
|
||||
本次改造保留这套评分语义和空间覆盖原则,主要处理以下问题:
|
||||
|
||||
- 稠密的节点与节点、节点与管道、管道与管道矩阵占用大量内存。
|
||||
- 显式计算行列式、逆矩阵和伪逆,计算量随节点数快速增长。
|
||||
- 从每个节点执行最短路径并保存全节点距离矩阵,时间和内存均为平方级。
|
||||
- 一次任务重复运行 EPANET,并保留算法没有使用的扩展时序结果。
|
||||
- 聚类没有固定随机状态,相同输入可能返回不同结果。
|
||||
- KMeans 按候选节点密度最小化平方距离,密集管网会系统性获得更多监测点,不能保证地图或管网路径覆盖均匀。
|
||||
- WNTR 管径使用米,接口参数使用毫米,旧候选过滤没有统一单位。
|
||||
|
||||
## 稀疏表示替代稠密矩阵
|
||||
|
||||
管网的节点通常只连接少量管道。新实现使用 SciPy CSR 或 CSC 矩阵保存节点与管道关联矩阵、水力有向图和水力雅可比矩阵,只记录真实存在的连接。
|
||||
|
||||
准备阶段生成一个只读的 `_PreparedNetwork`,其中包括:
|
||||
|
||||
- 参与分析的节点及其在完整模型中的索引。
|
||||
- 符合安装条件的候选节点索引。
|
||||
- 归一化前的二维坐标。
|
||||
- 稀疏节点与管道关联矩阵。
|
||||
- 管道导通系数和粗糙度响应系数。
|
||||
- 按实际流向构建的稀疏水力距离图。
|
||||
- 按初始运行状态构建的无向物理覆盖图。
|
||||
|
||||
水库、水箱、泵和阀门的边界节点继续沿用原算法的排除规则。与水源直接相连的管道不参加扰动计算。平行有向边只保留权重最小的边,以符合最短路径语义。
|
||||
|
||||
主体存储由平方级降到接近 `O(n + m)`。稀疏 LU 分解可能产生填充,其内存仍取决于管网拓扑,但实现不会再主动分配完整的 `n × n` 或 `n × m` 数组。
|
||||
|
||||
## 用 Cauchy 投影估计压力灵敏度
|
||||
|
||||
旧算法先显式计算压力对管道粗糙度的响应矩阵:
|
||||
|
||||
$$
|
||||
J = X^{-1} A S
|
||||
$$
|
||||
|
||||
其中,`X` 是节点水力雅可比矩阵,`A` 是节点与管道关联矩阵,`S` 是管道粗糙度响应矩阵。节点灵敏度是 `J` 对应行的 L1 范数。完整的 `J` 为 `节点数 × 管道数`,大模型无法保存。
|
||||
|
||||
新算法使用 Cauchy 分布的 1-stable 特性估计每一行的 L1 范数。设 `R` 为 Cauchy 随机投影矩阵,只需求解:
|
||||
|
||||
$$
|
||||
Y = X^{-1} A S R
|
||||
$$
|
||||
|
||||
对节点 `i` 而言,`Y` 中每个投影值服从以 `||J_i||_1` 为尺度的 Cauchy 分布。实现使用投影绝对值的对数几何均值估计 `log(||J_i||_1)`,不保存完整灵敏度矩阵。
|
||||
|
||||
当前固定参数如下:
|
||||
|
||||
| 参数 | 数值 | 用途 |
|
||||
|---|---:|---|
|
||||
| 随机种子 | 42 | 保证结果可复现 |
|
||||
| Cauchy 投影数 | 256 | 控制灵敏度估计精度 |
|
||||
| 投影批大小 | 16 | 限制投影中间矩阵内存 |
|
||||
| 雅可比正则化 | `max(abs(diag(X))) × sqrt(eps)` | 改善接近奇异矩阵的稳定性 |
|
||||
| 稀疏排序 | `MMD_AT_PLUS_A` | 减少 LU 分解填充 |
|
||||
|
||||
水力雅可比矩阵只进行一次稀疏 LU 分解,256 次投影复用该分解结果。批处理期间最多保留 16 列投影数据。
|
||||
|
||||
## 用空间代表点估计水力距离总和
|
||||
|
||||
旧算法从每个节点执行一次最短路径,并保存 `n × n` 的水力距离矩阵。新算法根据节点坐标构建最多 256 个空间代表点:
|
||||
|
||||
1. 使用固定随机状态的 `MiniBatchKMeans` 对节点坐标分组。
|
||||
2. 每组选择最靠近聚类中心的节点作为代表点。
|
||||
3. 代表点权重等于该组包含的节点数。
|
||||
4. 在反向水力图上从代表点执行有向 Dijkstra,得到原图中各节点到代表点的距离。
|
||||
|
||||
节点 `i` 的全网水力距离总和估计为:
|
||||
|
||||
$$
|
||||
distance\_sum_i \approx \sum_{l \in landmarks} weight_l \times distance(i, l)
|
||||
$$
|
||||
|
||||
Dijkstra 每批处理 16 个代表点,内存中只保留当前距离块。不可达距离按原算法约定计为 0,避免断开分支得到无穷评分。
|
||||
|
||||
## 评分约束下的混合覆盖选点
|
||||
|
||||
最终排序使用对数形式:
|
||||
|
||||
$$
|
||||
log\_score_i = log\_sensitivity_i + \log(distance\_sum_i)
|
||||
$$
|
||||
|
||||
对数是单调函数,因此该排序等价于比较 `sensitivity_i × distance_sum_i`,同时可以避免大数乘法溢出。
|
||||
|
||||
最终选点不再对全部候选节点执行 KMeans。KMeans 的目标函数按候选节点数计权,节点密集区域即使地理范围较小,也会获得更多聚类中心。本次改为评分约束下的最远空白区优先策略。
|
||||
|
||||
候选坐标使用同一个尺度因子归一化,保留管网原始长宽比。初始状态下开启的管道按物理长度构建无向覆盖图,开启的泵和阀门作为点连接;关闭连接会形成独立区域。监测点名额首先按各连通区域的有效管道长度分配:名额足够时每个区域至少一个,其余名额按最大余数法分配,并受该区域候选数量限制。
|
||||
|
||||
选点按区域名额从多到少处理,使主干管网先形成覆盖骨架。第一个区域的首点取综合评分最高的候选;后续区域的首点也必须考虑此前所有区域的已选点,先进入全局地图空白度前 70% 的候选集,再比较综合评分。这一约束避免两个拓扑断开但地图上重叠或相邻的区域各自选择一个近邻高分点。
|
||||
|
||||
设全局已选集合为 `S`,其余候选的最近地图距离和本连通区域内的最近管网路径距离分别为:
|
||||
|
||||
$$
|
||||
g_i = \min_{s \in S} ||x_i-x_s||, \qquad
|
||||
t_i = \min_{s \in S} shortest\_path(i, s)
|
||||
$$
|
||||
|
||||
两类距离分别除以当前未选候选中的最大值,混合空白度取两者较大值:
|
||||
|
||||
$$
|
||||
coverage_i = \max\left(\frac{g_i}{\max g}, \frac{t_i}{\max t}\right)
|
||||
$$
|
||||
|
||||
每轮只保留空白度达到当前最大值 70% 的候选,再从中选择综合评分最高的节点。地图距离始终相对全部已选区域更新,管网路径距离在当前连通区域内更新。这样地图或管网路径中任一维度仍有明显空白时,该区域都不会被高密度节点误判为已经覆盖。综合评分相同时按节点 ID 排序,结果数量、唯一性和可复现性保持不变。
|
||||
|
||||
实现只维护候选节点的最近距离数组。每新增一个监测点,执行一次单源 Dijkstra 并增量更新,不构造候选节点两两距离矩阵。
|
||||
|
||||
所有模型使用同一套算法和相同参数,不根据节点数量切换实现。
|
||||
|
||||
## EPANET 只计算初始状态
|
||||
|
||||
后续计算只读取水力结果的第一个时刻。新实现会临时将 `wn.options.time.duration` 设置为 0,只运行一次 EPANET 初始状态模拟,并在结束或异常后恢复原始时长。
|
||||
|
||||
EPANET 中间文件写入独立的 `TemporaryDirectory`,任务结束后自动清理。并发请求不再共用工作目录下的 `temp.*` 文件。
|
||||
|
||||
旧调用链最多重复运行约四次 EPANET,新调用链只运行一次,也不会分配没有使用的完整时序结果。
|
||||
|
||||
## 最小管径规则
|
||||
|
||||
`min_diameter` 的接口单位是毫米,WNTR 中的管径单位是米。准备阶段使用以下换算:
|
||||
|
||||
$$
|
||||
diameter\_mm = diameter\_m \times 1000
|
||||
$$
|
||||
|
||||
节点连接的管道中,只要至少一根达到最小管径,该节点就可以作为安装候选。小管径管道仍参加全网水力和灵敏度计算,管径条件只限制监测点安装位置。
|
||||
|
||||
当候选节点少于请求的监测点数量时,算法会返回包含候选数量和请求数量的明确错误。
|
||||
|
||||
## 复杂度变化
|
||||
|
||||
下表中的 `n` 为参与分析的节点数,`m` 为参与分析的管道数,`k=256` 为灵敏度投影数,`l≤256` 为水力距离代表点数,`b=16` 为批大小。
|
||||
|
||||
| 环节 | 原实现 | 新实现 |
|
||||
|---|---|---|
|
||||
| 节点与管道关系 | 稠密 `n × m` | CSR 稀疏矩阵,约 `O(n + m)` |
|
||||
| 节点关系与距离 | 多个稠密 `n × n` 矩阵 | 稀疏有向图和流式距离块 |
|
||||
| 灵敏度 | 稠密行列式、逆矩阵或伪逆,时间接近 `O(n³)` | 一次稀疏 LU 分解和 `k` 次稀疏求解 |
|
||||
| 灵敏度结果 | 保存完整 `n × m` 响应矩阵 | 保存 `n` 个对数灵敏度和当前投影批 |
|
||||
| 水力距离 | 从全部节点执行最短路径并保存 `n × n` 结果 | 从至多 `l` 个代表点执行 Dijkstra,每批 `b` 个 |
|
||||
| 最终选点 | 按节点密度分配的完整 KMeans | 连通区域配额和 70% 混合覆盖,线性距离数组 |
|
||||
| 水力模拟 | 调用链中重复执行,并可能保存完整时序 | 一次初始状态模拟 |
|
||||
|
||||
稀疏 LU 的时间和内存不能简单视为线性,其填充程度受网络拓扑影响。当前压力测试覆盖到 20.3 万原始节点,不能据此保证任意更大或连接更稠密的模型都保持相同比例。
|
||||
|
||||
## 精度取舍
|
||||
|
||||
新实现不逐元素生成旧算法的完整精确矩阵,而是估计最终排序需要的两个统计量:
|
||||
|
||||
- Cauchy 投影估计压力响应矩阵每一行的 L1 范数。
|
||||
- 加权空间代表点估计节点到全网的水力距离总和。
|
||||
|
||||
单元测试使用小型模型构造完整稠密参考结果,要求近似方案选点的精确参考目标值不低于精确方案的 95%。本地模型对比结果如下:
|
||||
|
||||
| 模型 | 近似选点的精确参考目标比 |
|
||||
|---|---:|
|
||||
| `fengxian.inp` | 98.80% |
|
||||
| MD 模型 | 99.71% |
|
||||
|
||||
固定随机种子和固定采样数保证同一模型、监测点数量和最小管径得到相同结果。近似排序仍可能与完整稠密算法不同,特别是多个候选节点得分接近时。
|
||||
|
||||
混合覆盖会主动放弃部分集中在同一区域的高分节点。单点综合评分之和因此不是唯一质量指标,还需要同时检查未覆盖半径、最小点间距和入选节点的评分百分位。
|
||||
|
||||
## 资源压力测试记录
|
||||
|
||||
以下结果来自 2026-08-03 的本地验证。环境为 Linux、Python 3.12、Conda `server` 环境,主机物理内存约 30 GiB。测试参数统一为 20 个监测点、最小管径 0。
|
||||
|
||||
外部看门狗使用以下停止条件:
|
||||
|
||||
- 算法进程树 RSS 达到 7.5 GiB。
|
||||
- 系统可用内存低于 6 GiB。
|
||||
- 单模型运行超过 600 秒。
|
||||
- 子进程虚拟地址空间硬限制为 8 GiB。
|
||||
|
||||
任一条件满足时,看门狗会终止整个进程组。三次压力测试均未触发停止条件。
|
||||
|
||||
| 模型 | 原始节点 | 实际分析节点 | 实际分析管道 | 算法流水线耗时 | 峰值 RSS |
|
||||
|---|---:|---:|---:|---:|---:|
|
||||
| `temp/leakage/temp_3698123.inp` | 31,143 | 28,723 | 29,974 | 2.77 秒 | 467 MiB |
|
||||
| `inp/jbh.inp` | 94,049 | 69,949 | 82,369 | 8.92 秒 | 980 MiB |
|
||||
| `inp/Todo/v-16常熟模型.inp` | 203,569 | 145,948 | 176,512 | 20.00 秒 | 1.84 GiB |
|
||||
|
||||
实际分析节点少于原始节点,是因为水库、水箱、泵和阀门边界节点按算法规则排除。20.3 万节点模型原文件使用非标准的 `REPORTING TIMESTEP`,并且缺少 `[END]`。压力测试只在隔离临时副本中将其规范化,没有修改原文件。
|
||||
|
||||
20.3 万节点模型各阶段耗时如下:
|
||||
|
||||
| 阶段 | 耗时 |
|
||||
|---|---:|
|
||||
| 模型加载 | 6.63 秒 |
|
||||
| EPANET 初始状态模拟 | 8.30 秒 |
|
||||
| 稀疏数据准备 | 3.00 秒 |
|
||||
| 压力灵敏度估计 | 0.76 秒 |
|
||||
| 水力距离估计 | 0.94 秒 |
|
||||
| 监测点选择 | 0.37 秒 |
|
||||
|
||||
### `tjwater` 分布优化前后对比
|
||||
|
||||
2026-08-03 使用 `db_inp/tjwater.db.inp`、20 个监测点、最小管径 0 进行同机对比。进程通过 systemd scope 限制在 2.5 GiB 内存,并设置 90 秒超时;两次运行均未触发保护。覆盖距离使用保持长宽比后的模型坐标,按管网最大轴跨度归一化。
|
||||
|
||||
| 指标 | KMeans 选点 | 70% 混合覆盖 | 变化 |
|
||||
|---|---:|---:|---:|
|
||||
| 实际分析/候选节点 | 87,877 | 87,877 | 不变 |
|
||||
| 最大地图覆盖半径 | 0.176786 | 0.173941 | -1.61% |
|
||||
| P95 地图覆盖半径 | 0.122093 | 0.090686 | -25.72% |
|
||||
| 最小监测点间距 | 0.000559 | 0.040887 | 约 73.2 倍 |
|
||||
| 综合评分中位百分位 | 98.76% | 95.41% | -3.35 个百分点 |
|
||||
| 端到端耗时 | 12.34 秒 | 11.71 秒 | -5.11% |
|
||||
| 峰值 RSS | 913 MiB | 932 MiB | +19 MiB |
|
||||
|
||||
结果达到预定验收条件:P95 覆盖半径下降超过 15%,评分中位百分位下降少于 10 个百分点,运行时间没有增加,峰值内存增加远低于 256 MiB。
|
||||
|
||||
### 2026-08-03:跨连通区域共享全局间距
|
||||
|
||||
首次混合覆盖结果中,节点 `121302` 与 `110874` 分属两个不可达连通区域,但地图距离只有约 550.47 个模型单位。旧的分区独立首点规则分别选中了两个区域的最高分节点,形成视觉近邻。加入跨区域全局地图间距后,`121302` 被替换,最小归一化点间距由 0.013685 进一步提高到 0.040887。
|
||||
|
||||
本次调整保留连通区域名额,改变区域之间互不感知的选点方式。区域按名额从多到少处理,主干管网先形成覆盖骨架。第一个区域仍从综合评分最高的候选开始;后续区域选择首点时,先计算该区域所有候选到全局已选点的最近地图距离,只保留达到本区域最大空白距离 70% 的候选,再比较灵敏度综合评分。区域内部后续选点继续使用地图距离与管网路径距离的混合空白度。
|
||||
|
||||
这项约束只影响跨区域首点选择,不改变灵敏度估计、水力距离估计、区域名额、最小管径规则和公开 API。合成回归模型会构造两个地图上重叠但拓扑断开的区域,确保算法不会再次分别选择两个相邻高分点。
|
||||
|
||||
## 测试与回归验证
|
||||
|
||||
新增测试位于 `tests/unit/test_sensor_sensitivity.py`,覆盖以下行为:
|
||||
|
||||
- 相同输入返回相同节点,并且每次调用只运行一次 EPANET。
|
||||
- EPANET 只保留初始状态,模型原始模拟时长能够恢复。
|
||||
- 关联矩阵和距离图保持 CSR 稀疏格式。
|
||||
- 最小管径按毫米过滤安装候选。
|
||||
- 近似方案在稠密参考目标上的结果不低于 95%。
|
||||
- 高密西部、低密东部的合成模型不再按候选节点密度分配名额。
|
||||
- 地理位置相邻但拓扑断开的区域在名额允许时分别获得监测点。
|
||||
- 地图上重叠的独立区域共享全局地理间距,不能各自选择相邻的首个高分点。
|
||||
- 名额不足时优先覆盖有效管道长度更大的连通区域。
|
||||
- 重复坐标依靠管网路径距离继续选点,并保持数量和确定性。
|
||||
- 非法监测点数量和最小管径返回明确错误。
|
||||
- 模拟结束后不残留共享 `temp.*` 文件。
|
||||
|
||||
回归命令:
|
||||
|
||||
```bash
|
||||
conda run -n server python -m pytest \
|
||||
tests/unit \
|
||||
tests/auth \
|
||||
tests/api/test_sensor_placement_endpoints.py \
|
||||
tests/api/test_simulation_endpoints.py \
|
||||
-q
|
||||
```
|
||||
|
||||
2026-08-03 的执行结果为 `142 passed, 2 skipped, 7 warnings`。`git diff --check` 同时通过。
|
||||
|
||||
## 实现边界
|
||||
|
||||
- 256 次投影和 256 个代表点是当前质量与性能验证后的固定参数。调整参数需要重新运行稠密参考质量测试和大模型压力测试。
|
||||
- 稀疏 LU 对高连接度或拓扑特殊的模型可能产生更多填充,应继续用进程级资源保护运行未知大模型。
|
||||
- 算法使用单个初始水力状态。如果业务目标改为覆盖全天多个工况,需要先定义多工况评分和结果合并规则,不能直接恢复长时段模拟后沿用当前评分。
|
||||
- 节点坐标用于代表点构建和地图覆盖,假定其能表达一致的平面相对距离;缺少有效二维坐标的模型会返回错误。
|
||||
- 物理覆盖图使用初始水力状态。全天工况中频繁开闭的阀门或泵需要在多工况方案中重新定义连通区域合并规则。
|
||||
- 当前压力测试验证到 203,569 个原始节点,没有验证 30 万节点模型。
|
||||
@@ -1,104 +0,0 @@
|
||||
# Keycloak 登录主题
|
||||
|
||||
`themes/tjwater` 是 TJWater 智慧水务平台的 Keycloak 登录主题。主题继承
|
||||
`keycloak.v2`,只覆盖样式、消息和本地 SVG 资源,不修改认证模板或认证流程。
|
||||
|
||||
## 在管理控制台切换登录主题
|
||||
|
||||
确认 `themes/tjwater` 已挂载到容器的
|
||||
`/opt/keycloak/themes/tjwater`,然后按以下步骤切换:
|
||||
|
||||
1. 打开 Keycloak 管理控制台:
|
||||
`http://<Keycloak 地址>:<端口>/admin/`。
|
||||
2. 使用管理员账号登录。
|
||||
3. 在左上角选择需要应用主题的 realm,例如 `tjwater`。不要停留在
|
||||
`master`,除非确实要修改 `master` realm。
|
||||
4. 在左侧菜单进入 `Realm settings`,打开 `Themes` 标签页。
|
||||
5. 在 `Login theme` 下拉框中选择 `tjwater`。
|
||||
6. 点击 `Save` 保存。
|
||||
7. 继续检查业务客户端是否单独指定了登录主题,再从业务前端重新进入登录页。
|
||||
|
||||
切回 Keycloak 默认登录页时,将 `Login theme` 改为 `keycloak` 并保存。
|
||||
|
||||
### 检查业务客户端的主题配置
|
||||
|
||||
Keycloak 的 realm 和 client 都可以设置登录主题。client 的配置优先于 realm。
|
||||
因此,即使 `Realm settings > Themes > Login theme` 已选择 `tjwater`,业务
|
||||
客户端如果仍指定 `keycloak`,从业务系统跳转后看到的还是默认登录页。
|
||||
|
||||
以授权地址中包含 `client_id=tjwater` 的业务系统为例:
|
||||
|
||||
1. 确认左上角当前 realm 是 `tjwater`。
|
||||
2. 在左侧菜单进入 `Clients`。
|
||||
3. 打开 `Client ID` 为 `tjwater` 的客户端。
|
||||
4. 在 `Settings` 页面找到 `Login settings > Login theme`。
|
||||
5. 将该字段设置为以下任一选项:
|
||||
- `Choose...`:不在 client 层指定主题,继承 realm 的 `tjwater` 主题,
|
||||
推荐使用此方式。
|
||||
- `tjwater`:在 client 层明确指定 `tjwater` 主题。
|
||||
6. 不要保留 `keycloak`,否则它会覆盖 realm 的主题。
|
||||
7. 点击 `Save`,关闭旧登录页,再从业务前端重新发起一次登录。
|
||||
|
||||
`Choose...` 不是未配置完成,而是表示当前 client 继承 realm 配置。管理控制台
|
||||
登录、账户中心和业务系统可能使用不同的 client。某一个入口已经显示
|
||||
`tjwater` 主题,并不能证明业务 client 也已正确配置。
|
||||
|
||||
验证时以业务系统实际生成的 OpenID Connect 授权地址为准,并检查其中的
|
||||
`client_id`。浏览器加载的主题资源路径应包含
|
||||
`/resources/<版本>/login/tjwater/`;如果路径仍包含
|
||||
`/resources/<版本>/login/keycloak/`,说明该 client 仍在使用默认主题。
|
||||
|
||||
如果 `Login theme` 下拉框中没有 `tjwater`,先检查容器内的主题文件:
|
||||
|
||||
```bash
|
||||
docker compose \
|
||||
--env-file .env \
|
||||
-f infra/docker/docker-compose.yml \
|
||||
exec -T keycloak \
|
||||
test -f /opt/keycloak/themes/tjwater/login/theme.properties
|
||||
```
|
||||
|
||||
命令成功但控制台仍未显示主题时,重新创建 Keycloak 容器后再检查:
|
||||
|
||||
```bash
|
||||
docker compose \
|
||||
--env-file .env \
|
||||
-f infra/docker/docker-compose.yml \
|
||||
up -d --force-recreate keycloak
|
||||
```
|
||||
|
||||
主题名称已经正确,但页面仍显示旧样式时,也执行上述命令,并在容器启动后使用
|
||||
`Ctrl+F5` 强制刷新登录页,避免继续使用浏览器缓存的 CSS。
|
||||
|
||||
## 启用
|
||||
|
||||
先启动 `infra/docker/docker-compose.yml` 中的 Keycloak,再从仓库根目录执行:
|
||||
|
||||
```bash
|
||||
bash infra/docker/keycloak/configure-theme.sh apply
|
||||
```
|
||||
|
||||
脚本默认配置 `tjwater` realm、简体中文默认语言、中英文切换和
|
||||
`TJWater 智慧水务平台` 品牌名,并清除 `tjwater` client 对登录主题的覆盖,
|
||||
使其继承 realm 主题。其他环境可临时覆盖:
|
||||
|
||||
```bash
|
||||
TJWATER_KEYCLOAK_REALM=example \
|
||||
TJWATER_KEYCLOAK_CLIENT_ID=example-web \
|
||||
TJWATER_KEYCLOAK_DISPLAY_NAME="示例智慧水务平台" \
|
||||
bash infra/docker/keycloak/configure-theme.sh apply
|
||||
```
|
||||
|
||||
管理员凭据继续使用 Compose 已注入的 `KC_BOOTSTRAP_ADMIN_USERNAME` /
|
||||
`KC_BOOTSTRAP_ADMIN_PASSWORD`,并兼容现有的 `KEYCLOAK_ADMIN` /
|
||||
`KEYCLOAK_ADMIN_PASSWORD`。
|
||||
|
||||
## 验证与回滚
|
||||
|
||||
```bash
|
||||
bash infra/docker/keycloak/configure-theme.sh verify
|
||||
bash infra/docker/keycloak/configure-theme.sh rollback
|
||||
```
|
||||
|
||||
使用 `latest` 镜像时,每次重新拉取 Keycloak 后都应重新执行 `verify`,并在
|
||||
1280px、375px 和 320px 视口检查登录、错误提示、忘记密码和 OTP 页面。
|
||||
@@ -1,115 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
action="${1:-apply}"
|
||||
script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
|
||||
repo_root="$(cd -- "${script_dir}/../../.." && pwd)"
|
||||
compose_file="${repo_root}/infra/docker/docker-compose.yml"
|
||||
realm="${TJWATER_KEYCLOAK_REALM:-tjwater}"
|
||||
client_id="${TJWATER_KEYCLOAK_CLIENT_ID:-tjwater}"
|
||||
display_name="${TJWATER_KEYCLOAK_DISPLAY_NAME:-TJWater 智慧水务平台}"
|
||||
|
||||
case "${action}" in
|
||||
apply|verify|rollback) ;;
|
||||
*)
|
||||
echo "用法: bash infra/docker/keycloak/configure-theme.sh [apply|verify|rollback]" >&2
|
||||
exit 2
|
||||
;;
|
||||
esac
|
||||
|
||||
compose_args=(docker compose)
|
||||
if [[ -f "${repo_root}/.env" ]]; then
|
||||
compose_args+=(--env-file "${repo_root}/.env")
|
||||
fi
|
||||
compose_args+=(-f "${compose_file}")
|
||||
|
||||
"${compose_args[@]}" exec -T \
|
||||
-e TJWATER_KEYCLOAK_ACTION="${action}" \
|
||||
-e TJWATER_KEYCLOAK_REALM="${realm}" \
|
||||
-e TJWATER_KEYCLOAK_CLIENT_ID="${client_id}" \
|
||||
-e TJWATER_KEYCLOAK_DISPLAY_NAME="${display_name}" \
|
||||
keycloak sh -s <<'KEYCLOAK_SCRIPT'
|
||||
set -eu
|
||||
|
||||
action="${TJWATER_KEYCLOAK_ACTION}"
|
||||
realm="${TJWATER_KEYCLOAK_REALM}"
|
||||
client_id="${TJWATER_KEYCLOAK_CLIENT_ID}"
|
||||
display_name="${TJWATER_KEYCLOAK_DISPLAY_NAME}"
|
||||
server_url="${TJWATER_KEYCLOAK_SERVER_URL:-http://127.0.0.1:8080}"
|
||||
admin_user="${KC_BOOTSTRAP_ADMIN_USERNAME:-${KEYCLOAK_ADMIN:-}}"
|
||||
admin_password="${KC_BOOTSTRAP_ADMIN_PASSWORD:-${KEYCLOAK_ADMIN_PASSWORD:-}}"
|
||||
config_file="/tmp/tjwater-kcadm-$$.config"
|
||||
kcadm="/opt/keycloak/bin/kcadm.sh"
|
||||
|
||||
cleanup() {
|
||||
rm -f "${config_file}"
|
||||
}
|
||||
trap cleanup EXIT
|
||||
|
||||
if [ -z "${admin_user}" ] || [ -z "${admin_password}" ]; then
|
||||
echo "缺少 Keycloak 管理员用户名或密码环境变量。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "${action}" = "apply" ] && [ ! -f /opt/keycloak/themes/tjwater/login/theme.properties ]; then
|
||||
echo "未找到 tjwater 登录主题,请检查主题目录挂载。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
"${kcadm}" config credentials \
|
||||
--config "${config_file}" \
|
||||
--server "${server_url}" \
|
||||
--realm master \
|
||||
--user "${admin_user}" \
|
||||
--password "${admin_password}" >/dev/null
|
||||
|
||||
client_uuid="$(
|
||||
"${kcadm}" get clients \
|
||||
--config "${config_file}" \
|
||||
--target-realm "${realm}" \
|
||||
--query "clientId=${client_id}" \
|
||||
--fields id \
|
||||
--format csv \
|
||||
--noquotes |
|
||||
sed -n '1p'
|
||||
)"
|
||||
|
||||
if [ -z "${client_uuid}" ]; then
|
||||
echo "realm ${realm} 中未找到 client ${client_id}。" >&2
|
||||
echo "可通过 TJWATER_KEYCLOAK_CLIENT_ID 指定实际的 client ID。" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
case "${action}" in
|
||||
apply)
|
||||
"${kcadm}" update "realms/${realm}" \
|
||||
--config "${config_file}" \
|
||||
-s "displayName=${display_name}" \
|
||||
-s "displayNameHtml=${display_name}" \
|
||||
-s "loginTheme=tjwater" \
|
||||
-s "internationalizationEnabled=true" \
|
||||
-s 'supportedLocales=["zh-CN","en"]' \
|
||||
-s "defaultLocale=zh-CN" >/dev/null
|
||||
"${kcadm}" update "clients/${client_uuid}" \
|
||||
--config "${config_file}" \
|
||||
--target-realm "${realm}" \
|
||||
--set attributes.login_theme= >/dev/null
|
||||
echo "已为 realm ${realm} 启用 tjwater 登录主题。"
|
||||
echo "client ${client_id} 已改为继承 realm 登录主题。"
|
||||
;;
|
||||
rollback)
|
||||
"${kcadm}" update "realms/${realm}" \
|
||||
--config "${config_file}" \
|
||||
-s "loginTheme=keycloak" >/dev/null
|
||||
echo "已将 realm ${realm} 恢复为 Keycloak 默认登录主题。"
|
||||
;;
|
||||
esac
|
||||
|
||||
"${kcadm}" get "realms/${realm}" \
|
||||
--config "${config_file}" \
|
||||
--fields realm,displayName,loginTheme,internationalizationEnabled,supportedLocales,defaultLocale
|
||||
"${kcadm}" get "clients/${client_uuid}" \
|
||||
--config "${config_file}" \
|
||||
--target-realm "${realm}" \
|
||||
--fields 'clientId,attributes(login_theme)'
|
||||
KEYCLOAK_SCRIPT
|
||||
@@ -1,44 +0,0 @@
|
||||
<#import "template.ftl" as layout>
|
||||
<#assign isLogout = message.summary == msg("successLogout")>
|
||||
<@layout.registrationLayout displayMessage=false; section>
|
||||
<#if section = "header">
|
||||
<#if isLogout>
|
||||
${kcSanitize(msg("tjwaterLogoutTitle"))?no_esc}
|
||||
<#elseif messageHeader??>
|
||||
${kcSanitize(msg("${messageHeader}"))?no_esc}
|
||||
<#else>
|
||||
${message.summary}
|
||||
</#if>
|
||||
<#elseif section = "form">
|
||||
<#if isLogout>
|
||||
<div id="kc-info-message" class="tjwater-logout-message" role="status">
|
||||
<div class="tjwater-logout-mark" aria-hidden="true">
|
||||
<span></span>
|
||||
</div>
|
||||
<div class="tjwater-logout-copy">
|
||||
<p class="tjwater-logout-eyebrow">${kcSanitize(msg("tjwaterLogoutEyebrow"))?no_esc}</p>
|
||||
<p class="tjwater-logout-description">${kcSanitize(msg("tjwaterLogoutDescription"))?no_esc}</p>
|
||||
</div>
|
||||
<#if pageRedirectUri?has_content>
|
||||
<a class="pf-v5-c-button pf-m-primary tjwater-logout-action" href="${pageRedirectUri}">${kcSanitize(msg("tjwaterReturnToApplication"))?no_esc}</a>
|
||||
<#elseif (client.baseUrl)?has_content>
|
||||
<a class="pf-v5-c-button pf-m-primary tjwater-logout-action" href="${client.baseUrl}">${kcSanitize(msg("tjwaterReturnToApplication"))?no_esc}</a>
|
||||
</#if>
|
||||
</div>
|
||||
<#else>
|
||||
<div id="kc-info-message">
|
||||
<p class="instruction">${message.summary}<#if requiredActions??><#list requiredActions>: <b><#items as reqActionItem>${kcSanitize(msg("requiredAction.${reqActionItem}"))?no_esc}<#sep>, </#items></b></#list><#else></#if></p>
|
||||
<#if skipLink??>
|
||||
<#else>
|
||||
<#if pageRedirectUri?has_content>
|
||||
<p><a href="${pageRedirectUri}">${kcSanitize(msg("backToApplication"))?no_esc}</a></p>
|
||||
<#elseif actionUri?has_content>
|
||||
<p><a href="${actionUri}">${kcSanitize(msg("proceedWithAction"))?no_esc}</a></p>
|
||||
<#elseif (client.baseUrl)?has_content>
|
||||
<p><a href="${client.baseUrl}">${kcSanitize(msg("backToApplication"))?no_esc}</a></p>
|
||||
</#if>
|
||||
</#if>
|
||||
</div>
|
||||
</#if>
|
||||
</#if>
|
||||
</@layout.registrationLayout>
|
||||
@@ -1,7 +0,0 @@
|
||||
loginAccountTitle=Account sign in
|
||||
doLogIn=Sign in
|
||||
doForgotPassword=Forgot password
|
||||
tjwaterLogoutTitle=Signed out securely
|
||||
tjwaterLogoutEyebrow=Your session has ended
|
||||
tjwaterLogoutDescription=Your platform and identity-provider sessions have been ended securely.
|
||||
tjwaterReturnToApplication=Return to sign in
|
||||
@@ -1,13 +0,0 @@
|
||||
loginAccountTitle=账号登录
|
||||
usernameOrEmail=用户名或邮箱
|
||||
doLogIn=登录
|
||||
doForgotPassword=忘记密码
|
||||
rememberMe=记住我
|
||||
invalidUserMessage=用户名或密码错误
|
||||
invalidUsernameOrPasswordMessage=用户名或密码错误
|
||||
expiredCodeMessage=登录已超时,请重新登录
|
||||
loginTimeout=登录已超时,请重新开始登录
|
||||
tjwaterLogoutTitle=已安全退出
|
||||
tjwaterLogoutEyebrow=会话已结束
|
||||
tjwaterLogoutDescription=您的平台与身份认证会话均已安全结束。
|
||||
tjwaterReturnToApplication=返回登录页
|
||||
@@ -1,589 +0,0 @@
|
||||
:root {
|
||||
--tjwater-canvas: oklch(0.965 0.014 205);
|
||||
--tjwater-surface: oklch(0.995 0.004 205);
|
||||
--tjwater-surface-soft: oklch(0.982 0.008 205);
|
||||
--tjwater-ink: oklch(0.3 0.055 215);
|
||||
--tjwater-muted: oklch(0.52 0.035 215);
|
||||
--tjwater-line: oklch(0.86 0.025 210);
|
||||
--tjwater-blue: oklch(0.57 0.16 242);
|
||||
--tjwater-blue-dark: oklch(0.49 0.15 242);
|
||||
--tjwater-teal: oklch(0.58 0.12 180);
|
||||
--tjwater-danger: oklch(0.55 0.19 27);
|
||||
--tjwater-radius-sm: 6px;
|
||||
--tjwater-radius-md: 12px;
|
||||
--tjwater-radius-lg: 18px;
|
||||
}
|
||||
|
||||
html.login-pf {
|
||||
height: 100%;
|
||||
min-height: 100%;
|
||||
overflow-x: hidden;
|
||||
background: var(--tjwater-canvas);
|
||||
}
|
||||
|
||||
body#keycloak-bg,
|
||||
.login-pf body {
|
||||
min-height: 100%;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
color: var(--tjwater-ink);
|
||||
background: var(--tjwater-canvas);
|
||||
font-family: -apple-system, BlinkMacSystemFont, "SF Pro Text", "Segoe UI",
|
||||
"PingFang SC", "Microsoft YaHei", "Noto Sans SC", sans-serif;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-moz-osx-font-smoothing: grayscale;
|
||||
}
|
||||
|
||||
.pf-v5-c-login,
|
||||
.pf-v5-c-login * {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
.pf-v5-c-login {
|
||||
min-height: 100svh;
|
||||
padding: 0;
|
||||
background-color: var(--tjwater-canvas);
|
||||
background-image:
|
||||
linear-gradient(
|
||||
90deg,
|
||||
transparent 0%,
|
||||
transparent 50%,
|
||||
oklch(0.975 0.01 205 / 62%) 68%,
|
||||
oklch(0.975 0.01 205 / 82%) 100%
|
||||
),
|
||||
url("../img/network-blueprint.svg");
|
||||
background-position: center;
|
||||
background-repeat: no-repeat;
|
||||
background-size: cover;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__container {
|
||||
display: grid;
|
||||
width: 100%;
|
||||
max-width: 1720px;
|
||||
min-height: 100svh;
|
||||
margin: 0 auto;
|
||||
padding: clamp(32px, 4.5vw, 76px) clamp(40px, 5vw, 88px);
|
||||
grid-template-columns: minmax(360px, 1fr) minmax(400px, 460px);
|
||||
grid-template-areas: "header main";
|
||||
align-items: center;
|
||||
gap: clamp(64px, 8vw, 152px);
|
||||
}
|
||||
|
||||
#kc-header {
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
grid-area: header;
|
||||
width: fit-content;
|
||||
max-width: 100%;
|
||||
align-self: center;
|
||||
justify-self: start;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
isolation: isolate;
|
||||
animation: tjwater-enter 480ms cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||
}
|
||||
|
||||
#kc-header::before {
|
||||
position: absolute;
|
||||
z-index: -1;
|
||||
inset: -54px -72px;
|
||||
background: radial-gradient(
|
||||
ellipse at center,
|
||||
oklch(0.925 0.018 205 / 98%) 0%,
|
||||
oklch(0.925 0.018 205 / 94%) 48%,
|
||||
oklch(0.925 0.018 205 / 62%) 65%,
|
||||
transparent 82%
|
||||
);
|
||||
pointer-events: none;
|
||||
content: "";
|
||||
}
|
||||
|
||||
#kc-header-wrapper {
|
||||
display: flex;
|
||||
max-width: 680px;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
color: var(--tjwater-ink) !important;
|
||||
font-size: clamp(34px, 3vw, 46px);
|
||||
font-weight: 720;
|
||||
line-height: 1.28;
|
||||
letter-spacing: 0;
|
||||
text-align: left;
|
||||
text-transform: none;
|
||||
text-wrap: balance;
|
||||
}
|
||||
|
||||
#kc-header-wrapper::before {
|
||||
width: 56px;
|
||||
height: 56px;
|
||||
margin-bottom: 24px;
|
||||
background: url("../img/logo-mark.svg") center / contain no-repeat;
|
||||
content: "";
|
||||
}
|
||||
|
||||
#kc-header-wrapper::after {
|
||||
width: 64px;
|
||||
height: 3px;
|
||||
margin-top: 26px;
|
||||
border-radius: 999px;
|
||||
background: var(--tjwater-teal);
|
||||
content: "";
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main {
|
||||
grid-area: main;
|
||||
width: 100%;
|
||||
max-width: 460px;
|
||||
margin: 0;
|
||||
align-self: center;
|
||||
justify-self: stretch;
|
||||
overflow: hidden;
|
||||
border: 0;
|
||||
border-radius: var(--tjwater-radius-lg);
|
||||
background: oklch(0.995 0.004 205 / 97%);
|
||||
box-shadow:
|
||||
0 32px 80px rgb(22 65 75 / 16%),
|
||||
0 5px 18px rgb(22 65 75 / 9%);
|
||||
animation: tjwater-enter 520ms 70ms cubic-bezier(0.16, 1, 0.3, 1) both;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-header {
|
||||
display: grid;
|
||||
margin: 0;
|
||||
padding: 36px 36px 18px;
|
||||
grid-template-columns: minmax(0, 1fr) auto;
|
||||
gap: 20px;
|
||||
align-items: center;
|
||||
border-top: 0;
|
||||
}
|
||||
|
||||
#kc-page-title {
|
||||
margin: 0;
|
||||
color: var(--tjwater-ink);
|
||||
font-size: 26px;
|
||||
font-weight: 720;
|
||||
line-height: 1.4;
|
||||
letter-spacing: 0;
|
||||
text-wrap: balance;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-header-utilities {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-body {
|
||||
margin: 0;
|
||||
padding: 0 36px 38px;
|
||||
}
|
||||
|
||||
.pf-v5-c-form {
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.pf-v5-c-form__group {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.pf-v5-c-form__group-label {
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.pf-v5-c-form__label-text {
|
||||
color: var(--tjwater-ink);
|
||||
font-size: 14px;
|
||||
font-weight: 650;
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.pf-v5-c-form-control {
|
||||
min-height: 48px;
|
||||
overflow: hidden;
|
||||
border: 1px solid var(--tjwater-line);
|
||||
border-radius: var(--tjwater-radius-sm);
|
||||
background: var(--tjwater-surface-soft);
|
||||
box-shadow: none;
|
||||
transition-property: border-color, box-shadow, background-color;
|
||||
transition-duration: 160ms;
|
||||
transition-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
.pf-v5-c-form-control::before,
|
||||
.pf-v5-c-form-control::after {
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.pf-v5-c-form-control:focus-within {
|
||||
border-color: var(--tjwater-blue);
|
||||
background: var(--tjwater-surface);
|
||||
box-shadow: 0 0 0 3px oklch(0.78 0.1 235 / 28%);
|
||||
}
|
||||
|
||||
.pf-v5-c-form-control > input,
|
||||
.pf-v5-c-form-control > select {
|
||||
min-height: 46px;
|
||||
padding-inline: 14px;
|
||||
color: var(--tjwater-ink);
|
||||
font-size: 16px;
|
||||
outline: 0;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-header-utilities .pf-v5-c-form-control {
|
||||
width: 116px;
|
||||
min-height: 40px;
|
||||
background: var(--tjwater-surface);
|
||||
}
|
||||
|
||||
#login-select-toggle {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
min-height: 38px;
|
||||
padding-inline: 12px 32px;
|
||||
color: var(--tjwater-muted);
|
||||
font-size: 14px;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.pf-v5-c-form-control.pf-m-error {
|
||||
border-color: var(--tjwater-danger);
|
||||
}
|
||||
|
||||
.pf-v5-c-input-group {
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.pf-v5-c-input-group__item.pf-m-fill {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.pf-v5-c-button.pf-m-control {
|
||||
min-width: 48px;
|
||||
min-height: 48px;
|
||||
border: 1px solid var(--tjwater-line);
|
||||
border-radius: var(--tjwater-radius-sm);
|
||||
color: var(--tjwater-muted);
|
||||
background: var(--tjwater-surface-soft);
|
||||
touch-action: manipulation;
|
||||
transition-property: color, border-color, background-color, transform;
|
||||
transition-duration: 160ms;
|
||||
transition-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
.pf-v5-c-button.pf-m-control:active {
|
||||
transform: scale(0.96);
|
||||
}
|
||||
|
||||
.pf-v5-c-button.pf-m-control:focus-visible,
|
||||
.pf-v5-c-button.pf-m-primary:focus-visible,
|
||||
.pf-v5-c-button.pf-m-secondary:focus-visible,
|
||||
a:focus-visible {
|
||||
outline: 3px solid oklch(0.74 0.12 235 / 60%);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
|
||||
.pf-v5-c-form__helper-text {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.pf-v5-c-helper-text {
|
||||
min-height: 22px;
|
||||
}
|
||||
|
||||
.pf-v5-c-helper-text__item-text {
|
||||
color: var(--tjwater-muted);
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.pf-v5-c-helper-text__item-text a,
|
||||
#kc-registration a,
|
||||
.pf-v5-c-login__main-footer a {
|
||||
color: var(--tjwater-blue-dark);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
text-underline-offset: 3px;
|
||||
}
|
||||
|
||||
.kc-feedback-text.pf-m-error,
|
||||
.pf-v5-c-helper-text__item.pf-m-error .kc-feedback-text {
|
||||
color: var(--tjwater-danger);
|
||||
}
|
||||
|
||||
.pf-v5-c-check__input {
|
||||
accent-color: var(--tjwater-blue);
|
||||
}
|
||||
|
||||
.pf-v5-c-check__label {
|
||||
color: var(--tjwater-muted);
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.pf-v5-c-form__actions {
|
||||
padding-top: 6px;
|
||||
}
|
||||
|
||||
.pf-v5-c-button.pf-m-primary {
|
||||
min-height: 48px;
|
||||
border: 0;
|
||||
border-radius: var(--tjwater-radius-md);
|
||||
color: oklch(0.99 0.004 230);
|
||||
background: var(--tjwater-blue);
|
||||
font-size: 16px;
|
||||
font-weight: 700;
|
||||
box-shadow: 0 8px 18px oklch(0.48 0.15 242 / 20%);
|
||||
touch-action: manipulation;
|
||||
transition-property: transform, background-color, box-shadow;
|
||||
transition-duration: 160ms;
|
||||
transition-timing-function: cubic-bezier(0.16, 1, 0.3, 1);
|
||||
}
|
||||
|
||||
.pf-v5-c-button.pf-m-primary:active {
|
||||
transform: scale(0.96);
|
||||
background: var(--tjwater-blue-dark);
|
||||
box-shadow: 0 4px 10px oklch(0.48 0.15 242 / 18%);
|
||||
}
|
||||
|
||||
.pf-v5-c-button.pf-m-secondary {
|
||||
min-height: 44px;
|
||||
border-radius: var(--tjwater-radius-md);
|
||||
color: var(--tjwater-blue-dark);
|
||||
border-color: var(--tjwater-line);
|
||||
}
|
||||
|
||||
.pf-v5-c-alert {
|
||||
border-radius: var(--tjwater-radius-md);
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-footer {
|
||||
color: var(--tjwater-muted);
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-footer-band {
|
||||
margin-top: 26px;
|
||||
padding: 18px 0 0;
|
||||
border-top: 1px solid var(--tjwater-line);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.tjwater-logout-message {
|
||||
display: grid;
|
||||
gap: 20px;
|
||||
padding-top: 4px;
|
||||
}
|
||||
|
||||
.tjwater-logout-mark {
|
||||
display: grid;
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border: 1px solid oklch(0.76 0.09 184 / 52%);
|
||||
border-radius: 50%;
|
||||
background: oklch(0.92 0.04 184 / 58%);
|
||||
place-items: center;
|
||||
}
|
||||
|
||||
.tjwater-logout-mark span {
|
||||
width: 18px;
|
||||
height: 10px;
|
||||
border-bottom: 3px solid var(--tjwater-teal);
|
||||
border-left: 3px solid var(--tjwater-teal);
|
||||
transform: translateY(-2px) rotate(-45deg);
|
||||
}
|
||||
|
||||
.tjwater-logout-copy {
|
||||
display: grid;
|
||||
gap: 7px;
|
||||
}
|
||||
|
||||
.tjwater-logout-eyebrow {
|
||||
margin: 0;
|
||||
color: var(--tjwater-ink);
|
||||
font-size: 17px;
|
||||
font-weight: 700;
|
||||
line-height: 1.45;
|
||||
}
|
||||
|
||||
.tjwater-logout-description {
|
||||
margin: 0;
|
||||
color: var(--tjwater-muted);
|
||||
font-size: 14px;
|
||||
line-height: 1.75;
|
||||
}
|
||||
|
||||
.tjwater-logout-action {
|
||||
display: inline-flex;
|
||||
width: 100%;
|
||||
min-height: 48px;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
text-align: center;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
@keyframes tjwater-enter {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateY(12px);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateY(0);
|
||||
}
|
||||
}
|
||||
|
||||
@media (hover: hover) {
|
||||
.pf-v5-c-button.pf-m-primary:hover {
|
||||
background: var(--tjwater-blue-dark);
|
||||
box-shadow: 0 10px 22px oklch(0.48 0.15 242 / 25%);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.pf-v5-c-button.pf-m-control:hover {
|
||||
color: var(--tjwater-blue-dark);
|
||||
border-color: oklch(0.69 0.08 230);
|
||||
background: var(--tjwater-surface);
|
||||
}
|
||||
|
||||
.pf-v5-c-helper-text__item-text a:hover,
|
||||
#kc-registration a:hover,
|
||||
.pf-v5-c-login__main-footer a:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 900px) {
|
||||
.pf-v5-c-login {
|
||||
background-image:
|
||||
linear-gradient(oklch(0.965 0.014 205 / 34%), oklch(0.965 0.014 205 / 34%)),
|
||||
url("../img/network-blueprint.svg");
|
||||
background-position: 34% center;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__container {
|
||||
max-width: 560px;
|
||||
padding:
|
||||
max(28px, env(safe-area-inset-top))
|
||||
max(24px, env(safe-area-inset-right))
|
||||
max(32px, env(safe-area-inset-bottom))
|
||||
max(24px, env(safe-area-inset-left));
|
||||
grid-template-columns: minmax(0, 1fr);
|
||||
grid-template-areas:
|
||||
"header"
|
||||
"main";
|
||||
align-content: center;
|
||||
gap: 24px;
|
||||
}
|
||||
|
||||
#kc-header-wrapper {
|
||||
max-width: none;
|
||||
flex-direction: row;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
font-size: clamp(22px, 5vw, 28px);
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
#kc-header::before {
|
||||
inset: -24px -20px;
|
||||
background: radial-gradient(
|
||||
ellipse at center,
|
||||
oklch(0.965 0.014 205 / 98%) 0%,
|
||||
oklch(0.965 0.014 205 / 88%) 58%,
|
||||
transparent 84%
|
||||
);
|
||||
}
|
||||
|
||||
#kc-header-wrapper::before {
|
||||
width: 46px;
|
||||
height: 46px;
|
||||
margin: 0;
|
||||
flex: 0 0 46px;
|
||||
}
|
||||
|
||||
#kc-header-wrapper::after {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main {
|
||||
max-width: none;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.pf-v5-c-login__container {
|
||||
gap: 18px;
|
||||
padding-inline:
|
||||
max(14px, env(safe-area-inset-left))
|
||||
max(14px, env(safe-area-inset-right));
|
||||
}
|
||||
|
||||
#kc-header-wrapper {
|
||||
gap: 12px;
|
||||
font-size: 21px;
|
||||
}
|
||||
|
||||
#kc-header-wrapper::before {
|
||||
width: 42px;
|
||||
height: 42px;
|
||||
flex-basis: 42px;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main {
|
||||
border-radius: 16px;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-header {
|
||||
gap: 12px;
|
||||
padding: 26px 22px 15px;
|
||||
}
|
||||
|
||||
#kc-page-title {
|
||||
font-size: 23px;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-header-utilities .pf-v5-c-form-control {
|
||||
width: 108px;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-body {
|
||||
padding: 0 22px 28px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-height: 680px) and (min-width: 901px) {
|
||||
.pf-v5-c-login__container {
|
||||
padding-block: 24px;
|
||||
}
|
||||
|
||||
#kc-header-wrapper::before {
|
||||
width: 48px;
|
||||
height: 48px;
|
||||
margin-bottom: 18px;
|
||||
}
|
||||
|
||||
#kc-header-wrapper::after {
|
||||
margin-top: 20px;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-header {
|
||||
padding-top: 28px;
|
||||
}
|
||||
|
||||
.pf-v5-c-login__main-body {
|
||||
padding-bottom: 30px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
#kc-header,
|
||||
.pf-v5-c-login__main {
|
||||
animation: none;
|
||||
}
|
||||
|
||||
.pf-v5-c-button,
|
||||
.pf-v5-c-form-control {
|
||||
transition-duration: 0.01ms;
|
||||
}
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 72 72" role="img" aria-labelledby="title">
|
||||
<title id="title">TJWater</title>
|
||||
<rect width="72" height="72" rx="18" fill="#1478d4"/>
|
||||
<path d="M36 13c-7.8 11.1-16.1 19.4-16.1 29.3A16.1 16.1 0 0 0 36 58.4a16.1 16.1 0 0 0 16.1-16.1C52.1 32.4 43.8 24.1 36 13Z" fill="#f5fbfc"/>
|
||||
<path d="M26.5 43.5h19M31 36.5l5 7 5-7" fill="none" stroke="#0b8f82" stroke-linecap="round" stroke-linejoin="round" stroke-width="3"/>
|
||||
<circle cx="26.5" cy="43.5" r="2.7" fill="#0b8f82"/>
|
||||
<circle cx="45.5" cy="43.5" r="2.7" fill="#0b8f82"/>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 585 B |
@@ -1,39 +0,0 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1440 900" preserveAspectRatio="xMidYMid slice">
|
||||
<rect width="1440" height="900" fill="#edf5f5"/>
|
||||
<path d="M0 0h790L650 900H0Z" fill="#dceced"/>
|
||||
<path d="M0 182c187-78 303-73 451-16 153 59 288 47 409-25M0 552c193-45 327-19 461 74 128 90 266 100 410 47" fill="none" stroke="#c8dddd" stroke-width="2"/>
|
||||
<g fill="none" stroke="#a9ccce" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M-32 725 178 608l142 51 155-190 184 67 176-205" stroke-width="5"/>
|
||||
<path d="m178 608 25-222 151-92 121 175" stroke-width="3"/>
|
||||
<path d="m203 386-92-95 55-161M354 294l92-141 152 58 98-106" stroke-width="3"/>
|
||||
<path d="m320 659-4 132 171 81M659 536l88 116 124-42" stroke-width="3"/>
|
||||
</g>
|
||||
<g fill="#edf5f5" stroke="#1478d4" stroke-width="4">
|
||||
<circle cx="178" cy="608" r="10"/>
|
||||
<circle cx="203" cy="386" r="9"/>
|
||||
<circle cx="354" cy="294" r="9"/>
|
||||
<circle cx="475" cy="469" r="11"/>
|
||||
<circle cx="659" cy="536" r="10"/>
|
||||
<circle cx="747" cy="652" r="9"/>
|
||||
<circle cx="320" cy="659" r="8"/>
|
||||
</g>
|
||||
<g fill="#0b8f82">
|
||||
<circle cx="111" cy="291" r="6"/>
|
||||
<circle cx="166" cy="130" r="6"/>
|
||||
<circle cx="446" cy="153" r="7"/>
|
||||
<circle cx="598" cy="211" r="6"/>
|
||||
<circle cx="696" cy="105" r="6"/>
|
||||
<circle cx="316" cy="791" r="6"/>
|
||||
<circle cx="487" cy="872" r="6"/>
|
||||
<circle cx="835" cy="331" r="7"/>
|
||||
</g>
|
||||
<g fill="none" stroke="#86b8bb" stroke-width="2" opacity=".72">
|
||||
<circle cx="615" cy="448" r="222"/>
|
||||
<circle cx="615" cy="448" r="276"/>
|
||||
<circle cx="615" cy="448" r="334"/>
|
||||
</g>
|
||||
<g fill="#1478d4" opacity=".08">
|
||||
<rect x="40" y="40" width="118" height="10" rx="5"/>
|
||||
<rect x="40" y="62" width="72" height="6" rx="3"/>
|
||||
</g>
|
||||
</svg>
|
||||
|
Before Width: | Height: | Size: 1.7 KiB |
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user