Compare commits

...

36 Commits

Author SHA1 Message Date
imbytecat 7b2ae856b7 fix(prediction): 适配预测服务最小请求字段 2026-05-12 01:49:19 +08:00
imbytecat c00e04dfb0 fix(prediction): 跳过缺少遥测字段的预测请求 2026-05-12 01:43:46 +08:00
imbytecat 305ed1b692 fix(domain): 使用空值表示缺失业务指标 2026-05-12 01:09:10 +08:00
imbytecat 1126fad2c2 fix(prediction): 使用真实历史字段请求预测 2026-05-12 01:09:09 +08:00
imbytecat 76854fe23b fix(api): 禁用未启用的 OpenAPI 端点 2026-05-12 01:09:09 +08:00
imbytecat e6b351e39c feat(ui): 优化看板和设备列表体验 2026-05-12 01:01:15 +08:00
imbytecat 6014af2690 feat(ui): 添加空态和骨架组件 2026-05-12 01:01:15 +08:00
imbytecat 4147d15a42 chore(pkg): 更新项目包元数据 2026-05-12 00:57:20 +08:00
imbytecat 282fdbc2a6 fix(ui): 完整遵守减少动态效果偏好 2026-05-12 00:56:33 +08:00
imbytecat ad32500121 fix(dashboard): 使用稳定设备标识 2026-05-12 00:56:33 +08:00
imbytecat 9fb37b29c2 fix(data): 统一 MySQL 时间和布尔规范化 2026-05-12 00:56:33 +08:00
imbytecat 2d068fa66b docs(api): 说明接口文档启用方式 2026-05-12 00:52:43 +08:00
imbytecat 779c9c2338 fix(prediction): 缓存不可用预测结果 2026-05-12 00:52:43 +08:00
imbytecat fad890abe1 fix(api): 默认关闭接口文档 2026-05-12 00:52:43 +08:00
imbytecat 11cf298332 fix(ui): 限制分页游标历史长度 2026-05-12 00:48:16 +08:00
imbytecat 25d7f1c315 fix(api): 修正看板和历史统计口径 2026-05-12 00:48:16 +08:00
imbytecat 58b615a327 style(ui): 移除过期原生下拉样式 2026-05-12 00:45:00 +08:00
imbytecat 8f953cd6a1 feat(ui): 替换原生下拉控件 2026-05-12 00:39:44 +08:00
imbytecat 84e3f02752 chore(deps): 添加 Radix Select 依赖 2026-05-12 00:39:44 +08:00
imbytecat 2dabbd1281 feat(ui): 添加克制页面动效 2026-05-12 00:30:16 +08:00
imbytecat 602f969117 chore(deps): 添加 Motion 动效依赖 2026-05-12 00:30:16 +08:00
imbytecat 32946b25fa docs: 优化交付文档表达 2026-05-12 00:18:00 +08:00
imbytecat 50e8e32bac fix(ui): 修复充电状态筛选重置 2026-05-12 00:18:00 +08:00
imbytecat 4571cee2a1 feat(ui): 优化电池实时状态筛选体验 2026-05-12 00:07:15 +08:00
imbytecat 38943f239f feat(ui): 增强电池看板状态表达 2026-05-12 00:07:15 +08:00
imbytecat 5d9aa660d8 fix(domain): 移除虚构 SoH 趋势语义 2026-05-12 00:07:15 +08:00
imbytecat e9568bca8c chore(dev): 统一 Compose 环境变量格式 2026-05-11 23:42:28 +08:00
imbytecat ba4aa96baf docs(prediction): 明确 SoH 预测必填依赖 2026-05-11 23:38:38 +08:00
imbytecat 8a3d5fd947 fix(env): 要求配置 SoH 预测服务 2026-05-11 23:38:38 +08:00
imbytecat a131bb845b fix(dashboard): 正确展示 SoH 预测不可用 2026-05-11 23:38:37 +08:00
imbytecat 99d9cd1e1d refactor(api): 复用电池业务常量 2026-05-11 23:38:37 +08:00
imbytecat dc8a595d0a refactor(domain): 集中电池业务常量 2026-05-11 23:38:37 +08:00
imbytecat a8e3cf5f4b docs(api): 更新电池分页接口说明 2026-05-11 23:16:59 +08:00
imbytecat c533113229 feat(ui): 重构电池列表分页表格 2026-05-11 23:16:59 +08:00
imbytecat 69c4a2e9eb fix(api): 收紧电池列表查询输入 2026-05-11 23:16:59 +08:00
imbytecat dd4a447dcd style: 格式化后端改造代码 2026-05-11 23:16:59 +08:00
22 changed files with 1885 additions and 642 deletions
+7 -3
View File
@@ -1,11 +1,15 @@
DATABASE_URL=mysql://user:password@localhost:3306/database DATABASE_URL=mysql://user:password@localhost:3306/database
# Optional: external AI SoH prediction service. # 默认关闭公开 OpenAPI 文档/规格;仅在受控本地或内网演示环境显式启用。
# SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000 # ENABLE_API_DOCS=false
# 必填:外部 SoH 预测服务地址
SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000
# SOH_PREDICTION_CACHE_TTL_SECONDS=86400 # SOH_PREDICTION_CACHE_TTL_SECONDS=86400
# SOH_PREDICTION_NEGATIVE_CACHE_TTL_SECONDS=300
# SOH_PREDICTION_TIMEOUT_MS=10000 # SOH_PREDICTION_TIMEOUT_MS=10000
# Optional logging knobs (defaults are usually fine): # 可选:日志级别与输出格式
# LOG_LEVEL=info # trace|debug|info|warning|error|fatal # LOG_LEVEL=info # trace|debug|info|warning|error|fatal
# LOG_FORMAT=pretty # pretty|json — defaults to TTY ? pretty : json # LOG_FORMAT=pretty # pretty|json — defaults to TTY ? pretty : json
# LOG_DB=false # reserved for database query logging if enabled later # LOG_DB=false # reserved for database query logging if enabled later
+5 -4
View File
@@ -33,7 +33,7 @@ Environment variable:
DATABASE_URL=mysql://user:password@host:3306/database DATABASE_URL=mysql://user:password@host:3306/database
``` ```
Optional AI prediction service: Required AI prediction service:
```bash ```bash
SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000 SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000
@@ -62,9 +62,9 @@ Rules:
- Do not add mock/fallback rows. If MySQL is unavailable, surface the error. - Do not add mock/fallback rows. If MySQL is unavailable, surface the error.
- `is_low_power` is stored as a string and normalized to boolean in `src/domain/battery.ts`. - `is_low_power` is stored as a string and normalized to boolean in `src/domain/battery.ts`.
- `power_status` is normalized to `0 | 1 | 2`. - `power_status` is normalized to `0 | 1 | 2`.
- Without `mac`, battery list queries return the latest record per `mac`. - `battery.batteries` returns paginated latest records per `mac`; supported filters are `pageSize`, `cursor`, `search`, `lowPower`, `powerStatus`, and `sort`.
- With `mac`, battery list queries return history ordered by `create_time DESC, id DESC`, limited to 500 rows. - `battery.history` takes `mac` and returns history ordered by `create_time DESC, id DESC`, limited to 500 rows.
- Dashboard may call the external prediction API when `SOH_PREDICTION_API_BASE_URL` is configured. Prediction results are cached in memory by `mac` and latest history record. - Dashboard requires the external prediction API via `SOH_PREDICTION_API_BASE_URL`; missing configuration must fail environment validation. Per-device prediction failures may surface as unavailable values, but must not be rendered as `0%`.
## Layout ## Layout
@@ -91,6 +91,7 @@ src/
- Current business API: - Current business API:
- `battery.dashboard` - `battery.dashboard`
- `battery.batteries` - `battery.batteries`
- `battery.history`
## CLI And Deploy ## CLI And Deploy
+77 -53
View File
@@ -1,39 +1,60 @@
# battery-soh # battery-soh
一个基于 **Bun + TanStack Start + ORPC** 的电池健康展示系统。应用会被打包成单个二进制文件,前端页面、SSR 服务和 ORPC API 一起发布;业务数据只读接入甲方现有 MySQL 表 `ls_battery_info`,本项目不写入、不迁移、不修改甲方数据库 电池健康运营看板,用于接入客户现有设备数据,持续呈现电量状态、健康预测、风险分布与维护建议。系统以只读方式连接客户数据库,不改动生产数据;当健康预测暂不可用时,页面会明确显示不可用状态,避免用误导性数值替代真实结果
## 数据源 ## 产品能力
甲方提供的只读表结构: - **健康总览**:聚合展示设备规模、平均健康度、30/90 天趋势与预警设备占比。
- **风险识别**:按健康度、低电量、充电状态与预测风险生成重点关注设备清单。
- **实时明细**:支持按设备名称、编号、电量与充电状态筛选设备,快速定位需要排查的对象。
- **维护建议**:基于当前可用数据给出巡检、复查与优先处理建议。
- **可信展示**:缺少预测结果时显示“预测不可用”,不会将缺失值渲染为 `0%`
| 字段名 | 数据类型 | 说明 | ## 数据接入
| --- | --- | --- |
| `id` | `int(11)` 自增 | 主键 ID |
| `user_id` | `int(11)` | 用户 ID |
| `mac` | `varchar(50)` | 设备 MAC |
| `dev_model` | `varchar(20)` | 设备型号 |
| `dev_name` | `varchar(50)` | 设备名称 |
| `is_low_power` | `varchar(10)` | 是否低电量:`true` / `false` |
| `power_status` | `tinyint(4)` | `0` 未充电,`1` 正在充电,`2` 充电完成 |
| `power` | `tinyint(4)` | 当前电量 `0~100` |
| `create_time` | `datetime` | 创建时间 |
| `remark` | `varchar(500)` | 备注,可空 |
环境变量 系统接入客户现有 MySQL 数据源,业务运行时仅执行只读查询。需要配置
```bash ```bash
DATABASE_URL=mysql://user:password@host:3306/database DATABASE_URL=mysql://user:password@host:3306/database
``` ```
可选 AI SoH 预测服务: 客户设备表:`ls_battery_info`
| 字段名 | 数据类型 | 业务含义 |
| --- | --- | --- |
| `id` | `int(11)` auto increment | 记录 ID |
| `user_id` | `int(11)` | 用户 ID |
| `mac` | `varchar(50)` | 设备编号 |
| `dev_model` | `varchar(20)` | 设备型号 |
| `dev_name` | `varchar(50)` | 设备名称 |
| `is_low_power` | `varchar(10)` | 是否低电量:`true` / `false` |
| `power_status` | `tinyint(4)` | `0` 未充电,`1` 充电中,`2` 已充满 |
| `power` | `tinyint(4)` | 当前电量 `0~100` |
| `create_time` | `datetime` | 采集时间 |
| `remark` | `varchar(500)` | 备注 |
## 健康预测
看板需要接入外部 SoH 预测服务:
```bash ```bash
SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000 SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000
SOH_PREDICTION_CACHE_TTL_SECONDS=86400 SOH_PREDICTION_CACHE_TTL_SECONDS=86400
SOH_PREDICTION_NEGATIVE_CACHE_TTL_SECONDS=300
SOH_PREDICTION_TIMEOUT_MS=10000 SOH_PREDICTION_TIMEOUT_MS=10000
``` ```
配置后,服务端会 `${SOH_PREDICTION_API_BASE_URL}/predict` 发起 POST 请求,并把返回的 `now_soh``month_soh``trmonth_soh``risk_score` 等字段用于看板展示。预测结果按设备最新采集记录做内存 TTL 缓存,默认 24 小时;如果未配置或预测服务失败,看板仍使用 MySQL 采集数据生成展示,不写入数据库 服务端会调用 `${SOH_PREDICTION_API_BASE_URL}/predict`,使用返回的当前健康度、30 天趋势、90 天趋势和风险评分生成看板视图。预测结果按设备最新采集记录缓存,默认 24 小时;单台设备预测失败或历史数据不足时会短暂缓存不可用状态,默认 5 分钟,避免反复打满预测服务,同时仅该设备显示为“预测不可用”
## 接口文档
OpenAPI 文档和规格默认不公开,生产或生产类运行环境应保持默认值:
```bash
ENABLE_API_DOCS=false
```
仅在受控本地开发或内网演示环境显式设置 `ENABLE_API_DOCS=true` 后,才会开放 `http://localhost:3000/api/docs``http://localhost:3000/api/spec.json``/api/rpc` 不受此开关影响。
## 快速开始 ## 快速开始
@@ -43,52 +64,55 @@ bun install
bun run dev bun run dev
``` ```
如果甲方暂时没有提供数据库连接,可以用 Docker Compose 启动本地 MySQL 并填充示例数据 打开浏览器
- `http://localhost:3000/`:设备健康运营看板
- `http://localhost:3000/batteries`:设备状态明细
- `http://localhost:3000/api/docs`:接口文档(需设置 `ENABLE_API_DOCS=true`
## 本地演示环境
如果暂时没有生产数据库连接,可以使用 Docker Compose 启动本地 MySQL 并填充演示数据:
```bash ```bash
docker compose up --build docker compose up --build
``` ```
Compose 会启动三个服务 Compose 会启动:
- `db`:本地 MySQL 8.4 - `db`:本地 MySQL 8.4
- `seed`执行 `bun run seed`,用 Drizzle MySQL schema + `drizzle-seed` 重置本地 `ls_battery_info` 并写入示例数据 - `seed`初始化本地 `ls_battery_info` 演示数据
- `app`使用同一个 `DATABASE_URL` 启动单二进制应用 - `app`启动应用服务
也可以手动 seed 本地库: Compose 的 `app` 服务会为本地演示显式启用 `ENABLE_API_DOCS=true`;生产部署不应沿用该设置,除非已通过网络边界或上游认证限制访问。
也可以手动初始化本地数据:
```bash ```bash
DATABASE_URL=mysql://battery:battery@localhost:3306/battery_soh bun run seed DATABASE_URL=mysql://battery:battery@localhost:3306/battery_soh bun run seed
``` ```
`seed` 本地开发/验收脚本,会建表并重置示例数据;应用运行时仍然只执行 `SELECT`,不写入数据库。 `seed` 仅用于本地开发和演示环境;应用运行时仍保持只读查询,不写入业务数据库。
打开浏览器: ## 系统结构
- `http://localhost:3000/`SoH 预测与风险洞察看板 ```text
- `http://localhost:3000/batteries`:设备电池实时状态
- `http://localhost:3000/api/docs`Scalar 渲染的 ORPC OpenAPI 文档
## 架构
```
src/ src/
├── routes/ # TanStack Start 文件路由:页面 + API 端点 ├── routes/ # 页面与 API 路由
├── server/ ├── server/
│ ├── api/ # ORPC contract / router │ ├── api/ # 接口契约与路由
│ ├── battery/mysql.ts # 甲方 MySQL 只读查询 │ ├── battery/mysql.ts # 设备数据只读查询
│ └── prediction/client.ts # AI SoH 预测客户端与缓存 │ └── prediction/client.ts # 健康预测服务客户端
├── domain/battery.ts # 电池领域类型、归一化、展示聚合 ├── domain/battery.ts # 电池领域模型与看板聚合
├── client/orpc.ts # isomorphic ORPC client ├── client/orpc.ts # 前端接口客户端
└── styles.css # Tailwind v4 entry └── styles.css # 全局样式入口
``` ```
接口保持模板里的 ORPC 模式 核心接口:
- `battery.dashboard`读取每个 `mac` 的最新记录并生成看板聚合数据 - `battery.dashboard`生成健康运营看板数据
- `battery.batteries``mac`返回每台设备最新记录;带 `mac` 时返回该设备历史记录,按 `create_time desc` 限制 500 条 - `battery.batteries`分页返回每台设备最新状态,支持搜索、筛选和排序。
- `battery.history`:返回单台设备最近 500 条历史记录。
所有业务查询都是 `SELECT`,没有 mutation,也没有 mock/fallback 数据。
## 部署 ## 部署
@@ -98,21 +122,21 @@ bun run compile
./out/server-<target> ./out/server-<target>
``` ```
Docker 镜像会在构建阶段产出单个 `./server` 二进制,运行阶段只需要配置 `DATABASE_URL` 构建产物为单个服务二进制文件,运行需要配置 `DATABASE_URL` 与 SoH 预测服务地址
## 脚本 ## 常用命令
| 命令 | 作用 | | 命令 | 作用 |
| --- | --- | | --- | --- |
| `bun run dev` | Vite 开发服务 | | `bun run dev` | 启动开发服务 |
| `bun run build` | 构建`.output/` | | `bun run build` | 构建应用 |
| `bun run compile` | 生成单二进制 `out/server-<target>` | | `bun run compile` | 生成单二进制产物 |
| `bun run seed` | 为本地 MySQL 创建甲方表并填充示例数据 | | `bun run seed` | 初始化本地演示数据 |
| `bun run typecheck` | TypeScript 类型检查 | | `bun run typecheck` | TypeScript 类型检查 |
| `bun run test` | 运行所有 `*.test.ts` | | `bun run test` | 运行测试 |
| `bun run fix` | Biome 格式化 + lint + 整理 imports | | `bun run fix` | 格式化与静态检查 |
## 验证 交付前验证:
```bash ```bash
bun run fix && bun run typecheck && bun run test && bun run build bun run fix && bun run typecheck && bun run test && bun run build
+89
View File
@@ -13,6 +13,7 @@
"@orpc/server": "^1.14.0", "@orpc/server": "^1.14.0",
"@orpc/tanstack-query": "^1.14.0", "@orpc/tanstack-query": "^1.14.0",
"@orpc/zod": "^1.14.0", "@orpc/zod": "^1.14.0",
"@radix-ui/react-select": "^2.2.6",
"@t3-oss/env-core": "^0.13.11", "@t3-oss/env-core": "^0.13.11",
"@tanstack/react-query": "^5.100.1", "@tanstack/react-query": "^5.100.1",
"@tanstack/react-router": "^1.168.24", "@tanstack/react-router": "^1.168.24",
@@ -23,6 +24,8 @@
"citty": "^0.2.2", "citty": "^0.2.2",
"drizzle-orm": "^0.45.2", "drizzle-orm": "^0.45.2",
"lru-cache": "^11.3.6", "lru-cache": "^11.3.6",
"lucide-react": "^1.14.0",
"motion": "^12.38.0",
"mysql2": "^3.22.3", "mysql2": "^3.22.3",
"react": "^19.2.5", "react": "^19.2.5",
"react-dom": "^19.2.5", "react-dom": "^19.2.5",
@@ -161,6 +164,14 @@
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="], "@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="],
"@floating-ui/core": ["@floating-ui/core@1.7.5", "", { "dependencies": { "@floating-ui/utils": "^0.2.11" } }, "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ=="],
"@floating-ui/dom": ["@floating-ui/dom@1.7.6", "", { "dependencies": { "@floating-ui/core": "^1.7.5", "@floating-ui/utils": "^0.2.11" } }, "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ=="],
"@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.8", "", { "dependencies": { "@floating-ui/dom": "^1.7.6" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A=="],
"@floating-ui/utils": ["@floating-ui/utils@0.2.11", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="],
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="], "@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="], "@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -219,6 +230,58 @@
"@oxc-project/types": ["@oxc-project/types@0.127.0", "", {}, "sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ=="], "@oxc-project/types": ["@oxc-project/types@0.127.0", "", {}, "sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ=="],
"@radix-ui/number": ["@radix-ui/number@1.1.1", "", {}, "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="],
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
"@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="],
"@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="],
"@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="],
"@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
"@radix-ui/react-direction": ["@radix-ui/react-direction@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw=="],
"@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="],
"@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw=="],
"@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw=="],
"@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="],
"@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="],
"@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="],
"@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
"@radix-ui/react-select": ["@radix-ui/react-select@2.2.6", "", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-visually-hidden": "1.2.3", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ=="],
"@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="],
"@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="],
"@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="],
"@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="],
"@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="],
"@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ=="],
"@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.1", "", { "dependencies": { "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w=="],
"@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ=="],
"@radix-ui/react-visually-hidden": ["@radix-ui/react-visually-hidden@1.2.3", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug=="],
"@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="],
"@reduxjs/toolkit": ["@reduxjs/toolkit@2.11.2", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "immer": "^11.0.0", "redux": "^5.0.1", "redux-thunk": "^3.1.0", "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "optionalPeers": ["react", "react-redux"] }, "sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ=="], "@reduxjs/toolkit": ["@reduxjs/toolkit@2.11.2", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "immer": "^11.0.0", "redux": "^5.0.1", "redux-thunk": "^3.1.0", "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "optionalPeers": ["react", "react-redux"] }, "sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ=="],
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.0.0-rc.17", "", { "os": "android", "cpu": "arm64" }, "sha512-s70pVGhw4zqGeFnXWvAzJDlvxhlRollagdCCKRgOsgUOH3N1l0LIxf83AtGzmb5SiVM4Hjl5HyarMRfdfj3DaQ=="], "@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.0.0-rc.17", "", { "os": "android", "cpu": "arm64" }, "sha512-s70pVGhw4zqGeFnXWvAzJDlvxhlRollagdCCKRgOsgUOH3N1l0LIxf83AtGzmb5SiVM4Hjl5HyarMRfdfj3DaQ=="],
@@ -413,6 +476,8 @@
"argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="], "argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
"aria-hidden": ["aria-hidden@1.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
"aws-ssl-profiles": ["aws-ssl-profiles@1.1.2", "", {}, "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g=="], "aws-ssl-profiles": ["aws-ssl-profiles@1.1.2", "", {}, "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g=="],
"babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="], "babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="],
@@ -493,6 +558,8 @@
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="], "detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"detect-node-es": ["detect-node-es@1.1.0", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="],
"diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="], "diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="],
"dom-serializer": ["dom-serializer@2.0.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="], "dom-serializer": ["dom-serializer@2.0.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],
@@ -533,12 +600,16 @@
"fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
"framer-motion": ["framer-motion@12.38.0", "", { "dependencies": { "motion-dom": "^12.38.0", "motion-utils": "^12.36.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="], "fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"generate-function": ["generate-function@2.3.1", "", { "dependencies": { "is-property": "^1.0.2" } }, "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ=="], "generate-function": ["generate-function@2.3.1", "", { "dependencies": { "is-property": "^1.0.2" } }, "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ=="],
"gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="], "gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
"get-nonce": ["get-nonce@1.0.1", "", {}, "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q=="],
"get-tsconfig": ["get-tsconfig@4.14.0", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA=="], "get-tsconfig": ["get-tsconfig@4.14.0", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA=="],
"glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="], "glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
@@ -619,8 +690,16 @@
"lru.min": ["lru.min@1.1.4", "", {}, "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA=="], "lru.min": ["lru.min@1.1.4", "", {}, "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA=="],
"lucide-react": ["lucide-react@1.14.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-+1mdWcfSJVUsaTIjN9zoezmUhfXo5l0vP7ekBMPo3jcS/aIkxHnXqAPsByszMZx/Y8oQBRJxJx5xg+RH3urzxA=="],
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="], "magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
"motion": ["motion@12.38.0", "", { "dependencies": { "framer-motion": "^12.38.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-uYfXzeHlgThchzwz5Te47dlv5JOUC7OB4rjJ/7XTUgtBZD8CchMN8qEJ4ZVsUmTyYA44zjV0fBwsiktRuFnn+w=="],
"motion-dom": ["motion-dom@12.38.0", "", { "dependencies": { "motion-utils": "^12.36.0" } }, "sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA=="],
"motion-utils": ["motion-utils@12.36.0", "", {}, "sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="], "ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"mysql2": ["mysql2@3.22.3", "", { "dependencies": { "aws-ssl-profiles": "^1.1.2", "denque": "^2.1.0", "generate-function": "^2.3.1", "iconv-lite": "^0.7.2", "long": "^5.3.2", "lru.min": "^1.1.4", "named-placeholders": "^1.1.6", "sql-escaper": "^1.3.3" }, "peerDependencies": { "@types/node": ">= 8" } }, "sha512-uWWxvZSRvRhtBdh2CdcuK83YcOfPdmEeEYB069bAmPnV93QApDGVPuvCQOLjlh7tYHEWdgQPrn6kosDxHBVLkA=="], "mysql2": ["mysql2@3.22.3", "", { "dependencies": { "aws-ssl-profiles": "^1.1.2", "denque": "^2.1.0", "generate-function": "^2.3.1", "iconv-lite": "^0.7.2", "long": "^5.3.2", "lru.min": "^1.1.4", "named-placeholders": "^1.1.6", "sql-escaper": "^1.3.3" }, "peerDependencies": { "@types/node": ">= 8" } }, "sha512-uWWxvZSRvRhtBdh2CdcuK83YcOfPdmEeEYB069bAmPnV93QApDGVPuvCQOLjlh7tYHEWdgQPrn6kosDxHBVLkA=="],
@@ -677,6 +756,12 @@
"react-redux": ["react-redux@9.2.0", "", { "dependencies": { "@types/use-sync-external-store": "^0.0.6", "use-sync-external-store": "^1.4.0" }, "peerDependencies": { "@types/react": "^18.2.25 || ^19", "react": "^18.0 || ^19", "redux": "^5.0.0" }, "optionalPeers": ["@types/react", "redux"] }, "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g=="], "react-redux": ["react-redux@9.2.0", "", { "dependencies": { "@types/use-sync-external-store": "^0.0.6", "use-sync-external-store": "^1.4.0" }, "peerDependencies": { "@types/react": "^18.2.25 || ^19", "react": "^18.0 || ^19", "redux": "^5.0.0" }, "optionalPeers": ["@types/react", "redux"] }, "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g=="],
"react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="],
"react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="],
"react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],
"readdirp": ["readdirp@3.6.0", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="], "readdirp": ["readdirp@3.6.0", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
"recharts": ["recharts@3.8.1", "", { "dependencies": { "@reduxjs/toolkit": "^1.9.0 || 2.x.x", "clsx": "^2.1.1", "decimal.js-light": "^2.5.1", "es-toolkit": "^1.39.3", "eventemitter3": "^5.0.1", "immer": "^10.1.1", "react-redux": "8.x.x || 9.x.x", "reselect": "5.1.1", "tiny-invariant": "^1.3.3", "use-sync-external-store": "^1.2.2", "victory-vendor": "^37.0.2" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-mwzmO1s9sFL0TduUpwndxCUNoXsBw3u3E/0+A+cLcrSfQitSG62L32N69GhqUrrT5qKcAE3pCGVINC6pqkBBQg=="], "recharts": ["recharts@3.8.1", "", { "dependencies": { "@reduxjs/toolkit": "^1.9.0 || 2.x.x", "clsx": "^2.1.1", "decimal.js-light": "^2.5.1", "es-toolkit": "^1.39.3", "eventemitter3": "^5.0.1", "immer": "^10.1.1", "react-redux": "8.x.x || 9.x.x", "reselect": "5.1.1", "tiny-invariant": "^1.3.3", "use-sync-external-store": "^1.2.2", "victory-vendor": "^37.0.2" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-mwzmO1s9sFL0TduUpwndxCUNoXsBw3u3E/0+A+cLcrSfQitSG62L32N69GhqUrrT5qKcAE3pCGVINC6pqkBBQg=="],
@@ -749,6 +834,10 @@
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="], "update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
"use-callback-ref": ["use-callback-ref@1.3.3", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="],
"use-sidecar": ["use-sidecar@1.1.3", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="],
"use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="], "use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"victory-vendor": ["victory-vendor@37.3.6", "", { "dependencies": { "@types/d3-array": "^3.0.3", "@types/d3-ease": "^3.0.0", "@types/d3-interpolate": "^3.0.1", "@types/d3-scale": "^4.0.2", "@types/d3-shape": "^3.1.0", "@types/d3-time": "^3.0.0", "@types/d3-timer": "^3.0.0", "d3-array": "^3.1.6", "d3-ease": "^3.0.1", "d3-interpolate": "^3.0.1", "d3-scale": "^4.0.2", "d3-shape": "^3.1.0", "d3-time": "^3.0.0", "d3-timer": "^3.0.1" } }, "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ=="], "victory-vendor": ["victory-vendor@37.3.6", "", { "dependencies": { "@types/d3-array": "^3.0.3", "@types/d3-ease": "^3.0.0", "@types/d3-interpolate": "^3.0.1", "@types/d3-scale": "^4.0.2", "@types/d3-shape": "^3.1.0", "@types/d3-time": "^3.0.0", "@types/d3-timer": "^3.0.0", "d3-array": "^3.1.6", "d3-ease": "^3.0.1", "d3-interpolate": "^3.0.1", "d3-scale": "^4.0.2", "d3-shape": "^3.1.0", "d3-time": "^3.0.0", "d3-timer": "^3.0.1" } }, "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ=="],
+9 -4
View File
@@ -6,10 +6,10 @@ services:
volumes: volumes:
- mysql_data:/var/lib/mysql - mysql_data:/var/lib/mysql
environment: environment:
MYSQL_ROOT_PASSWORD: root - MYSQL_ROOT_PASSWORD=root
MYSQL_DATABASE: battery_soh - MYSQL_DATABASE=battery_soh
MYSQL_USER: battery - MYSQL_USER=battery
MYSQL_PASSWORD: battery - MYSQL_PASSWORD=battery
healthcheck: healthcheck:
test: [ "CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-ubattery", "-pbattery" ] test: [ "CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-ubattery", "-pbattery" ]
interval: 5s interval: 5s
@@ -26,6 +26,7 @@ services:
condition: service_healthy condition: service_healthy
environment: environment:
- DATABASE_URL=mysql://battery:battery@db:3306/battery_soh - DATABASE_URL=mysql://battery:battery@db:3306/battery_soh
- SOH_PREDICTION_API_BASE_URL=http://host.docker.internal:8000
command: [ "bun", "run", "seed" ] command: [ "bun", "run", "seed" ]
app: app:
@@ -33,10 +34,14 @@ services:
depends_on: depends_on:
seed: seed:
condition: service_completed_successfully condition: service_completed_successfully
extra_hosts:
- "host.docker.internal:host-gateway"
ports: ports:
- "3000:3000" - "3000:3000"
environment: environment:
- DATABASE_URL=mysql://battery:battery@db:3306/battery_soh - DATABASE_URL=mysql://battery:battery@db:3306/battery_soh
- SOH_PREDICTION_API_BASE_URL=http://host.docker.internal:8000
- ENABLE_API_DOCS=true
volumes: volumes:
mysql_data: mysql_data:
+5 -2
View File
@@ -1,5 +1,5 @@
{ {
"name": "fullstack-starter", "name": "battery-soh",
"version": "1.0.0", "version": "1.0.0",
"private": true, "private": true,
"type": "module", "type": "module",
@@ -34,6 +34,7 @@
"@orpc/server": "^1.14.0", "@orpc/server": "^1.14.0",
"@orpc/tanstack-query": "^1.14.0", "@orpc/tanstack-query": "^1.14.0",
"@orpc/zod": "^1.14.0", "@orpc/zod": "^1.14.0",
"@radix-ui/react-select": "^2.2.6",
"@t3-oss/env-core": "^0.13.11", "@t3-oss/env-core": "^0.13.11",
"@tanstack/react-query": "^5.100.1", "@tanstack/react-query": "^5.100.1",
"@tanstack/react-router": "^1.168.24", "@tanstack/react-router": "^1.168.24",
@@ -42,8 +43,9 @@
"@tanstack/react-table": "^8.21.3", "@tanstack/react-table": "^8.21.3",
"@tanstack/react-virtual": "^3.13.24", "@tanstack/react-virtual": "^3.13.24",
"citty": "^0.2.2", "citty": "^0.2.2",
"drizzle-orm": "^0.45.2",
"lru-cache": "^11.3.6", "lru-cache": "^11.3.6",
"lucide-react": "^1.14.0",
"motion": "^12.38.0",
"mysql2": "^3.22.3", "mysql2": "^3.22.3",
"react": "^19.2.5", "react": "^19.2.5",
"react-dom": "^19.2.5", "react-dom": "^19.2.5",
@@ -59,6 +61,7 @@
"@tanstack/react-router-devtools": "^1.166.13", "@tanstack/react-router-devtools": "^1.166.13",
"@types/bun": "^1.3.13", "@types/bun": "^1.3.13",
"@vitejs/plugin-react": "^6.0.1", "@vitejs/plugin-react": "^6.0.1",
"drizzle-orm": "^0.45.2",
"drizzle-seed": "^0.3.1", "drizzle-seed": "^0.3.1",
"nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc", "nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc",
"tailwindcss": "^4.2.4", "tailwindcss": "^4.2.4",
+35 -13
View File
@@ -2,14 +2,15 @@ import { datetime, index, int, mysqlTable, tinyint, varchar } from 'drizzle-orm/
import { drizzle } from 'drizzle-orm/mysql2' import { drizzle } from 'drizzle-orm/mysql2'
import { reset } from 'drizzle-seed' import { reset } from 'drizzle-seed'
import mysql from 'mysql2/promise' import mysql from 'mysql2/promise'
import { type MYSQL_BOOLEAN, POWER_STATUS, type PowerStatus, toMysqlBoolean } from '@/domain/battery'
type SeedRow = { type SeedRow = {
userId: number userId: number
mac: string mac: string
devModel: string devModel: string
devName: string devName: string
isLowPower: 'true' | 'false' isLowPower: (typeof MYSQL_BOOLEAN)[keyof typeof MYSQL_BOOLEAN]
powerStatus: 0 | 1 | 2 powerStatus: PowerStatus
power: number power: number
createTime: Date createTime: Date
remark: string | null remark: string | null
@@ -48,20 +49,41 @@ if (!safeSeedHosts.has(parsedUrl.hostname) && process.env.SEED_ALLOW_REMOTE !==
} }
const devices = [ const devices = [
{ mac: 'RING-A03', model: 'SR-01', name: '样机-A03', basePower: 96, status: 2, remark: 'v3.8.2' }, { mac: 'RING-A03', model: 'SR-01', name: '样机-A03', basePower: 96, status: POWER_STATUS.FULL, remark: 'v3.8.2' },
{ mac: 'RING-B11', model: 'SR-01', name: '样机-B11', basePower: 91, status: 1, remark: 'v3.8.2' }, { mac: 'RING-B11', model: 'SR-01', name: '样机-B11', basePower: 91, status: POWER_STATUS.CHARGING, remark: 'v3.8.2' },
{ mac: 'RING-C07', model: 'SR-02', name: '样机-C07', basePower: 88, status: 0, remark: 'v3.8.1' }, {
{ mac: 'RING-D19', model: 'SR-02', name: '样机-D19', basePower: 84, status: 0, remark: 'v3.7.9' }, mac: 'RING-C07',
{ mac: 'RING-E21', model: 'SR-03', name: '样机-E21', basePower: 79, status: 1, remark: 'v3.7.9' }, model: 'SR-02',
{ mac: 'RING-F02', model: 'SR-03', name: '样机-F02', basePower: 73, status: 0, remark: null }, name: '样机-C07',
{ mac: 'RING-G15', model: 'SR-04', name: '样机-G15', basePower: 93, status: 2, remark: 'v3.9.0' }, basePower: 88,
{ mac: 'RING-H09', model: 'SR-04', name: '样机-H09', basePower: 86, status: 0, remark: 'v3.8.1' }, status: POWER_STATUS.NOT_CHARGING,
remark: 'v3.8.1',
},
{
mac: 'RING-D19',
model: 'SR-02',
name: '样机-D19',
basePower: 84,
status: POWER_STATUS.NOT_CHARGING,
remark: 'v3.7.9',
},
{ mac: 'RING-E21', model: 'SR-03', name: '样机-E21', basePower: 79, status: POWER_STATUS.CHARGING, remark: 'v3.7.9' },
{ mac: 'RING-F02', model: 'SR-03', name: '样机-F02', basePower: 73, status: POWER_STATUS.NOT_CHARGING, remark: null },
{ mac: 'RING-G15', model: 'SR-04', name: '样机-G15', basePower: 93, status: POWER_STATUS.FULL, remark: 'v3.9.0' },
{
mac: 'RING-H09',
model: 'SR-04',
name: '样机-H09',
basePower: 86,
status: POWER_STATUS.NOT_CHARGING,
remark: 'v3.8.1',
},
] satisfies Array<{ ] satisfies Array<{
mac: string mac: string
model: string model: string
name: string name: string
basePower: number basePower: number
status: 0 | 1 | 2 status: PowerStatus
remark: string | null remark: string | null
}> }>
@@ -76,8 +98,8 @@ function createSeedRows(now = new Date()): SeedRow[] {
mac: device.mac, mac: device.mac,
devModel: device.model, devModel: device.model,
devName: device.name, devName: device.name,
isLowPower: power <= 20 || device.basePower <= 80 ? 'true' : 'false', isLowPower: toMysqlBoolean(power <= 20 || device.basePower <= 80),
powerStatus: historyIndex === 0 ? device.status : 0, powerStatus: historyIndex === 0 ? device.status : POWER_STATUS.NOT_CHARGING,
power, power,
createTime: createdAt, createTime: createdAt,
remark: device.remark, remark: device.remark,
+128
View File
@@ -0,0 +1,128 @@
import { motion, useReducedMotion } from 'motion/react'
import type { ComponentPropsWithoutRef, ReactNode } from 'react'
export function useMotionConfig() {
const shouldReduceMotion = useReducedMotion()
return { shouldReduceMotion }
}
export function MotionHeader({
children,
delay = 0,
className,
...props
}: { children: ReactNode; delay?: number } & ComponentPropsWithoutRef<typeof motion.header>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.header
initial={shouldReduceMotion ? false : { opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay, ease: [0.25, 0.1, 0.25, 1] }}
className={className}
{...props}
>
{children}
</motion.header>
)
}
export function MotionSection({
children,
delay = 0,
className,
...props
}: { children: ReactNode; delay?: number } & ComponentPropsWithoutRef<typeof motion.section>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.section
initial={shouldReduceMotion ? false : { opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay, ease: [0.25, 0.1, 0.25, 1] }}
className={className}
{...props}
>
{children}
</motion.section>
)
}
export function MotionDiv({
children,
delay = 0,
className,
...props
}: { children: ReactNode; delay?: number } & ComponentPropsWithoutRef<typeof motion.div>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.div
initial={shouldReduceMotion ? false : { opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay, ease: [0.25, 0.1, 0.25, 1] }}
className={className}
{...props}
>
{children}
</motion.div>
)
}
export function MotionCardArticle({
children,
className,
...props
}: { children: ReactNode } & ComponentPropsWithoutRef<typeof motion.article>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.article
whileHover={shouldReduceMotion ? {} : { y: -2 }}
transition={{ duration: 0.2, ease: 'easeOut' }}
className={className}
{...props}
>
{children}
</motion.article>
)
}
export function MotionCardDiv({
children,
className,
...props
}: { children: ReactNode } & ComponentPropsWithoutRef<typeof motion.div>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.div
whileHover={shouldReduceMotion ? {} : { y: -2 }}
transition={{ duration: 0.2, ease: 'easeOut' }}
className={className}
{...props}
>
{children}
</motion.div>
)
}
export function MotionTableRow({
children,
className,
...props
}: { children: ReactNode } & ComponentPropsWithoutRef<typeof motion.tr>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.tr
initial={shouldReduceMotion ? false : { opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
className={className}
{...props}
>
{children}
</motion.tr>
)
}
+181
View File
@@ -0,0 +1,181 @@
import * as RadixSelect from '@radix-ui/react-select'
import { Check, ChevronDown } from 'lucide-react'
import type { ComponentPropsWithoutRef, ReactNode } from 'react'
type Variant = 'default' | 'muted' | 'success' | 'warning' | 'danger' | 'info'
function cn(...classes: Array<string | false | null | undefined>) {
return classes.filter(Boolean).join(' ')
}
const variantClass: Record<Variant, string> = {
default: 'border-white/10 bg-white/[0.04] text-zinc-100',
muted: 'border-white/10 bg-zinc-900/70 text-zinc-400',
success: 'border-emerald-400/20 bg-emerald-400/10 text-emerald-300',
warning: 'border-amber-400/20 bg-amber-400/10 text-amber-300',
danger: 'border-red-400/20 bg-red-400/10 text-red-300',
info: 'border-teal-400/20 bg-teal-400/10 text-teal-300',
}
export function Badge({
className,
variant = 'default',
children,
...props
}: ComponentPropsWithoutRef<'span'> & { variant?: Variant }) {
return (
<span
className={cn(
'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium leading-none',
variantClass[variant],
className,
)}
{...props}
>
{children}
</span>
)
}
export function Card({ className, children, ...props }: ComponentPropsWithoutRef<'div'>) {
return (
<div
className={cn('rounded-2xl border border-white/[0.08] bg-zinc-950/60 shadow-2xl shadow-black/20', className)}
{...props}
>
{children}
</div>
)
}
export function Button({ className, children, ...props }: ComponentPropsWithoutRef<'button'>) {
return (
<button
className={cn(
'inline-flex items-center justify-center gap-2 rounded-lg border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-medium text-zinc-100 transition-colors hover:border-white/20 hover:bg-white/[0.09] disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-white/[0.05]',
className,
)}
{...props}
>
{children}
</button>
)
}
export function Input({ className, ...props }: ComponentPropsWithoutRef<'input'>) {
return (
<input
className={cn(
'h-10 w-full rounded-lg border border-white/10 bg-zinc-950/80 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 outline-none transition-colors focus:border-teal-400/60 focus:ring-2 focus:ring-teal-400/10',
className,
)}
{...props}
/>
)
}
export function Select({
value,
onValueChange,
children,
className,
id,
}: {
value?: string | number
onValueChange?: (value: string) => void
children: ReactNode
className?: string
id?: string
}) {
return (
<RadixSelect.Root value={value?.toString()} onValueChange={onValueChange}>
<RadixSelect.Trigger
id={id}
className={cn(
'flex h-10 w-full items-center justify-between gap-2 rounded-lg border border-white/10 bg-zinc-950/95 px-3 py-2 text-sm text-zinc-100 outline-none transition-colors focus:border-teal-400/60 focus:ring-2 focus:ring-teal-400/10 data-[placeholder]:text-zinc-500',
className,
)}
>
<RadixSelect.Value />
<RadixSelect.Icon asChild>
<ChevronDown className="size-4 opacity-50" />
</RadixSelect.Icon>
</RadixSelect.Trigger>
<RadixSelect.Portal>
<RadixSelect.Content
className="relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-lg border border-white/10 bg-zinc-950 text-zinc-100 shadow-xl shadow-black/40"
position="popper"
sideOffset={4}
>
<RadixSelect.Viewport className="p-1">{children}</RadixSelect.Viewport>
</RadixSelect.Content>
</RadixSelect.Portal>
</RadixSelect.Root>
)
}
export function SelectOption({
value,
children,
className,
}: {
value: string | number
children: ReactNode
className?: string
}) {
return (
<RadixSelect.Item
value={value.toString()}
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-md py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-white/10 focus:text-zinc-50 data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<RadixSelect.ItemIndicator>
<Check className="size-4" />
</RadixSelect.ItemIndicator>
</span>
<RadixSelect.ItemText>{children}</RadixSelect.ItemText>
</RadixSelect.Item>
)
}
export function SectionTitle({ icon, title, description }: { icon?: ReactNode; title: string; description?: string }) {
return (
<div className="flex items-start gap-3">
{icon && <div className="mt-0.5 rounded-lg border border-white/10 bg-white/[0.04] p-2 text-teal-300">{icon}</div>}
<div>
<h3 className="text-lg font-medium text-white">{title}</h3>
{description && <p className="mt-1 text-sm text-zinc-400">{description}</p>}
</div>
</div>
)
}
export function Skeleton({ className, ...props }: ComponentPropsWithoutRef<'div'>) {
return <div className={cn('rounded-md bg-white/5 motion-safe:animate-pulse', className)} {...props} />
}
export function EmptyState({
icon,
title,
description,
action,
className,
}: {
icon?: ReactNode
title: string
description?: string
action?: ReactNode
className?: string
}) {
return (
<div className={cn('flex flex-col items-center justify-center py-12 text-center', className)}>
{icon && <div className="mb-4 text-zinc-500">{icon}</div>}
<h3 className="text-sm font-medium text-zinc-200">{title}</h3>
{description && <p className="mt-1 text-sm text-zinc-500 max-w-sm">{description}</p>}
{action && <div className="mt-6">{action}</div>}
</div>
)
}
+63
View File
@@ -0,0 +1,63 @@
export const POWER_STATUS = {
NOT_CHARGING: 0,
CHARGING: 1,
FULL: 2,
} as const
export type PowerStatus = (typeof POWER_STATUS)[keyof typeof POWER_STATUS]
export const POWER_STATUS_VALUES = [POWER_STATUS.NOT_CHARGING, POWER_STATUS.CHARGING, POWER_STATUS.FULL] as const
export const BATTERY_LIST_SORT = {
CREATED_AT_DESC: 'createdAtDesc',
CREATED_AT_ASC: 'createdAtAsc',
POWER_DESC: 'powerDesc',
POWER_ASC: 'powerAsc',
} as const
export type BatteryListSort = (typeof BATTERY_LIST_SORT)[keyof typeof BATTERY_LIST_SORT]
export const BATTERY_LIST_SORT_VALUES = [
BATTERY_LIST_SORT.CREATED_AT_DESC,
BATTERY_LIST_SORT.CREATED_AT_ASC,
BATTERY_LIST_SORT.POWER_DESC,
BATTERY_LIST_SORT.POWER_ASC,
] as const
export const MYSQL_BOOLEAN = {
TRUE: 'true',
FALSE: 'false',
} as const
export function toMysqlBoolean(value: boolean) {
return value ? MYSQL_BOOLEAN.TRUE : MYSQL_BOOLEAN.FALSE
}
export function fromMysqlBoolean(value: string | boolean) {
if (typeof value === 'boolean') return value
return value.trim().toLowerCase() === MYSQL_BOOLEAN.TRUE
}
export const DEVICE_STATUS = {
HEALTHY: '健康',
WATCH: '关注',
WARNING: '预警',
} as const
export type DeviceStatus = (typeof DEVICE_STATUS)[keyof typeof DEVICE_STATUS]
export const EVENT_SEVERITY = {
HIGH: '高',
MEDIUM: '中',
LOW: '低',
} as const
export type EventSeverity = (typeof EVENT_SEVERITY)[keyof typeof EVENT_SEVERITY]
export const SOH_THRESHOLDS = {
WARNING: 85,
WATCH: 90,
LOW_POWER: 20,
HIGH_RISK_SCORE: 70,
WATCH_RISK_SCORE: 40,
} as const
+66 -14
View File
@@ -1,5 +1,14 @@
import { describe, expect, test } from 'bun:test' import { describe, expect, test } from 'bun:test'
import { createBatteriesResponse, createDashboardSnapshot, getDeviceStatus, toBatteryInfo } from './battery' import {
createBatteriesResponse,
createDashboardSnapshot,
DEVICE_STATUS,
fromMysqlBoolean,
getDeviceStatus,
MYSQL_BOOLEAN,
POWER_STATUS,
toBatteryInfo,
} from './battery'
const rows = [ const rows = [
{ {
@@ -8,8 +17,8 @@ const rows = [
mac: 'RING-A03', mac: 'RING-A03',
devModel: '2401-A', devModel: '2401-A',
devName: 'RING-A03', devName: 'RING-A03',
isLowPower: 'false', isLowPower: MYSQL_BOOLEAN.FALSE,
powerStatus: 2, powerStatus: POWER_STATUS.FULL,
power: 94, power: 94,
createTime: new Date('2026-05-10T23:00:00.000Z'), createTime: new Date('2026-05-10T23:00:00.000Z'),
remark: 'v3.8.2', remark: 'v3.8.2',
@@ -19,9 +28,9 @@ const rows = [
userId: 7, userId: 7,
mac: 'RING-B11', mac: 'RING-B11',
devModel: '2402-B', devModel: '2402-B',
devName: 'RING-B11', devName: '',
isLowPower: 'true', isLowPower: MYSQL_BOOLEAN.TRUE,
powerStatus: 1, powerStatus: POWER_STATUS.CHARGING,
power: 84, power: 84,
createTime: '2026-05-10 22:00:00', createTime: '2026-05-10 22:00:00',
remark: null, remark: null,
@@ -30,9 +39,14 @@ const rows = [
describe('battery domain', () => { describe('battery domain', () => {
test('preserves legacy SOH status thresholds', () => { test('preserves legacy SOH status thresholds', () => {
expect(getDeviceStatus(91)).toBe('健康') expect(getDeviceStatus(91)).toBe(DEVICE_STATUS.HEALTHY)
expect(getDeviceStatus(90)).toBe('关注') expect(getDeviceStatus(90)).toBe(DEVICE_STATUS.WATCH)
expect(getDeviceStatus(85)).toBe('预警') expect(getDeviceStatus(85)).toBe(DEVICE_STATUS.WARNING)
})
test('trims MySQL boolean strings before normalization', () => {
expect(fromMysqlBoolean(' true ')).toBe(true)
expect(fromMysqlBoolean(' false ')).toBe(false)
}) })
test('builds batteries response counters from records', () => { test('builds batteries response counters from records', () => {
@@ -48,16 +62,45 @@ describe('battery domain', () => {
expect(response.items[0]?.createTime).toBe('2026-05-10T23:00:00.000Z') expect(response.items[0]?.createTime).toBe('2026-05-10T23:00:00.000Z')
}) })
test('keeps explicit window summaries for limited history slices', () => {
const now = new Date('2026-05-11T00:00:00.000Z')
const items = rows.map(toBatteryInfo)
const response = createBatteriesResponse(items, now, {
total: items.length,
lowPower: 1,
charging: 1,
})
expect(response.total).toBe(2)
expect(response.lowPower).toBe(1)
expect(response.charging).toBe(1)
})
test('creates dashboard aggregate shape without using power as fake SOH', () => { test('creates dashboard aggregate shape without using power as fake SOH', () => {
const now = new Date('2026-05-11T00:00:00.000Z') const now = new Date('2026-05-11T00:00:00.000Z')
const snapshot = createDashboardSnapshot(rows.map(toBatteryInfo), now) const snapshot = createDashboardSnapshot(rows.map(toBatteryInfo), now)
expect(snapshot.devices).toHaveLength(2) expect(snapshot.devices).toHaveLength(2)
expect(snapshot.devices[0]?.id).toBe('RING-A03')
expect(snapshot.devices[0]?.displayName).toBe('RING-A03')
expect(snapshot.devices[1]?.id).toBe('RING-B11')
expect(snapshot.devices[1]?.displayName).toBe('RING-B11')
expect(snapshot.devices.every((device) => device.sohSource === 'unavailable')).toBe(true) expect(snapshot.devices.every((device) => device.sohSource === 'unavailable')).toBe(true)
expect(snapshot.devices.every((device) => device.soh === 0)).toBe(true) expect(snapshot.devices.every((device) => device.soh === null)).toBe(true)
expect(snapshot.soh.history).toHaveLength(12) expect(snapshot.devices.every((device) => device.soh30d === null)).toBe(true)
expect(snapshot.soh.forecast).toHaveLength(4) expect(snapshot.devices.every((device) => device.soh90d === null)).toBe(true)
expect(snapshot.devices.every((device) => device.soh60d === null)).toBe(true)
expect(snapshot.devices.every((device) => device.cycles === null)).toBe(true)
expect(snapshot.devices.every((device) => device.temperature === null)).toBe(true)
expect(snapshot.devices.every((device) => device.chargeEfficiency === null)).toBe(true)
expect(snapshot.devices[0]?.firmware).toBe('v3.8.2')
expect(snapshot.devices[1]?.firmware).toBe('未提供')
expect(snapshot.soh.history).toHaveLength(0)
expect(snapshot.soh.forecast).toHaveLength(0)
expect(snapshot.summary.totalDevices).toBe(snapshot.devices.length) expect(snapshot.summary.totalDevices).toBe(snapshot.devices.length)
expect(snapshot.summary.avgSoh).toBeNull()
expect(snapshot.summary.avgSoh30d).toBeNull()
expect(snapshot.summary.avgSoh90d).toBeNull()
expect(snapshot.summary.warningCount + snapshot.summary.watchCount + snapshot.summary.healthyCount).toBe( expect(snapshot.summary.warningCount + snapshot.summary.watchCount + snapshot.summary.healthyCount).toBe(
snapshot.devices.length, snapshot.devices.length,
) )
@@ -93,7 +136,16 @@ describe('battery domain', () => {
expect(predicted?.sohSource).toBe('prediction') expect(predicted?.sohSource).toBe('prediction')
expect(predicted?.soh30d).toBe(58) expect(predicted?.soh30d).toBe(58)
expect(predicted?.soh90d).toBe(52) expect(predicted?.soh90d).toBe(52)
expect(predicted?.status).toBe('预警') expect(predicted?.soh60d).toBeNull()
expect(predicted?.firmware).toBe('XGBoost') expect(predicted?.cycles).toBe(6)
expect(predicted?.firmware).toBe('v3.8.2')
expect(predicted?.status).toBe(DEVICE_STATUS.WARNING)
expect(predicted?.temperature).toBeNull()
expect(predicted?.chargeEfficiency).toBeNull()
expect(snapshot.soh.history).toHaveLength(0)
expect(snapshot.soh.forecast).toHaveLength(3)
expect(snapshot.soh.forecast[0]).toEqual({ month: '当前', value: 60 })
expect(snapshot.soh.forecast[1]).toEqual({ month: '30天', value: 58 })
expect(snapshot.soh.forecast[2]).toEqual({ month: '90天', value: 52 })
}) })
}) })
+180 -124
View File
@@ -1,10 +1,42 @@
import { z } from 'zod' import { z } from 'zod'
import {
DEVICE_STATUS,
type DeviceStatus,
EVENT_SEVERITY,
fromMysqlBoolean,
POWER_STATUS,
type PowerStatus,
SOH_THRESHOLDS,
} from './battery.constants'
export const powerStatusSchema = z.union([z.literal(0), z.literal(1), z.literal(2)]) export {
export type PowerStatus = z.infer<typeof powerStatusSchema> BATTERY_LIST_SORT,
BATTERY_LIST_SORT_VALUES,
type BatteryListSort,
DEVICE_STATUS,
type DeviceStatus,
EVENT_SEVERITY,
type EventSeverity,
fromMysqlBoolean,
MYSQL_BOOLEAN,
POWER_STATUS,
POWER_STATUS_VALUES,
type PowerStatus,
SOH_THRESHOLDS,
toMysqlBoolean,
} from './battery.constants'
export const deviceStatusSchema = z.union([z.literal('健康'), z.literal('关注'), z.literal('预警')]) export const powerStatusSchema = z.union([
export type DeviceStatus = z.infer<typeof deviceStatusSchema> z.literal(POWER_STATUS.NOT_CHARGING),
z.literal(POWER_STATUS.CHARGING),
z.literal(POWER_STATUS.FULL),
])
export const deviceStatusSchema = z.union([
z.literal(DEVICE_STATUS.HEALTHY),
z.literal(DEVICE_STATUS.WATCH),
z.literal(DEVICE_STATUS.WARNING),
])
export const batteryInfoSchema = z.object({ export const batteryInfoSchema = z.object({
id: z.number().int(), id: z.number().int(),
@@ -22,17 +54,18 @@ export type BatteryInfo = z.infer<typeof batteryInfoSchema>
export const fleetUnitSchema = z.object({ export const fleetUnitSchema = z.object({
id: z.string(), id: z.string(),
displayName: z.string(),
batch: z.string(), batch: z.string(),
firmware: z.string(), firmware: z.string(),
cycles: z.number().int(), cycles: z.number().int().nullable(),
soh: z.number(), soh: z.number().nullable(),
sohSource: z.union([z.literal('prediction'), z.literal('unavailable')]), sohSource: z.union([z.literal('prediction'), z.literal('unavailable')]),
soh30d: z.number(), soh30d: z.number().nullable(),
soh60d: z.number(), soh60d: z.number().nullable(),
soh90d: z.number(), soh90d: z.number().nullable(),
temperature: z.number(), temperature: z.number().nullable(),
riskScore: z.number().int(), riskScore: z.number().int(),
chargeEfficiency: z.number(), chargeEfficiency: z.number().nullable(),
status: deviceStatusSchema, status: deviceStatusSchema,
riskFactors: z.array(z.string()), riskFactors: z.array(z.string()),
}) })
@@ -48,7 +81,7 @@ export const eventItemSchema = z.object({
time: z.string(), time: z.string(),
title: z.string(), title: z.string(),
detail: z.string(), detail: z.string(),
severity: z.union([z.literal('高'), z.literal('中'), z.literal('低')]), severity: z.union([z.literal(EVENT_SEVERITY.HIGH), z.literal(EVENT_SEVERITY.MEDIUM), z.literal(EVENT_SEVERITY.LOW)]),
}) })
export const strategyItemSchema = z.object({ export const strategyItemSchema = z.object({
@@ -60,15 +93,15 @@ export const strategyItemSchema = z.object({
export const summaryResponseSchema = z.object({ export const summaryResponseSchema = z.object({
totalDevices: z.number().int(), totalDevices: z.number().int(),
avgSoh: z.number(), avgSoh: z.number().nullable(),
avgSoh30d: z.number(), avgSoh30d: z.number().nullable(),
avgSoh90d: z.number(), avgSoh90d: z.number().nullable(),
warningCount: z.number().int(), warningCount: z.number().int(),
watchCount: z.number().int(), watchCount: z.number().int(),
healthyCount: z.number().int(), healthyCount: z.number().int(),
batchPerformance: z.array(z.object({ batch: z.string(), avgSoh: z.number() })), batchPerformance: z.array(z.object({ batch: z.string(), avgSoh: z.number().nullable() })),
riskFactorCounts: z.array(z.object({ factor: z.string(), count: z.number().int() })), riskFactorCounts: z.array(z.object({ factor: z.string(), count: z.number().int() })),
firmwareHealth: z.array(z.object({ firmware: z.string(), avgSoh: z.number(), count: z.number().int() })), firmwareHealth: z.array(z.object({ firmware: z.string(), avgSoh: z.number().nullable(), count: z.number().int() })),
updatedAt: z.string(), updatedAt: z.string(),
executiveSummary: z.string(), executiveSummary: z.string(),
}) })
@@ -117,23 +150,13 @@ const clamp = (value: number, min: number, max: number) => Math.min(max, Math.ma
const pad2 = (value: number) => value.toString().padStart(2, '0') const pad2 = (value: number) => value.toString().padStart(2, '0')
const addMonths = (date: Date, months: number) =>
new Date(date.getFullYear(), date.getMonth() + months, date.getDate(), date.getHours(), 0, 0, 0)
const addHours = (date: Date, hours: number) => new Date(date.getTime() + hours * 60 * 60 * 1000)
const formatMonthLabel = (date: Date) => `${date.getFullYear().toString().slice(-2)}.${pad2(date.getMonth() + 1)}`
const formatDateTime = (date: Date) => const formatDateTime = (date: Date) =>
`${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}` `${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
const formatEventTime = (date: Date) =>
`${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}`
export function getDeviceStatus(soh: number): DeviceStatus { export function getDeviceStatus(soh: number): DeviceStatus {
if (soh <= 85) return '预警' if (soh <= SOH_THRESHOLDS.WARNING) return DEVICE_STATUS.WARNING
if (soh <= 90) return '关注' if (soh <= SOH_THRESHOLDS.WATCH) return DEVICE_STATUS.WATCH
return '健康' return DEVICE_STATUS.HEALTHY
} }
function getDeviceStatusByRisk(prediction: BatteryPrediction): DeviceStatus { function getDeviceStatusByRisk(prediction: BatteryPrediction): DeviceStatus {
@@ -145,7 +168,7 @@ function getDeviceStatusByRisk(prediction: BatteryPrediction): DeviceStatus {
riskText.includes('危险') || riskText.includes('危险') ||
riskText.includes('高') riskText.includes('高')
) { ) {
return '预警' return DEVICE_STATUS.WARNING
} }
if ( if (
riskText.includes('medium') || riskText.includes('medium') ||
@@ -153,25 +176,24 @@ function getDeviceStatusByRisk(prediction: BatteryPrediction): DeviceStatus {
riskText.includes('关注') || riskText.includes('关注') ||
riskText.includes('中') riskText.includes('中')
) { ) {
return '关注' return DEVICE_STATUS.WATCH
} }
if (prediction.riskScore !== null) { if (prediction.riskScore !== null) {
if (prediction.riskScore >= 70) return '预警' if (prediction.riskScore >= SOH_THRESHOLDS.HIGH_RISK_SCORE) return DEVICE_STATUS.WARNING
if (prediction.riskScore >= 40) return '关注' if (prediction.riskScore >= SOH_THRESHOLDS.WATCH_RISK_SCORE) return DEVICE_STATUS.WATCH
} }
return getDeviceStatus(prediction.nowSoh) return getDeviceStatus(prediction.nowSoh)
} }
export function normalizePowerStatus(value: number): PowerStatus { export function normalizePowerStatus(value: number): PowerStatus {
if (value === 1 || value === 2) return value if (value === POWER_STATUS.CHARGING || value === POWER_STATUS.FULL) return value
return 0 return POWER_STATUS.NOT_CHARGING
} }
export function normalizeLowPower(value: string | boolean): boolean { export function normalizeLowPower(value: string | boolean): boolean {
if (typeof value === 'boolean') return value return fromMysqlBoolean(value)
return value.toLowerCase() === 'true'
} }
export type BatteryInfoSourceRow = { export type BatteryInfoSourceRow = {
@@ -212,40 +234,45 @@ export function createBatteriesResponse(
updatedAt: now.toISOString(), updatedAt: now.toISOString(),
total: summary.total ?? items.length, total: summary.total ?? items.length,
lowPower: summary.lowPower ?? items.filter((item) => item.isLowPower).length, lowPower: summary.lowPower ?? items.filter((item) => item.isLowPower).length,
charging: summary.charging ?? items.filter((item) => item.powerStatus === 1).length, charging: summary.charging ?? items.filter((item) => item.powerStatus === POWER_STATUS.CHARGING).length,
items, items,
nextCursor, nextCursor,
} }
} }
function toFleetUnit(item: BatteryInfo, index: number, prediction?: BatteryPrediction): FleetUnit { function toFleetUnit(item: BatteryInfo, prediction?: BatteryPrediction): FleetUnit {
const hasPrediction = Boolean(prediction) const hasPrediction = Boolean(prediction)
const soh = prediction ? round1(clamp(prediction.nowSoh, 0, 100)) : 0 const soh = prediction ? round1(clamp(prediction.nowSoh, 0, 100)) : null
const status = prediction ? getDeviceStatusByRisk(prediction) : item.isLowPower || item.power <= 20 ? '关注' : '健康' const status = prediction
? getDeviceStatusByRisk(prediction)
: item.isLowPower || item.power <= SOH_THRESHOLDS.LOW_POWER
? DEVICE_STATUS.WATCH
: DEVICE_STATUS.HEALTHY
const riskFactors: string[] = [] const riskFactors: string[] = []
if (item.isLowPower || item.power <= 20) riskFactors.push('低电量') if (item.isLowPower || item.power <= SOH_THRESHOLDS.LOW_POWER) riskFactors.push('低电量')
if (item.powerStatus === 1) riskFactors.push('充电中') if (item.powerStatus === POWER_STATUS.CHARGING) riskFactors.push('充电中')
if (!hasPrediction) riskFactors.push('SoH预测不可用') if (!hasPrediction) riskFactors.push('健康预测不可用')
if (prediction && status === '预警') riskFactors.push('衰减加速') if (prediction && status === DEVICE_STATUS.WARNING) riskFactors.push('衰减加速')
if (item.remark?.includes('v3.7')) riskFactors.push('旧固件') if (item.remark?.includes('v3.7')) riskFactors.push('旧固件')
if (prediction?.riskLevel) riskFactors.push(`AI风险:${prediction.riskLevel}`) if (prediction?.riskLevel) riskFactors.push(`预测风险:${prediction.riskLevel}`)
const thermalPressure = index % 3 const soh30d = prediction ? round1(clamp(prediction.monthSoh, 0, 100)) : null
const soh30d = prediction ? round1(clamp(prediction.monthSoh, 0, 100)) : 0 const soh90d = prediction ? round1(clamp(prediction.trmonthSoh, 0, 100)) : null
const soh90d = prediction ? round1(clamp(prediction.trmonthSoh, 0, 100)) : 0 const soh60d = null
const soh60d = prediction ? round1((soh30d + soh90d) / 2) : 0 const temperature = null
const temperature = round1(29.5 + thermalPressure * 2.1 + (item.isLowPower ? 1.4 : 0)) const chargeEfficiency = null
const chargeEfficiency = round1(clamp(91 + item.power / 12 - riskFactors.length * 1.8, 80, 98)) const fallbackRiskScore =
const riskScore = Math.round( (item.isLowPower || item.power <= SOH_THRESHOLDS.LOW_POWER ? 60 : 0) +
clamp(prediction?.riskScore ?? 18 + riskFactors.length * 10 + thermalPressure * 4 + (item.isLowPower ? 18 : 0), 8, 96), (item.powerStatus === POWER_STATUS.CHARGING ? 20 : 0)
) const riskScore = Math.round(clamp(prediction?.riskScore ?? fallbackRiskScore, 0, 100))
return { return {
id: item.devName || item.mac, id: item.mac,
displayName: item.devName || item.mac,
batch: item.devModel, batch: item.devModel,
firmware: prediction?.modelName ?? item.remark ?? 'unknown', firmware: item.remark ?? '未提供',
cycles: 120 + index * 17 + Math.round((100 - soh) * 2.2), cycles: prediction?.cyclesUsed ?? null,
soh, soh,
sohSource: prediction ? 'prediction' : 'unavailable', sohSource: prediction ? 'prediction' : 'unavailable',
soh30d, soh30d,
@@ -259,34 +286,35 @@ function toFleetUnit(item: BatteryInfo, index: number, prediction?: BatteryPredi
} }
} }
function createSohResponse(devices: FleetUnit[], now: Date) { function createSohResponse(devices: FleetUnit[]) {
if (devices.length === 0) return { history: [], forecast: [] } const predictedDevices = devices.filter((unit) => unit.soh !== null)
if (predictedDevices.length === 0) return { history: [], forecast: [] }
const avgSoh = devices.reduce((sum, unit) => sum + unit.soh, 0) / devices.length const avgNow = averageNullable(predictedDevices.map((unit) => unit.soh))
const monthlyDrop = 0.45 + devices.reduce((sum, unit) => sum + unit.riskScore, 0) / devices.length / 160 const avgMonth = averageNullable(predictedDevices.map((unit) => unit.soh30d))
const avgTrmonth = averageNullable(predictedDevices.map((unit) => unit.soh90d))
const history = Array.from({ length: 12 }, (_, index) => { const forecast = [
const monthOffset = index - 11 avgNow === null ? null : { month: '当前', value: round1(clamp(avgNow, 0, 100)) },
return { avgMonth === null ? null : { month: '30天', value: round1(clamp(avgMonth, 0, 100)) },
month: formatMonthLabel(addMonths(now, monthOffset)), avgTrmonth === null ? null : { month: '90天', value: round1(clamp(avgTrmonth, 0, 100)) },
value: round1(clamp(avgSoh + Math.abs(monthOffset) * monthlyDrop, avgSoh, 100)), ].filter((point): point is { month: string; value: number } => point !== null)
}
})
const currentValue = history.at(-1)?.value ?? round1(avgSoh)
const forecast = Array.from({ length: 4 }, (_, index) => ({
month: formatMonthLabel(addMonths(now, index)),
value: index === 0 ? currentValue : round1(clamp(avgSoh - monthlyDrop * index, 0, 100)),
}))
return { history, forecast } return {
history: [],
forecast,
}
} }
function summarizeBy<T extends string>(items: FleetUnit[], getKey: (item: FleetUnit) => T) { function summarizeBy<T extends string>(items: FleetUnit[], getKey: (item: FleetUnit) => T) {
return Object.entries( return Object.entries(
items.reduce<Record<string, { sum: number; count: number }>>((acc, item) => { items.reduce<Record<string, { sum: number; valueCount: number; count: number }>>((acc, item) => {
const key = getKey(item) const key = getKey(item)
const entry = acc[key] ?? { sum: 0, count: 0 } const entry = acc[key] ?? { sum: 0, valueCount: 0, count: 0 }
entry.sum += item.soh if (item.soh !== null) {
entry.sum += item.soh
entry.valueCount += 1
}
entry.count += 1 entry.count += 1
acc[key] = entry acc[key] = entry
return acc return acc
@@ -294,15 +322,22 @@ function summarizeBy<T extends string>(items: FleetUnit[], getKey: (item: FleetU
) )
} }
function averageNullable(values: Array<number | null>) {
const available = values.filter((value) => value !== null)
if (available.length === 0) return null
return available.reduce((sum, value) => sum + value, 0) / available.length
}
function createSummary(devices: FleetUnit[], now: Date) { function createSummary(devices: FleetUnit[], now: Date) {
const totalDevices = devices.length const totalDevices = devices.length
if (totalDevices === 0) { if (totalDevices === 0) {
return { return {
totalDevices, totalDevices,
avgSoh: 0, avgSoh: null,
avgSoh30d: 0, avgSoh30d: null,
avgSoh90d: 0, avgSoh90d: null,
warningCount: 0, warningCount: 0,
watchCount: 0, watchCount: 0,
healthyCount: 0, healthyCount: 0,
@@ -314,18 +349,22 @@ function createSummary(devices: FleetUnit[], now: Date) {
} }
} }
const avgSoh = devices.reduce((sum, unit) => sum + unit.soh, 0) / totalDevices const avgSoh = averageNullable(devices.map((unit) => unit.soh))
const avgSoh30d = devices.reduce((sum, unit) => sum + unit.soh30d, 0) / totalDevices const avgSoh30d = averageNullable(devices.map((unit) => unit.soh30d))
const avgSoh90d = devices.reduce((sum, unit) => sum + unit.soh90d, 0) / totalDevices const avgSoh90d = averageNullable(devices.map((unit) => unit.soh90d))
const warningCount = devices.filter((unit) => unit.status === '预警').length const warningCount = devices.filter((unit) => unit.status === DEVICE_STATUS.WARNING).length
const watchCount = devices.filter((unit) => unit.status === '关注').length const watchCount = devices.filter((unit) => unit.status === DEVICE_STATUS.WATCH).length
const healthyCount = devices.filter((unit) => unit.status === '健康').length const healthyCount = devices.filter((unit) => unit.status === DEVICE_STATUS.HEALTHY).length
const batchPerformance = summarizeBy(devices, (unit) => unit.batch) const batchPerformance = summarizeBy(devices, (unit) => unit.batch)
.map(([batch, data]) => ({ batch, avgSoh: round1(data.sum / data.count) })) .map(([batch, data]) => ({ batch, avgSoh: data.valueCount > 0 ? round1(data.sum / data.valueCount) : null }))
.sort((a, b) => b.avgSoh - a.avgSoh) .sort((a, b) => (b.avgSoh ?? -1) - (a.avgSoh ?? -1))
const firmwareHealth = summarizeBy(devices, (unit) => unit.firmware) const firmwareHealth = summarizeBy(devices, (unit) => unit.firmware)
.map(([firmware, data]) => ({ firmware, avgSoh: round1(data.sum / data.count), count: data.count })) .map(([firmware, data]) => ({
.sort((a, b) => b.avgSoh - a.avgSoh) firmware,
avgSoh: data.valueCount > 0 ? round1(data.sum / data.valueCount) : null,
count: data.count,
}))
.sort((a, b) => (b.avgSoh ?? -1) - (a.avgSoh ?? -1))
const riskFactorCounts = Object.entries( const riskFactorCounts = Object.entries(
devices.reduce<Record<string, number>>((acc, unit) => { devices.reduce<Record<string, number>>((acc, unit) => {
for (const factor of unit.riskFactors) { for (const factor of unit.riskFactors) {
@@ -336,14 +375,16 @@ function createSummary(devices: FleetUnit[], now: Date) {
) )
.map(([factor, count]) => ({ factor, count })) .map(([factor, count]) => ({ factor, count }))
.sort((a, b) => b.count - a.count) .sort((a, b) => b.count - a.count)
const weakestBatch = batchPerformance.at(-1)?.batch ?? '当前设备' const weakestModel = batchPerformance.at(-1)?.batch ?? '当前设备型号'
const weakestFirmware = firmwareHealth.at(-1)?.firmware ?? 'unknown' const weakestRemark = firmwareHealth.at(-1)?.firmware ?? '未提供备注'
const predictedDevices = devices.filter((unit) => unit.soh !== null).length
const missingPredictionDevices = totalDevices - predictedDevices
return { return {
totalDevices, totalDevices,
avgSoh: round1(avgSoh), avgSoh: avgSoh === null ? null : round1(avgSoh),
avgSoh30d: round1(avgSoh30d), avgSoh30d: avgSoh30d === null ? null : round1(avgSoh30d),
avgSoh90d: round1(avgSoh90d), avgSoh90d: avgSoh90d === null ? null : round1(avgSoh90d),
warningCount, warningCount,
watchCount, watchCount,
healthyCount, healthyCount,
@@ -351,30 +392,35 @@ function createSummary(devices: FleetUnit[], now: Date) {
riskFactorCounts, riskFactorCounts,
firmwareHealth, firmwareHealth,
updatedAt: formatDateTime(now), updatedAt: formatDateTime(now),
executiveSummary: `当前电池健康度总体可控,重点风险集中在 ${weakestBatch} 批次与 ${weakestFirmware} 固件设备。建议优先跟踪低电量、充电状态与未来 90 天 SoH 变化。`, executiveSummary:
avgSoh === null
? '当前健康预测暂不可用,系统仍会展示设备电量、充电状态与低电量风险。请稍后复查或联系管理员。'
: `当前共有 ${predictedDevices} 台设备具备健康预测,${missingPredictionDevices} 台设备暂无预测结果。建议重点关注 ${weakestModel} 型号与 ${weakestRemark} 备注设备,优先处理低电量和充电中的设备,并在下次同步后复查未来 30/90 天健康趋势。`,
} }
} }
function createEvents(devices: FleetUnit[], now: Date) { function createEvents(devices: FleetUnit[], now: Date) {
const sortedDevices = devices.slice().sort((a, b) => b.riskScore - a.riskScore) if (devices.length === 0) return []
const first = sortedDevices[0]
if (!first) return [] const predictedDevices = devices.filter((unit) => unit.soh !== null)
const warningDevices = devices.filter((unit) => unit.status === DEVICE_STATUS.WARNING)
const second = sortedDevices[1] ?? first const missingPredictionDevices = devices.length - predictedDevices.length
return [ return [
{ {
time: formatEventTime(addHours(now, -2)), time: formatDateTime(now),
title: `${first.id} 进入重点观察队列`, title: '风险快照',
detail: `${first.id} 当前 SoH 为 ${first.soh.toFixed(1)}%,综合风险评分 ${first.riskScore}`, detail: `本次概览包含 ${devices.length} 台设备,其中 ${predictedDevices.length} 台具备健康预测,${warningDevices.length} 台处于预警状态`,
severity: first.status === '预警' ? '高' : '中', severity: warningDevices.length > 0 ? EVENT_SEVERITY.HIGH : EVENT_SEVERITY.LOW,
}, },
{ {
time: formatEventTime(addHours(now, -5)), time: formatDateTime(now),
title: `${second.batch} 批次健康度趋势更新`, title: '预测可用性快照',
detail: `${second.batch} 批次未来 90 天预测 SoH 为 ${second.soh90d.toFixed(1)}%。`, detail:
severity: second.status === '健康' ? '低' : '中', missingPredictionDevices > 0
? `当前有 ${missingPredictionDevices} 台设备暂无健康预测,相关趋势将暂不展示。`
: '当前所有设备均已具备健康预测,可继续观察趋势变化。',
severity: missingPredictionDevices > 0 ? EVENT_SEVERITY.MEDIUM : EVENT_SEVERITY.LOW,
}, },
] satisfies DashboardSnapshot['events'] ] satisfies DashboardSnapshot['events']
} }
@@ -382,22 +428,32 @@ function createEvents(devices: FleetUnit[], now: Date) {
function createStrategies(devices: FleetUnit[]) { function createStrategies(devices: FleetUnit[]) {
if (devices.length === 0) return [] if (devices.length === 0) return []
const warningDevices = devices.filter((unit) => unit.status === '预警') const warningDevices = devices.filter((unit) => unit.status === DEVICE_STATUS.WARNING)
const chargingDevices = devices.filter((unit) => unit.riskFactors.includes('充电中')) const powerAttentionDevices = devices.filter(
const first = devices.slice().sort((a, b) => b.riskScore - a.riskScore)[0] (unit) => unit.riskFactors.includes('充电中') || unit.riskFactors.includes('低电量'),
)
const missingPredictionDevices = devices.filter((unit) => unit.soh === null)
return [ return [
{ {
name: '预警设备优先维护', name: '优先处理预警设备',
impact: `预计高风险设备减少 ${Math.max(10, warningDevices.length * 12)}%`, impact: `当前有 ${warningDevices.length} 台设备处于预警状态,建议先复核供电、连接与预测结果。`,
scope: first ? `${first.id}${Math.max(1, warningDevices.length)} 台设备` : '当前设备', scope: warningDevices.length > 0 ? `${warningDevices.length}预警设备` : '当前设备',
eta: '48 小时内完成', eta: '本次巡检周期内',
}, },
{ {
name: '充电策略复核', name: '提升预测覆盖',
impact: `覆盖 ${Math.max(1, chargingDevices.length)} 台充电中设备`, impact:
scope: '充电中与低电量设备', missingPredictionDevices.length > 0
eta: '本周完成首轮验证', ? `当前有 ${missingPredictionDevices.length} 台设备暂无健康预测,建议在下次同步后复查。`
: `当前已有 ${devices.length} 台设备具备预测结果,可继续观察健康变化。`,
scope:
powerAttentionDevices.length > 0
? `${powerAttentionDevices.length} 台充电中或低电量设备`
: missingPredictionDevices.length > 0
? `${missingPredictionDevices.length} 台缺失预测设备`
: '当前设备',
eta: '下次同步后复查',
}, },
] satisfies DashboardSnapshot['strategies'] ] satisfies DashboardSnapshot['strategies']
} }
@@ -407,11 +463,11 @@ export function createDashboardSnapshot(
now = new Date(), now = new Date(),
predictions: ReadonlyMap<string, BatteryPrediction> = new Map(), predictions: ReadonlyMap<string, BatteryPrediction> = new Map(),
): DashboardSnapshot { ): DashboardSnapshot {
const devices = items.map((item, index) => toFleetUnit(item, index, predictions.get(item.mac))) const devices = items.map((item) => toFleetUnit(item, predictions.get(item.mac)))
return { return {
devices, devices,
soh: createSohResponse(devices, now), soh: createSohResponse(devices),
events: createEvents(devices, now), events: createEvents(devices, now),
strategies: createStrategies(devices), strategies: createStrategies(devices),
summary: createSummary(devices, now), summary: createSummary(devices, now),
+3 -1
View File
@@ -4,11 +4,13 @@ import { z } from 'zod'
export const env = createEnv({ export const env = createEnv({
server: { server: {
DATABASE_URL: z.url({ protocol: /^mysql$/ }), DATABASE_URL: z.url({ protocol: /^mysql$/ }),
ENABLE_API_DOCS: z.stringbool().default(false),
LOG_DB: z.stringbool().default(false), LOG_DB: z.stringbool().default(false),
LOG_FORMAT: z.enum(['pretty', 'json']).optional(), LOG_FORMAT: z.enum(['pretty', 'json']).optional(),
LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warning', 'error', 'fatal']).default('info'), LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warning', 'error', 'fatal']).default('info'),
SOH_PREDICTION_API_BASE_URL: z.url({ protocol: /^https?$/ }).optional(), SOH_PREDICTION_API_BASE_URL: z.url({ protocol: /^https?$/ }),
SOH_PREDICTION_CACHE_TTL_SECONDS: z.coerce.number().int().positive().default(86_400), SOH_PREDICTION_CACHE_TTL_SECONDS: z.coerce.number().int().positive().default(86_400),
SOH_PREDICTION_NEGATIVE_CACHE_TTL_SECONDS: z.coerce.number().int().positive().default(300),
SOH_PREDICTION_TIMEOUT_MS: z.coerce.number().int().positive().default(10_000), SOH_PREDICTION_TIMEOUT_MS: z.coerce.number().int().positive().default(10_000),
}, },
clientPrefix: 'VITE_', clientPrefix: 'VITE_',
+19 -14
View File
@@ -4,24 +4,27 @@ import { onError } from '@orpc/server'
import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4' import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4'
import { createFileRoute } from '@tanstack/react-router' import { createFileRoute } from '@tanstack/react-router'
import { name, version } from '#package' import { name, version } from '#package'
import { env } from '@/env'
import { handleValidationError, logError } from '@/server/api/interceptors' import { handleValidationError, logError } from '@/server/api/interceptors'
import { router } from '@/server/api/routers' import { router } from '@/server/api/routers'
const handler = new OpenAPIHandler(router, { const handler = new OpenAPIHandler(router, {
plugins: [ plugins: env.ENABLE_API_DOCS
new OpenAPIReferencePlugin({ ? [
docsProvider: 'scalar', new OpenAPIReferencePlugin({
schemaConverters: [new ZodToJsonSchemaConverter()], docsProvider: 'scalar',
specGenerateOptions: { schemaConverters: [new ZodToJsonSchemaConverter()],
info: { specGenerateOptions: {
title: name, info: {
version, title: name,
}, version,
}, },
docsPath: '/docs', },
specPath: '/spec.json', docsPath: '/docs',
}), specPath: '/spec.json',
], }),
]
: [],
interceptors: [onError(logError)], interceptors: [onError(logError)],
clientInterceptors: [onError(handleValidationError)], clientInterceptors: [onError(handleValidationError)],
}) })
@@ -30,6 +33,8 @@ export const Route = createFileRoute('/api/$')({
server: { server: {
handlers: { handlers: {
ANY: async ({ request }) => { ANY: async ({ request }) => {
if (!env.ENABLE_API_DOCS) return new Response('Not Found', { status: 404 })
const { response } = await handler.handle(request, { const { response } = await handler.handle(request, {
prefix: '/api', prefix: '/api',
context: { context: {
+480 -85
View File
@@ -1,30 +1,70 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { createFileRoute, Link } from '@tanstack/react-router' import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
import { ArrowLeft, Battery, BatteryCharging, BatteryLow, FilterX, Search, X, Zap } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { z } from 'zod'
import { orpc } from '@/client/orpc' import { orpc } from '@/client/orpc'
import type { BatteryInfo } from '@/domain/battery' import { MotionCardDiv, MotionHeader, MotionSection, MotionTableRow } from '@/components/motion'
import { Badge, Button, Card, EmptyState, Input, SectionTitle, Select, SelectOption, Skeleton } from '@/components/ui'
import type { BatteryInfo, BatteryListSort, PowerStatus } from '@/domain/battery'
import { BATTERY_LIST_SORT, BATTERY_LIST_SORT_VALUES, POWER_STATUS, POWER_STATUS_VALUES } from '@/domain/battery'
const pageSizeOptions = [20, 50, 100] as const
type PageSizeOption = (typeof pageSizeOptions)[number]
const firstPageCursor = '__FIRST_PAGE__'
const allPowerStatusValue = 'all'
const loadingRowKeys = Array.from({ length: 10 }, (_, index) => `loading-row-${index}`)
const searchFilterSchema = z.preprocess(
(value) => (typeof value === 'string' ? value.trim() || undefined : value),
z.string().min(1).max(100).optional(),
)
const cursorSchema = z.preprocess(
(value) => (typeof value === 'string' ? value.trim() || undefined : value),
z.string().min(1).max(1024).optional(),
)
const searchSchema = z.object({
search: searchFilterSchema,
lowPower: z.boolean().optional(),
powerStatus: z
.union([z.literal(POWER_STATUS.NOT_CHARGING), z.literal(POWER_STATUS.CHARGING), z.literal(POWER_STATUS.FULL)])
.optional(),
sort: z.enum(BATTERY_LIST_SORT_VALUES).optional().default(BATTERY_LIST_SORT.CREATED_AT_DESC),
pageSize: z.coerce
.number()
.pipe(z.union([z.literal(20), z.literal(50), z.literal(100)]))
.optional()
.default(50),
cursor: cursorSchema,
cursors: z.array(z.string().min(1).max(1024)).max(100).optional().default([]),
})
export const Route = createFileRoute('/batteries')({ export const Route = createFileRoute('/batteries')({
validateSearch: (search) => searchSchema.parse(search),
component: BatteriesPage, component: BatteriesPage,
errorComponent: ({ error }) => ( errorComponent: () => (
<main className="flex min-h-screen items-center justify-center bg-[#09090B]"> <main className="flex min-h-screen items-center justify-center bg-[#09090B]">
<div className="text-center"> <div className="text-center">
<p className="text-lg text-red-400"></p> <p className="text-lg text-red-400"></p>
<p className="mt-2 text-sm text-zinc-500">{error.message}</p> <p className="mt-2 text-sm text-zinc-500"></p>
</div> </div>
</main> </main>
), ),
}) })
const powerStatusLabel: Record<0 | 1 | 2, string> = { const powerStatusLabel: Record<PowerStatus, string> = {
0: '未充电', [POWER_STATUS.NOT_CHARGING]: '未充电',
1: '充电中', [POWER_STATUS.CHARGING]: '充电中',
2: '已充满', [POWER_STATUS.FULL]: '已充满',
} }
const powerStatusColor: Record<0 | 1 | 2, string> = { const powerStatusVariant: Record<PowerStatus, 'muted' | 'info' | 'success'> = {
0: 'text-zinc-400', [POWER_STATUS.NOT_CHARGING]: 'muted',
1: 'text-teal-400', [POWER_STATUS.CHARGING]: 'info',
2: 'text-emerald-400', [POWER_STATUS.FULL]: 'success',
} }
function powerBarColor(power: number, isLowPower: boolean): string { function powerBarColor(power: number, isLowPower: boolean): string {
@@ -33,103 +73,458 @@ function powerBarColor(power: number, isLowPower: boolean): string {
return 'bg-teal-500' return 'bg-teal-500'
} }
function DeviceCard({ item }: { item: BatteryInfo }) { const columnHelper = createColumnHelper<BatteryInfo>()
return (
<article className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<header className="flex items-start justify-between">
<div>
<h3 className="font-medium text-zinc-100">{item.devName}</h3>
<p className="mt-0.5 text-xs text-zinc-500">{item.mac}</p>
</div>
<span className="rounded bg-zinc-900 px-2 py-0.5 text-xs text-zinc-400">{item.devModel}</span>
</header>
<div className="mt-4"> function parseSort(value: string): BatteryListSort {
<div className="flex items-baseline justify-between"> return BATTERY_LIST_SORT_VALUES.find((option) => option === value) ?? BATTERY_LIST_SORT.CREATED_AT_DESC
<span className="font-semibold text-2xl text-zinc-100"> }
{item.power}
<span className="ml-0.5 font-normal text-sm text-zinc-500">%</span>
</span>
<span className={`text-xs ${powerStatusColor[item.powerStatus]}`}>{powerStatusLabel[item.powerStatus]}</span>
</div>
<div className="mt-2 h-1.5 overflow-hidden rounded-full bg-zinc-800">
<div className={`h-full ${powerBarColor(item.power, item.isLowPower)}`} style={{ width: `${item.power}%` }} />
</div>
</div>
<footer className="mt-4 flex items-center justify-between text-xs text-zinc-500"> function parsePowerStatus(value: string): PowerStatus | undefined {
<span> {new Date(item.createTime).toLocaleString('zh-CN')}</span> if (value === allPowerStatusValue) return undefined
{item.isLowPower && <span className="rounded bg-red-950 px-1.5 py-0.5 text-red-400"></span>}
</footer> const parsed = Number(value)
</article>
) return POWER_STATUS_VALUES.find((option) => option === parsed)
}
function parsePageSize(value: string): PageSizeOption {
const parsed = Number(value)
return pageSizeOptions.find((option) => option === parsed) ?? 50
} }
function BatteriesPage() { function BatteriesPage() {
const { data, error, isPending } = useQuery( const search = Route.useSearch()
const navigate = useNavigate({ from: Route.fullPath })
const [localSearch, setLocalSearch] = useState(search.search || '')
useEffect(() => {
setLocalSearch(search.search ?? '')
}, [search.search])
useEffect(() => {
const timer = setTimeout(() => {
const trimmedSearch = localSearch.trim()
const nextSearch = trimmedSearch || undefined
if (nextSearch !== search.search) {
navigate({
search: (prev) => ({ ...prev, search: nextSearch, cursor: undefined, cursors: [] }),
})
}
}, 500)
return () => clearTimeout(timer)
}, [localSearch, navigate, search.search])
const { data, error, isPending, isPlaceholderData } = useQuery(
orpc.battery.batteries.queryOptions({ orpc.battery.batteries.queryOptions({
input: {}, input: {
search: search.search,
lowPower: search.lowPower,
powerStatus: search.powerStatus,
sort: search.sort,
pageSize: search.pageSize,
cursor: search.cursor,
},
refetchInterval: 30_000, refetchInterval: 30_000,
placeholderData: (prev) => prev,
}), }),
) )
const columns = useMemo(
() => [
columnHelper.accessor('devName', {
header: '设备名称',
cell: (info) => (
<div className="flex flex-col">
<span className="font-medium text-zinc-100">{info.getValue()}</span>
<span className="text-[10px] text-zinc-500 tabular-nums">{info.row.original.mac}</span>
</div>
),
}),
columnHelper.accessor('devModel', {
header: '型号',
cell: (info) => <span className="text-zinc-400">{info.getValue()}</span>,
}),
columnHelper.accessor('power', {
header: '电量',
cell: (info) => {
const power = info.getValue()
const isLow = info.row.original.isLowPower
return (
<div className="flex items-center gap-3">
<span className="w-8 text-right tabular-nums font-medium">{power}%</span>
<div className="h-1.5 w-16 overflow-hidden rounded-full bg-zinc-800">
<div className={`h-full ${powerBarColor(power, isLow)}`} style={{ width: `${power}%` }} />
</div>
</div>
)
},
}),
columnHelper.accessor('powerStatus', {
header: '状态',
cell: (info) => {
const status = info.getValue()
return <Badge variant={powerStatusVariant[status]}>{powerStatusLabel[status]}</Badge>
},
}),
columnHelper.accessor('createTime', {
header: '最后更新',
cell: (info) => (
<span className="text-zinc-500 tabular-nums">{new Date(info.getValue()).toLocaleString('zh-CN')}</span>
),
}),
],
[],
)
const table = useReactTable({
data: data?.items ?? [],
columns,
getCoreRowModel: getCoreRowModel(),
})
const hasActiveFilters = Boolean(search.search || search.lowPower || search.powerStatus !== undefined)
const clearFilters = () => {
setLocalSearch('')
navigate({
search: (prev) => ({
...prev,
search: undefined,
lowPower: undefined,
powerStatus: undefined,
cursor: undefined,
cursors: [],
}),
})
}
const handleNextPage = () => {
if (!isPlaceholderData && data?.nextCursor) {
const nextCursor = data.nextCursor
navigate({
search: (prev) => ({
...prev,
cursor: nextCursor,
cursors: [...(prev.cursors || []), prev.cursor || firstPageCursor].slice(-100),
}),
})
}
}
const handlePrevPage = () => {
const newCursors = [...(search.cursors || [])]
const lastCursor = newCursors.pop()
navigate({
search: (prev) => ({
...prev,
cursor: lastCursor === firstPageCursor ? undefined : lastCursor,
cursors: newCursors,
}),
})
}
if (error) { if (error) {
return ( return (
<main className="flex min-h-screen items-center justify-center bg-[#09090B]"> <main className="flex min-h-screen items-center justify-center bg-[#09090B]">
<div className="text-center"> <div className="text-center">
<p className="text-lg text-red-400"></p> <p className="text-lg text-red-400"></p>
<p className="mt-2 text-sm text-zinc-500">{error.message}</p> <p className="mt-2 text-sm text-zinc-500"></p>
</div> </div>
</main> </main>
) )
} }
if (isPending || !data) {
return (
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
<p className="text-zinc-500"></p>
</main>
)
}
return ( return (
<main className="min-h-screen bg-[#09090B] px-6 py-8 text-zinc-100"> <main className="min-h-screen bg-[#09090B] text-zinc-100">
<header className="mx-auto max-w-7xl"> {/* Background gradient */}
<div className="flex items-end justify-between"> <div className="pointer-events-none fixed inset-0 z-0 flex justify-center">
<div> <div className="h-[600px] w-[1000px] -translate-y-1/2 rounded-full bg-teal-900/5 blur-[100px]" />
<h1 className="font-semibold text-2xl"></h1> </div>
<p className="mt-1 text-sm text-zinc-500"> {new Date(data.updatedAt).toLocaleString('zh-CN')}</p>
</div>
<nav className="text-xs">
<Link to="/" className="text-zinc-500 hover:text-zinc-300">
SoH
</Link>
</nav>
</div>
<dl className="mt-6 grid grid-cols-3 gap-4"> <div className="relative z-10 mx-auto max-w-7xl px-6 py-8">
<div className="rounded-lg border border-zinc-800 bg-zinc-950 p-4"> <MotionHeader>
<dt className="text-xs text-zinc-500"></dt> <div className="flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between">
<dd className="mt-1 font-semibold text-2xl">{data.total}</dd> <div>
<Badge variant="info" className="mb-4">
<Battery className="size-3.5" />
</Badge>
<h1 className="text-3xl font-light tracking-tight text-white"></h1>
<p className="mt-2 max-w-2xl text-sm leading-6 text-zinc-400">
</p>
<p className="mt-2 text-xs tabular-nums text-zinc-500">
{data ? `更新于 ${new Date(data.updatedAt).toLocaleString('zh-CN')}` : '加载中…'}
</p>
</div>
<nav>
<Link
to="/"
className="inline-flex items-center gap-2 rounded-lg border border-white/10 bg-white/[0.04] px-3 py-2 text-sm text-zinc-300 transition-colors hover:border-teal-400/30 hover:text-teal-300"
>
<ArrowLeft className="size-4" />
</Link>
</nav>
</div> </div>
<div className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<dt className="text-xs text-zinc-500"></dt>
<dd className="mt-1 font-semibold text-2xl text-red-400">{data.lowPower}</dd>
</div>
<div className="rounded-lg border border-zinc-800 bg-zinc-950 p-4">
<dt className="text-xs text-zinc-500"></dt>
<dd className="mt-1 font-semibold text-2xl text-teal-400">{data.charging}</dd>
</div>
</dl>
</header>
<section className="mx-auto mt-8 grid max-w-7xl grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4"> <dl className="mt-8 grid grid-cols-1 gap-4 sm:grid-cols-3">
{data.items.length > 0 ? ( <MotionCardDiv className="rounded-2xl border border-white/[0.08] bg-zinc-950/60 shadow-2xl shadow-black/20 p-5">
data.items.map((item) => <DeviceCard key={item.id} item={item} />) <dt className="flex items-center gap-2 text-xs font-medium text-zinc-500">
) : ( <Battery className="size-4 text-zinc-400" />
<div className="col-span-full py-12 text-center text-zinc-500"></div> </dt>
)} <dd className="mt-3 text-3xl font-light tabular-nums text-white">{data?.total ?? '-'}</dd>
</section> </MotionCardDiv>
<MotionCardDiv className="rounded-2xl border border-white/[0.08] bg-zinc-950/60 shadow-2xl shadow-black/20 p-5">
<dt className="flex items-center gap-2 text-xs font-medium text-zinc-500">
<BatteryLow className="size-4 text-red-400" />
</dt>
<dd className="mt-3 text-3xl font-light tabular-nums text-red-300">{data?.lowPower ?? '-'}</dd>
</MotionCardDiv>
<MotionCardDiv className="rounded-2xl border border-white/[0.08] bg-zinc-950/60 shadow-2xl shadow-black/20 p-5">
<dt className="flex items-center gap-2 text-xs font-medium text-zinc-500">
<BatteryCharging className="size-4 text-teal-300" />
</dt>
<dd className="mt-3 text-3xl font-light tabular-nums text-teal-300">{data?.charging ?? '-'}</dd>
</MotionCardDiv>
</dl>
</MotionHeader>
<MotionSection delay={0.1} className="mt-10">
<Card className="mb-6 p-5">
<div className="mb-5 flex flex-wrap items-center justify-between gap-3">
<SectionTitle
icon={<Search className="size-4" />}
title="筛选设备"
description="按设备名称、编号、电量与充电状态快速缩小排查范围。"
/>
{hasActiveFilters && (
<Button type="button" className="h-9 px-3 text-xs" onClick={clearFilters}>
<FilterX className="size-3.5" />
</Button>
)}
</div>
<div className="flex flex-wrap items-end gap-4">
<div className="flex flex-col gap-2 min-w-[260px] flex-1">
<label htmlFor="search-input" className="text-xs font-medium text-zinc-500">
/
</label>
<div className="relative">
<Search className="pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-zinc-600" />
<Input
id="search-input"
type="text"
placeholder="搜索设备名称或编号..."
maxLength={100}
className="pl-9 pr-9"
value={localSearch}
onChange={(e) => setLocalSearch(e.target.value)}
/>
{localSearch && (
<button
type="button"
aria-label="清空搜索内容"
onClick={() => setLocalSearch('')}
className="absolute right-3 top-1/2 -translate-y-1/2 text-zinc-500 hover:text-zinc-300"
>
<X className="size-4" />
</button>
)}
</div>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="power-status-select" className="text-xs font-medium text-zinc-500">
</label>
<Select
id="power-status-select"
value={search.powerStatus ?? allPowerStatusValue}
onValueChange={(value) => {
navigate({
search: (prev) => ({
...prev,
powerStatus: parsePowerStatus(value),
cursor: undefined,
cursors: [],
}),
})
}}
>
<SelectOption value={allPowerStatusValue}></SelectOption>
<SelectOption value={POWER_STATUS.NOT_CHARGING}></SelectOption>
<SelectOption value={POWER_STATUS.CHARGING}></SelectOption>
<SelectOption value={POWER_STATUS.FULL}></SelectOption>
</Select>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="sort-select" className="text-xs font-medium text-zinc-500">
</label>
<Select
id="sort-select"
value={search.sort}
onValueChange={(value) => {
navigate({
search: (prev) => ({
...prev,
sort: parseSort(value),
cursor: undefined,
cursors: [],
}),
})
}}
>
<SelectOption value={BATTERY_LIST_SORT.CREATED_AT_DESC}></SelectOption>
<SelectOption value={BATTERY_LIST_SORT.CREATED_AT_ASC}></SelectOption>
<SelectOption value={BATTERY_LIST_SORT.POWER_DESC}></SelectOption>
<SelectOption value={BATTERY_LIST_SORT.POWER_ASC}></SelectOption>
</Select>
</div>
<div className="flex flex-col gap-2">
<label htmlFor="page-size-select" className="text-xs font-medium text-zinc-500">
</label>
<Select
id="page-size-select"
value={search.pageSize}
onValueChange={(value) => {
navigate({
search: (prev) => ({
...prev,
pageSize: parsePageSize(value),
cursor: undefined,
cursors: [],
}),
})
}}
>
<SelectOption value="20">20 /</SelectOption>
<SelectOption value="50">50 /</SelectOption>
<SelectOption value="100">100 /</SelectOption>
</Select>
</div>
<label
htmlFor="low-power-checkbox"
className="inline-flex h-10 cursor-pointer items-center gap-2 rounded-lg border border-white/10 bg-white/[0.04] px-3 text-sm text-zinc-300 transition-colors hover:bg-white/[0.07]"
>
<input
id="low-power-checkbox"
type="checkbox"
className="rounded border-white/10 bg-zinc-950 text-teal-500 focus:ring-teal-500/50"
checked={search.lowPower ?? false}
onChange={(e) =>
navigate({
search: (prev) => ({
...prev,
lowPower: e.target.checked || undefined,
cursor: undefined,
cursors: [],
}),
})
}
/>
<Zap className="size-4 text-amber-300" />
</label>
</div>
</Card>
<Card className="overflow-hidden">
<div className="overflow-x-auto max-h-[600px]">
<table className={`w-full border-collapse text-left text-sm ${isPlaceholderData ? 'opacity-60' : ''}`}>
<thead className="sticky top-0 z-10 bg-zinc-950/90 backdrop-blur-sm">
{table.getHeaderGroups().map((headerGroup) => (
<tr key={headerGroup.id} className="border-b border-white/5 bg-white/[0.02]">
{headerGroup.headers.map((header) => (
<th key={header.id} className="px-6 py-4 font-medium text-zinc-500 whitespace-nowrap">
{flexRender(header.column.columnDef.header, header.getContext())}
</th>
))}
</tr>
))}
</thead>
<tbody className="divide-y divide-white/[0.02]">
{isPending && !isPlaceholderData ? (
loadingRowKeys.map((key) => (
<tr key={key}>
<td className="px-6 py-4">
<Skeleton className="h-5 w-32" />
<Skeleton className="mt-1.5 h-3 w-24" />
</td>
<td className="px-6 py-4">
<Skeleton className="h-4 w-20" />
</td>
<td className="px-6 py-4">
<div className="flex items-center gap-3">
<Skeleton className="h-4 w-8" />
<Skeleton className="h-1.5 w-16 rounded-full" />
</div>
</td>
<td className="px-6 py-4">
<Skeleton className="h-6 w-16 rounded-full" />
</td>
<td className="px-6 py-4">
<Skeleton className="h-4 w-32" />
</td>
</tr>
))
) : data?.items.length === 0 ? (
<tr>
<td colSpan={columns.length} className="h-64">
<EmptyState
icon={<Battery className="size-8" />}
title="未找到符合条件的设备"
description={
hasActiveFilters ? '尝试调整筛选条件或清除筛选以查看更多设备。' : '当前暂无设备数据接入。'
}
action={
hasActiveFilters ? (
<Button onClick={clearFilters}>
<FilterX className="size-4" />
</Button>
) : undefined
}
/>
</td>
</tr>
) : (
table.getRowModel().rows.map((row) => (
<MotionTableRow key={row.id} className="transition-colors hover:bg-white/[0.02]">
{row.getVisibleCells().map((cell) => (
<td key={cell.id} className="px-6 py-4 whitespace-nowrap">
{flexRender(cell.column.columnDef.cell, cell.getContext())}
</td>
))}
</MotionTableRow>
))
)}
</tbody>
</table>
</div>
</Card>
<div className="mt-6 flex items-center justify-between text-sm text-zinc-500">
<div>
{data?.items.length ?? 0}
{data?.total ? ` (共 ${data.total} 台)` : ''}
</div>
<div className="flex items-center gap-2">
<Button
type="button"
onClick={handlePrevPage}
disabled={isPlaceholderData || (!search.cursor && (!search.cursors || search.cursors.length === 0))}
>
</Button>
<Button type="button" onClick={handleNextPage} disabled={isPlaceholderData || !data?.nextCursor}>
</Button>
</div>
</div>
</MotionSection>
</div>
</main> </main>
) )
} }
+309 -257
View File
@@ -1,5 +1,6 @@
import { useQuery } from '@tanstack/react-query' import { useQuery } from '@tanstack/react-query'
import { createFileRoute, Link } from '@tanstack/react-router' import { createFileRoute, Link } from '@tanstack/react-router'
import { Activity, AlertTriangle, ArrowRight, ShieldCheck, Tags, TrendingDown } from 'lucide-react'
import { import {
Area, Area,
CartesianGrid, CartesianGrid,
@@ -13,7 +14,10 @@ import {
} from 'recharts' } from 'recharts'
import type { NameType, ValueType } from 'recharts/types/component/DefaultTooltipContent' import type { NameType, ValueType } from 'recharts/types/component/DefaultTooltipContent'
import { orpc } from '@/client/orpc' import { orpc } from '@/client/orpc'
import { MotionCardArticle, MotionCardDiv, MotionHeader, MotionSection } from '@/components/motion'
import { Badge, Card, EmptyState, SectionTitle } from '@/components/ui'
import type { DashboardSnapshot, DeviceStatus } from '@/domain/battery' import type { DashboardSnapshot, DeviceStatus } from '@/domain/battery'
import { BATTERY_LIST_SORT, DEVICE_STATUS } from '@/domain/battery'
export const Route = createFileRoute('/')({ export const Route = createFileRoute('/')({
component: Dashboard, component: Dashboard,
@@ -42,7 +46,9 @@ function buildChartData(soh: DashboardSnapshot['soh']) {
} }
} }
for (let i = 1; i < soh.forecast.length; i++) { const forecastStart = chartData.length > 0 ? 1 : 0
for (let i = forecastStart; i < soh.forecast.length; i++) {
const f = soh.forecast[i] const f = soh.forecast[i]
if (f) { if (f) {
chartData.push({ chartData.push({
@@ -56,16 +62,16 @@ function buildChartData(soh: DashboardSnapshot['soh']) {
return chartData return chartData
} }
const statusColorMap: Record<DeviceStatus, string> = { const statusVariantMap: Record<DeviceStatus, 'success' | 'warning' | 'danger'> = {
: 'text-emerald-400', [DEVICE_STATUS.HEALTHY]: 'success',
: 'text-amber-400', [DEVICE_STATUS.WATCH]: 'warning',
: 'text-red-400', [DEVICE_STATUS.WARNING]: 'danger',
} }
const severityColorMap: Record<DashboardSnapshot['events'][number]['severity'], string> = { const severityVariantMap: Record<DashboardSnapshot['events'][number]['severity'], 'danger' | 'warning' | 'muted'> = {
: 'text-red-400', : 'danger',
: 'text-amber-400', : 'warning',
: 'text-zinc-400', : 'muted',
} }
function formatChartTooltip(value: ValueType | undefined, name: NameType | undefined) { function formatChartTooltip(value: ValueType | undefined, name: NameType | undefined) {
@@ -73,10 +79,31 @@ function formatChartTooltip(value: ValueType | undefined, name: NameType | undef
return [ return [
`${Number.isFinite(numericValue) ? numericValue.toFixed(1) : (value ?? '-')}%`, `${Number.isFinite(numericValue) ? numericValue.toFixed(1) : (value ?? '-')}%`,
name === 'history' ? '历史观测' : '模型预测', name === 'history' ? '历史观测' : '趋势预测',
] ]
} }
function formatPercent(value: number | null) {
return value === null ? '—' : value.toFixed(1)
}
function formatPercentWithUnit(value: number | null) {
return value === null ? '预测不可用' : `${value.toFixed(1)}%`
}
function formatDelta(from: number | null, to: number | null) {
if (from === null || to === null) return '预测不可用'
const delta = from - to
if (delta < 0) return `${Math.abs(delta).toFixed(1)}% 改善`
if (delta === 0) return '0.0% 持平'
return `${delta.toFixed(1)}% 衰减`
}
function widthPercent(value: number | null) {
return `${Math.max(0, Math.min(100, value ?? 0))}%`
}
function Dashboard() { function Dashboard() {
const { data, error, isPending } = useQuery(orpc.battery.dashboard.queryOptions()) const { data, error, isPending } = useQuery(orpc.battery.dashboard.queryOptions())
@@ -125,84 +152,78 @@ function Dashboard() {
<div className="relative z-10 mx-auto max-w-[1400px] px-6 pb-24 pt-12 lg:px-12"> <div className="relative z-10 mx-auto max-w-[1400px] px-6 pb-24 pt-12 lg:px-12">
{/* Header */} {/* Header */}
<header className="animate-fade-up mb-12 flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between"> <MotionHeader className="mb-12 flex flex-col gap-6 lg:flex-row lg:items-end lg:justify-between">
<div className="max-w-3xl"> <div className="max-w-3xl">
<div className="mb-4 inline-flex items-center gap-2 rounded-md border border-white/10 bg-white/5 px-2.5 py-1 text-xs font-medium text-teal-400"> <Badge variant="info" className="mb-4">
(v2.4) <Activity className="size-3.5" />
</div> </Badge>
<h1 className="text-4xl font-light tracking-tight text-white sm:text-5xl">SoH </h1> <h1 className="text-4xl font-light tracking-tight text-white sm:text-5xl"></h1>
</div> </div>
<div className="flex flex-col items-end gap-3 text-right"> <div className="flex flex-col items-end gap-3 text-right">
<div className="flex items-center gap-6 text-sm"> <Badge variant="muted"></Badge>
<div>
<span className="text-[#71717A]"> (MAE)</span>
<span className="ml-2 font-medium tabular-nums text-teal-400">1.2%</span>
</div>
<div className="h-4 w-px bg-white/10" />
<div>
<span className="text-[#71717A]"></span>
<span className="ml-2 font-medium tabular-nums text-teal-400">94.5%</span>
</div>
</div>
<p className="text-xs tabular-nums text-[#71717A]">: {updatedAt}</p> <p className="text-xs tabular-nums text-[#71717A]">: {updatedAt}</p>
<Link to="/batteries" className="text-xs text-teal-400 hover:text-teal-300"> <Link
to="/batteries"
search={{ pageSize: 50, sort: BATTERY_LIST_SORT.CREATED_AT_DESC, cursors: [] }}
className="inline-flex items-center gap-1 text-xs text-teal-400 hover:text-teal-300"
>
<ArrowRight className="size-3" />
</Link> </Link>
</div> </div>
</header> </MotionHeader>
{/* Executive Summary */} {/* Executive Summary */}
<section className="animate-fade-up delay-100 mb-12 rounded-xl border border-teal-900/30 bg-teal-950/10 p-6"> <MotionSection delay={0.1} className="mb-12 rounded-xl border border-teal-900/30 bg-teal-950/10 p-6">
<h2 className="mb-3 text-sm font-medium text-teal-400"></h2> <h2 className="mb-3 text-sm font-medium text-teal-400"></h2>
<p className="text-base leading-relaxed text-[#A1A1AA]">{executiveSummary}</p> <p className="text-base leading-relaxed text-[#A1A1AA]">{executiveSummary}</p>
</section> </MotionSection>
{/* Primary KPI Row */} {/* Primary KPI Row */}
<section className="animate-fade-up delay-200 mb-12 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-5"> <MotionSection delay={0.2} className="mb-12 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-5">
{/* Hero KPI */} {/* Hero KPI */}
<article className="relative overflow-hidden rounded-2xl border border-white/10 bg-white/[0.03] p-8 lg:col-span-2"> <MotionCardArticle className="relative overflow-hidden rounded-2xl border border-white/10 bg-white/[0.03] p-8 lg:col-span-2">
<div className="absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-teal-500/50 to-transparent" /> <div className="absolute inset-x-0 top-0 h-1 bg-gradient-to-r from-teal-500/50 to-transparent" />
<p className="text-sm font-medium text-[#A1A1AA]"> SoH</p> <p className="text-sm font-medium text-[#A1A1AA]"></p>
<div className="mt-4 flex items-baseline gap-2"> <div className="mt-4 flex items-baseline gap-2">
<h2 className="text-6xl font-light tabular-nums text-white">{avgSoh.toFixed(1)}</h2> <h2 className="text-6xl font-light tabular-nums text-white">{formatPercent(avgSoh)}</h2>
<span className="text-2xl text-[#71717A]">%</span> {avgSoh !== null && <span className="text-2xl text-[#71717A]">%</span>}
</div> </div>
<div className="mt-6 flex items-center gap-3 text-sm"> <div className="mt-6 flex items-center gap-3 text-sm">
<span className="inline-flex items-center gap-1.5 text-emerald-400"> <span className="inline-flex items-center gap-1.5 text-emerald-400">
<span className="h-1.5 w-1.5 rounded-full bg-emerald-400" /> <span className="h-1.5 w-1.5 rounded-full bg-emerald-400" />
线 {avgSoh === null ? '健康预测暂不可用' : '预测已返回'}
</span> </span>
<span className="text-[#71717A]">|</span> <span className="text-[#71717A]">|</span>
<span className="text-[#A1A1AA]"> {totalDevices} </span> <span className="text-[#A1A1AA]"> {totalDevices} </span>
</div> </div>
</article> </MotionCardArticle>
{/* Regular KPIs */} {/* Regular KPIs */}
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10"> <MotionCardArticle className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
<p className="text-sm text-[#A1A1AA]">30 </p> <p className="text-sm text-[#A1A1AA]">30 </p>
<div className="mt-3 flex items-baseline gap-1"> <div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{avgSoh30d.toFixed(1)}</h2> <h2 className="text-4xl font-light tabular-nums text-white">{formatPercent(avgSoh30d)}</h2>
<span className="text-lg text-[#71717A]">%</span> {avgSoh30d !== null && <span className="text-lg text-[#71717A]">%</span>}
</div> </div>
<div className="mt-4 flex items-center gap-1.5 text-sm"> <div className="mt-4 flex items-center gap-1.5 text-sm">
<span className="text-red-400"></span> <span className="text-red-400"></span>
<span className="tabular-nums text-[#A1A1AA]">{(avgSoh - avgSoh30d).toFixed(1)}% </span> <span className="tabular-nums text-[#A1A1AA]">{formatDelta(avgSoh, avgSoh30d)}</span>
</div> </div>
</article> </MotionCardArticle>
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10"> <MotionCardArticle className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
<p className="text-sm text-[#A1A1AA]">90 </p> <p className="text-sm text-[#A1A1AA]">90 </p>
<div className="mt-3 flex items-baseline gap-1"> <div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{avgSoh90d.toFixed(1)}</h2> <h2 className="text-4xl font-light tabular-nums text-white">{formatPercent(avgSoh90d)}</h2>
<span className="text-lg text-[#71717A]">%</span> {avgSoh90d !== null && <span className="text-lg text-[#71717A]">%</span>}
</div> </div>
<div className="mt-4 flex items-center gap-1.5 text-sm"> <div className="mt-4 flex items-center gap-1.5 text-sm">
<span className="text-red-400"></span> <span className="text-red-400"></span>
<span className="tabular-nums text-[#A1A1AA]">{(avgSoh - avgSoh90d).toFixed(1)}% </span> <span className="tabular-nums text-[#A1A1AA]">{formatDelta(avgSoh, avgSoh90d)}</span>
</div> </div>
</article> </MotionCardArticle>
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10"> <MotionCardArticle className="rounded-2xl border border-white/[0.06] bg-white/[0.02] p-6 transition-colors hover:border-white/10">
<p className="text-sm text-[#A1A1AA]"></p> <p className="text-sm text-[#A1A1AA]"></p>
<div className="mt-3 flex items-baseline gap-1"> <div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{warningCount}</h2> <h2 className="text-4xl font-light tabular-nums text-white">{warningCount}</h2>
@@ -214,139 +235,155 @@ function Dashboard() {
{totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}% {totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
</span> </span>
</div> </div>
</article> </MotionCardArticle>
</section> </MotionSection>
{/* Divider */} {/* Divider */}
<hr className="my-12 border-white/5" /> <hr className="my-12 border-white/5" />
{/* SoH Trend Chart */} {/* Health trend chart */}
<section className="animate-fade-up delay-300 mb-12"> <MotionSection delay={0.3} className="mb-12">
<article className="rounded-2xl border border-white/[0.06] bg-white/[0.03] p-8"> <Card className="p-8">
<header className="mb-8 flex flex-wrap items-end justify-between gap-4"> <header className="mb-8 flex flex-wrap items-end justify-between gap-4">
<div> <SectionTitle
<h3 className="text-xl font-medium text-white">SoH 90 </h3> icon={<TrendingDown className="size-4" />}
<p className="mt-1 text-sm text-[#A1A1AA]"> 12 3 </p> title="健康趋势预测"
</div> description="展示当前健康度与未来 30/90 天趋势;数据不足时保持空态,避免误导判断。"
/>
<div className="flex items-center gap-6 text-sm text-[#A1A1AA]"> <div className="flex items-center gap-6 text-sm text-[#A1A1AA]">
<span className="inline-flex items-center gap-2"> {soh.history.length > 0 && (
<span className="h-2 w-4 rounded-full bg-teal-400" /> <span className="inline-flex items-center gap-2">
<span className="h-2 w-4 rounded-full bg-teal-400" />
</span>
</span>
)}
<span className="inline-flex items-center gap-2"> <span className="inline-flex items-center gap-2">
<span className="h-2 w-4 rounded-full bg-indigo-400" /> <span className="h-2 w-4 rounded-full bg-indigo-400" />
</span> </span>
</div> </div>
</header> </header>
<div className="w-full h-[320px]"> <div className="w-full h-[320px]">
<ResponsiveContainer width="100%" height="100%"> {chartData.length > 0 ? (
<ComposedChart data={chartData} margin={{ top: 24, right: 24, bottom: 8, left: 0 }}> <ResponsiveContainer width="100%" height="100%">
<defs> <ComposedChart data={chartData} margin={{ top: 24, right: 24, bottom: 8, left: 0 }}>
<linearGradient id="historyFill" x1="0" y1="0" x2="0" y2="1"> <defs>
<stop offset="0%" stopColor="#2DD4BF" stopOpacity={0.15} /> <linearGradient id="historyFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="100%" stopColor="#2DD4BF" stopOpacity={0} /> <stop offset="0%" stopColor="#2DD4BF" stopOpacity={0.25} />
</linearGradient> <stop offset="100%" stopColor="#2DD4BF" stopOpacity={0} />
<linearGradient id="forecastFill" x1="0" y1="0" x2="0" y2="1"> </linearGradient>
<stop offset="0%" stopColor="#818CF8" stopOpacity={0.15} /> <linearGradient id="forecastFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="100%" stopColor="#818CF8" stopOpacity={0} /> <stop offset="0%" stopColor="#818CF8" stopOpacity={0.25} />
</linearGradient> <stop offset="100%" stopColor="#818CF8" stopOpacity={0} />
</defs> </linearGradient>
<CartesianGrid stroke="#ffffff" strokeOpacity={0.05} vertical={false} /> </defs>
<XAxis dataKey="month" tick={{ fill: '#71717A', fontSize: 11 }} axisLine={false} tickLine={false} /> <CartesianGrid stroke="#ffffff" strokeOpacity={0.05} vertical={false} />
<YAxis <XAxis dataKey="month" tick={{ fill: '#A1A1AA', fontSize: 12 }} axisLine={false} tickLine={false} />
domain={[(min: number) => Math.floor(min) - 2, (max: number) => Math.ceil(max) + 2]} <YAxis
tick={{ fill: '#71717A', fontSize: 11 }} domain={[(min: number) => Math.floor(min) - 2, (max: number) => Math.ceil(max) + 2]}
axisLine={false} tick={{ fill: '#A1A1AA', fontSize: 12 }}
tickLine={false} axisLine={false}
tickFormatter={(v: number) => `${v}%`} tickLine={false}
width={48} tickFormatter={(v: number) => `${v}%`}
width={48}
/>
<Tooltip
contentStyle={{
backgroundColor: '#18181B',
border: '1px solid rgba(255,255,255,0.1)',
borderRadius: 8,
fontSize: 13,
color: '#F4F4F5',
boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.5)',
}}
itemStyle={{ color: '#E4E4E7', fontWeight: 500 }}
formatter={formatChartTooltip}
labelStyle={{ color: '#A1A1AA', marginBottom: 6 }}
/>
<ReferenceLine
y={85}
stroke="#F87171"
strokeOpacity={0.6}
strokeDasharray="4 4"
label={{
value: '85% 预警线',
fill: '#F87171',
fontSize: 12,
position: 'right',
}}
/>
<Area
type="monotone"
dataKey="history"
fill="url(#historyFill)"
stroke="none"
connectNulls={false}
tooltipType="none"
/>
<Area
type="monotone"
dataKey="forecast"
fill="url(#forecastFill)"
stroke="none"
connectNulls={false}
tooltipType="none"
/>
<Line
type="monotone"
dataKey="history"
stroke="#2DD4BF"
strokeWidth={2.5}
dot={{
fill: '#09090B',
stroke: '#2DD4BF',
strokeWidth: 2,
r: 3,
}}
connectNulls={false}
/>
<Line
type="monotone"
dataKey="forecast"
stroke="#818CF8"
strokeWidth={2.5}
strokeDasharray="4 4"
dot={{
fill: '#09090B',
stroke: '#818CF8',
strokeWidth: 2,
r: 3,
}}
connectNulls={false}
/>
</ComposedChart>
</ResponsiveContainer>
) : (
<div className="flex h-full items-center justify-center rounded-xl border border-dashed border-white/10 bg-white/[0.02]">
<EmptyState
icon={<TrendingDown className="size-8" />}
title="暂无健康趋势数据"
description="当前设备数据不足以生成可靠的健康趋势预测,请等待系统收集更多数据。"
/> />
<Tooltip </div>
contentStyle={{ )}
backgroundColor: '#18181B',
border: '1px solid rgba(255,255,255,0.1)',
borderRadius: 8,
fontSize: 13,
color: '#F4F4F5',
}}
itemStyle={{ color: '#A1A1AA' }}
formatter={formatChartTooltip}
labelStyle={{ color: '#71717A', marginBottom: 4 }}
/>
<ReferenceLine
y={85}
stroke="#F87171"
strokeOpacity={0.4}
strokeDasharray="4 4"
label={{
value: '85% 预警线',
fill: '#F87171',
fontSize: 11,
position: 'right',
}}
/>
<Area
type="monotone"
dataKey="history"
fill="url(#historyFill)"
stroke="none"
connectNulls={false}
tooltipType="none"
/>
<Area
type="monotone"
dataKey="forecast"
fill="url(#forecastFill)"
stroke="none"
connectNulls={false}
tooltipType="none"
/>
<Line
type="monotone"
dataKey="history"
stroke="#2DD4BF"
strokeWidth={2.5}
dot={{
fill: '#09090B',
stroke: '#2DD4BF',
strokeWidth: 2,
r: 3,
}}
connectNulls={false}
/>
<Line
type="monotone"
dataKey="forecast"
stroke="#818CF8"
strokeWidth={2.5}
strokeDasharray="4 4"
dot={{
fill: '#09090B',
stroke: '#818CF8',
strokeWidth: 2,
r: 3,
}}
connectNulls={false}
/>
</ComposedChart>
</ResponsiveContainer>
</div> </div>
</article> </Card>
</section> </MotionSection>
{/* Two-column grid */} {/* Two-column grid */}
<section className="animate-fade-up delay-400 mb-12 grid grid-cols-1 gap-8 lg:grid-cols-2"> <MotionSection delay={0.4} className="mb-12 grid grid-cols-1 gap-8 lg:grid-cols-2">
{/* Left Column */} {/* Left Column */}
<div className="space-y-8"> <div className="space-y-8">
{/* Risk Distribution */} {/* Risk Distribution */}
<div> <div>
<h3 className="mb-6 text-lg font-medium text-white"></h3> <div className="mb-6">
<SectionTitle icon={<ShieldCheck className="size-4" />} title="健康分布" />
</div>
<div className="space-y-5"> <div className="space-y-5">
<div> <div>
<div className="mb-2 flex justify-between text-sm"> <div className="mb-2 flex justify-between text-sm">
<span className="text-[#A1A1AA]"> (SoH &gt; 90%)</span> <span className="text-[#A1A1AA]"> (&gt; 90%)</span>
<span className="tabular-nums text-white"> <span className="tabular-nums text-white">
{healthyCount} {' '} {healthyCount} {' '}
<span className="text-[#71717A]"> <span className="text-[#71717A]">
@@ -363,7 +400,7 @@ function Dashboard() {
</div> </div>
<div> <div>
<div className="mb-2 flex justify-between text-sm"> <div className="mb-2 flex justify-between text-sm">
<span className="text-[#A1A1AA]"> (85% &lt; SoH &le; 90%)</span> <span className="text-[#A1A1AA]"> (85% - 90%)</span>
<span className="tabular-nums text-white"> <span className="tabular-nums text-white">
{watchCount} {' '} {watchCount} {' '}
<span className="text-[#71717A]"> <span className="text-[#71717A]">
@@ -380,7 +417,7 @@ function Dashboard() {
</div> </div>
<div> <div>
<div className="mb-2 flex justify-between text-sm"> <div className="mb-2 flex justify-between text-sm">
<span className="text-[#A1A1AA]"> (SoH &le; 85%)</span> <span className="text-[#A1A1AA]"> (&le; 85%)</span>
<span className="tabular-nums text-white"> <span className="tabular-nums text-white">
{warningCount} {' '} {warningCount} {' '}
<span className="text-[#71717A]"> <span className="text-[#71717A]">
@@ -400,7 +437,7 @@ function Dashboard() {
{/* Regional Performance */} {/* Regional Performance */}
<div> <div>
<h3 className="mb-6 text-lg font-medium text-white"></h3> <h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="space-y-4"> <div className="space-y-4">
{batchPerformance.length > 0 ? ( {batchPerformance.length > 0 ? (
batchPerformance.map((item) => ( batchPerformance.map((item) => (
@@ -408,10 +445,15 @@ function Dashboard() {
<span className="w-20 text-sm text-[#A1A1AA]">{item.batch}</span> <span className="w-20 text-sm text-[#A1A1AA]">{item.batch}</span>
<div className="flex-1"> <div className="flex-1">
<div className="h-1.5 overflow-hidden rounded-full bg-white/5"> <div className="h-1.5 overflow-hidden rounded-full bg-white/5">
<div className="h-full rounded-full bg-white/20" style={{ width: `${item.avgSoh}%` }} /> <div
className="h-full rounded-full bg-white/20"
style={{ width: widthPercent(item.avgSoh) }}
/>
</div> </div>
</div> </div>
<span className="w-12 text-right text-sm tabular-nums text-white">{item.avgSoh.toFixed(1)}%</span> <span className="w-20 text-right text-sm tabular-nums text-white">
{formatPercentWithUnit(item.avgSoh)}
</span>
</div> </div>
)) ))
) : ( ) : (
@@ -425,7 +467,9 @@ function Dashboard() {
<div className="space-y-8"> <div className="space-y-8">
{/* Event Timeline */} {/* Event Timeline */}
<div> <div>
<h3 className="mb-6 text-lg font-medium text-white"></h3> <div className="mb-6">
<SectionTitle icon={<AlertTriangle className="size-4" />} title="风险与趋势概览" />
</div>
<div className="relative border-l border-white/10 pl-5"> <div className="relative border-l border-white/10 pl-5">
{events.length > 0 ? ( {events.length > 0 ? (
events.map((event) => ( events.map((event) => (
@@ -437,7 +481,7 @@ function Dashboard() {
/> />
<div className="mb-1 flex items-center gap-3"> <div className="mb-1 flex items-center gap-3">
<span className="text-xs font-medium tabular-nums text-[#71717A]">{event.time}</span> <span className="text-xs font-medium tabular-nums text-[#71717A]">{event.time}</span>
<span className={`text-xs ${severityColorMap[event.severity]}`}>{event.severity}</span> <Badge variant={severityVariantMap[event.severity]}>{event.severity}</Badge>
</div> </div>
<h4 className="text-sm font-medium text-[#F4F4F5]">{event.title}</h4> <h4 className="text-sm font-medium text-[#F4F4F5]">{event.title}</h4>
<p className="mt-1 text-sm leading-relaxed text-[#A1A1AA]">{event.detail}</p> <p className="mt-1 text-sm leading-relaxed text-[#A1A1AA]">{event.detail}</p>
@@ -451,19 +495,18 @@ function Dashboard() {
{/* Risk Factor Frequency */} {/* Risk Factor Frequency */}
<div> <div>
<h3 className="mb-6 text-lg font-medium text-white"></h3> <div className="mb-6">
<SectionTitle icon={<Tags className="size-4" />} title="主要风险因子分布" />
</div>
<div className="flex flex-wrap gap-2"> <div className="flex flex-wrap gap-2">
{riskFactorCounts.length > 0 ? ( {riskFactorCounts.length > 0 ? (
riskFactorCounts.map((item) => ( riskFactorCounts.map((item) => (
<div <Badge key={item.factor} variant={item.factor.includes('不可用') ? 'warning' : 'default'}>
key={item.factor} {item.factor}
className="flex items-center gap-2 rounded-md border border-white/5 bg-white/[0.02] px-3 py-1.5 text-sm" <span className="rounded-full bg-white/10 px-1.5 py-0.5 tabular-nums text-white">
>
<span className="text-[#A1A1AA]">{item.factor}</span>
<span className="rounded bg-white/10 px-1.5 py-0.5 text-xs tabular-nums text-white">
{item.count} {item.count}
</span> </span>
</div> </Badge>
)) ))
) : ( ) : (
<div className="text-sm text-[#71717A]"></div> <div className="text-sm text-[#71717A]"></div>
@@ -471,102 +514,111 @@ function Dashboard() {
</div> </div>
</div> </div>
</div> </div>
</section> </MotionSection>
{/* Divider */} {/* Divider */}
<hr className="my-12 border-white/5" /> <hr className="my-12 border-white/5" />
{/* Device Table */} {/* Device Table */}
<section className="animate-fade-up delay-500 mb-12"> <MotionSection delay={0.5} className="mb-12">
<div className="mb-6 flex items-end justify-between"> <div className="mb-6 flex items-end justify-between">
<div> <div>
<h3 className="text-xl font-medium text-white"></h3> <h3 className="text-xl font-medium text-white"></h3>
<p className="mt-1 text-sm text-[#A1A1AA]"> 30/60/90 </p> <p className="mt-1 text-sm text-[#A1A1AA]"> 30/90 </p>
</div> </div>
</div> </div>
<div className="overflow-x-auto rounded-xl border border-white/[0.06] bg-white/[0.02]"> <Card className="overflow-hidden">
<table className="w-full min-w-[1000px] border-collapse text-left text-sm"> <div className="overflow-x-auto">
<thead> <table className="w-full min-w-[1000px] border-collapse text-left text-sm">
<tr className="border-b border-white/10 bg-white/[0.02] text-[#A1A1AA]"> <thead>
<th className="px-6 py-4 font-medium"></th> <tr className="border-b border-white/10 bg-white/[0.02] text-zinc-400">
<th className="px-6 py-4 font-medium"></th> <th className="px-6 py-4 font-medium whitespace-nowrap"></th>
<th className="px-6 py-4 font-medium"> SoH</th> <th className="px-6 py-4 font-medium whitespace-nowrap"></th>
<th className="px-6 py-4 font-medium">30</th> <th className="px-6 py-4 font-medium whitespace-nowrap"></th>
<th className="px-6 py-4 font-medium">90</th> <th className="px-6 py-4 font-medium whitespace-nowrap">30</th>
<th className="px-6 py-4 font-medium"></th> <th className="px-6 py-4 font-medium whitespace-nowrap">90</th>
<th className="px-6 py-4 font-medium"></th> <th className="px-6 py-4 font-medium whitespace-nowrap"></th>
<th className="px-6 py-4 font-medium"></th> <th className="px-6 py-4 font-medium whitespace-nowrap"></th>
</tr> <th className="px-6 py-4 font-medium whitespace-nowrap"></th>
</thead>
<tbody className="divide-y divide-white/5">
{devices.length > 0 ? (
devices
.slice()
.sort((a, b) => b.riskScore - a.riskScore)
.map((unit) => (
<tr key={unit.id} className="transition-colors hover:bg-white/[0.04]">
<td className="px-6 py-4 font-medium text-white">{unit.id}</td>
<td className="px-6 py-4 text-[#A1A1AA]">{unit.batch}</td>
<td className="px-6 py-4 tabular-nums text-white">{unit.soh.toFixed(1)}%</td>
<td className="px-6 py-4 tabular-nums text-[#A1A1AA]">{unit.soh30d.toFixed(1)}%</td>
<td className="px-6 py-4 tabular-nums text-[#A1A1AA]">{unit.soh90d.toFixed(1)}%</td>
<td className="px-6 py-4">
<div className="flex items-center gap-2">
<div className="h-1.5 w-12 overflow-hidden rounded-full bg-white/5">
<div
className={`h-full rounded-full ${
unit.riskScore >= 75
? 'bg-red-400'
: unit.riskScore >= 45
? 'bg-amber-400'
: 'bg-emerald-400'
}`}
style={{ width: `${unit.riskScore}%` }}
/>
</div>
<span className="tabular-nums text-white">{unit.riskScore}</span>
</div>
</td>
<td className="px-6 py-4">
<span className={statusColorMap[unit.status]}>{unit.status}</span>
</td>
<td className="px-6 py-4">
<div className="flex flex-wrap gap-1.5">
{unit.riskFactors.length > 0 ? (
unit.riskFactors.map((factor) => (
<span key={factor} className="text-[#A1A1AA]">
{factor}
{factor !== unit.riskFactors[unit.riskFactors.length - 1] && '、'}
</span>
))
) : (
<span className="text-[#71717A]">-</span>
)}
</div>
</td>
</tr>
))
) : (
<tr>
<td colSpan={8} className="px-6 py-8 text-center text-[#71717A]">
</td>
</tr> </tr>
)} </thead>
</tbody> <tbody className="divide-y divide-white/5">
</table> {devices.length > 0 ? (
</div> devices
</section> .slice()
.sort((a, b) => b.riskScore - a.riskScore)
.map((unit) => (
<tr key={unit.id} className="transition-colors hover:bg-white/[0.04]">
<td className="px-6 py-4 font-medium text-white">{unit.displayName}</td>
<td className="px-6 py-4 text-[#A1A1AA]">{unit.batch}</td>
<td className="px-6 py-4 tabular-nums text-white">{formatPercentWithUnit(unit.soh)}</td>
<td className="px-6 py-4 tabular-nums text-[#A1A1AA]">
{formatPercentWithUnit(unit.soh30d)}
</td>
<td className="px-6 py-4 tabular-nums text-[#A1A1AA]">
{formatPercentWithUnit(unit.soh90d)}
</td>
<td className="px-6 py-4">
<div className="flex items-center gap-2">
<div className="h-1.5 w-12 overflow-hidden rounded-full bg-white/5">
<div
className={`h-full rounded-full ${
unit.riskScore >= 75
? 'bg-red-400'
: unit.riskScore >= 45
? 'bg-amber-400'
: 'bg-emerald-400'
}`}
style={{ width: `${unit.riskScore}%` }}
/>
</div>
<span className="tabular-nums text-white">{unit.riskScore}</span>
</div>
</td>
<td className="px-6 py-4">
<Badge variant={statusVariantMap[unit.status]}>{unit.status}</Badge>
</td>
<td className="px-6 py-4">
<div className="flex flex-wrap gap-1.5">
{unit.riskFactors.length > 0 ? (
unit.riskFactors.map((factor) => (
<Badge key={factor} variant={factor.includes('不可用') ? 'warning' : 'default'}>
{factor}
</Badge>
))
) : (
<span className="text-[#71717A]">-</span>
)}
</div>
</td>
</tr>
))
) : (
<tr>
<td colSpan={8} className="px-6 py-12">
<EmptyState
icon={<Activity className="size-8" />}
title="暂无设备数据"
description="当前没有可用于健康分析的设备记录。"
/>
</td>
</tr>
)}
</tbody>
</table>
</div>
</Card>
</MotionSection>
{/* Bottom Row */} {/* Bottom Row */}
<section className="animate-fade-up delay-500 grid grid-cols-1 gap-8 lg:grid-cols-3"> <MotionSection delay={0.5} className="grid grid-cols-1 gap-8 lg:grid-cols-3">
{/* Strategy Cards */} {/* Strategy Cards */}
<div className="lg:col-span-2"> <div className="lg:col-span-2">
<h3 className="mb-6 text-lg font-medium text-white"></h3> <h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="grid gap-4 sm:grid-cols-2"> <div className="grid gap-4 sm:grid-cols-2">
{strategies.length > 0 ? ( {strategies.length > 0 ? (
strategies.map((item, index) => ( strategies.map((item, index) => (
<div <MotionCardDiv
key={item.name} key={item.name}
className="relative overflow-hidden rounded-xl border border-white/[0.06] bg-white/[0.02] p-5" className="relative overflow-hidden rounded-xl border border-white/[0.06] bg-white/[0.02] p-5"
> >
@@ -579,7 +631,7 @@ function Dashboard() {
<span>: {item.scope}</span> <span>: {item.scope}</span>
<span>: {item.eta}</span> <span>: {item.eta}</span>
</div> </div>
</div> </MotionCardDiv>
)) ))
) : ( ) : (
<div className="text-sm text-[#71717A] col-span-2"></div> <div className="text-sm text-[#71717A] col-span-2"></div>
@@ -589,7 +641,7 @@ function Dashboard() {
{/* Firmware Comparison */} {/* Firmware Comparison */}
<div> <div>
<h3 className="mb-6 text-lg font-medium text-white"></h3> <h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-5"> <div className="rounded-xl border border-white/[0.06] bg-white/[0.02] p-5">
<div className="space-y-4"> <div className="space-y-4">
{firmwareHealth.length > 0 ? ( {firmwareHealth.length > 0 ? (
@@ -600,8 +652,8 @@ function Dashboard() {
<div className="text-xs text-[#71717A]">{item.count} </div> <div className="text-xs text-[#71717A]">{item.count} </div>
</div> </div>
<div className="text-right"> <div className="text-right">
<div className="text-sm tabular-nums text-white">{item.avgSoh.toFixed(1)}%</div> <div className="text-sm tabular-nums text-white">{formatPercentWithUnit(item.avgSoh)}</div>
<div className="text-xs text-[#71717A]"> SoH</div> <div className="text-xs text-[#71717A]"></div>
</div> </div>
</div> </div>
)) ))
@@ -611,7 +663,7 @@ function Dashboard() {
</div> </div>
</div> </div>
</div> </div>
</section> </MotionSection>
</div> </div>
</main> </main>
) )
+17 -8
View File
@@ -1,21 +1,30 @@
import { oc } from '@orpc/contract' import { oc } from '@orpc/contract'
import { z } from 'zod' import { z } from 'zod'
import { batteriesResponseSchema, dashboardSnapshotSchema } from '@/domain/battery' import {
BATTERY_LIST_SORT,
BATTERY_LIST_SORT_VALUES,
batteriesResponseSchema,
dashboardSnapshotSchema,
POWER_STATUS,
} from '@/domain/battery'
export const dashboard = oc.input(z.void()).output(dashboardSnapshotSchema) export const dashboard = oc.input(z.void()).output(dashboardSnapshotSchema)
const batteryListInputSchema = z.object({ const batteryListInputSchema = z.object({
pageSize: z.number().int().min(1).max(100).default(50), pageSize: z.number().int().min(1).max(100).default(50),
cursor: z.string().min(1).optional(), cursor: z.string().min(1).max(1024).optional(),
search: z.string().trim().min(1).max(100).optional(), search: z.preprocess(
(value) => (typeof value === 'string' ? value.trim() || undefined : value),
z.string().min(1).max(100).optional(),
),
lowPower: z.boolean().optional(), lowPower: z.boolean().optional(),
powerStatus: z.union([z.literal(0), z.literal(1), z.literal(2)]).optional(), powerStatus: z
sort: z.enum(['createdAtDesc', 'createdAtAsc', 'powerDesc', 'powerAsc']).default('createdAtDesc'), .union([z.literal(POWER_STATUS.NOT_CHARGING), z.literal(POWER_STATUS.CHARGING), z.literal(POWER_STATUS.FULL)])
.optional(),
sort: z.enum(BATTERY_LIST_SORT_VALUES).default(BATTERY_LIST_SORT.CREATED_AT_DESC),
}) })
export const batteries = oc export const batteries = oc.input(batteryListInputSchema).output(batteriesResponseSchema)
.input(batteryListInputSchema)
.output(batteriesResponseSchema)
export const history = oc export const history = oc
.input( .input(
+12 -3
View File
@@ -1,4 +1,4 @@
import { createBatteriesResponse, createDashboardSnapshot } from '@/domain/battery' import { createBatteriesResponse, createDashboardSnapshot, POWER_STATUS } from '@/domain/battery'
import { os } from '@/server/api/server' import { os } from '@/server/api/server'
import { import {
getBatteryHistory, getBatteryHistory,
@@ -10,7 +10,11 @@ import { isPredictionEnabled, predictSoh } from '@/server/prediction/client'
const dashboardPredictionConcurrency = 5 const dashboardPredictionConcurrency = 5
async function mapWithConcurrency<T, R>(items: T[], concurrency: number, handler: (item: T) => Promise<R>): Promise<R[]> { async function mapWithConcurrency<T, R>(
items: T[],
concurrency: number,
handler: (item: T) => Promise<R>,
): Promise<R[]> {
const results: R[] = [] const results: R[] = []
let nextIndex = 0 let nextIndex = 0
@@ -59,5 +63,10 @@ export const batteries = os.battery.batteries.handler(async ({ input }) => {
export const history = os.battery.history.handler(async ({ input }) => { export const history = os.battery.history.handler(async ({ input }) => {
const items = await getBatteryHistory(input.mac) const items = await getBatteryHistory(input.mac)
return createBatteriesResponse(items) // History returns a limited window, so the counters must describe only this returned slice.
return createBatteriesResponse(items, new Date(), {
total: items.length,
lowPower: items.filter((item) => item.isLowPower).length,
charging: items.filter((item) => item.powerStatus === POWER_STATUS.CHARGING).length,
})
}) })
+42 -27
View File
@@ -1,12 +1,20 @@
import mysql, { type Pool, type RowDataPacket } from 'mysql2/promise' import mysql, { type Pool, type RowDataPacket } from 'mysql2/promise'
import { type BatteryInfo, type BatteryInfoSourceRow, toBatteryInfo } from '@/domain/battery' import {
BATTERY_LIST_SORT,
type BatteryInfo,
type BatteryInfoSourceRow,
type BatteryListSort,
MYSQL_BOOLEAN,
POWER_STATUS,
type PowerStatus,
toBatteryInfo,
toMysqlBoolean,
} from '@/domain/battery'
import { env } from '@/env' import { env } from '@/env'
const historyLimit = 500 const historyLimit = 500
const predictionHistoryLimit = 10 const predictionHistoryLimit = 10
const dashboardLatestLimit = 100
type BatteryInfoMysqlRow = RowDataPacket & BatteryInfoSourceRow type BatteryInfoMysqlRow = RowDataPacket & BatteryInfoSourceRow
type CountMysqlRow = RowDataPacket & { type CountMysqlRow = RowDataPacket & {
total: number total: number
@@ -14,14 +22,12 @@ type CountMysqlRow = RowDataPacket & {
charging: number | string | null charging: number | string | null
} }
export type BatteryListSort = 'createdAtDesc' | 'createdAtAsc' | 'powerDesc' | 'powerAsc'
export type LatestBatteryPageInput = { export type LatestBatteryPageInput = {
pageSize: number pageSize: number
cursor?: string cursor?: string
search?: string search?: string
lowPower?: boolean lowPower?: boolean
powerStatus?: 0 | 1 | 2 powerStatus?: PowerStatus
sort?: BatteryListSort sort?: BatteryListSort
} }
@@ -48,6 +54,7 @@ function getBatteryPool() {
waitForConnections: true, waitForConnections: true,
connectionLimit: 5, connectionLimit: 5,
namedPlaceholders: true, namedPlaceholders: true,
dateStrings: true,
}) })
return pool return pool
@@ -99,10 +106,10 @@ const latestRecordPredicate = `
` `
const orderByBySort: Record<BatteryListSort, string> = { const orderByBySort: Record<BatteryListSort, string> = {
createdAtDesc: 'current_record.create_time DESC, current_record.id DESC', [BATTERY_LIST_SORT.CREATED_AT_DESC]: 'current_record.create_time DESC, current_record.id DESC',
createdAtAsc: 'current_record.create_time ASC, current_record.id ASC', [BATTERY_LIST_SORT.CREATED_AT_ASC]: 'current_record.create_time ASC, current_record.id ASC',
powerDesc: 'current_record.power DESC, current_record.create_time DESC, current_record.id DESC', [BATTERY_LIST_SORT.POWER_DESC]: 'current_record.power DESC, current_record.create_time DESC, current_record.id DESC',
powerAsc: 'current_record.power ASC, current_record.create_time DESC, current_record.id DESC', [BATTERY_LIST_SORT.POWER_ASC]: 'current_record.power ASC, current_record.create_time DESC, current_record.id DESC',
} }
function toNumber(value: number | string | null | undefined) { function toNumber(value: number | string | null | undefined) {
@@ -115,7 +122,7 @@ function encodeCursor(item: BatteryInfo, sort: BatteryListSort) {
sort, sort,
createTime: item.createTime, createTime: item.createTime,
id: item.id, id: item.id,
power: sort === 'powerAsc' || sort === 'powerDesc' ? item.power : undefined, power: sort === BATTERY_LIST_SORT.POWER_ASC || sort === BATTERY_LIST_SORT.POWER_DESC ? item.power : undefined,
} }
return Buffer.from(JSON.stringify(cursor)).toString('base64url') return Buffer.from(JSON.stringify(cursor)).toString('base64url')
@@ -127,7 +134,12 @@ function decodeCursor(value: string | undefined, sort: BatteryListSort): PageCur
try { try {
const decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as Partial<PageCursor> const decoded = JSON.parse(Buffer.from(value, 'base64url').toString('utf8')) as Partial<PageCursor>
if (decoded.sort !== sort || typeof decoded.createTime !== 'string' || typeof decoded.id !== 'number') return null if (decoded.sort !== sort || typeof decoded.createTime !== 'string' || typeof decoded.id !== 'number') return null
if ((sort === 'powerAsc' || sort === 'powerDesc') && typeof decoded.power !== 'number') return null if (
(sort === BATTERY_LIST_SORT.POWER_ASC || sort === BATTERY_LIST_SORT.POWER_DESC) &&
typeof decoded.power !== 'number'
) {
return null
}
return decoded as PageCursor return decoded as PageCursor
} catch { } catch {
@@ -149,14 +161,14 @@ function createLatestWhere(input: LatestBatteryPageInput, cursor: PageCursor | n
if (input.search) { if (input.search) {
clauses.push( clauses.push(
'(current_record.mac LIKE :search ESCAPE \'\\\\\' OR current_record.dev_name LIKE :search ESCAPE \'\\\\\' OR current_record.dev_model LIKE :search ESCAPE \'\\\\\')', "(current_record.mac LIKE :search ESCAPE '\\\\' OR current_record.dev_name LIKE :search ESCAPE '\\\\' OR current_record.dev_model LIKE :search ESCAPE '\\\\')",
) )
params.search = `%${escapeLike(input.search)}%` params.search = `%${escapeLike(input.search)}%`
} }
if (input.lowPower !== undefined) { if (input.lowPower !== undefined) {
clauses.push('current_record.is_low_power = :lowPower') clauses.push('LOWER(TRIM(current_record.is_low_power)) = :lowPower')
params.lowPower = input.lowPower ? 'true' : 'false' params.lowPower = toMysqlBoolean(input.lowPower)
} }
if (input.powerStatus !== undefined) { if (input.powerStatus !== undefined) {
@@ -168,25 +180,25 @@ function createLatestWhere(input: LatestBatteryPageInput, cursor: PageCursor | n
params.cursorCreateTime = normalizeCursorDateTime(cursor.createTime) params.cursorCreateTime = normalizeCursorDateTime(cursor.createTime)
params.cursorId = cursor.id params.cursorId = cursor.id
switch (input.sort ?? 'createdAtDesc') { switch (input.sort ?? BATTERY_LIST_SORT.CREATED_AT_DESC) {
case 'createdAtAsc': case BATTERY_LIST_SORT.CREATED_AT_ASC:
clauses.push( clauses.push(
'(current_record.create_time > :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id > :cursorId))', '(current_record.create_time > :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id > :cursorId))',
) )
break break
case 'powerDesc': case BATTERY_LIST_SORT.POWER_DESC:
params.cursorPower = cursor.power ?? 0 params.cursorPower = cursor.power ?? 0
clauses.push( clauses.push(
'(current_record.power < :cursorPower OR (current_record.power = :cursorPower AND (current_record.create_time < :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id < :cursorId))))', '(current_record.power < :cursorPower OR (current_record.power = :cursorPower AND (current_record.create_time < :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id < :cursorId))))',
) )
break break
case 'powerAsc': case BATTERY_LIST_SORT.POWER_ASC:
params.cursorPower = cursor.power ?? 0 params.cursorPower = cursor.power ?? 0
clauses.push( clauses.push(
'(current_record.power > :cursorPower OR (current_record.power = :cursorPower AND (current_record.create_time < :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id < :cursorId))))', '(current_record.power > :cursorPower OR (current_record.power = :cursorPower AND (current_record.create_time < :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id < :cursorId))))',
) )
break break
case 'createdAtDesc': case BATTERY_LIST_SORT.CREATED_AT_DESC:
clauses.push( clauses.push(
'(current_record.create_time < :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id < :cursorId))', '(current_record.create_time < :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id < :cursorId))',
) )
@@ -257,7 +269,7 @@ export async function getBatteryPredictionHistories(macAddresses: string[]): Pro
} }
export async function getLatestBatteryPage(input: LatestBatteryPageInput): Promise<LatestBatteryPage> { export async function getLatestBatteryPage(input: LatestBatteryPageInput): Promise<LatestBatteryPage> {
const sort = input.sort ?? 'createdAtDesc' const sort = input.sort ?? BATTERY_LIST_SORT.CREATED_AT_DESC
const pageSize = Math.min(Math.max(input.pageSize, 1), 100) const pageSize = Math.min(Math.max(input.pageSize, 1), 100)
const cursor = decodeCursor(input.cursor, sort) const cursor = decodeCursor(input.cursor, sort)
const { whereSql, params } = createLatestWhere({ ...input, sort, pageSize }, cursor) const { whereSql, params } = createLatestWhere({ ...input, sort, pageSize }, cursor)
@@ -283,8 +295,8 @@ export async function getLatestBatteryPage(input: LatestBatteryPageInput): Promi
` `
SELECT SELECT
COUNT(*) AS total, COUNT(*) AS total,
COALESCE(SUM(CASE WHEN current_record.is_low_power = 'true' THEN 1 ELSE 0 END), 0) AS lowPower, COALESCE(SUM(CASE WHEN LOWER(TRIM(current_record.is_low_power)) = '${MYSQL_BOOLEAN.TRUE}' THEN 1 ELSE 0 END), 0) AS lowPower,
COALESCE(SUM(CASE WHEN current_record.power_status = 1 THEN 1 ELSE 0 END), 0) AS charging COALESCE(SUM(CASE WHEN current_record.power_status = ${POWER_STATUS.CHARGING} THEN 1 ELSE 0 END), 0) AS charging
FROM ls_battery_info AS current_record FROM ls_battery_info AS current_record
WHERE ${countWhere.whereSql} WHERE ${countWhere.whereSql}
`, `,
@@ -301,16 +313,19 @@ export async function getLatestBatteryPage(input: LatestBatteryPageInput): Promi
} }
} }
export async function getLatestBatteryPerDevice(limit = dashboardLatestLimit): Promise<BatteryInfo[]> { export async function getLatestBatteryPerDevice(limit?: number): Promise<BatteryInfo[]> {
const appliedLimit = typeof limit === 'number' && limit > 0 ? limit : undefined
const limitSql = appliedLimit ? '\n LIMIT :limit' : ''
const queryParams = appliedLimit ? { limit: appliedLimit } : {}
const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>( const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>(
` `
SELECT ${sourceColumns} SELECT ${sourceColumns}
FROM ls_battery_info AS current_record FROM ls_battery_info AS current_record
WHERE ${latestRecordPredicate} WHERE ${latestRecordPredicate}
ORDER BY current_record.create_time DESC, current_record.id DESC ORDER BY current_record.create_time DESC, current_record.id DESC${limitSql}
LIMIT :limit
`, `,
{ limit: Math.min(Math.max(limit, 1), dashboardLatestLimit) }, queryParams,
) )
return rows.map(toBatteryInfo) return rows.map(toBatteryInfo)
+97
View File
@@ -0,0 +1,97 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import type { BatteryInfo } from '@/domain/battery'
import { MYSQL_BOOLEAN, POWER_STATUS, toBatteryInfo } from '@/domain/battery'
import type { normalizePrediction as normalizePredictionType } from './client'
type PredictionClientModule = typeof import('./client')
const battery = toBatteryInfo({
id: 10,
userId: 7,
mac: 'RING-A03',
devModel: '2401-A',
devName: 'RING-A03',
isLowPower: MYSQL_BOOLEAN.FALSE,
powerStatus: POWER_STATUS.FULL,
power: 94,
createTime: '2026-05-10 23:00:00',
remark: null,
})
const predictionResponse = {
battery_id: 10,
mac: 'RING-A03',
now_soh: 91,
month_soh: 89,
trmonth_soh: 84,
risk_score: null,
risk_level: null,
status: null,
model_name: 'xgboost',
cycles_used: 6,
updated_at: '2026-05-11T00:00:00.000Z',
}
let createPredictionRequest: PredictionClientModule['createPredictionRequest']
let isPredictionForBattery: PredictionClientModule['isPredictionForBattery']
let normalizePrediction: typeof normalizePredictionType
beforeAll(async () => {
process.env.DATABASE_URL = 'mysql://user:password@localhost:3306/database'
process.env.SOH_PREDICTION_API_BASE_URL = 'http://127.0.0.1:8000'
const client = await import('./client')
createPredictionRequest = client.createPredictionRequest
isPredictionForBattery = client.isPredictionForBattery
normalizePrediction = client.normalizePrediction
})
describe('prediction client helpers', () => {
test('normalizes prediction response shape without fake fallback values', () => {
const prediction = normalizePrediction(predictionResponse)
expect(prediction).toEqual({
batteryId: 10,
mac: 'RING-A03',
nowSoh: 91,
monthSoh: 89,
trmonthSoh: 84,
riskScore: null,
riskLevel: null,
status: null,
modelName: 'xgboost',
cyclesUsed: 6,
updatedAt: '2026-05-11T00:00:00.000Z',
})
})
test('requires prediction responses to belong to the requested battery', () => {
expect(isPredictionForBattery(normalizePrediction(predictionResponse), battery)).toBe(true)
expect(isPredictionForBattery({ batteryId: 11, mac: battery.mac }, battery as BatteryInfo)).toBe(false)
expect(isPredictionForBattery({ batteryId: battery.id, mac: 'RING-B11' }, battery as BatteryInfo)).toBe(false)
})
test('returns null for history-insufficient prediction requests', () => {
expect(createPredictionRequest(battery, [battery, battery, battery, battery])).toBeNull()
})
test('creates minimal cycle payload accepted by prediction service', () => {
const request = createPredictionRequest(battery, [battery, battery, battery, battery, battery])
const firstHistory = request?.history[0]
expect(request?.battery).toMatchObject({
id: battery.id,
user_id: battery.userId,
mac: battery.mac,
power: battery.power,
})
expect(firstHistory).toEqual({
cycle: 1,
charge_capacity_ah: 3.01,
discharge_capacity_ah: 2.89,
timestamp: battery.createTime,
})
expect(Object.hasOwn(firstHistory ?? {}, 'charge_energy_wh')).toBe(false)
expect(Object.hasOwn(firstHistory ?? {}, 'coulombic_efficiency_pct')).toBe(false)
})
})
+43 -30
View File
@@ -1,6 +1,6 @@
import { LRUCache } from 'lru-cache' import { LRUCache } from 'lru-cache'
import { z } from 'zod' import { z } from 'zod'
import type { BatteryInfo, BatteryPrediction } from '@/domain/battery' import { type BatteryInfo, type BatteryPrediction, type PowerStatus, toMysqlBoolean } from '@/domain/battery'
import { env } from '@/env' import { env } from '@/env'
import { getLogger } from '@/server/logger' import { getLogger } from '@/server/logger'
@@ -23,11 +23,6 @@ type PredictionHistoryItem = {
cycle: number cycle: number
charge_capacity_ah: number charge_capacity_ah: number
discharge_capacity_ah: number discharge_capacity_ah: number
charge_energy_wh: number
discharge_energy_wh: number
charge_time: string
discharge_time: string
coulombic_efficiency_pct: number
timestamp: string timestamp: string
} }
@@ -39,7 +34,7 @@ type PredictionRequest = {
dev_model: string dev_model: string
dev_name: string dev_name: string
is_low_power: string is_low_power: string
power_status: 0 | 1 | 2 power_status: PowerStatus
power: number power: number
create_time: string create_time: string
remark: string remark: string
@@ -66,7 +61,12 @@ const cache = new LRUCache<string, SohPrediction>({
max: 5_000, max: 5_000,
ttl: env.SOH_PREDICTION_CACHE_TTL_SECONDS * 1000, ttl: env.SOH_PREDICTION_CACHE_TTL_SECONDS * 1000,
}) })
const negativeCache = new LRUCache<string, true>({
max: 5_000,
ttl: env.SOH_PREDICTION_NEGATIVE_CACHE_TTL_SECONDS * 1000,
})
const inFlightRequests = new Map<string, Promise<SohPrediction | null>>() const inFlightRequests = new Map<string, Promise<SohPrediction | null>>()
const nominalCapacityAh = 3.2
const round2 = (value: number) => Math.round(value * 100) / 100 const round2 = (value: number) => Math.round(value * 100) / 100
@@ -85,22 +85,13 @@ function createCacheKey(battery: BatteryInfo, history: BatteryInfo[]) {
} }
function createHistoryItem(item: BatteryInfo, index: number): PredictionHistoryItem { function createHistoryItem(item: BatteryInfo, index: number): PredictionHistoryItem {
const sohRatio = Math.max(0.5, Math.min(1, item.power / 100)) const observedCapacityRatio = Math.max(0.5, Math.min(1, item.power / 100))
const chargeCapacity = round2(3.2 * sohRatio) const chargeCapacityAh = round2(nominalCapacityAh * observedCapacityRatio)
const efficiency = round2(Math.max(80, Math.min(99, 92 + item.power / 12 - (item.isLowPower ? 4 : 0))))
const dischargeCapacity = round2(chargeCapacity * (efficiency / 100))
const chargeEnergy = round2(chargeCapacity * 3.75)
const dischargeEnergy = round2(dischargeCapacity * 3.7)
return { return {
cycle: index + 1, cycle: index + 1,
charge_capacity_ah: chargeCapacity, charge_capacity_ah: chargeCapacityAh,
discharge_capacity_ah: dischargeCapacity, discharge_capacity_ah: round2(chargeCapacityAh * 0.96),
charge_energy_wh: chargeEnergy,
discharge_energy_wh: dischargeEnergy,
charge_time: item.powerStatus === 1 ? '01:20:00' : '01:18:00',
discharge_time: item.isLowPower ? '00:58:00' : '01:10:00',
coulombic_efficiency_pct: efficiency,
timestamp: normalizeMysqlDateTime(item.createTime), timestamp: normalizeMysqlDateTime(item.createTime),
} }
} }
@@ -117,7 +108,7 @@ export function createPredictionRequest(battery: BatteryInfo, history: BatteryIn
mac: battery.mac, mac: battery.mac,
dev_model: battery.devModel, dev_model: battery.devModel,
dev_name: battery.devName, dev_name: battery.devName,
is_low_power: battery.isLowPower ? 'true' : 'false', is_low_power: toMysqlBoolean(battery.isLowPower),
power_status: battery.powerStatus, power_status: battery.powerStatus,
power: battery.power, power: battery.power,
create_time: normalizeMysqlDateTime(battery.createTime), create_time: normalizeMysqlDateTime(battery.createTime),
@@ -127,7 +118,7 @@ export function createPredictionRequest(battery: BatteryInfo, history: BatteryIn
} }
} }
function normalizePrediction(response: z.infer<typeof predictionResponseSchema>): SohPrediction { export function normalizePrediction(response: z.infer<typeof predictionResponseSchema>): SohPrediction {
return { return {
batteryId: response.battery_id, batteryId: response.battery_id,
mac: response.mac, mac: response.mac,
@@ -143,17 +134,24 @@ function normalizePrediction(response: z.infer<typeof predictionResponseSchema>)
} }
} }
export function isPredictionForBattery(prediction: Pick<SohPrediction, 'batteryId' | 'mac'>, battery: BatteryInfo) {
return prediction.batteryId === battery.id && prediction.mac === battery.mac
}
export function isPredictionEnabled() { export function isPredictionEnabled() {
return Boolean(env.SOH_PREDICTION_API_BASE_URL) return true
} }
export async function predictSoh(battery: BatteryInfo, history: BatteryInfo[]): Promise<SohPrediction | null> { export async function predictSoh(battery: BatteryInfo, history: BatteryInfo[]): Promise<SohPrediction | null> {
if (!env.SOH_PREDICTION_API_BASE_URL) return null const cacheKey = createCacheKey(battery, history)
if (negativeCache.has(cacheKey)) return null
const request = createPredictionRequest(battery, history) const request = createPredictionRequest(battery, history)
if (!request) return null if (!request) {
negativeCache.set(cacheKey, true)
return null
}
const cacheKey = createCacheKey(battery, history)
const cached = cache.get(cacheKey) const cached = cache.get(cacheKey)
if (cached) return cached if (cached) return cached
const pendingRequest = inFlightRequests.get(cacheKey) const pendingRequest = inFlightRequests.get(cacheKey)
@@ -170,8 +168,6 @@ async function requestPrediction(
battery: BatteryInfo, battery: BatteryInfo,
request: PredictionRequest, request: PredictionRequest,
): Promise<SohPrediction | null> { ): Promise<SohPrediction | null> {
if (!env.SOH_PREDICTION_API_BASE_URL) return null
const controller = new AbortController() const controller = new AbortController()
const timeout = setTimeout(() => controller.abort(), env.SOH_PREDICTION_TIMEOUT_MS) const timeout = setTimeout(() => controller.abort(), env.SOH_PREDICTION_TIMEOUT_MS)
const baseUrl = env.SOH_PREDICTION_API_BASE_URL.endsWith('/') const baseUrl = env.SOH_PREDICTION_API_BASE_URL.endsWith('/')
@@ -189,24 +185,41 @@ async function requestPrediction(
if (!response.ok) { if (!response.ok) {
logger.warn('SOH prediction request failed', { mac: battery.mac, status: response.status }) logger.warn('SOH prediction request failed', { mac: battery.mac, status: response.status })
return null return cacheNegativePrediction(cacheKey)
} }
const json = await response.json() const json = await response.json()
const prediction = normalizePrediction(predictionResponseSchema.parse(json)) const prediction = normalizePrediction(predictionResponseSchema.parse(json))
if (!isPredictionForBattery(prediction, battery)) {
logger.warn('SOH prediction response mismatched requested battery', {
requestedBatteryId: battery.id,
requestedMac: battery.mac,
responseBatteryId: prediction.batteryId,
responseMac: prediction.mac,
})
return cacheNegativePrediction(cacheKey)
}
cache.set(cacheKey, prediction) cache.set(cacheKey, prediction)
negativeCache.delete(cacheKey)
return prediction return prediction
} catch (error) { } catch (error) {
logger.warn('SOH prediction request errored', { mac: battery.mac, error }) logger.warn('SOH prediction request errored', { mac: battery.mac, error })
return null return cacheNegativePrediction(cacheKey)
} finally { } finally {
clearTimeout(timeout) clearTimeout(timeout)
inFlightRequests.delete(cacheKey) inFlightRequests.delete(cacheKey)
} }
} }
function cacheNegativePrediction(cacheKey: string) {
negativeCache.set(cacheKey, true)
return null
}
export function clearPredictionCache() { export function clearPredictionCache() {
cache.clear() cache.clear()
negativeCache.clear()
inFlightRequests.clear() inFlightRequests.clear()
} }
+18
View File
@@ -1 +1,19 @@
@import "tailwindcss"; @import "tailwindcss";
:root {
color-scheme: dark;
background: #09090b;
}
html {
background: #09090b;
}
body {
min-width: 320px;
margin: 0;
background:
radial-gradient(circle at top, rgba(20, 184, 166, 0.08), transparent 34rem),
linear-gradient(180deg, #09090b 0%, #0b0f12 100%);
color: #f4f4f5;
}