Compare commits

..

21 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
19 changed files with 684 additions and 167 deletions
+4
View File
@@ -1,8 +1,12 @@
DATABASE_URL=mysql://user:password@localhost:3306/database
# 默认关闭公开 OpenAPI 文档/规格;仅在受控本地或内网演示环境显式启用。
# ENABLE_API_DOCS=false
# 必填:外部 SoH 预测服务地址
SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000
# SOH_PREDICTION_CACHE_TTL_SECONDS=86400
# SOH_PREDICTION_NEGATIVE_CACHE_TTL_SECONDS=300
# SOH_PREDICTION_TIMEOUT_MS=10000
# 可选:日志级别与输出格式
+15 -2
View File
@@ -40,10 +40,21 @@ DATABASE_URL=mysql://user:password@host:3306/database
```bash
SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000
SOH_PREDICTION_CACHE_TTL_SECONDS=86400
SOH_PREDICTION_NEGATIVE_CACHE_TTL_SECONDS=300
SOH_PREDICTION_TIMEOUT_MS=10000
```
服务端会调用 `${SOH_PREDICTION_API_BASE_URL}/predict`,使用返回的当前健康度、30 天趋势、90 天趋势和风险评分生成看板视图。预测结果会按设备与最新采集记录缓存,默认 24 小时;单台设备预测失败或历史数据不足时仅该设备显示为“预测不可用”。
服务端会调用 `${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` 不受此开关影响。
## 快速开始
@@ -57,7 +68,7 @@ bun run dev
- `http://localhost:3000/`:设备健康运营看板
- `http://localhost:3000/batteries`:设备状态明细
- `http://localhost:3000/api/docs`:接口文档
- `http://localhost:3000/api/docs`:接口文档(需设置 `ENABLE_API_DOCS=true`
## 本地演示环境
@@ -73,6 +84,8 @@ Compose 会启动:
- `seed`:初始化本地 `ls_battery_info` 演示数据
- `app`:启动应用服务
Compose 的 `app` 服务会为本地演示显式启用 `ENABLE_API_DOCS=true`;生产部署不应沿用该设置,除非已通过网络边界或上游认证限制访问。
也可以手动初始化本地数据:
```bash
+86
View File
@@ -13,6 +13,7 @@
"@orpc/server": "^1.14.0",
"@orpc/tanstack-query": "^1.14.0",
"@orpc/zod": "^1.14.0",
"@radix-ui/react-select": "^2.2.6",
"@t3-oss/env-core": "^0.13.11",
"@tanstack/react-query": "^5.100.1",
"@tanstack/react-router": "^1.168.24",
@@ -24,6 +25,7 @@
"drizzle-orm": "^0.45.2",
"lru-cache": "^11.3.6",
"lucide-react": "^1.14.0",
"motion": "^12.38.0",
"mysql2": "^3.22.3",
"react": "^19.2.5",
"react-dom": "^19.2.5",
@@ -162,6 +164,14 @@
"@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/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -220,6 +230,58 @@
"@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=="],
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.0.0-rc.17", "", { "os": "android", "cpu": "arm64" }, "sha512-s70pVGhw4zqGeFnXWvAzJDlvxhlRollagdCCKRgOsgUOH3N1l0LIxf83AtGzmb5SiVM4Hjl5HyarMRfdfj3DaQ=="],
@@ -414,6 +476,8 @@
"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=="],
"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=="],
@@ -494,6 +558,8 @@
"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=="],
"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=="],
@@ -534,12 +600,16 @@
"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=="],
"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=="],
"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=="],
"glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
@@ -624,6 +694,12 @@
"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=="],
"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=="],
@@ -680,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-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=="],
"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=="],
@@ -752,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=="],
"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=="],
"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=="],
+1
View File
@@ -41,6 +41,7 @@ services:
environment:
- DATABASE_URL=mysql://battery:battery@db:3306/battery_soh
- SOH_PREDICTION_API_BASE_URL=http://host.docker.internal:8000
- ENABLE_API_DOCS=true
volumes:
mysql_data:
+4 -2
View File
@@ -1,5 +1,5 @@
{
"name": "fullstack-starter",
"name": "battery-soh",
"version": "1.0.0",
"private": true,
"type": "module",
@@ -34,6 +34,7 @@
"@orpc/server": "^1.14.0",
"@orpc/tanstack-query": "^1.14.0",
"@orpc/zod": "^1.14.0",
"@radix-ui/react-select": "^2.2.6",
"@t3-oss/env-core": "^0.13.11",
"@tanstack/react-query": "^5.100.1",
"@tanstack/react-router": "^1.168.24",
@@ -42,9 +43,9 @@
"@tanstack/react-table": "^8.21.3",
"@tanstack/react-virtual": "^3.13.24",
"citty": "^0.2.2",
"drizzle-orm": "^0.45.2",
"lru-cache": "^11.3.6",
"lucide-react": "^1.14.0",
"motion": "^12.38.0",
"mysql2": "^3.22.3",
"react": "^19.2.5",
"react-dom": "^19.2.5",
@@ -60,6 +61,7 @@
"@tanstack/react-router-devtools": "^1.166.13",
"@types/bun": "^1.3.13",
"@vitejs/plugin-react": "^6.0.1",
"drizzle-orm": "^0.45.2",
"drizzle-seed": "^0.3.1",
"nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc",
"tailwindcss": "^4.2.4",
+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>
)
}
+88 -6
View File
@@ -1,3 +1,5 @@
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'
@@ -72,17 +74,70 @@ export function Input({ className, ...props }: ComponentPropsWithoutRef<'input'>
)
}
export function Select({ className, children, ...props }: ComponentPropsWithoutRef<'select'>) {
export function Select({
value,
onValueChange,
children,
className,
id,
}: {
value?: string | number
onValueChange?: (value: string) => void
children: ReactNode
className?: string
id?: string
}) {
return (
<select
<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(
'h-10 rounded-lg border border-white/10 bg-zinc-950/95 px-3 py-2 text-sm text-zinc-100 outline-none transition-colors [color-scheme:dark] focus:border-teal-400/60 focus:ring-2 focus:ring-teal-400/10',
'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,
)}
{...props}
>
{children}
</select>
<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>
)
}
@@ -97,3 +152,30 @@ export function SectionTitle({ icon, title, description }: { icon?: ReactNode; t
</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>
)
}
+1 -1
View File
@@ -35,7 +35,7 @@ export function toMysqlBoolean(value: boolean) {
export function fromMysqlBoolean(value: string | boolean) {
if (typeof value === 'boolean') return value
return value.toLowerCase() === MYSQL_BOOLEAN.TRUE
return value.trim().toLowerCase() === MYSQL_BOOLEAN.TRUE
}
export const DEVICE_STATUS = {
+30 -6
View File
@@ -3,6 +3,7 @@ import {
createBatteriesResponse,
createDashboardSnapshot,
DEVICE_STATUS,
fromMysqlBoolean,
getDeviceStatus,
MYSQL_BOOLEAN,
POWER_STATUS,
@@ -27,7 +28,7 @@ const rows = [
userId: 7,
mac: 'RING-B11',
devModel: '2402-B',
devName: 'RING-B11',
devName: '',
isLowPower: MYSQL_BOOLEAN.TRUE,
powerStatus: POWER_STATUS.CHARGING,
power: 84,
@@ -43,6 +44,11 @@ describe('battery domain', () => {
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', () => {
const now = new Date('2026-05-11T00:00:00.000Z')
const items = rows.map(toBatteryInfo)
@@ -56,19 +62,37 @@ describe('battery domain', () => {
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', () => {
const now = new Date('2026-05-11T00:00:00.000Z')
const snapshot = createDashboardSnapshot(rows.map(toBatteryInfo), now)
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.soh === null)).toBe(true)
expect(snapshot.devices.every((device) => device.soh30d === null)).toBe(true)
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 === 0)).toBe(true)
expect(snapshot.devices.every((device) => device.temperature === 0)).toBe(true)
expect(snapshot.devices.every((device) => device.chargeEfficiency === 0)).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)
@@ -116,8 +140,8 @@ describe('battery domain', () => {
expect(predicted?.cycles).toBe(6)
expect(predicted?.firmware).toBe('v3.8.2')
expect(predicted?.status).toBe(DEVICE_STATUS.WARNING)
expect(predicted?.temperature).toBe(0)
expect(predicted?.chargeEfficiency).toBe(0)
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 })
+9 -7
View File
@@ -54,17 +54,18 @@ export type BatteryInfo = z.infer<typeof batteryInfoSchema>
export const fleetUnitSchema = z.object({
id: z.string(),
displayName: z.string(),
batch: z.string(),
firmware: z.string(),
cycles: z.number().int(),
cycles: z.number().int().nullable(),
soh: z.number().nullable(),
sohSource: z.union([z.literal('prediction'), z.literal('unavailable')]),
soh30d: z.number().nullable(),
soh60d: z.number().nullable(),
soh90d: z.number().nullable(),
temperature: z.number(),
temperature: z.number().nullable(),
riskScore: z.number().int(),
chargeEfficiency: z.number(),
chargeEfficiency: z.number().nullable(),
status: deviceStatusSchema,
riskFactors: z.array(z.string()),
})
@@ -259,18 +260,19 @@ function toFleetUnit(item: BatteryInfo, prediction?: BatteryPrediction): FleetUn
const soh30d = prediction ? round1(clamp(prediction.monthSoh, 0, 100)) : null
const soh90d = prediction ? round1(clamp(prediction.trmonthSoh, 0, 100)) : null
const soh60d = null
const temperature = 0
const chargeEfficiency = 0
const temperature = null
const chargeEfficiency = null
const fallbackRiskScore =
(item.isLowPower || item.power <= SOH_THRESHOLDS.LOW_POWER ? 60 : 0) +
(item.powerStatus === POWER_STATUS.CHARGING ? 20 : 0)
const riskScore = Math.round(clamp(prediction?.riskScore ?? fallbackRiskScore, 0, 100))
return {
id: item.devName || item.mac,
id: item.mac,
displayName: item.devName || item.mac,
batch: item.devModel,
firmware: item.remark ?? '未提供',
cycles: prediction?.cyclesUsed ?? 0,
cycles: prediction?.cyclesUsed ?? null,
soh,
sohSource: prediction ? 'prediction' : 'unavailable',
soh30d,
+2
View File
@@ -4,11 +4,13 @@ import { z } from 'zod'
export const env = createEnv({
server: {
DATABASE_URL: z.url({ protocol: /^mysql$/ }),
ENABLE_API_DOCS: z.stringbool().default(false),
LOG_DB: z.stringbool().default(false),
LOG_FORMAT: z.enum(['pretty', 'json']).optional(),
LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warning', 'error', 'fatal']).default('info'),
SOH_PREDICTION_API_BASE_URL: z.url({ protocol: /^https?$/ }),
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),
},
clientPrefix: 'VITE_',
+19 -14
View File
@@ -4,24 +4,27 @@ import { onError } from '@orpc/server'
import { ZodToJsonSchemaConverter } from '@orpc/zod/zod4'
import { createFileRoute } from '@tanstack/react-router'
import { name, version } from '#package'
import { env } from '@/env'
import { handleValidationError, logError } from '@/server/api/interceptors'
import { router } from '@/server/api/routers'
const handler = new OpenAPIHandler(router, {
plugins: [
new OpenAPIReferencePlugin({
docsProvider: 'scalar',
schemaConverters: [new ZodToJsonSchemaConverter()],
specGenerateOptions: {
info: {
title: name,
version,
},
},
docsPath: '/docs',
specPath: '/spec.json',
}),
],
plugins: env.ENABLE_API_DOCS
? [
new OpenAPIReferencePlugin({
docsProvider: 'scalar',
schemaConverters: [new ZodToJsonSchemaConverter()],
specGenerateOptions: {
info: {
title: name,
version,
},
},
docsPath: '/docs',
specPath: '/spec.json',
}),
]
: [],
interceptors: [onError(logError)],
clientInterceptors: [onError(handleValidationError)],
})
@@ -30,6 +33,8 @@ export const Route = createFileRoute('/api/$')({
server: {
handlers: {
ANY: async ({ request }) => {
if (!env.ENABLE_API_DOCS) return new Response('Not Found', { status: 404 })
const { response } = await handler.handle(request, {
prefix: '/api',
context: {
+88 -44
View File
@@ -1,17 +1,20 @@
import { useQuery } from '@tanstack/react-query'
import { createFileRoute, Link, useNavigate } from '@tanstack/react-router'
import { createColumnHelper, flexRender, getCoreRowModel, useReactTable } from '@tanstack/react-table'
import { ArrowLeft, Battery, BatteryCharging, BatteryLow, FilterX, Search, Zap } from 'lucide-react'
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 { Badge, Button, Card, Input, SectionTitle, Select } from '@/components/ui'
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),
@@ -77,7 +80,7 @@ function parseSort(value: string): BatteryListSort {
}
function parsePowerStatus(value: string): PowerStatus | undefined {
if (value === '') return undefined
if (value === allPowerStatusValue) return undefined
const parsed = Number(value)
@@ -203,7 +206,7 @@ function BatteriesPage() {
search: (prev) => ({
...prev,
cursor: nextCursor,
cursors: [...(prev.cursors || []), prev.cursor || firstPageCursor],
cursors: [...(prev.cursors || []), prev.cursor || firstPageCursor].slice(-100),
}),
})
}
@@ -240,7 +243,7 @@ function BatteriesPage() {
</div>
<div className="relative z-10 mx-auto max-w-7xl px-6 py-8">
<header>
<MotionHeader>
<div className="flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between">
<div>
<Badge variant="info" className="mb-4">
@@ -265,28 +268,28 @@ function BatteriesPage() {
</div>
<dl className="mt-8 grid grid-cols-1 gap-4 sm:grid-cols-3">
<Card className="p-5">
<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">
<Battery className="size-4 text-zinc-400" />
</dt>
<dd className="mt-3 text-3xl font-light tabular-nums text-white">{data?.total ?? '-'}</dd>
</Card>
<Card className="p-5">
</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>
</Card>
<Card className="p-5">
</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>
</Card>
</MotionCardDiv>
</dl>
</header>
</MotionHeader>
<section className="mt-10">
<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
@@ -312,10 +315,20 @@ function BatteriesPage() {
type="text"
placeholder="搜索设备名称或编号..."
maxLength={100}
className="pl-9"
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>
@@ -325,22 +338,22 @@ function BatteriesPage() {
</label>
<Select
id="power-status-select"
value={search.powerStatus ?? ''}
onChange={(e) => {
value={search.powerStatus ?? allPowerStatusValue}
onValueChange={(value) => {
navigate({
search: (prev) => ({
...prev,
powerStatus: parsePowerStatus(e.target.value),
powerStatus: parsePowerStatus(value),
cursor: undefined,
cursors: [],
}),
})
}}
>
<option value=""></option>
<option value={POWER_STATUS.NOT_CHARGING}></option>
<option value={POWER_STATUS.CHARGING}></option>
<option value={POWER_STATUS.FULL}></option>
<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>
@@ -351,21 +364,21 @@ function BatteriesPage() {
<Select
id="sort-select"
value={search.sort}
onChange={(e) => {
onValueChange={(value) => {
navigate({
search: (prev) => ({
...prev,
sort: parseSort(e.target.value),
sort: parseSort(value),
cursor: undefined,
cursors: [],
}),
})
}}
>
<option value={BATTERY_LIST_SORT.CREATED_AT_DESC}></option>
<option value={BATTERY_LIST_SORT.CREATED_AT_ASC}></option>
<option value={BATTERY_LIST_SORT.POWER_DESC}></option>
<option value={BATTERY_LIST_SORT.POWER_ASC}></option>
<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>
@@ -376,20 +389,20 @@ function BatteriesPage() {
<Select
id="page-size-select"
value={search.pageSize}
onChange={(e) => {
onValueChange={(value) => {
navigate({
search: (prev) => ({
...prev,
pageSize: parsePageSize(e.target.value),
pageSize: parsePageSize(value),
cursor: undefined,
cursors: [],
}),
})
}}
>
<option value="20">20 /</option>
<option value="50">50 /</option>
<option value="100">100 /</option>
<SelectOption value="20">20 /</SelectOption>
<SelectOption value="50">50 /</SelectOption>
<SelectOption value="100">100 /</SelectOption>
</Select>
</div>
@@ -419,9 +432,9 @@ function BatteriesPage() {
</Card>
<Card className="overflow-hidden">
<div className="overflow-x-auto">
<div className="overflow-x-auto max-h-[600px]">
<table className={`w-full border-collapse text-left text-sm ${isPlaceholderData ? 'opacity-60' : ''}`}>
<thead>
<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) => (
@@ -434,26 +447,57 @@ function BatteriesPage() {
</thead>
<tbody className="divide-y divide-white/[0.02]">
{isPending && !isPlaceholderData ? (
<tr>
<td colSpan={columns.length} className="h-32 text-center text-zinc-500">
</td>
</tr>
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-32 text-center text-zinc-500">
<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) => (
<tr key={row.id} className="transition-colors hover:bg-white/[0.02]">
<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>
))}
</tr>
</MotionTableRow>
))
)}
</tbody>
@@ -479,7 +523,7 @@ function BatteriesPage() {
</Button>
</div>
</div>
</section>
</MotionSection>
</div>
</main>
)
+53 -39
View File
@@ -14,7 +14,8 @@ import {
} from 'recharts'
import type { NameType, ValueType } from 'recharts/types/component/DefaultTooltipContent'
import { orpc } from '@/client/orpc'
import { Badge, Card, SectionTitle } from '@/components/ui'
import { MotionCardArticle, MotionCardDiv, MotionHeader, MotionSection } from '@/components/motion'
import { Badge, Card, EmptyState, SectionTitle } from '@/components/ui'
import type { DashboardSnapshot, DeviceStatus } from '@/domain/battery'
import { BATTERY_LIST_SORT, DEVICE_STATUS } from '@/domain/battery'
@@ -92,7 +93,11 @@ function formatPercentWithUnit(value: number | null) {
function formatDelta(from: number | null, to: number | null) {
if (from === null || to === null) return '预测不可用'
return `${(from - to).toFixed(1)}% 衰减`
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) {
@@ -147,7 +152,7 @@ function Dashboard() {
<div className="relative z-10 mx-auto max-w-[1400px] px-6 pb-24 pt-12 lg:px-12">
{/* 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">
<Badge variant="info" className="mb-4">
<Activity className="size-3.5" />
@@ -165,18 +170,18 @@ function Dashboard() {
<ArrowRight className="size-3" />
</Link>
</div>
</header>
</MotionHeader>
{/* 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>
<p className="text-base leading-relaxed text-[#A1A1AA]">{executiveSummary}</p>
</section>
</MotionSection>
{/* 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 */}
<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" />
<p className="text-sm font-medium text-[#A1A1AA]"></p>
<div className="mt-4 flex items-baseline gap-2">
@@ -191,10 +196,10 @@ function Dashboard() {
<span className="text-[#71717A]">|</span>
<span className="text-[#A1A1AA]"> {totalDevices} </span>
</div>
</article>
</MotionCardArticle>
{/* 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>
<div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{formatPercent(avgSoh30d)}</h2>
@@ -204,9 +209,9 @@ function Dashboard() {
<span className="text-red-400"></span>
<span className="tabular-nums text-[#A1A1AA]">{formatDelta(avgSoh, avgSoh30d)}</span>
</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>
<div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{formatPercent(avgSoh90d)}</h2>
@@ -216,9 +221,9 @@ function Dashboard() {
<span className="text-red-400"></span>
<span className="tabular-nums text-[#A1A1AA]">{formatDelta(avgSoh, avgSoh90d)}</span>
</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>
<div className="mt-3 flex items-baseline gap-1">
<h2 className="text-4xl font-light tabular-nums text-white">{warningCount}</h2>
@@ -230,14 +235,14 @@ function Dashboard() {
{totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
</span>
</div>
</article>
</section>
</MotionCardArticle>
</MotionSection>
{/* Divider */}
<hr className="my-12 border-white/5" />
{/* Health trend chart */}
<section className="animate-fade-up delay-300 mb-12">
<MotionSection delay={0.3} className="mb-12">
<Card className="p-8">
<header className="mb-8 flex flex-wrap items-end justify-between gap-4">
<SectionTitle
@@ -265,19 +270,19 @@ function Dashboard() {
<ComposedChart data={chartData} margin={{ top: 24, right: 24, bottom: 8, left: 0 }}>
<defs>
<linearGradient id="historyFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#2DD4BF" stopOpacity={0.15} />
<stop offset="0%" stopColor="#2DD4BF" stopOpacity={0.25} />
<stop offset="100%" stopColor="#2DD4BF" stopOpacity={0} />
</linearGradient>
<linearGradient id="forecastFill" x1="0" y1="0" x2="0" y2="1">
<stop offset="0%" stopColor="#818CF8" stopOpacity={0.15} />
<stop offset="0%" stopColor="#818CF8" stopOpacity={0.25} />
<stop offset="100%" stopColor="#818CF8" stopOpacity={0} />
</linearGradient>
</defs>
<CartesianGrid stroke="#ffffff" strokeOpacity={0.05} vertical={false} />
<XAxis dataKey="month" tick={{ fill: '#71717A', fontSize: 11 }} axisLine={false} tickLine={false} />
<XAxis dataKey="month" tick={{ fill: '#A1A1AA', fontSize: 12 }} axisLine={false} tickLine={false} />
<YAxis
domain={[(min: number) => Math.floor(min) - 2, (max: number) => Math.ceil(max) + 2]}
tick={{ fill: '#71717A', fontSize: 11 }}
tick={{ fill: '#A1A1AA', fontSize: 12 }}
axisLine={false}
tickLine={false}
tickFormatter={(v: number) => `${v}%`}
@@ -290,20 +295,21 @@ function Dashboard() {
borderRadius: 8,
fontSize: 13,
color: '#F4F4F5',
boxShadow: '0 10px 15px -3px rgba(0, 0, 0, 0.5)',
}}
itemStyle={{ color: '#A1A1AA' }}
itemStyle={{ color: '#E4E4E7', fontWeight: 500 }}
formatter={formatChartTooltip}
labelStyle={{ color: '#71717A', marginBottom: 4 }}
labelStyle={{ color: '#A1A1AA', marginBottom: 6 }}
/>
<ReferenceLine
y={85}
stroke="#F87171"
strokeOpacity={0.4}
strokeOpacity={0.6}
strokeDasharray="4 4"
label={{
value: '85% 预警线',
fill: '#F87171',
fontSize: 11,
fontSize: 12,
position: 'right',
}}
/>
@@ -353,16 +359,20 @@ function Dashboard() {
</ComposedChart>
</ResponsiveContainer>
) : (
<div className="flex h-full items-center justify-center rounded-xl border border-dashed border-white/10 bg-white/[0.02] text-sm text-[#71717A]">
<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="当前设备数据不足以生成可靠的健康趋势预测,请等待系统收集更多数据。"
/>
</div>
)}
</div>
</Card>
</section>
</MotionSection>
{/* 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 */}
<div className="space-y-8">
{/* Risk Distribution */}
@@ -504,13 +514,13 @@ function Dashboard() {
</div>
</div>
</div>
</section>
</MotionSection>
{/* Divider */}
<hr className="my-12 border-white/5" />
{/* 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>
<h3 className="text-xl font-medium text-white"></h3>
@@ -539,7 +549,7 @@ function Dashboard() {
.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 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]">
@@ -585,8 +595,12 @@ function Dashboard() {
))
) : (
<tr>
<td colSpan={8} className="px-6 py-8 text-center text-[#71717A]">
<td colSpan={8} className="px-6 py-12">
<EmptyState
icon={<Activity className="size-8" />}
title="暂无设备数据"
description="当前没有可用于健康分析的设备记录。"
/>
</td>
</tr>
)}
@@ -594,17 +608,17 @@ function Dashboard() {
</table>
</div>
</Card>
</section>
</MotionSection>
{/* 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 */}
<div className="lg:col-span-2">
<h3 className="mb-6 text-lg font-medium text-white"></h3>
<div className="grid gap-4 sm:grid-cols-2">
{strategies.length > 0 ? (
strategies.map((item, index) => (
<div
<MotionCardDiv
key={item.name}
className="relative overflow-hidden rounded-xl border border-white/[0.06] bg-white/[0.02] p-5"
>
@@ -617,7 +631,7 @@ function Dashboard() {
<span>: {item.scope}</span>
<span>: {item.eta}</span>
</div>
</div>
</MotionCardDiv>
))
) : (
<div className="text-sm text-[#71717A] col-span-2"></div>
@@ -649,7 +663,7 @@ function Dashboard() {
</div>
</div>
</div>
</section>
</MotionSection>
</div>
</main>
)
+7 -2
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 {
getBatteryHistory,
@@ -63,5 +63,10 @@ export const batteries = os.battery.batteries.handler(async ({ input }) => {
export const history = os.battery.history.handler(async ({ input }) => {
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,
})
})
+10 -8
View File
@@ -15,8 +15,6 @@ import { env } from '@/env'
const historyLimit = 500
const predictionHistoryLimit = 10
const dashboardLatestLimit = 100
type BatteryInfoMysqlRow = RowDataPacket & BatteryInfoSourceRow
type CountMysqlRow = RowDataPacket & {
total: number
@@ -56,6 +54,7 @@ function getBatteryPool() {
waitForConnections: true,
connectionLimit: 5,
namedPlaceholders: true,
dateStrings: true,
})
return pool
@@ -168,7 +167,7 @@ function createLatestWhere(input: LatestBatteryPageInput, cursor: PageCursor | n
}
if (input.lowPower !== undefined) {
clauses.push('current_record.is_low_power = :lowPower')
clauses.push('LOWER(TRIM(current_record.is_low_power)) = :lowPower')
params.lowPower = toMysqlBoolean(input.lowPower)
}
@@ -296,7 +295,7 @@ export async function getLatestBatteryPage(input: LatestBatteryPageInput): Promi
`
SELECT
COUNT(*) AS total,
COALESCE(SUM(CASE WHEN current_record.is_low_power = '${MYSQL_BOOLEAN.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 = ${POWER_STATUS.CHARGING} THEN 1 ELSE 0 END), 0) AS charging
FROM ls_battery_info AS current_record
WHERE ${countWhere.whereSql}
@@ -314,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[]>(
`
SELECT ${sourceColumns}
FROM ls_battery_info AS current_record
WHERE ${latestRecordPredicate}
ORDER BY current_record.create_time DESC, current_record.id DESC
LIMIT :limit
ORDER BY current_record.create_time DESC, current_record.id DESC${limitSql}
`,
{ limit: Math.min(Math.max(limit, 1), dashboardLatestLimit) },
queryParams,
)
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)
})
})
+42 -31
View File
@@ -1,12 +1,6 @@
import { LRUCache } from 'lru-cache'
import { z } from 'zod'
import {
type BatteryInfo,
type BatteryPrediction,
POWER_STATUS,
type PowerStatus,
toMysqlBoolean,
} from '@/domain/battery'
import { type BatteryInfo, type BatteryPrediction, type PowerStatus, toMysqlBoolean } from '@/domain/battery'
import { env } from '@/env'
import { getLogger } from '@/server/logger'
@@ -29,11 +23,6 @@ type PredictionHistoryItem = {
cycle: number
charge_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
}
@@ -72,7 +61,12 @@ const cache = new LRUCache<string, SohPrediction>({
max: 5_000,
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 nominalCapacityAh = 3.2
const round2 = (value: number) => Math.round(value * 100) / 100
@@ -91,22 +85,13 @@ function createCacheKey(battery: BatteryInfo, history: BatteryInfo[]) {
}
function createHistoryItem(item: BatteryInfo, index: number): PredictionHistoryItem {
const sohRatio = Math.max(0.5, Math.min(1, item.power / 100))
const chargeCapacity = round2(3.2 * sohRatio)
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)
const observedCapacityRatio = Math.max(0.5, Math.min(1, item.power / 100))
const chargeCapacityAh = round2(nominalCapacityAh * observedCapacityRatio)
return {
cycle: index + 1,
charge_capacity_ah: chargeCapacity,
discharge_capacity_ah: dischargeCapacity,
charge_energy_wh: chargeEnergy,
discharge_energy_wh: dischargeEnergy,
charge_time: item.powerStatus === POWER_STATUS.CHARGING ? '01:20:00' : '01:18:00',
discharge_time: item.isLowPower ? '00:58:00' : '01:10:00',
coulombic_efficiency_pct: efficiency,
charge_capacity_ah: chargeCapacityAh,
discharge_capacity_ah: round2(chargeCapacityAh * 0.96),
timestamp: normalizeMysqlDateTime(item.createTime),
}
}
@@ -133,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 {
batteryId: response.battery_id,
mac: response.mac,
@@ -149,15 +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() {
return true
}
export async function predictSoh(battery: BatteryInfo, history: BatteryInfo[]): Promise<SohPrediction | null> {
const request = createPredictionRequest(battery, history)
if (!request) return null
const cacheKey = createCacheKey(battery, history)
if (negativeCache.has(cacheKey)) return null
const request = createPredictionRequest(battery, history)
if (!request) {
negativeCache.set(cacheKey, true)
return null
}
const cached = cache.get(cacheKey)
if (cached) return cached
const pendingRequest = inFlightRequests.get(cacheKey)
@@ -191,24 +185,41 @@ async function requestPrediction(
if (!response.ok) {
logger.warn('SOH prediction request failed', { mac: battery.mac, status: response.status })
return null
return cacheNegativePrediction(cacheKey)
}
const json = await response.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)
negativeCache.delete(cacheKey)
return prediction
} catch (error) {
logger.warn('SOH prediction request errored', { mac: battery.mac, error })
return null
return cacheNegativePrediction(cacheKey)
} finally {
clearTimeout(timeout)
inFlightRequests.delete(cacheKey)
}
}
function cacheNegativePrediction(cacheKey: string) {
negativeCache.set(cacheKey, true)
return null
}
export function clearPredictionCache() {
cache.clear()
negativeCache.clear()
inFlightRequests.clear()
}
-5
View File
@@ -17,8 +17,3 @@ body {
linear-gradient(180deg, #09090b 0%, #0b0f12 100%);
color: #f4f4f5;
}
select option {
background: #09090b;
color: #f4f4f5;
}