Compare commits
3 Commits
main
..
f7f86e4462
| Author | SHA1 | Date | |
|---|---|---|---|
| f7f86e4462 | |||
| 5cc476cedc | |||
| 1ccda13cdf |
@@ -1,13 +0,0 @@
|
||||
node_modules/
|
||||
.output/
|
||||
.tanstack/
|
||||
out/
|
||||
.git/
|
||||
.env
|
||||
.env.*
|
||||
|
||||
*.md
|
||||
*.tsbuildinfo
|
||||
*.bun-build
|
||||
|
||||
.vscode/
|
||||
@@ -1,15 +1 @@
|
||||
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
|
||||
|
||||
# 可选:日志级别与输出格式
|
||||
# LOG_LEVEL=info # trace|debug|info|warning|error|fatal
|
||||
# LOG_FORMAT=pretty # pretty|json — defaults to TTY ? pretty : json
|
||||
# LOG_DB=false # reserved for database query logging if enabled later
|
||||
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres
|
||||
|
||||
@@ -1,24 +1,157 @@
|
||||
# Dependencies
|
||||
node_modules/
|
||||
### Custom ###
|
||||
|
||||
# Build output
|
||||
.output/
|
||||
# TanStack
|
||||
.tanstack/
|
||||
.vite/
|
||||
out/
|
||||
volumes/
|
||||
*.bun-build
|
||||
*.tsbuildinfo
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
|
||||
# Env
|
||||
# Nitro
|
||||
.output/
|
||||
|
||||
# Bun build
|
||||
*.bun-build
|
||||
|
||||
# Turborepo
|
||||
.turbo/
|
||||
|
||||
### Node ###
|
||||
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
lerna-debug.log*
|
||||
|
||||
# Diagnostic reports (https://nodejs.org/api/report.html)
|
||||
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
*.lcov
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (https://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Snowpack dependency directory (https://snowpack.dev/)
|
||||
web_modules/
|
||||
|
||||
# TypeScript cache
|
||||
*.tsbuildinfo
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional stylelint cache
|
||||
.stylelintcache
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
# dotenv environment variable files
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
# parcel-bundler cache (https://parceljs.org/)
|
||||
.cache
|
||||
.parcel-cache
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
# Next.js build output
|
||||
.next
|
||||
out
|
||||
|
||||
# Nuxt.js build / generate output
|
||||
.nuxt
|
||||
dist
|
||||
.output
|
||||
|
||||
# Gatsby files
|
||||
.cache/
|
||||
# Comment in the public line in if your project uses Gatsby and not Next.js
|
||||
# https://nextjs.org/blog/next-9-1#public-directory-support
|
||||
# public
|
||||
|
||||
# vuepress build output
|
||||
.vuepress/dist
|
||||
|
||||
# vuepress v2.x temp and cache directory
|
||||
.temp
|
||||
.cache
|
||||
|
||||
# Sveltekit cache directory
|
||||
.svelte-kit/
|
||||
|
||||
# vitepress build output
|
||||
**/.vitepress/dist
|
||||
|
||||
# vitepress cache directory
|
||||
**/.vitepress/cache
|
||||
|
||||
# Docusaurus cache and generated files
|
||||
.docusaurus
|
||||
|
||||
# Serverless directories
|
||||
.serverless/
|
||||
|
||||
# FuseBox cache
|
||||
.fusebox/
|
||||
|
||||
# DynamoDB Local files
|
||||
.dynamodb/
|
||||
|
||||
# Firebase cache directory
|
||||
.firebase/
|
||||
|
||||
# TernJS port file
|
||||
.tern-port
|
||||
|
||||
# Stores VSCode versions used for testing VSCode extensions
|
||||
.vscode-test
|
||||
|
||||
# yarn v3
|
||||
.pnp.*
|
||||
.yarn/*
|
||||
!.yarn/patches
|
||||
!.yarn/plugins
|
||||
!.yarn/releases
|
||||
!.yarn/sdks
|
||||
!.yarn/versions
|
||||
|
||||
# Vite files
|
||||
vite.config.js.timestamp-*
|
||||
vite.config.ts.timestamp-*
|
||||
.vite/
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
{
|
||||
"recommendations": [
|
||||
"biomejs.biome",
|
||||
"codezombiech.gitignore",
|
||||
"hverlin.mise-vscode",
|
||||
"mikestead.dotenv",
|
||||
"oven.bun-vscode",
|
||||
"redhat.vscode-yaml",
|
||||
"rust-lang.rust-analyzer",
|
||||
"tamasfe.even-better-toml",
|
||||
"unional.vscode-sort-package-json"
|
||||
"tauri-apps.tauri-vscode"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,50 +1,54 @@
|
||||
{
|
||||
// Disable the default formatter & linter, use biome instead
|
||||
"prettier.enable": false,
|
||||
"eslint.enable": false,
|
||||
|
||||
// Auto fix
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.biome": "explicit",
|
||||
"source.organizeImports.biome": "explicit"
|
||||
},
|
||||
"editor.defaultFormatter": "biomejs.biome",
|
||||
"editor.formatOnSave": true,
|
||||
"[javascript]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[javascriptreact]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[typescriptreact]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[json]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[jsonc]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[toml]": {
|
||||
"editor.defaultFormatter": "tamasfe.even-better-toml"
|
||||
},
|
||||
"[typescript]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[typescriptreact]": {
|
||||
"editor.defaultFormatter": "biomejs.biome"
|
||||
},
|
||||
"[yaml]": {
|
||||
"editor.defaultFormatter": "redhat.vscode-yaml"
|
||||
},
|
||||
"editor.codeActionsOnSave": {
|
||||
"source.fixAll.biome": "explicit",
|
||||
"source.organizeImports.biome": "explicit"
|
||||
"[toml]": {
|
||||
"editor.defaultFormatter": "tamasfe.even-better-toml"
|
||||
},
|
||||
"editor.defaultFormatter": "biomejs.biome",
|
||||
"editor.formatOnSave": true,
|
||||
"files.associations": {
|
||||
".env": "dotenv",
|
||||
".env.*": "dotenv",
|
||||
"**/tsconfig*.json": "jsonc",
|
||||
"**/biome.json": "jsonc",
|
||||
"**/opencode.json": "jsonc",
|
||||
"**/tsconfig.*.json": "jsonc",
|
||||
"**/tsconfig.json": "jsonc"
|
||||
"**/opencode.json": "jsonc"
|
||||
},
|
||||
|
||||
// TanStack Router
|
||||
"files.readonlyInclude": {
|
||||
"**/routeTree.gen.ts": true
|
||||
},
|
||||
"files.watcherExclude": {
|
||||
"**/routeTree.gen.ts": true
|
||||
},
|
||||
"js/ts.tsdk.path": "node_modules/typescript/lib",
|
||||
"js/ts.tsdk.promptToUseWorkspaceVersion": true,
|
||||
"search.exclude": {
|
||||
"**/routeTree.gen.ts": true
|
||||
}
|
||||
|
||||
@@ -1,109 +1,193 @@
|
||||
# AGENTS.md
|
||||
# AGENTS.md - AI Coding Agent Guidelines
|
||||
|
||||
Repo-specific notes for AI agents.
|
||||
## Project Overview
|
||||
|
||||
## Stack
|
||||
TanStack Start fullstack app with Tauri desktop shell.
|
||||
|
||||
- Bun-only (`mise.toml` pins `bun = 1.3.13`). Do not use `npm` / `npx` / `node` / `yarn` / `pnpm`.
|
||||
- TanStack Start + React 19 SSR + Vite + Nitro `bun` preset.
|
||||
- ORPC contract-first API, TanStack Query v5, Tailwind v4.
|
||||
- Business data source is the customer's existing **MySQL** database. This app is read-only display software.
|
||||
- There is no PostgreSQL, Drizzle schema, embedded migration flow, or local DB mutation path in this project now.
|
||||
- `scripts/seed.ts` is the only local development helper allowed to create/truncate/insert sample data. The app runtime must stay read-only.
|
||||
| Layer | Tech |
|
||||
|-------|------|
|
||||
| Framework | TanStack Start (React SSR, file-based routing) |
|
||||
| Runtime | Bun |
|
||||
| Language | TypeScript (strict mode) |
|
||||
| Styling | Tailwind CSS v4 |
|
||||
| Database | PostgreSQL + Drizzle ORM |
|
||||
| RPC | ORPC (contract-first, type-safe) |
|
||||
| Build | Vite + Turbo |
|
||||
| Linting | Biome |
|
||||
| Desktop | Tauri v2 (optional, see `src-tauri/AGENTS.md`) |
|
||||
|
||||
## Scripts
|
||||
## Commands
|
||||
|
||||
```bash
|
||||
bun run dev
|
||||
bun run build
|
||||
bun run compile
|
||||
bun run seed
|
||||
bun run typecheck
|
||||
bun run test
|
||||
bun run fix
|
||||
# Development
|
||||
bun dev # Start Tauri + Vite via Turbo
|
||||
bun dev:vite # Vite only (localhost:3000)
|
||||
bun db:studio # Drizzle Studio
|
||||
|
||||
# Build
|
||||
bun build # Full build (Vite → compile → Tauri)
|
||||
bun build:vite # Vite only (outputs to .output/)
|
||||
|
||||
# Code Quality
|
||||
bun typecheck # TypeScript check (tsc -b)
|
||||
bun fix # Biome auto-fix (format + lint)
|
||||
|
||||
# Database
|
||||
bun db:generate # Generate migrations from schema
|
||||
bun db:migrate # Run migrations
|
||||
bun db:push # Push schema changes (dev only)
|
||||
|
||||
# Testing (not configured yet)
|
||||
# When adding tests, use Vitest or Bun test runner:
|
||||
# bun test path/to/test.ts # Single file
|
||||
# bun test -t "pattern" # By test name
|
||||
```
|
||||
|
||||
Before shipping: `bun run fix && bun run typecheck && bun run test && bun run build`.
|
||||
|
||||
## MySQL Source
|
||||
|
||||
Environment variable:
|
||||
|
||||
```bash
|
||||
DATABASE_URL=mysql://user:password@host:3306/database
|
||||
```
|
||||
|
||||
Required AI prediction service:
|
||||
|
||||
```bash
|
||||
SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000
|
||||
SOH_PREDICTION_CACHE_TTL_SECONDS=86400
|
||||
SOH_PREDICTION_TIMEOUT_MS=10000
|
||||
```
|
||||
|
||||
Customer table: `ls_battery_info`.
|
||||
|
||||
| Column | Type | Meaning |
|
||||
| --- | --- | --- |
|
||||
| `id` | `int(11)` auto increment | primary key |
|
||||
| `user_id` | `int(11)` | user ID |
|
||||
| `mac` | `varchar(50)` | device MAC |
|
||||
| `dev_model` | `varchar(20)` | device model |
|
||||
| `dev_name` | `varchar(50)` | device name |
|
||||
| `is_low_power` | `varchar(10)` | `true` / `false` |
|
||||
| `power_status` | `tinyint(4)` | `0` not charging, `1` charging, `2` full |
|
||||
| `power` | `tinyint(4)` | current battery `0~100` |
|
||||
| `create_time` | `datetime` | created time |
|
||||
| `remark` | `varchar(500)` | nullable remark |
|
||||
|
||||
Rules:
|
||||
|
||||
- Only run `SELECT` queries against this table. Do not insert, update, delete, migrate, or create tables.
|
||||
- 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`.
|
||||
- `power_status` is normalized to `0 | 1 | 2`.
|
||||
- `battery.batteries` returns paginated latest records per `mac`; supported filters are `pageSize`, `cursor`, `search`, `lowPower`, `powerStatus`, and `sort`.
|
||||
- `battery.history` takes `mac` and returns history ordered by `create_time DESC, id DESC`, limited to 500 rows.
|
||||
- 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
|
||||
|
||||
```
|
||||
src/
|
||||
├── routes/
|
||||
│ ├── index.tsx # SoH dashboard
|
||||
│ ├── batteries.tsx # battery monitor page
|
||||
│ └── api/ # ORPC handlers
|
||||
├── server/
|
||||
│ ├── api/ # contracts / routers / interceptors
|
||||
│ ├── battery/mysql.ts
|
||||
│ └── prediction/client.ts
|
||||
├── domain/battery.ts
|
||||
├── client/orpc.ts
|
||||
└── styles.css
|
||||
```
|
||||
|
||||
## ORPC
|
||||
|
||||
- Contracts live in `src/server/api/contracts/`.
|
||||
- Routers live in `src/server/api/routers/`.
|
||||
- Use `os` from `@/server/api/server`.
|
||||
- Current business API:
|
||||
- `battery.dashboard`
|
||||
- `battery.batteries`
|
||||
- `battery.history`
|
||||
|
||||
## CLI And Deploy
|
||||
|
||||
- `src/bin.ts` must keep static imports minimal. Nitro's bun preset starts the server as a side effect when `.output/server/index.mjs` is imported.
|
||||
- `serve` is lazy-loaded via citty.
|
||||
- `bun run compile` produces `out/server-<target>`.
|
||||
- Runtime artifact is a single binary plus `DATABASE_URL` configuration.
|
||||
|
||||
## Code Style
|
||||
|
||||
- 2-space indentation, LF, single quotes, semicolons as-needed, 120-column line width.
|
||||
- Route components use `function Foo()` declarations below route config.
|
||||
- No `console.*` in business code; use `getLogger([...])` from `@/server/logger` if logging is needed.
|
||||
- No `as any`, `@ts-ignore`, or `@ts-expect-error`.
|
||||
- Do not edit `src/routeTree.gen.ts` manually.
|
||||
### Formatting (Biome enforced)
|
||||
|
||||
- **Indent**: 2 spaces
|
||||
- **Line endings**: LF
|
||||
- **Quotes**: Single `'string'`
|
||||
- **Semicolons**: As needed (ASI)
|
||||
- **Arrow parens**: Always `(x) => x`
|
||||
|
||||
### Imports
|
||||
|
||||
Biome auto-organizes. Order: external → internal (`@/*`) → type-only imports.
|
||||
|
||||
```typescript
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { z } from 'zod'
|
||||
import { db } from '@/db'
|
||||
import type { ReactNode } from 'react'
|
||||
```
|
||||
|
||||
### TypeScript
|
||||
|
||||
Strict mode with extra checks:
|
||||
- `noUncheckedIndexedAccess: true` - array/object index returns `T | undefined`
|
||||
- `noImplicitOverride: true`
|
||||
- `verbatimModuleSyntax: true`
|
||||
|
||||
Path alias: `@/*` → `src/*`
|
||||
|
||||
### Naming
|
||||
|
||||
| Entity | Convention | Example |
|
||||
|--------|------------|---------|
|
||||
| Files (utils) | kebab-case | `utils.ts`, `db-provider.ts` |
|
||||
| Files (components) | PascalCase | `NotFound.tsx` |
|
||||
| Routes | TanStack conventions | `routes/index.tsx`, `routes/__root.tsx` |
|
||||
| Components | PascalCase arrow functions | `const MyComponent = () => {}` |
|
||||
| Functions | camelCase | `handleSubmit` |
|
||||
| Constants | UPPER_SNAKE_CASE | `MAX_RETRIES` |
|
||||
| Types/Interfaces | PascalCase | `TodoItem`, `RouterContext` |
|
||||
|
||||
### React Patterns
|
||||
|
||||
```typescript
|
||||
// Components: arrow functions (Biome enforces)
|
||||
const MyComponent = ({ title }: { title: string }) => {
|
||||
return <div>{title}</div>
|
||||
}
|
||||
|
||||
// Routes: createFileRoute
|
||||
export const Route = createFileRoute('/')({
|
||||
component: Home,
|
||||
loader: async ({ context }) => {
|
||||
await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions())
|
||||
},
|
||||
})
|
||||
|
||||
// Data fetching: TanStack Query
|
||||
const query = useSuspenseQuery(orpc.todo.list.queryOptions())
|
||||
const mutation = useMutation(orpc.todo.create.mutationOptions())
|
||||
```
|
||||
|
||||
### ORPC Pattern (Contract-First RPC)
|
||||
|
||||
1. **Define contract** (`src/orpc/contracts/my-feature.ts`):
|
||||
```typescript
|
||||
import { oc } from '@orpc/contract'
|
||||
import { z } from 'zod'
|
||||
|
||||
export const get = oc.input(z.object({ id: z.uuid() })).output(schema)
|
||||
export const create = oc.input(insertSchema).output(schema)
|
||||
```
|
||||
|
||||
2. **Implement handler** (`src/orpc/handlers/my-feature.ts`):
|
||||
```typescript
|
||||
import { os } from '@/orpc/server'
|
||||
import { dbProvider } from '@/orpc/middlewares'
|
||||
|
||||
export const get = os.myFeature.get
|
||||
.use(dbProvider)
|
||||
.handler(async ({ context, input }) => {
|
||||
return await context.db.query.myTable.findFirst(...)
|
||||
})
|
||||
```
|
||||
|
||||
3. **Register** in `contract.ts` and `router.ts`
|
||||
4. **Use** in components via `orpc.myFeature.get.queryOptions()`
|
||||
|
||||
### Drizzle Schema
|
||||
|
||||
```typescript
|
||||
import { sql } from 'drizzle-orm'
|
||||
import { pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'
|
||||
|
||||
export const myTable = pgTable('my_table', {
|
||||
id: uuid('id').primaryKey().default(sql`uuidv7()`),
|
||||
name: text('name').notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow().$onUpdateFn(() => new Date()),
|
||||
})
|
||||
```
|
||||
|
||||
### Environment Variables
|
||||
|
||||
- Server: no prefix (e.g., `DATABASE_URL`)
|
||||
- Client: `VITE_` prefix required
|
||||
- Validated via `@t3-oss/env-core` in `src/env.ts`
|
||||
|
||||
## Directory Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── components/ # Reusable React components
|
||||
├── db/
|
||||
│ ├── schema/ # Drizzle schema definitions
|
||||
│ └── index.ts # Database instance
|
||||
├── integrations/ # TanStack Query/Router setup
|
||||
├── lib/ # Utility functions
|
||||
├── orpc/
|
||||
│ ├── contracts/ # Input/output schemas
|
||||
│ ├── handlers/ # Server procedure implementations
|
||||
│ ├── middlewares/ # Middleware (e.g., dbProvider)
|
||||
│ ├── contract.ts # Contract aggregation
|
||||
│ ├── router.ts # Router composition
|
||||
│ └── client.ts # Isomorphic client
|
||||
├── routes/ # File-based routes
|
||||
│ ├── __root.tsx # Root layout
|
||||
│ └── api/rpc.$.ts # ORPC HTTP endpoint
|
||||
└── env.ts # Environment validation
|
||||
```
|
||||
|
||||
## Critical Rules
|
||||
|
||||
- **DO NOT** edit `src/routeTree.gen.ts` (auto-generated)
|
||||
- **DO NOT** commit `.env` files
|
||||
- **MUST** run `bun fix` before commits
|
||||
- **MUST** use `@/*` path alias (not relative imports)
|
||||
- **MUST** use React Compiler (no manual memoization needed)
|
||||
- **MUST** use `Readonly<T>` for immutable props
|
||||
|
||||
## Git Workflow
|
||||
|
||||
1. Make changes following style guide
|
||||
2. Run `bun fix` (format + lint)
|
||||
3. Run `bun typecheck` (type safety)
|
||||
4. Test with `bun dev`
|
||||
5. Commit with descriptive message
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
FROM oven/bun:1.3.13 AS source
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
COPY package.json bun.lock ./
|
||||
RUN bun install --frozen-lockfile
|
||||
|
||||
COPY . .
|
||||
|
||||
FROM source AS build
|
||||
|
||||
RUN bun run build \
|
||||
&& bun run compile \
|
||||
&& mv out/server-* out/server
|
||||
|
||||
FROM gcr.io/distroless/cc-debian13:nonroot
|
||||
|
||||
WORKDIR /app
|
||||
COPY --from=build --chown=nonroot:nonroot /app/out/server ./server
|
||||
|
||||
ENV HOST=0.0.0.0
|
||||
EXPOSE 3000
|
||||
|
||||
CMD ["./server"]
|
||||
@@ -1,143 +0,0 @@
|
||||
# battery-soh
|
||||
|
||||
电池健康运营看板,用于接入客户现有设备数据,持续呈现电量状态、健康预测、风险分布与维护建议。系统以只读方式连接客户数据库,不改动生产数据;当健康预测暂不可用时,页面会明确显示不可用状态,避免用误导性数值替代真实结果。
|
||||
|
||||
## 产品能力
|
||||
|
||||
- **健康总览**:聚合展示设备规模、平均健康度、30/90 天趋势与预警设备占比。
|
||||
- **风险识别**:按健康度、低电量、充电状态与预测风险生成重点关注设备清单。
|
||||
- **实时明细**:支持按设备名称、编号、电量与充电状态筛选设备,快速定位需要排查的对象。
|
||||
- **维护建议**:基于当前可用数据给出巡检、复查与优先处理建议。
|
||||
- **可信展示**:缺少预测结果时显示“预测不可用”,不会将缺失值渲染为 `0%`。
|
||||
|
||||
## 数据接入
|
||||
|
||||
系统接入客户现有 MySQL 数据源,业务运行时仅执行只读查询。需要配置:
|
||||
|
||||
```bash
|
||||
DATABASE_URL=mysql://user:password@host:3306/database
|
||||
```
|
||||
|
||||
客户设备表:`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
|
||||
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 小时;单台设备预测失败或历史数据不足时会短暂缓存不可用状态,默认 5 分钟,避免反复打满预测服务,同时仅该设备显示为“预测不可用”。
|
||||
|
||||
## 接口文档
|
||||
|
||||
OpenAPI 文档和规格默认不公开,生产或生产类运行环境应保持默认值:
|
||||
|
||||
```bash
|
||||
ENABLE_API_DOCS=false
|
||||
```
|
||||
|
||||
仅在受控本地开发或内网演示环境显式设置 `ENABLE_API_DOCS=true` 后,才会开放 `http://localhost:3000/api/docs` 与 `http://localhost:3000/api/spec.json`。`/api/rpc` 不受此开关影响。
|
||||
|
||||
## 快速开始
|
||||
|
||||
```bash
|
||||
cp .env.example .env
|
||||
bun install
|
||||
bun run dev
|
||||
```
|
||||
|
||||
打开浏览器:
|
||||
|
||||
- `http://localhost:3000/`:设备健康运营看板
|
||||
- `http://localhost:3000/batteries`:设备状态明细
|
||||
- `http://localhost:3000/api/docs`:接口文档(需设置 `ENABLE_API_DOCS=true`)
|
||||
|
||||
## 本地演示环境
|
||||
|
||||
如果暂时没有生产数据库连接,可以使用 Docker Compose 启动本地 MySQL 并填充演示数据:
|
||||
|
||||
```bash
|
||||
docker compose up --build
|
||||
```
|
||||
|
||||
Compose 会启动:
|
||||
|
||||
- `db`:本地 MySQL 8.4
|
||||
- `seed`:初始化本地 `ls_battery_info` 演示数据
|
||||
- `app`:启动应用服务
|
||||
|
||||
Compose 的 `app` 服务会为本地演示显式启用 `ENABLE_API_DOCS=true`;生产部署不应沿用该设置,除非已通过网络边界或上游认证限制访问。
|
||||
|
||||
也可以手动初始化本地数据:
|
||||
|
||||
```bash
|
||||
DATABASE_URL=mysql://battery:battery@localhost:3306/battery_soh bun run seed
|
||||
```
|
||||
|
||||
`seed` 仅用于本地开发和演示环境;应用运行时仍保持只读查询,不写入业务数据库。
|
||||
|
||||
## 系统结构
|
||||
|
||||
```text
|
||||
src/
|
||||
├── routes/ # 页面与 API 路由
|
||||
├── server/
|
||||
│ ├── api/ # 接口契约与路由
|
||||
│ ├── battery/mysql.ts # 设备数据只读查询
|
||||
│ └── prediction/client.ts # 健康预测服务客户端
|
||||
├── domain/battery.ts # 电池领域模型与看板聚合
|
||||
├── client/orpc.ts # 前端接口客户端
|
||||
└── styles.css # 全局样式入口
|
||||
```
|
||||
|
||||
核心接口:
|
||||
|
||||
- `battery.dashboard`:生成健康运营看板数据。
|
||||
- `battery.batteries`:分页返回每台设备的最新状态,支持搜索、筛选和排序。
|
||||
- `battery.history`:返回单台设备最近 500 条历史记录。
|
||||
|
||||
## 部署
|
||||
|
||||
```bash
|
||||
bun run build
|
||||
bun run compile
|
||||
./out/server-<target>
|
||||
```
|
||||
|
||||
构建产物为单个服务二进制文件,运行时需要配置 `DATABASE_URL` 与 SoH 预测服务地址。
|
||||
|
||||
## 常用命令
|
||||
|
||||
| 命令 | 作用 |
|
||||
| --- | --- |
|
||||
| `bun run dev` | 启动开发服务 |
|
||||
| `bun run build` | 构建应用 |
|
||||
| `bun run compile` | 生成单二进制产物 |
|
||||
| `bun run seed` | 初始化本地演示数据 |
|
||||
| `bun run typecheck` | TypeScript 类型检查 |
|
||||
| `bun run test` | 运行测试 |
|
||||
| `bun run fix` | 格式化与静态检查 |
|
||||
|
||||
交付前验证:
|
||||
|
||||
```bash
|
||||
bun run fix && bun run typecheck && bun run test && bun run build
|
||||
```
|
||||
@@ -6,21 +6,16 @@
|
||||
"useIgnoreFile": true
|
||||
},
|
||||
"files": {
|
||||
"ignoreUnknown": false,
|
||||
"includes": ["**", "!**/routeTree.gen.ts", "!**/migrations.gen.ts", "!volumes"]
|
||||
"includes": ["**", "!**/routeTree.gen.ts"],
|
||||
"ignoreUnknown": false
|
||||
},
|
||||
"formatter": {
|
||||
"enabled": true,
|
||||
"indentStyle": "space",
|
||||
"lineEnding": "lf",
|
||||
"lineWidth": 120
|
||||
"lineEnding": "lf"
|
||||
},
|
||||
"linter": {
|
||||
"enabled": true,
|
||||
"domains": {
|
||||
"react": "recommended",
|
||||
"types": "all"
|
||||
},
|
||||
"rules": {
|
||||
"recommended": true,
|
||||
"complexity": {
|
||||
@@ -28,14 +23,6 @@
|
||||
},
|
||||
"correctness": {
|
||||
"noReactPropAssignments": "error"
|
||||
},
|
||||
"style": {
|
||||
"noNonNullAssertion": "error"
|
||||
},
|
||||
"suspicious": {
|
||||
"noExplicitAny": "error",
|
||||
"noImportCycles": "error",
|
||||
"noTsIgnore": "error"
|
||||
}
|
||||
}
|
||||
},
|
||||
@@ -46,11 +33,6 @@
|
||||
"arrowParentheses": "always"
|
||||
}
|
||||
},
|
||||
"css": {
|
||||
"parser": {
|
||||
"tailwindDirectives": true
|
||||
}
|
||||
},
|
||||
"assist": {
|
||||
"enabled": true,
|
||||
"actions": {
|
||||
|
||||
@@ -0,0 +1,289 @@
|
||||
import { Schema } from '@effect/schema'
|
||||
import { $ } from 'bun'
|
||||
import { Console, Context, Data, Effect, Layer } from 'effect'
|
||||
|
||||
// ============================================================================
|
||||
// Domain Models & Schema
|
||||
// ============================================================================
|
||||
|
||||
const targetMap = {
|
||||
'bun-windows-x64': 'x86_64-pc-windows-msvc',
|
||||
'bun-darwin-arm64': 'aarch64-apple-darwin',
|
||||
'bun-darwin-x64': 'x86_64-apple-darwin',
|
||||
'bun-linux-x64': 'x86_64-unknown-linux-gnu',
|
||||
'bun-linux-arm64': 'aarch64-unknown-linux-gnu',
|
||||
} as const
|
||||
|
||||
const BunTargetSchema = Schema.Literal(
|
||||
'bun-windows-x64',
|
||||
'bun-darwin-arm64',
|
||||
'bun-darwin-x64',
|
||||
'bun-linux-x64',
|
||||
'bun-linux-arm64',
|
||||
)
|
||||
|
||||
type BunTarget = Schema.Schema.Type<typeof BunTargetSchema>
|
||||
|
||||
const BuildConfigSchema = Schema.Struct({
|
||||
entrypoint: Schema.String.pipe(Schema.nonEmptyString()),
|
||||
outputDir: Schema.String.pipe(Schema.nonEmptyString()),
|
||||
targets: Schema.Array(BunTargetSchema).pipe(Schema.minItems(1)),
|
||||
})
|
||||
|
||||
type BuildConfig = Schema.Schema.Type<typeof BuildConfigSchema>
|
||||
|
||||
const BuildResultSchema = Schema.Struct({
|
||||
target: BunTargetSchema,
|
||||
outputs: Schema.Array(Schema.String),
|
||||
})
|
||||
|
||||
type BuildResult = Schema.Schema.Type<typeof BuildResultSchema>
|
||||
|
||||
// ============================================================================
|
||||
// Error Models (使用 Data.TaggedError)
|
||||
// ============================================================================
|
||||
|
||||
class CleanError extends Data.TaggedError('CleanError')<{
|
||||
readonly dir: string
|
||||
readonly cause: unknown
|
||||
}> {}
|
||||
|
||||
class BuildError extends Data.TaggedError('BuildError')<{
|
||||
readonly target: BunTarget
|
||||
readonly cause: unknown
|
||||
}> {}
|
||||
|
||||
class ConfigError extends Data.TaggedError('ConfigError')<{
|
||||
readonly message: string
|
||||
readonly cause: unknown
|
||||
}> {}
|
||||
|
||||
// ============================================================================
|
||||
// Services
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* 配置服务
|
||||
*/
|
||||
class BuildConfigService extends Context.Tag('BuildConfigService')<
|
||||
BuildConfigService,
|
||||
BuildConfig
|
||||
>() {
|
||||
/**
|
||||
* 从原始数据创建并验证配置
|
||||
*/
|
||||
static fromRaw = (raw: unknown) =>
|
||||
Effect.gen(function* () {
|
||||
const decoded = yield* Schema.decodeUnknown(BuildConfigSchema)(raw)
|
||||
return decoded
|
||||
}).pipe(
|
||||
Effect.catchAll((error) =>
|
||||
Effect.fail(
|
||||
new ConfigError({
|
||||
message: '配置验证失败',
|
||||
cause: error,
|
||||
}),
|
||||
),
|
||||
),
|
||||
)
|
||||
|
||||
/**
|
||||
* 默认配置 Layer
|
||||
*/
|
||||
static readonly Live = Layer.effect(
|
||||
BuildConfigService,
|
||||
BuildConfigService.fromRaw({
|
||||
entrypoint: '.output/server/index.mjs',
|
||||
// outputDir: 'out',
|
||||
outputDir: 'src-tauri/binaries',
|
||||
targets: ['bun-windows-x64', 'bun-darwin-arm64', 'bun-linux-x64'],
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件系统服务
|
||||
*/
|
||||
class FileSystemService extends Context.Tag('FileSystemService')<
|
||||
FileSystemService,
|
||||
{
|
||||
readonly cleanDir: (dir: string) => Effect.Effect<void, CleanError>
|
||||
}
|
||||
>() {
|
||||
static readonly Live = Layer.succeed(FileSystemService, {
|
||||
cleanDir: (dir: string) =>
|
||||
Effect.tryPromise({
|
||||
try: async () => {
|
||||
await $`rm -rf ${dir}`
|
||||
},
|
||||
catch: (cause: unknown) =>
|
||||
new CleanError({
|
||||
dir,
|
||||
cause,
|
||||
}),
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建服务
|
||||
*/
|
||||
class BuildService extends Context.Tag('BuildService')<
|
||||
BuildService,
|
||||
{
|
||||
readonly buildForTarget: (
|
||||
config: BuildConfig,
|
||||
target: BunTarget,
|
||||
) => Effect.Effect<BuildResult, BuildError>
|
||||
readonly buildAll: (
|
||||
config: BuildConfig,
|
||||
) => Effect.Effect<ReadonlyArray<BuildResult>, BuildError>
|
||||
}
|
||||
>() {
|
||||
static readonly Live = Layer.succeed(BuildService, {
|
||||
buildForTarget: (config: BuildConfig, target: BunTarget) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Console.log(`🔨 开始构建: ${target}`)
|
||||
|
||||
const output = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Bun.build({
|
||||
entrypoints: [config.entrypoint],
|
||||
compile: {
|
||||
outfile: `app-${targetMap[target]}`,
|
||||
target: target,
|
||||
},
|
||||
outdir: config.outputDir,
|
||||
}),
|
||||
catch: (cause: unknown) =>
|
||||
new BuildError({
|
||||
target,
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
|
||||
const paths = output.outputs.map((item: { path: string }) => item.path)
|
||||
|
||||
return {
|
||||
target,
|
||||
outputs: paths,
|
||||
} satisfies BuildResult
|
||||
}),
|
||||
|
||||
buildAll: (config: BuildConfig) =>
|
||||
Effect.gen(function* () {
|
||||
const effects = config.targets.map((target) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Console.log(`🔨 开始构建: ${target}`)
|
||||
|
||||
const output = yield* Effect.tryPromise({
|
||||
try: () =>
|
||||
Bun.build({
|
||||
entrypoints: [config.entrypoint],
|
||||
compile: {
|
||||
outfile: `app-${targetMap[target]}`,
|
||||
target: target,
|
||||
},
|
||||
outdir: config.outputDir,
|
||||
}),
|
||||
catch: (cause: unknown) =>
|
||||
new BuildError({
|
||||
target,
|
||||
cause,
|
||||
}),
|
||||
})
|
||||
|
||||
const paths = output.outputs.map(
|
||||
(item: { path: string }) => item.path,
|
||||
)
|
||||
|
||||
return {
|
||||
target,
|
||||
outputs: paths,
|
||||
} satisfies BuildResult
|
||||
}),
|
||||
)
|
||||
return yield* Effect.all(effects, { concurrency: 'unbounded' })
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 报告服务
|
||||
*/
|
||||
class ReporterService extends Context.Tag('ReporterService')<
|
||||
ReporterService,
|
||||
{
|
||||
readonly printSummary: (
|
||||
results: ReadonlyArray<BuildResult>,
|
||||
) => Effect.Effect<void>
|
||||
}
|
||||
>() {
|
||||
static readonly Live = Layer.succeed(ReporterService, {
|
||||
printSummary: (results: ReadonlyArray<BuildResult>) =>
|
||||
Effect.gen(function* () {
|
||||
yield* Console.log('\n📦 构建完成:')
|
||||
for (const result of results) {
|
||||
yield* Console.log(` ${result.target}:`)
|
||||
for (const path of result.outputs) {
|
||||
yield* Console.log(` - ${path}`)
|
||||
}
|
||||
}
|
||||
}),
|
||||
})
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// Main Program
|
||||
// ============================================================================
|
||||
|
||||
const program = Effect.gen(function* () {
|
||||
const config = yield* BuildConfigService
|
||||
const fs = yield* FileSystemService
|
||||
const builder = yield* BuildService
|
||||
const reporter = yield* ReporterService
|
||||
|
||||
// 1. 清理输出目录
|
||||
yield* fs.cleanDir(config.outputDir)
|
||||
yield* Console.log(`✓ 已清理输出目录: ${config.outputDir}`)
|
||||
|
||||
// 2. 并行构建所有目标
|
||||
const results = yield* builder.buildAll(config)
|
||||
|
||||
// 3. 输出构建摘要
|
||||
yield* reporter.printSummary(results)
|
||||
|
||||
return results
|
||||
})
|
||||
|
||||
// ============================================================================
|
||||
// Layer Composition
|
||||
// ============================================================================
|
||||
|
||||
const MainLayer = Layer.mergeAll(
|
||||
BuildConfigService.Live,
|
||||
FileSystemService.Live,
|
||||
BuildService.Live,
|
||||
ReporterService.Live,
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// Runner
|
||||
// ============================================================================
|
||||
|
||||
const runnable = program.pipe(
|
||||
Effect.provide(MainLayer),
|
||||
Effect.catchTags({
|
||||
CleanError: (error) =>
|
||||
Console.error(`❌ 清理目录失败: ${error.dir}`, error.cause),
|
||||
BuildError: (error) =>
|
||||
Console.error(`❌ 构建失败 [${error.target}]:`, error.cause),
|
||||
ConfigError: (error) =>
|
||||
Console.error(`❌ 配置错误: ${error.message}`, error.cause),
|
||||
}),
|
||||
Effect.tapErrorCause((cause) => Console.error('❌ 未预期的错误:', cause)),
|
||||
)
|
||||
|
||||
Effect.runPromise(runnable).catch(() => {
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,47 +0,0 @@
|
||||
services:
|
||||
db:
|
||||
image: mysql:8.4
|
||||
ports:
|
||||
- "3306:3306"
|
||||
volumes:
|
||||
- mysql_data:/var/lib/mysql
|
||||
environment:
|
||||
- MYSQL_ROOT_PASSWORD=root
|
||||
- MYSQL_DATABASE=battery_soh
|
||||
- MYSQL_USER=battery
|
||||
- MYSQL_PASSWORD=battery
|
||||
healthcheck:
|
||||
test: [ "CMD", "mysqladmin", "ping", "-h", "127.0.0.1", "-ubattery", "-pbattery" ]
|
||||
interval: 5s
|
||||
timeout: 5s
|
||||
retries: 20
|
||||
|
||||
seed:
|
||||
build:
|
||||
context: .
|
||||
target: source
|
||||
restart: "no"
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
environment:
|
||||
- DATABASE_URL=mysql://battery:battery@db:3306/battery_soh
|
||||
- SOH_PREDICTION_API_BASE_URL=http://host.docker.internal:8000
|
||||
command: [ "bun", "run", "seed" ]
|
||||
|
||||
app:
|
||||
build: .
|
||||
depends_on:
|
||||
seed:
|
||||
condition: service_completed_successfully
|
||||
extra_hosts:
|
||||
- "host.docker.internal:host-gateway"
|
||||
ports:
|
||||
- "3000:3000"
|
||||
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:
|
||||
@@ -0,0 +1,11 @@
|
||||
import { defineConfig } from 'drizzle-kit'
|
||||
import { env } from '@/env'
|
||||
|
||||
export default defineConfig({
|
||||
out: './drizzle',
|
||||
schema: './src/db/schema/index.ts',
|
||||
dialect: 'postgresql',
|
||||
dbCredentials: {
|
||||
url: env.DATABASE_URL,
|
||||
},
|
||||
})
|
||||
@@ -1,2 +1,4 @@
|
||||
[tools]
|
||||
bun = "1.3.13"
|
||||
node = "24"
|
||||
bun = "1"
|
||||
rust = 'latest'
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
{
|
||||
"$schema": "https://opencode.ai/config.json",
|
||||
"mcp": {
|
||||
"shadcn": {
|
||||
"type": "local",
|
||||
"command": ["bunx", "--bun", "shadcn", "mcp"]
|
||||
},
|
||||
"tanstack": {
|
||||
"type": "remote",
|
||||
"url": "https://tanstack.com/api/mcp"
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,71 +1,64 @@
|
||||
{
|
||||
"name": "battery-soh",
|
||||
"version": "1.0.0",
|
||||
"name": "fullstack-starter",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"imports": {
|
||||
"#package": "./package.json",
|
||||
"#server": "./.output/server/index.mjs"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "bunx --bun vite build",
|
||||
"cli": "bun src/bin.ts",
|
||||
"compile": "bun scripts/compile.ts",
|
||||
"compile:darwin": "bun run compile:darwin:arm64 && bun run compile:darwin:x64",
|
||||
"compile:darwin:arm64": "bun scripts/compile.ts --target bun-darwin-arm64",
|
||||
"compile:darwin:x64": "bun scripts/compile.ts --target bun-darwin-x64",
|
||||
"compile:linux": "bun run compile:linux:x64 && bun run compile:linux:arm64",
|
||||
"compile:linux:arm64": "bun scripts/compile.ts --target bun-linux-arm64",
|
||||
"compile:linux:x64": "bun scripts/compile.ts --target bun-linux-x64",
|
||||
"compile:windows": "bun run compile:windows:x64",
|
||||
"compile:windows:x64": "bun scripts/compile.ts --target bun-windows-x64",
|
||||
"dev": "bunx --bun vite dev",
|
||||
"build": "turbo build:tauri",
|
||||
"build:compile": "bun build.ts",
|
||||
"build:tauri": "NO_STRIP=1 tauri build",
|
||||
"build:vite": "vite build",
|
||||
"db:generate": "drizzle-kit generate",
|
||||
"db:migrate": "drizzle-kit migrate",
|
||||
"db:push": "drizzle-kit push",
|
||||
"db:studio": "drizzle-kit studio",
|
||||
"dev": "turbo dev:tauri",
|
||||
"dev:tauri": "tauri dev",
|
||||
"dev:vite": "vite dev",
|
||||
"fix": "biome check --write",
|
||||
"seed": "bun scripts/seed.ts",
|
||||
"test": "bun test",
|
||||
"typecheck": "tsc --noEmit"
|
||||
"typecheck": "tsc -b"
|
||||
},
|
||||
"dependencies": {
|
||||
"@logtape/logtape": "^2.0.5",
|
||||
"@logtape/pretty": "^2.0.5",
|
||||
"@orpc/client": "^1.14.0",
|
||||
"@orpc/contract": "^1.14.0",
|
||||
"@orpc/openapi": "^1.14.0",
|
||||
"@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",
|
||||
"@tanstack/react-router-ssr-query": "^1.166.11",
|
||||
"@tanstack/react-start": "^1.167.48",
|
||||
"@tanstack/react-table": "^8.21.3",
|
||||
"@tanstack/react-virtual": "^3.13.24",
|
||||
"citty": "^0.2.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",
|
||||
"recharts": "^3.8.1",
|
||||
"@orpc/client": "^1.13.4",
|
||||
"@orpc/contract": "^1.13.4",
|
||||
"@orpc/server": "^1.13.4",
|
||||
"@orpc/tanstack-query": "^1.13.4",
|
||||
"@orpc/zod": "^1.13.4",
|
||||
"@t3-oss/env-core": "^0.13.10",
|
||||
"@tanstack/react-query": "^5.90.20",
|
||||
"@tanstack/react-router": "^1.158.1",
|
||||
"@tanstack/react-router-ssr-query": "^1.158.1",
|
||||
"@tanstack/react-start": "^1.158.3",
|
||||
"@tauri-apps/api": "^2.10.1",
|
||||
"drizzle-orm": "^0.45.1",
|
||||
"drizzle-zod": "^0.8.3",
|
||||
"postgres": "^3.4.8",
|
||||
"react": "^19.2.4",
|
||||
"react-dom": "^19.2.4",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@biomejs/biome": "^2.4.13",
|
||||
"@tailwindcss/vite": "^4.2.4",
|
||||
"@tanstack/devtools-vite": "^0.6.0",
|
||||
"@tanstack/react-devtools": "^0.10.2",
|
||||
"@tanstack/react-query-devtools": "^5.100.1",
|
||||
"@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",
|
||||
"typescript": "^6.0.3",
|
||||
"vite": "^8.0.10"
|
||||
"@biomejs/biome": "^2.3.14",
|
||||
"@effect/platform": "^0.94.3",
|
||||
"@effect/schema": "^0.75.5",
|
||||
"@tailwindcss/vite": "^4.1.18",
|
||||
"@tanstack/devtools-vite": "^0.4.1",
|
||||
"@tanstack/react-devtools": "^0.9.4",
|
||||
"@tanstack/react-query-devtools": "^5.91.3",
|
||||
"@tanstack/react-router-devtools": "^1.158.1",
|
||||
"@tauri-apps/cli": "^2.10.0",
|
||||
"@types/bun": "^1.3.8",
|
||||
"@vitejs/plugin-react": "^5.1.3",
|
||||
"babel-plugin-react-compiler": "^1.0.0",
|
||||
"drizzle-kit": "^0.31.8",
|
||||
"effect": "^3.19.16",
|
||||
"nitro": "npm:nitro-nightly@latest",
|
||||
"tailwindcss": "^4.1.18",
|
||||
"turbo": "^2.8.3",
|
||||
"typescript": "^5.9.3",
|
||||
"vite": "^8.0.0-beta.13",
|
||||
"vite-tsconfig-paths": "^6.0.5"
|
||||
},
|
||||
"overrides": {
|
||||
"@tanstack/query-core": "^5.90.20"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
# https://www.robotstxt.org/robotstxt.html
|
||||
User-agent: *
|
||||
Disallow:
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
import { mkdir, rm } from 'node:fs/promises'
|
||||
import { basename } from 'node:path'
|
||||
import { parseArgs } from 'node:util'
|
||||
|
||||
const ENTRYPOINT = 'src/bin.ts'
|
||||
const OUTDIR = 'out'
|
||||
|
||||
const SUPPORTED_TARGETS: readonly Bun.Build.CompileTarget[] = [
|
||||
'bun-windows-x64',
|
||||
'bun-darwin-arm64',
|
||||
'bun-darwin-x64',
|
||||
'bun-linux-x64',
|
||||
'bun-linux-arm64',
|
||||
]
|
||||
|
||||
const SUPPORTED_TARGET_SET: ReadonlySet<string> = new Set(SUPPORTED_TARGETS)
|
||||
|
||||
const isSupportedTarget = (value: string): value is Bun.Build.CompileTarget => SUPPORTED_TARGET_SET.has(value)
|
||||
|
||||
const { values } = parseArgs({
|
||||
options: { target: { type: 'string' } },
|
||||
strict: true,
|
||||
allowPositionals: false,
|
||||
})
|
||||
|
||||
const resolveTarget = (): Bun.Build.CompileTarget => {
|
||||
if (values.target !== undefined) {
|
||||
if (!isSupportedTarget(values.target)) {
|
||||
throw new Error(`Invalid target: ${values.target}\nAllowed: ${SUPPORTED_TARGETS.join(', ')}`)
|
||||
}
|
||||
return values.target
|
||||
}
|
||||
|
||||
const os = process.platform === 'win32' ? 'windows' : process.platform
|
||||
const candidate = `bun-${os}-${process.arch}`
|
||||
if (!isSupportedTarget(candidate)) {
|
||||
throw new Error(`Unsupported host: ${process.platform}-${process.arch}`)
|
||||
}
|
||||
return candidate
|
||||
}
|
||||
|
||||
const main = async () => {
|
||||
const target = resolveTarget()
|
||||
const suffix = target.replace('bun-', '')
|
||||
const outfile = `server-${suffix}`
|
||||
|
||||
await mkdir(OUTDIR, { recursive: true })
|
||||
await Promise.all([rm(`${OUTDIR}/${outfile}`, { force: true }), rm(`${OUTDIR}/${outfile}.exe`, { force: true })])
|
||||
|
||||
const result = await Bun.build({
|
||||
entrypoints: [ENTRYPOINT],
|
||||
outdir: OUTDIR,
|
||||
// autoloadDotenv: false — produce a deterministic binary; it must not silently consume a .env from cwd.
|
||||
compile: { outfile, target, autoloadDotenv: false },
|
||||
minify: true,
|
||||
bytecode: true,
|
||||
sourcemap: 'inline',
|
||||
})
|
||||
|
||||
if (!result.success) {
|
||||
throw new Error(result.logs.map(String).join('\n'))
|
||||
}
|
||||
|
||||
// Bun bundler still writes *.js.map next to the binary even with inline sourcemap.
|
||||
await rm(`${OUTDIR}/${basename(ENTRYPOINT, '.ts')}.js.map`, { force: true })
|
||||
|
||||
console.log(`✓ ${target} → ${OUTDIR}/${outfile}`)
|
||||
}
|
||||
|
||||
main().catch((err) => {
|
||||
console.error('❌', err instanceof Error ? err.message : err)
|
||||
process.exit(1)
|
||||
})
|
||||
@@ -1,138 +0,0 @@
|
||||
import { datetime, index, int, mysqlTable, tinyint, varchar } from 'drizzle-orm/mysql-core'
|
||||
import { drizzle } from 'drizzle-orm/mysql2'
|
||||
import { reset } from 'drizzle-seed'
|
||||
import mysql from 'mysql2/promise'
|
||||
import { type MYSQL_BOOLEAN, POWER_STATUS, type PowerStatus, toMysqlBoolean } from '@/domain/battery'
|
||||
|
||||
type SeedRow = {
|
||||
userId: number
|
||||
mac: string
|
||||
devModel: string
|
||||
devName: string
|
||||
isLowPower: (typeof MYSQL_BOOLEAN)[keyof typeof MYSQL_BOOLEAN]
|
||||
powerStatus: PowerStatus
|
||||
power: number
|
||||
createTime: Date
|
||||
remark: string | null
|
||||
}
|
||||
|
||||
const lsBatteryInfo = mysqlTable(
|
||||
'ls_battery_info',
|
||||
{
|
||||
id: int('id').autoincrement().primaryKey(),
|
||||
userId: int('user_id').notNull(),
|
||||
mac: varchar('mac', { length: 50 }).notNull(),
|
||||
devModel: varchar('dev_model', { length: 20 }).notNull(),
|
||||
devName: varchar('dev_name', { length: 50 }).notNull(),
|
||||
isLowPower: varchar('is_low_power', { length: 10 }).notNull(),
|
||||
powerStatus: tinyint('power_status').notNull(),
|
||||
power: tinyint('power').notNull(),
|
||||
createTime: datetime('create_time').notNull(),
|
||||
remark: varchar('remark', { length: 500 }),
|
||||
},
|
||||
(table) => [index('idx_ls_battery_info_mac_time_id').on(table.mac, table.createTime, table.id)],
|
||||
)
|
||||
|
||||
const databaseUrl = process.env.DATABASE_URL
|
||||
|
||||
if (!databaseUrl) {
|
||||
throw new Error('DATABASE_URL is required, for example mysql://battery:battery@localhost:3306/battery_soh')
|
||||
}
|
||||
|
||||
const parsedUrl = new URL(databaseUrl)
|
||||
const safeSeedHosts = new Set(['localhost', '127.0.0.1', '0.0.0.0', 'db', 'mysql'])
|
||||
|
||||
if (!safeSeedHosts.has(parsedUrl.hostname) && process.env.SEED_ALLOW_REMOTE !== 'true') {
|
||||
throw new Error(
|
||||
`Refusing to seed non-local MySQL host "${parsedUrl.hostname}". Set SEED_ALLOW_REMOTE=true only for disposable test databases.`,
|
||||
)
|
||||
}
|
||||
|
||||
const devices = [
|
||||
{ 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: POWER_STATUS.CHARGING, remark: 'v3.8.2' },
|
||||
{
|
||||
mac: 'RING-C07',
|
||||
model: 'SR-02',
|
||||
name: '样机-C07',
|
||||
basePower: 88,
|
||||
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<{
|
||||
mac: string
|
||||
model: string
|
||||
name: string
|
||||
basePower: number
|
||||
status: PowerStatus
|
||||
remark: string | null
|
||||
}>
|
||||
|
||||
function createSeedRows(now = new Date()): SeedRow[] {
|
||||
return devices.flatMap((device, deviceIndex) =>
|
||||
Array.from({ length: 8 }, (_, historyIndex) => {
|
||||
const createdAt = new Date(now.getTime() - (historyIndex * 24 + deviceIndex * 2) * 60 * 60 * 1000)
|
||||
const power = Math.max(1, Math.min(100, device.basePower - historyIndex * 2 + (deviceIndex % 3)))
|
||||
|
||||
return {
|
||||
userId: 1001 + (deviceIndex % 3),
|
||||
mac: device.mac,
|
||||
devModel: device.model,
|
||||
devName: device.name,
|
||||
isLowPower: toMysqlBoolean(power <= 20 || device.basePower <= 80),
|
||||
powerStatus: historyIndex === 0 ? device.status : POWER_STATUS.NOT_CHARGING,
|
||||
power,
|
||||
createTime: createdAt,
|
||||
remark: device.remark,
|
||||
}
|
||||
}),
|
||||
)
|
||||
}
|
||||
|
||||
const connection = await mysql.createConnection({ uri: databaseUrl })
|
||||
const db = drizzle(connection)
|
||||
|
||||
try {
|
||||
await db.execute(`
|
||||
CREATE TABLE IF NOT EXISTS ls_battery_info (
|
||||
id int(11) NOT NULL AUTO_INCREMENT,
|
||||
user_id int(11) NOT NULL,
|
||||
mac varchar(50) NOT NULL,
|
||||
dev_model varchar(20) NOT NULL,
|
||||
dev_name varchar(50) NOT NULL,
|
||||
is_low_power varchar(10) NOT NULL,
|
||||
power_status tinyint(4) NOT NULL,
|
||||
power tinyint(4) NOT NULL,
|
||||
create_time datetime NOT NULL,
|
||||
remark varchar(500) DEFAULT NULL,
|
||||
PRIMARY KEY (id),
|
||||
KEY idx_ls_battery_info_mac_time_id (mac, create_time, id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci
|
||||
`)
|
||||
|
||||
await reset(db, { lsBatteryInfo })
|
||||
await db.insert(lsBatteryInfo).values(createSeedRows())
|
||||
|
||||
process.stdout.write(`Seeded ${devices.length} devices into ls_battery_info.\n`)
|
||||
} finally {
|
||||
await connection.end()
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
/target/
|
||||
|
||||
# Generated by Tauri
|
||||
# will have schema files for capabilities auto-completion
|
||||
/gen/schemas
|
||||
|
||||
# Tauri Sidecar
|
||||
binaries/
|
||||
@@ -0,0 +1,357 @@
|
||||
# AGENTS.md - Tauri Shell 项目开发指南
|
||||
|
||||
本文档为 AI 编程助手和开发者提供项目规范、构建命令和代码风格指南。
|
||||
|
||||
## 项目概览
|
||||
|
||||
- **项目类型**: Tauri v2 桌面应用(轻量级壳子)
|
||||
- **后端**: Rust (Edition 2021)
|
||||
- **架构**: Sidecar 模式 - Sidecar App 承载主要业务逻辑
|
||||
- **设计理念**: Tauri 仅提供原生桌面能力(文件对话框、系统通知等),Web 逻辑全部由 Sidecar App 处理
|
||||
- **开发模式**: 使用 localhost:3000(需手动启动开发服务器)
|
||||
- **生产模式**: 自动启动 Sidecar 二进制
|
||||
- **异步运行时**: Tokio
|
||||
- **Rust 版本**: 1.92.0+
|
||||
- **工具管理**: 使用 mise 管理 Rust 和 Tauri CLI 版本(见 `mise.toml`)
|
||||
|
||||
## 构建、测试、运行命令
|
||||
|
||||
### 开发运行
|
||||
```bash
|
||||
# 开发模式运行 (需要先启动开发服务器)
|
||||
# 终端 1: 启动前端开发服务器
|
||||
bun run dev
|
||||
|
||||
# 终端 2: 启动 Tauri 应用
|
||||
tauri dev
|
||||
|
||||
# 或者使用单命令并行启动(需要配置 package.json)
|
||||
bun run dev:tauri
|
||||
```
|
||||
|
||||
**开发模式说明**:
|
||||
- 开发模式下,Tauri 直接连接到 `localhost:3000`(不启动 sidecar 二进制)
|
||||
- 需要手动运行 `bun run dev` 来启动开发服务器
|
||||
- 支持热重载(HMR),无需重启 Tauri 应用
|
||||
|
||||
### 构建
|
||||
```bash
|
||||
# 开发构建 (debug mode)
|
||||
cargo build
|
||||
|
||||
# 生产构建
|
||||
cargo build --release
|
||||
|
||||
# Tauri 应用打包 (生成安装程序)
|
||||
tauri build
|
||||
```
|
||||
|
||||
### 代码检查
|
||||
```bash
|
||||
# 编译检查 (不生成二进制)
|
||||
cargo check
|
||||
|
||||
# Clippy 代码质量检查
|
||||
cargo clippy
|
||||
|
||||
# Clippy 严格模式 (所有警告视为错误)
|
||||
cargo clippy -- -D warnings
|
||||
|
||||
# 代码格式化检查
|
||||
cargo fmt -- --check
|
||||
|
||||
# 自动格式化代码
|
||||
cargo fmt
|
||||
```
|
||||
|
||||
### 测试
|
||||
```bash
|
||||
# 运行所有测试
|
||||
cargo test
|
||||
|
||||
# 运行单个测试 (按名称过滤)
|
||||
cargo test test_function_name
|
||||
|
||||
# 运行特定模块的测试
|
||||
cargo test module_name::
|
||||
|
||||
# 显示测试输出 (包括 println!)
|
||||
cargo test -- --nocapture
|
||||
|
||||
# 运行单个测试并显示输出
|
||||
cargo test test_name -- --nocapture
|
||||
```
|
||||
|
||||
### 清理
|
||||
```bash
|
||||
# 清理构建产物
|
||||
cargo clean
|
||||
```
|
||||
|
||||
## 项目结构
|
||||
|
||||
```
|
||||
app-desktop/
|
||||
├── src/
|
||||
│ ├── main.rs # 入口文件 (仅调用 lib::run)
|
||||
│ ├── lib.rs # 核心应用逻辑 (注册插件、命令、状态)
|
||||
│ ├── commands/
|
||||
│ │ └── mod.rs # 原生桌面功能命令 (文件对话框、通知等)
|
||||
│ └── sidecar.rs # Sidecar 进程管理 (启动、端口扫描、清理)
|
||||
├── binaries/ # Sidecar 二进制文件
|
||||
│ └── app-* # Sidecar App 可执行文件 (示例: app)
|
||||
├── capabilities/ # Tauri v2 权限配置
|
||||
│ └── default.json
|
||||
├── icons/ # 应用图标资源
|
||||
├── gen/schemas/ # 自动生成的 Schema (不要手动编辑)
|
||||
├── Cargo.toml # Rust 项目配置
|
||||
├── tauri.conf.json # Tauri 应用配置
|
||||
├── build.rs # Rust 构建脚本
|
||||
└── mise.toml # 开发工具版本管理
|
||||
```
|
||||
|
||||
## Rust 代码风格指南
|
||||
|
||||
### 导入 (Imports)
|
||||
|
||||
- 使用标准库、外部 crate、当前 crate 的顺序,用空行分隔
|
||||
- 按字母顺序排列
|
||||
- 优先使用具体导入而非通配符 `*`
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use tauri::Manager;
|
||||
use tauri_plugin_shell::ShellExt;
|
||||
use tauri_plugin_shell::process::{CommandEvent, CommandChild};
|
||||
|
||||
// ❌ 避免
|
||||
use tauri::*;
|
||||
```
|
||||
|
||||
### 命名规范
|
||||
|
||||
- **函数和变量**: `snake_case`
|
||||
- **类型、结构体、枚举、Trait**: `PascalCase`
|
||||
- **常量和静态变量**: `SCREAMING_SNAKE_CASE`
|
||||
- **生命周期参数**: 简短小写字母,如 `'a`, `'b`
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
struct SidecarProcess(Mutex<Option<CommandChild>>);
|
||||
const DEFAULT_PORT: u16 = 3000;
|
||||
async fn find_available_port(start: u16) -> u16 { }
|
||||
|
||||
// ❌ 避免
|
||||
struct sidecar_process { }
|
||||
const defaultPort: u16 = 3000;
|
||||
```
|
||||
|
||||
### 类型注解
|
||||
|
||||
- 函数参数必须有类型注解
|
||||
- 函数返回值必须明确声明 (除非返回 `()`)
|
||||
- 优先使用具体类型而非 `impl Trait` (除非必要)
|
||||
- 使用 `&str` 而非 `String` 作为只读字符串参数
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
#[tauri::command]
|
||||
fn greet(name: &str) -> String {
|
||||
format!("Hello, {}!", name)
|
||||
}
|
||||
|
||||
async fn is_port_available(port: u16) -> bool {
|
||||
tokio::net::TcpListener::bind(format!("127.0.0.1:{}", port))
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
```
|
||||
|
||||
### 错误处理
|
||||
|
||||
- 使用 `Result<T, E>` 返回可能失败的操作
|
||||
- 使用 `expect()` 时提供有意义的错误消息 (中文)
|
||||
- 避免 `unwrap()` 在生产代码中,除非逻辑上保证不会 panic
|
||||
- 使用 `?` 操作符传播错误
|
||||
- 记录关键错误信息到控制台
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
let sidecar = app_handle
|
||||
.shell()
|
||||
.sidecar("app")
|
||||
.expect("无法找到 app sidecar");
|
||||
|
||||
let (mut rx, child) = sidecar.spawn().expect("启动 sidecar 失败");
|
||||
|
||||
// 日志记录
|
||||
eprintln!("✗ Sidecar App 启动失败");
|
||||
println!("✓ Sidecar App 启动成功!");
|
||||
|
||||
// ❌ 避免
|
||||
let data = read_file().unwrap(); // 无上下文信息
|
||||
```
|
||||
|
||||
### 异步代码
|
||||
|
||||
- 使用 `async/await` 而非手动创建 Future
|
||||
- Tauri 内部使用 `tauri::async_runtime::spawn` 启动异步任务
|
||||
- 使用 Tokio 的异步 API (如 `tokio::net::TcpListener`)
|
||||
- 避免阻塞异步运行时 (使用 `tokio::task::spawn_blocking`)
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
tauri::async_runtime::spawn(async move {
|
||||
let port = find_available_port(3000).await;
|
||||
// ...
|
||||
});
|
||||
```
|
||||
|
||||
### 格式化
|
||||
|
||||
- 使用 `cargo fmt` 自动格式化
|
||||
- 缩进: 4 空格
|
||||
- 行宽: 100 字符 (rustfmt 默认)
|
||||
- 结构体和枚举的字段每行一个 (如果超过一定长度)
|
||||
- 链式调用适当换行提高可读性
|
||||
|
||||
### 注释
|
||||
|
||||
- 使用中文注释说明复杂逻辑
|
||||
- 代码块前添加简短说明注释
|
||||
- 避免显而易见的注释
|
||||
|
||||
```rust
|
||||
// ✅ 推荐
|
||||
// 全局状态:存储 Sidecar App 进程句柄
|
||||
struct SidecarProcess(Mutex<Option<CommandChild>>);
|
||||
|
||||
// 检查端口是否可用
|
||||
async fn is_port_available(port: u16) -> bool { }
|
||||
```
|
||||
|
||||
## Tauri 特定规范
|
||||
|
||||
### 模块组织
|
||||
|
||||
- **`lib.rs`**: 主入口,负责注册插件、命令、状态管理
|
||||
- **`commands/mod.rs`**: 所有 Tauri 命令集中定义,命令必须是 `pub fn`
|
||||
- **`sidecar.rs`**: Sidecar 进程管理逻辑,导出公共 API(`spawn_sidecar`, `cleanup_sidecar_process`)
|
||||
|
||||
```rust
|
||||
// lib.rs - 模块声明
|
||||
mod commands;
|
||||
mod sidecar;
|
||||
|
||||
use sidecar::SidecarProcess;
|
||||
|
||||
// 注册命令时使用模块路径
|
||||
.invoke_handler(tauri::generate_handler![commands::greet])
|
||||
```
|
||||
|
||||
### 命令定义
|
||||
|
||||
- 使用 `#[tauri::command]` 宏标记命令
|
||||
- 命令函数必须是公开的或在 `invoke_handler` 中注册
|
||||
- 参数类型必须实现 `serde::Deserialize`
|
||||
- 返回类型必须实现 `serde::Serialize`
|
||||
|
||||
```rust
|
||||
#[tauri::command]
|
||||
fn greet(name: &str) -> String {
|
||||
format!("Hello, {}!", name)
|
||||
}
|
||||
|
||||
// 在 Builder 中注册
|
||||
.invoke_handler(tauri::generate_handler![greet])
|
||||
```
|
||||
|
||||
### 状态管理
|
||||
|
||||
- 使用 `app.manage()` 注册全局状态
|
||||
- 状态必须实现 `Send + Sync`
|
||||
- 使用 `Mutex` 或 `RwLock` 保证线程安全
|
||||
|
||||
```rust
|
||||
struct SidecarProcess(Mutex<Option<CommandChild>>);
|
||||
|
||||
// 注册状态
|
||||
app.manage(SidecarProcess(Mutex::new(None)));
|
||||
|
||||
// 访问状态
|
||||
if let Some(state) = app_handle.try_state::<SidecarProcess>() {
|
||||
*state.0.lock().unwrap() = Some(child);
|
||||
}
|
||||
```
|
||||
|
||||
### Sidecar 进程管理
|
||||
|
||||
- Sidecar 二进制必须在 `tauri.conf.json` 的 `bundle.externalBin` 中声明
|
||||
- 使用 `app.shell().sidecar()` 启动 sidecar
|
||||
- 在应用退出时清理子进程 (监听 `RunEvent::ExitRequested`)
|
||||
|
||||
```rust
|
||||
// 启动 sidecar
|
||||
let sidecar = app_handle
|
||||
.shell()
|
||||
.sidecar("app")
|
||||
.expect("无法找到 app sidecar")
|
||||
.env("PORT", port.to_string());
|
||||
|
||||
// 清理进程
|
||||
match event {
|
||||
tauri::RunEvent::ExitRequested { .. } | tauri::RunEvent::Exit => {
|
||||
if let Some(child) = process.take() {
|
||||
let _ = child.kill();
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
```
|
||||
|
||||
## 依赖管理
|
||||
|
||||
- 在 `Cargo.toml` 中明确声明依赖版本
|
||||
- 使用语义化版本 (如 `"2"` 表示兼容 2.x.x)
|
||||
- 仅启用需要的 feature 以减少编译时间和二进制大小
|
||||
|
||||
```toml
|
||||
tauri = { version = "2", features = [] }
|
||||
tauri-plugin-opener = "2"
|
||||
tauri-plugin-shell = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["net"] }
|
||||
```
|
||||
|
||||
## 开发工具
|
||||
|
||||
推荐安装以下 VSCode 扩展:
|
||||
- `tauri-apps.tauri-vscode` - Tauri 官方支持
|
||||
- `rust-lang.rust-analyzer` - Rust 语言服务器
|
||||
|
||||
## 最佳实践
|
||||
|
||||
1. **开发环境配置**:
|
||||
- 开发模式下需先启动前端开发服务器(`bun run dev`),再启动 Tauri(`tauri dev`)
|
||||
- 生产构建自动打包 sidecar 二进制,无需额外配置
|
||||
2. **进程生命周期**: 始终在应用退出时清理子进程和资源
|
||||
3. **端口管理**:
|
||||
- 开发模式固定使用 3000 端口(与开发服务器匹配)
|
||||
- 生产模式使用端口扫描避免硬编码端口冲突
|
||||
4. **超时处理**: 异步操作设置合理的超时时间 (如 5 秒)
|
||||
5. **日志**: 使用表情符号 (✓/✗/🔧/🚀) 和中文消息提供清晰的状态反馈
|
||||
6. **错误退出**: 关键错误时调用 `std::process::exit(1)`
|
||||
7. **窗口配置**: 使用 `WebviewWindowBuilder` 动态创建窗口
|
||||
|
||||
## 提交代码前检查清单
|
||||
|
||||
- [ ] `cargo fmt` 格式化通过
|
||||
- [ ] `cargo clippy` 无警告
|
||||
- [ ] `cargo check` 编译通过
|
||||
- [ ] `cargo test` 测试通过
|
||||
- [ ] 更新相关注释和文档
|
||||
- [ ] 检查是否有 `unwrap()` 需要替换为 `expect()`
|
||||
- [ ] 验证 Tauri 应用正常启动和退出
|
||||
@@ -0,0 +1,24 @@
|
||||
[package]
|
||||
name = "app-desktop"
|
||||
version = "0.1.0"
|
||||
description = "A Tauri App"
|
||||
authors = ["imbytecat"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[lib]
|
||||
# The `_lib` suffix may seem redundant but it is necessary
|
||||
# to make the lib name unique and wouldn't conflict with the bin name.
|
||||
# This seems to be only an issue on Windows, see https://github.com/rust-lang/cargo/issues/8519
|
||||
name = "app_desktop_lib"
|
||||
crate-type = ["staticlib", "cdylib", "rlib"]
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2", features = [] }
|
||||
tauri-plugin-shell = "2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
tokio = { version = "1", features = ["net"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Capability for the main window",
|
||||
"windows": ["main"],
|
||||
"local": true,
|
||||
"remote": {
|
||||
"urls": [
|
||||
"http://localhost:*",
|
||||
"http://127.0.0.1:*",
|
||||
"http{s}?://localhost(:\\d+)?/*"
|
||||
]
|
||||
},
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"core:window:allow-set-title",
|
||||
{
|
||||
"identifier": "shell:allow-execute",
|
||||
"allow": [
|
||||
{
|
||||
"name": "binaries/app",
|
||||
"sidecar": true
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
|
After Width: | Height: | Size: 3.4 KiB |
|
After Width: | Height: | Size: 6.8 KiB |
|
After Width: | Height: | Size: 974 B |
|
After Width: | Height: | Size: 2.8 KiB |
|
After Width: | Height: | Size: 3.8 KiB |
|
After Width: | Height: | Size: 3.9 KiB |
|
After Width: | Height: | Size: 7.6 KiB |
|
After Width: | Height: | Size: 903 B |
|
After Width: | Height: | Size: 8.4 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 2.0 KiB |
|
After Width: | Height: | Size: 2.4 KiB |
|
After Width: | Height: | Size: 1.5 KiB |
|
After Width: | Height: | Size: 85 KiB |
|
After Width: | Height: | Size: 14 KiB |
@@ -0,0 +1,8 @@
|
||||
// 原生桌面功能命令
|
||||
// 未来可能包含: 文件对话框、系统通知、剪贴板等
|
||||
|
||||
// 示例命令 (可根据需要删除或替换)
|
||||
#[tauri::command]
|
||||
pub fn greet(name: &str) -> String {
|
||||
format!("Hello, {}! You've been greeted from Rust!", name)
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
use tauri::Manager;
|
||||
|
||||
// 模块声明
|
||||
mod commands;
|
||||
mod sidecar;
|
||||
|
||||
use sidecar::SidecarProcess;
|
||||
|
||||
#[cfg_attr(mobile, tauri::mobile_entry_point)]
|
||||
pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_shell::init())
|
||||
.setup(|app| {
|
||||
// 注册全局状态
|
||||
app.manage(SidecarProcess(std::sync::Mutex::new(None)));
|
||||
|
||||
// 启动 Sidecar 进程
|
||||
let app_handle = app.handle().clone();
|
||||
sidecar::spawn_sidecar(app_handle);
|
||||
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![commands::greet])
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building tauri application")
|
||||
.run(|app_handle, event| {
|
||||
// 监听应用退出事件,清理 Sidecar 进程
|
||||
if let tauri::RunEvent::Exit = event {
|
||||
// 只在 Exit 事件时清理,避免重复执行
|
||||
sidecar::cleanup_sidecar_process(app_handle);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
// Prevents additional console window on Windows in release, DO NOT REMOVE!!
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
fn main() {
|
||||
app_desktop_lib::run()
|
||||
}
|
||||
@@ -0,0 +1,166 @@
|
||||
use std::sync::Mutex;
|
||||
use std::time::Duration;
|
||||
|
||||
use tauri::Manager;
|
||||
use tauri_plugin_shell::process::{CommandChild, CommandEvent};
|
||||
use tauri_plugin_shell::ShellExt;
|
||||
|
||||
// ===== 配置常量 =====
|
||||
|
||||
/// Sidecar App 启动超时时间(秒)
|
||||
const STARTUP_TIMEOUT_SECS: u64 = 5;
|
||||
|
||||
/// 默认起始端口
|
||||
const DEFAULT_PORT: u16 = 3000;
|
||||
|
||||
/// 端口扫描范围(从起始端口开始扫描的端口数量)
|
||||
const PORT_SCAN_RANGE: u16 = 100;
|
||||
|
||||
/// 窗口默认宽度
|
||||
const DEFAULT_WINDOW_WIDTH: f64 = 1200.0;
|
||||
|
||||
/// 窗口默认高度
|
||||
const DEFAULT_WINDOW_HEIGHT: f64 = 800.0;
|
||||
|
||||
/// 窗口标题
|
||||
const WINDOW_TITLE: &str = "Tauri App";
|
||||
|
||||
// ===== 数据结构 =====
|
||||
|
||||
/// 全局状态:存储 Sidecar 进程句柄
|
||||
pub struct SidecarProcess(pub Mutex<Option<CommandChild>>);
|
||||
|
||||
// 检查端口是否可用(未被占用)
|
||||
async fn is_port_available(port: u16) -> bool {
|
||||
tokio::net::TcpListener::bind(format!("127.0.0.1:{}", port))
|
||||
.await
|
||||
.is_ok()
|
||||
}
|
||||
|
||||
// 查找可用端口
|
||||
async fn find_available_port(start: u16) -> u16 {
|
||||
for port in start..start + PORT_SCAN_RANGE {
|
||||
if is_port_available(port).await {
|
||||
return port;
|
||||
}
|
||||
}
|
||||
start // 回退到起始端口
|
||||
}
|
||||
|
||||
/// 启动 Sidecar 进程并创建主窗口
|
||||
pub fn spawn_sidecar(app_handle: tauri::AppHandle) {
|
||||
// 检测是否为开发模式
|
||||
let is_dev = cfg!(debug_assertions);
|
||||
|
||||
if is_dev {
|
||||
// 开发模式:直接创建窗口连接到 Vite 开发服务器
|
||||
println!("🔧 开发模式");
|
||||
|
||||
match tauri::WebviewWindowBuilder::new(
|
||||
&app_handle,
|
||||
"main",
|
||||
tauri::WebviewUrl::External("http://localhost:3000".parse().unwrap()),
|
||||
)
|
||||
.title(WINDOW_TITLE)
|
||||
.inner_size(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT)
|
||||
.center()
|
||||
.build()
|
||||
{
|
||||
Ok(_) => println!("✓ 开发窗口创建成功"),
|
||||
Err(e) => {
|
||||
eprintln!("✗ 窗口创建失败: {}", e);
|
||||
}
|
||||
}
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
// 生产模式:启动 sidecar 二进制
|
||||
tauri::async_runtime::spawn(async move {
|
||||
println!("🚀 生产模式");
|
||||
|
||||
// 查找可用端口
|
||||
let port = find_available_port(DEFAULT_PORT).await;
|
||||
println!("使用端口: {}", port);
|
||||
|
||||
// 启动 sidecar
|
||||
let sidecar = app_handle
|
||||
.shell()
|
||||
.sidecar("app")
|
||||
.expect("无法找到 app")
|
||||
.env("PORT", port.to_string());
|
||||
|
||||
let (mut rx, child) = sidecar.spawn().expect("启动 sidecar 失败");
|
||||
|
||||
// 保存进程句柄到全局状态
|
||||
if let Some(state) = app_handle.try_state::<SidecarProcess>() {
|
||||
*state.0.lock().unwrap() = Some(child);
|
||||
}
|
||||
|
||||
// 监听 stdout,等待服务器就绪信号
|
||||
let start_time = std::time::Instant::now();
|
||||
let timeout = Duration::from_secs(STARTUP_TIMEOUT_SECS);
|
||||
let mut app_ready = false;
|
||||
|
||||
while let Some(event) = rx.recv().await {
|
||||
if let CommandEvent::Stdout(line) = event {
|
||||
let output = String::from_utf8_lossy(&line);
|
||||
println!("App: {}", output);
|
||||
|
||||
// 检测 App 启动成功的标志
|
||||
if output.contains("Listening on:") || output.contains("localhost") {
|
||||
app_ready = true;
|
||||
println!("✓ App 启动成功!");
|
||||
|
||||
// 创建主窗口
|
||||
let url = format!("http://localhost:{}", port);
|
||||
tauri::WebviewWindowBuilder::new(
|
||||
&app_handle,
|
||||
"main",
|
||||
tauri::WebviewUrl::External(url.parse().unwrap()),
|
||||
)
|
||||
.title(WINDOW_TITLE)
|
||||
.inner_size(DEFAULT_WINDOW_WIDTH, DEFAULT_WINDOW_HEIGHT)
|
||||
.center()
|
||||
.build()
|
||||
.expect("创建窗口失败");
|
||||
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// 超时检查
|
||||
if start_time.elapsed() > timeout {
|
||||
eprintln!("✗ 启动超时: App 未能在 {} 秒内启动", STARTUP_TIMEOUT_SECS);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if !app_ready {
|
||||
eprintln!("✗ App 启动失败");
|
||||
std::process::exit(1);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// 清理 Sidecar 进程 (在应用退出时调用)
|
||||
pub fn cleanup_sidecar_process(app_handle: &tauri::AppHandle) {
|
||||
let is_dev = cfg!(debug_assertions);
|
||||
|
||||
if is_dev {
|
||||
// 开发模式:退出时发送异常信号(exit 1),让 Turbo 停止 Vite 服务器
|
||||
println!("🔧 开发模式退出,终止所有依赖任务...");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
// 生产模式:正常清理 sidecar 进程
|
||||
println!("应用退出,正在清理 Sidecar 进程...");
|
||||
if let Some(state) = app_handle.try_state::<SidecarProcess>() {
|
||||
if let Ok(mut process) = state.0.lock() {
|
||||
if let Some(child) = process.take() {
|
||||
let _ = child.kill();
|
||||
println!("✓ Sidecar 进程已终止");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "app-desktop",
|
||||
"version": "0.1.0",
|
||||
"identifier": "com.imbytecat.app-desktop",
|
||||
"app": {
|
||||
"withGlobalTauri": true,
|
||||
"windows": [],
|
||||
"security": {
|
||||
"csp": null
|
||||
}
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/128x128@2x.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
],
|
||||
"externalBin": ["binaries/app"]
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
import { defineCommand, runMain } from 'citty'
|
||||
import { name, version } from '#package'
|
||||
|
||||
// IMPORTANT: keep this file's static imports minimal. Nitro's bun preset
|
||||
// emits `.output/server/index.mjs` with a top-level `serve(...)` call, so any
|
||||
// eager (transitive) import of it would start the HTTP server even for
|
||||
// `--help`. All subcommands are lazy-loaded via citty.
|
||||
const main = defineCommand({
|
||||
meta: {
|
||||
name,
|
||||
version,
|
||||
description: 'Fullstack server binary (default subcommand: serve)',
|
||||
},
|
||||
default: 'serve',
|
||||
subCommands: {
|
||||
serve: () => import('@/cli/serve').then((m) => m.default),
|
||||
},
|
||||
})
|
||||
|
||||
runMain(main)
|
||||
@@ -1 +0,0 @@
|
||||
export default function startNitroServer(): Promise<void>
|
||||
@@ -1,3 +0,0 @@
|
||||
export default async function startNitroServer() {
|
||||
await import('#server')
|
||||
}
|
||||
@@ -1,12 +0,0 @@
|
||||
import { defineCommand } from 'citty'
|
||||
|
||||
export default defineCommand({
|
||||
meta: {
|
||||
name: 'serve',
|
||||
description: 'Start the HTTP server',
|
||||
},
|
||||
async run() {
|
||||
const { default: startNitroServer } = await import('./_serve-nitro.mjs')
|
||||
await startNitroServer()
|
||||
},
|
||||
})
|
||||
@@ -1,27 +0,0 @@
|
||||
import { createORPCClient } from '@orpc/client'
|
||||
import { RPCLink } from '@orpc/client/fetch'
|
||||
import { createRouterClient } from '@orpc/server'
|
||||
import { createTanstackQueryUtils } from '@orpc/tanstack-query'
|
||||
import { createIsomorphicFn } from '@tanstack/react-start'
|
||||
import { getRequestHeaders } from '@tanstack/react-start/server'
|
||||
import { router } from '@/server/api/routers'
|
||||
import type { RouterClient } from '@/server/api/types'
|
||||
|
||||
const getORPCClient = createIsomorphicFn()
|
||||
.server(() =>
|
||||
createRouterClient(router, {
|
||||
context: () => ({
|
||||
headers: getRequestHeaders(),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
.client(() => {
|
||||
const link = new RPCLink({
|
||||
url: `${window.location.origin}/api/rpc`,
|
||||
})
|
||||
return createORPCClient<RouterClient>(link)
|
||||
})
|
||||
|
||||
const client: RouterClient = getORPCClient()
|
||||
|
||||
export const orpc = createTanstackQueryUtils(client)
|
||||
@@ -1,40 +1,3 @@
|
||||
export const ErrorComponent = ({ error, reset }: { error: Error; reset: () => void }) => {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50 px-4">
|
||||
<div className="max-w-md w-full text-center space-y-6">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-red-100">
|
||||
<svg
|
||||
className="w-8 h-8 text-red-500"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M12 9v3.75m9-.75a9 9 0 11-18 0 9 9 0 0118 0zm-9 3.75h.008v.008H12v-.008z"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900">出错了</h1>
|
||||
<p className="text-slate-500 mt-2">{import.meta.env.DEV ? error.message : '请求失败,请稍后重试'}</p>
|
||||
</div>
|
||||
<div className="flex items-center justify-center gap-4">
|
||||
<button
|
||||
type="button"
|
||||
onClick={reset}
|
||||
className="px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-colors"
|
||||
>
|
||||
重试
|
||||
</button>
|
||||
<a href="/" className="px-6 py-2.5 text-slate-600 hover:text-slate-900 font-medium transition-colors">
|
||||
返回首页
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
export function ErrorComponent() {
|
||||
return <div>An unhandled error happened!</div>
|
||||
}
|
||||
|
||||
@@ -1,23 +1,3 @@
|
||||
import { Link } from '@tanstack/react-router'
|
||||
|
||||
export const NotFoundComponent = () => {
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-slate-50 px-4">
|
||||
<div className="max-w-md w-full text-center space-y-6">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-100">
|
||||
<span className="text-3xl font-bold text-slate-400">404</span>
|
||||
</div>
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-slate-900">页面不存在</h1>
|
||||
<p className="text-slate-500 mt-2">您访问的页面可能已被移除或地址有误</p>
|
||||
</div>
|
||||
<Link
|
||||
to="/"
|
||||
className="inline-block px-6 py-2.5 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-colors"
|
||||
>
|
||||
返回首页
|
||||
</Link>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
export function NotFoundComponent() {
|
||||
return <div>404 - Not Found</div>
|
||||
}
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -1,181 +0,0 @@
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { drizzle } from 'drizzle-orm/postgres-js'
|
||||
import * as schema from '@/db/schema'
|
||||
import { env } from '@/env'
|
||||
|
||||
export function createDb() {
|
||||
return drizzle({
|
||||
connection: {
|
||||
url: env.DATABASE_URL,
|
||||
prepare: true,
|
||||
},
|
||||
schema,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './todo'
|
||||
@@ -0,0 +1,15 @@
|
||||
import { sql } from 'drizzle-orm'
|
||||
import { boolean, pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core'
|
||||
|
||||
export const todoTable = pgTable('todo', {
|
||||
id: uuid('id').primaryKey().default(sql`uuidv7()`),
|
||||
title: text('title').notNull(),
|
||||
completed: boolean('completed').notNull().default(false),
|
||||
createdAt: timestamp('created_at', { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||
.notNull()
|
||||
.defaultNow()
|
||||
.$onUpdateFn(() => new Date()),
|
||||
})
|
||||
@@ -1,63 +0,0 @@
|
||||
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
|
||||
@@ -1,151 +0,0 @@
|
||||
import { describe, expect, test } from 'bun:test'
|
||||
import {
|
||||
createBatteriesResponse,
|
||||
createDashboardSnapshot,
|
||||
DEVICE_STATUS,
|
||||
fromMysqlBoolean,
|
||||
getDeviceStatus,
|
||||
MYSQL_BOOLEAN,
|
||||
POWER_STATUS,
|
||||
toBatteryInfo,
|
||||
} from './battery'
|
||||
|
||||
const rows = [
|
||||
{
|
||||
id: 1,
|
||||
userId: 7,
|
||||
mac: 'RING-A03',
|
||||
devModel: '2401-A',
|
||||
devName: 'RING-A03',
|
||||
isLowPower: MYSQL_BOOLEAN.FALSE,
|
||||
powerStatus: POWER_STATUS.FULL,
|
||||
power: 94,
|
||||
createTime: new Date('2026-05-10T23:00:00.000Z'),
|
||||
remark: 'v3.8.2',
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
userId: 7,
|
||||
mac: 'RING-B11',
|
||||
devModel: '2402-B',
|
||||
devName: '',
|
||||
isLowPower: MYSQL_BOOLEAN.TRUE,
|
||||
powerStatus: POWER_STATUS.CHARGING,
|
||||
power: 84,
|
||||
createTime: '2026-05-10 22:00:00',
|
||||
remark: null,
|
||||
},
|
||||
]
|
||||
|
||||
describe('battery domain', () => {
|
||||
test('preserves legacy SOH status thresholds', () => {
|
||||
expect(getDeviceStatus(91)).toBe(DEVICE_STATUS.HEALTHY)
|
||||
expect(getDeviceStatus(90)).toBe(DEVICE_STATUS.WATCH)
|
||||
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)
|
||||
const response = createBatteriesResponse(items, now)
|
||||
|
||||
expect(response.updatedAt).toBe('2026-05-11T00:00:00.000Z')
|
||||
expect(response.total).toBe(items.length)
|
||||
expect(response.lowPower).toBe(1)
|
||||
expect(response.charging).toBe(1)
|
||||
expect(response.nextCursor).toBeNull()
|
||||
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 === 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.avgSoh).toBeNull()
|
||||
expect(snapshot.summary.avgSoh30d).toBeNull()
|
||||
expect(snapshot.summary.avgSoh90d).toBeNull()
|
||||
expect(snapshot.summary.warningCount + snapshot.summary.watchCount + snapshot.summary.healthyCount).toBe(
|
||||
snapshot.devices.length,
|
||||
)
|
||||
})
|
||||
|
||||
test('uses AI prediction values when available', () => {
|
||||
const now = new Date('2026-05-11T00:00:00.000Z')
|
||||
const items = rows.map(toBatteryInfo)
|
||||
const snapshot = createDashboardSnapshot(
|
||||
items,
|
||||
now,
|
||||
new Map([
|
||||
[
|
||||
'RING-A03',
|
||||
{
|
||||
mac: 'RING-A03',
|
||||
nowSoh: 60,
|
||||
monthSoh: 58,
|
||||
trmonthSoh: 52,
|
||||
riskScore: 40,
|
||||
riskLevel: 'high',
|
||||
status: '危险',
|
||||
modelName: 'XGBoost',
|
||||
cyclesUsed: 6,
|
||||
updatedAt: '2026-05-11T00:00:00.000Z',
|
||||
},
|
||||
],
|
||||
]),
|
||||
)
|
||||
const predicted = snapshot.devices.find((device) => device.id === 'RING-A03')
|
||||
|
||||
expect(predicted?.soh).toBe(60)
|
||||
expect(predicted?.sohSource).toBe('prediction')
|
||||
expect(predicted?.soh30d).toBe(58)
|
||||
expect(predicted?.soh90d).toBe(52)
|
||||
expect(predicted?.soh60d).toBeNull()
|
||||
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 })
|
||||
})
|
||||
})
|
||||
@@ -1,475 +0,0 @@
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
DEVICE_STATUS,
|
||||
type DeviceStatus,
|
||||
EVENT_SEVERITY,
|
||||
fromMysqlBoolean,
|
||||
POWER_STATUS,
|
||||
type PowerStatus,
|
||||
SOH_THRESHOLDS,
|
||||
} from './battery.constants'
|
||||
|
||||
export {
|
||||
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 powerStatusSchema = z.union([
|
||||
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({
|
||||
id: z.number().int(),
|
||||
userId: z.number().int(),
|
||||
mac: z.string(),
|
||||
devModel: z.string(),
|
||||
devName: z.string(),
|
||||
isLowPower: z.boolean(),
|
||||
powerStatus: powerStatusSchema,
|
||||
power: z.number().int().min(0).max(100),
|
||||
createTime: z.string(),
|
||||
remark: z.string().nullable(),
|
||||
})
|
||||
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().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().nullable(),
|
||||
riskScore: z.number().int(),
|
||||
chargeEfficiency: z.number().nullable(),
|
||||
status: deviceStatusSchema,
|
||||
riskFactors: z.array(z.string()),
|
||||
})
|
||||
export type FleetUnit = z.infer<typeof fleetUnitSchema>
|
||||
|
||||
export const sohPointSchema = z.object({ month: z.string(), value: z.number() })
|
||||
export const sohResponseSchema = z.object({
|
||||
history: z.array(sohPointSchema),
|
||||
forecast: z.array(sohPointSchema),
|
||||
})
|
||||
|
||||
export const eventItemSchema = z.object({
|
||||
time: z.string(),
|
||||
title: z.string(),
|
||||
detail: z.string(),
|
||||
severity: z.union([z.literal(EVENT_SEVERITY.HIGH), z.literal(EVENT_SEVERITY.MEDIUM), z.literal(EVENT_SEVERITY.LOW)]),
|
||||
})
|
||||
|
||||
export const strategyItemSchema = z.object({
|
||||
name: z.string(),
|
||||
impact: z.string(),
|
||||
scope: z.string(),
|
||||
eta: z.string(),
|
||||
})
|
||||
|
||||
export const summaryResponseSchema = z.object({
|
||||
totalDevices: z.number().int(),
|
||||
avgSoh: z.number().nullable(),
|
||||
avgSoh30d: z.number().nullable(),
|
||||
avgSoh90d: z.number().nullable(),
|
||||
warningCount: z.number().int(),
|
||||
watchCount: z.number().int(),
|
||||
healthyCount: z.number().int(),
|
||||
batchPerformance: z.array(z.object({ batch: z.string(), avgSoh: z.number().nullable() })),
|
||||
riskFactorCounts: z.array(z.object({ factor: z.string(), count: z.number().int() })),
|
||||
firmwareHealth: z.array(z.object({ firmware: z.string(), avgSoh: z.number().nullable(), count: z.number().int() })),
|
||||
updatedAt: z.string(),
|
||||
executiveSummary: z.string(),
|
||||
})
|
||||
|
||||
export const dashboardSnapshotSchema = z.object({
|
||||
devices: z.array(fleetUnitSchema),
|
||||
soh: sohResponseSchema,
|
||||
events: z.array(eventItemSchema),
|
||||
strategies: z.array(strategyItemSchema),
|
||||
summary: summaryResponseSchema,
|
||||
})
|
||||
export type DashboardSnapshot = z.infer<typeof dashboardSnapshotSchema>
|
||||
|
||||
export const batteriesResponseSchema = z.object({
|
||||
updatedAt: z.string(),
|
||||
total: z.number().int(),
|
||||
lowPower: z.number().int(),
|
||||
charging: z.number().int(),
|
||||
items: z.array(batteryInfoSchema),
|
||||
nextCursor: z.string().nullable(),
|
||||
})
|
||||
export type BatteriesResponse = z.infer<typeof batteriesResponseSchema>
|
||||
|
||||
export type BatteriesPageSummary = {
|
||||
total?: number
|
||||
lowPower?: number
|
||||
charging?: number
|
||||
}
|
||||
|
||||
export type BatteryPrediction = {
|
||||
mac: string
|
||||
nowSoh: number
|
||||
monthSoh: number
|
||||
trmonthSoh: number
|
||||
riskScore: number | null
|
||||
riskLevel: string | null
|
||||
status: string | null
|
||||
modelName: string | null
|
||||
cyclesUsed: number | null
|
||||
updatedAt: string | null
|
||||
}
|
||||
|
||||
const round1 = (value: number) => Math.round(value * 10) / 10
|
||||
|
||||
const clamp = (value: number, min: number, max: number) => Math.min(max, Math.max(min, value))
|
||||
|
||||
const pad2 = (value: number) => value.toString().padStart(2, '0')
|
||||
|
||||
const formatDateTime = (date: Date) =>
|
||||
`${date.getFullYear()}-${pad2(date.getMonth() + 1)}-${pad2(date.getDate())} ${pad2(date.getHours())}:${pad2(date.getMinutes())}:${pad2(date.getSeconds())}`
|
||||
|
||||
export function getDeviceStatus(soh: number): DeviceStatus {
|
||||
if (soh <= SOH_THRESHOLDS.WARNING) return DEVICE_STATUS.WARNING
|
||||
if (soh <= SOH_THRESHOLDS.WATCH) return DEVICE_STATUS.WATCH
|
||||
return DEVICE_STATUS.HEALTHY
|
||||
}
|
||||
|
||||
function getDeviceStatusByRisk(prediction: BatteryPrediction): DeviceStatus {
|
||||
const riskText = `${prediction.riskLevel ?? ''} ${prediction.status ?? ''}`.toLowerCase()
|
||||
|
||||
if (
|
||||
riskText.includes('high') ||
|
||||
riskText.includes('danger') ||
|
||||
riskText.includes('危险') ||
|
||||
riskText.includes('高')
|
||||
) {
|
||||
return DEVICE_STATUS.WARNING
|
||||
}
|
||||
if (
|
||||
riskText.includes('medium') ||
|
||||
riskText.includes('warning') ||
|
||||
riskText.includes('关注') ||
|
||||
riskText.includes('中')
|
||||
) {
|
||||
return DEVICE_STATUS.WATCH
|
||||
}
|
||||
|
||||
if (prediction.riskScore !== null) {
|
||||
if (prediction.riskScore >= SOH_THRESHOLDS.HIGH_RISK_SCORE) return DEVICE_STATUS.WARNING
|
||||
if (prediction.riskScore >= SOH_THRESHOLDS.WATCH_RISK_SCORE) return DEVICE_STATUS.WATCH
|
||||
}
|
||||
|
||||
return getDeviceStatus(prediction.nowSoh)
|
||||
}
|
||||
|
||||
export function normalizePowerStatus(value: number): PowerStatus {
|
||||
if (value === POWER_STATUS.CHARGING || value === POWER_STATUS.FULL) return value
|
||||
return POWER_STATUS.NOT_CHARGING
|
||||
}
|
||||
|
||||
export function normalizeLowPower(value: string | boolean): boolean {
|
||||
return fromMysqlBoolean(value)
|
||||
}
|
||||
|
||||
export type BatteryInfoSourceRow = {
|
||||
id: number
|
||||
userId: number
|
||||
mac: string
|
||||
devModel: string
|
||||
devName: string
|
||||
isLowPower: string | boolean
|
||||
powerStatus: number
|
||||
power: number
|
||||
createTime: Date | string
|
||||
remark: string | null
|
||||
}
|
||||
|
||||
export function toBatteryInfo(row: BatteryInfoSourceRow): BatteryInfo {
|
||||
return {
|
||||
id: row.id,
|
||||
userId: row.userId,
|
||||
mac: row.mac,
|
||||
devModel: row.devModel,
|
||||
devName: row.devName,
|
||||
isLowPower: normalizeLowPower(row.isLowPower),
|
||||
powerStatus: normalizePowerStatus(row.powerStatus),
|
||||
power: row.power,
|
||||
createTime: row.createTime instanceof Date ? row.createTime.toISOString() : String(row.createTime),
|
||||
remark: row.remark,
|
||||
}
|
||||
}
|
||||
|
||||
export function createBatteriesResponse(
|
||||
items: BatteryInfo[],
|
||||
now = new Date(),
|
||||
summary: BatteriesPageSummary = {},
|
||||
nextCursor: string | null = null,
|
||||
): BatteriesResponse {
|
||||
return {
|
||||
updatedAt: now.toISOString(),
|
||||
total: summary.total ?? items.length,
|
||||
lowPower: summary.lowPower ?? items.filter((item) => item.isLowPower).length,
|
||||
charging: summary.charging ?? items.filter((item) => item.powerStatus === POWER_STATUS.CHARGING).length,
|
||||
items,
|
||||
nextCursor,
|
||||
}
|
||||
}
|
||||
|
||||
function toFleetUnit(item: BatteryInfo, prediction?: BatteryPrediction): FleetUnit {
|
||||
const hasPrediction = Boolean(prediction)
|
||||
const soh = prediction ? round1(clamp(prediction.nowSoh, 0, 100)) : null
|
||||
const status = prediction
|
||||
? getDeviceStatusByRisk(prediction)
|
||||
: item.isLowPower || item.power <= SOH_THRESHOLDS.LOW_POWER
|
||||
? DEVICE_STATUS.WATCH
|
||||
: DEVICE_STATUS.HEALTHY
|
||||
const riskFactors: string[] = []
|
||||
|
||||
if (item.isLowPower || item.power <= SOH_THRESHOLDS.LOW_POWER) riskFactors.push('低电量')
|
||||
if (item.powerStatus === POWER_STATUS.CHARGING) riskFactors.push('充电中')
|
||||
if (!hasPrediction) riskFactors.push('健康预测不可用')
|
||||
if (prediction && status === DEVICE_STATUS.WARNING) riskFactors.push('衰减加速')
|
||||
if (item.remark?.includes('v3.7')) riskFactors.push('旧固件')
|
||||
if (prediction?.riskLevel) riskFactors.push(`预测风险:${prediction.riskLevel}`)
|
||||
|
||||
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 = 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.mac,
|
||||
displayName: item.devName || item.mac,
|
||||
batch: item.devModel,
|
||||
firmware: item.remark ?? '未提供',
|
||||
cycles: prediction?.cyclesUsed ?? null,
|
||||
soh,
|
||||
sohSource: prediction ? 'prediction' : 'unavailable',
|
||||
soh30d,
|
||||
soh60d,
|
||||
soh90d,
|
||||
temperature,
|
||||
riskScore,
|
||||
chargeEfficiency,
|
||||
status,
|
||||
riskFactors,
|
||||
}
|
||||
}
|
||||
|
||||
function createSohResponse(devices: FleetUnit[]) {
|
||||
const predictedDevices = devices.filter((unit) => unit.soh !== null)
|
||||
if (predictedDevices.length === 0) return { history: [], forecast: [] }
|
||||
|
||||
const avgNow = averageNullable(predictedDevices.map((unit) => unit.soh))
|
||||
const avgMonth = averageNullable(predictedDevices.map((unit) => unit.soh30d))
|
||||
const avgTrmonth = averageNullable(predictedDevices.map((unit) => unit.soh90d))
|
||||
|
||||
const forecast = [
|
||||
avgNow === null ? null : { month: '当前', value: round1(clamp(avgNow, 0, 100)) },
|
||||
avgMonth === null ? null : { month: '30天', value: round1(clamp(avgMonth, 0, 100)) },
|
||||
avgTrmonth === null ? null : { month: '90天', value: round1(clamp(avgTrmonth, 0, 100)) },
|
||||
].filter((point): point is { month: string; value: number } => point !== null)
|
||||
|
||||
return {
|
||||
history: [],
|
||||
forecast,
|
||||
}
|
||||
}
|
||||
|
||||
function summarizeBy<T extends string>(items: FleetUnit[], getKey: (item: FleetUnit) => T) {
|
||||
return Object.entries(
|
||||
items.reduce<Record<string, { sum: number; valueCount: number; count: number }>>((acc, item) => {
|
||||
const key = getKey(item)
|
||||
const entry = acc[key] ?? { sum: 0, valueCount: 0, count: 0 }
|
||||
if (item.soh !== null) {
|
||||
entry.sum += item.soh
|
||||
entry.valueCount += 1
|
||||
}
|
||||
entry.count += 1
|
||||
acc[key] = entry
|
||||
return acc
|
||||
}, {}),
|
||||
)
|
||||
}
|
||||
|
||||
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) {
|
||||
const totalDevices = devices.length
|
||||
|
||||
if (totalDevices === 0) {
|
||||
return {
|
||||
totalDevices,
|
||||
avgSoh: null,
|
||||
avgSoh30d: null,
|
||||
avgSoh90d: null,
|
||||
warningCount: 0,
|
||||
watchCount: 0,
|
||||
healthyCount: 0,
|
||||
batchPerformance: [],
|
||||
riskFactorCounts: [],
|
||||
firmwareHealth: [],
|
||||
updatedAt: formatDateTime(now),
|
||||
executiveSummary: '当前没有可用于电池健康分析的真实设备记录。',
|
||||
}
|
||||
}
|
||||
|
||||
const avgSoh = averageNullable(devices.map((unit) => unit.soh))
|
||||
const avgSoh30d = averageNullable(devices.map((unit) => unit.soh30d))
|
||||
const avgSoh90d = averageNullable(devices.map((unit) => unit.soh90d))
|
||||
const warningCount = devices.filter((unit) => unit.status === DEVICE_STATUS.WARNING).length
|
||||
const watchCount = devices.filter((unit) => unit.status === DEVICE_STATUS.WATCH).length
|
||||
const healthyCount = devices.filter((unit) => unit.status === DEVICE_STATUS.HEALTHY).length
|
||||
const batchPerformance = summarizeBy(devices, (unit) => unit.batch)
|
||||
.map(([batch, data]) => ({ batch, avgSoh: data.valueCount > 0 ? round1(data.sum / data.valueCount) : null }))
|
||||
.sort((a, b) => (b.avgSoh ?? -1) - (a.avgSoh ?? -1))
|
||||
const firmwareHealth = summarizeBy(devices, (unit) => unit.firmware)
|
||||
.map(([firmware, data]) => ({
|
||||
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(
|
||||
devices.reduce<Record<string, number>>((acc, unit) => {
|
||||
for (const factor of unit.riskFactors) {
|
||||
acc[factor] = (acc[factor] ?? 0) + 1
|
||||
}
|
||||
return acc
|
||||
}, {}),
|
||||
)
|
||||
.map(([factor, count]) => ({ factor, count }))
|
||||
.sort((a, b) => b.count - a.count)
|
||||
const weakestModel = batchPerformance.at(-1)?.batch ?? '当前设备型号'
|
||||
const weakestRemark = firmwareHealth.at(-1)?.firmware ?? '未提供备注'
|
||||
const predictedDevices = devices.filter((unit) => unit.soh !== null).length
|
||||
const missingPredictionDevices = totalDevices - predictedDevices
|
||||
|
||||
return {
|
||||
totalDevices,
|
||||
avgSoh: avgSoh === null ? null : round1(avgSoh),
|
||||
avgSoh30d: avgSoh30d === null ? null : round1(avgSoh30d),
|
||||
avgSoh90d: avgSoh90d === null ? null : round1(avgSoh90d),
|
||||
warningCount,
|
||||
watchCount,
|
||||
healthyCount,
|
||||
batchPerformance,
|
||||
riskFactorCounts,
|
||||
firmwareHealth,
|
||||
updatedAt: formatDateTime(now),
|
||||
executiveSummary:
|
||||
avgSoh === null
|
||||
? '当前健康预测暂不可用,系统仍会展示设备电量、充电状态与低电量风险。请稍后复查或联系管理员。'
|
||||
: `当前共有 ${predictedDevices} 台设备具备健康预测,${missingPredictionDevices} 台设备暂无预测结果。建议重点关注 ${weakestModel} 型号与 ${weakestRemark} 备注设备,优先处理低电量和充电中的设备,并在下次同步后复查未来 30/90 天健康趋势。`,
|
||||
}
|
||||
}
|
||||
|
||||
function createEvents(devices: FleetUnit[], now: Date) {
|
||||
if (devices.length === 0) return []
|
||||
|
||||
const predictedDevices = devices.filter((unit) => unit.soh !== null)
|
||||
const warningDevices = devices.filter((unit) => unit.status === DEVICE_STATUS.WARNING)
|
||||
const missingPredictionDevices = devices.length - predictedDevices.length
|
||||
|
||||
return [
|
||||
{
|
||||
time: formatDateTime(now),
|
||||
title: '风险快照',
|
||||
detail: `本次概览包含 ${devices.length} 台设备,其中 ${predictedDevices.length} 台具备健康预测,${warningDevices.length} 台处于预警状态。`,
|
||||
severity: warningDevices.length > 0 ? EVENT_SEVERITY.HIGH : EVENT_SEVERITY.LOW,
|
||||
},
|
||||
{
|
||||
time: formatDateTime(now),
|
||||
title: '预测可用性快照',
|
||||
detail:
|
||||
missingPredictionDevices > 0
|
||||
? `当前有 ${missingPredictionDevices} 台设备暂无健康预测,相关趋势将暂不展示。`
|
||||
: '当前所有设备均已具备健康预测,可继续观察趋势变化。',
|
||||
severity: missingPredictionDevices > 0 ? EVENT_SEVERITY.MEDIUM : EVENT_SEVERITY.LOW,
|
||||
},
|
||||
] satisfies DashboardSnapshot['events']
|
||||
}
|
||||
|
||||
function createStrategies(devices: FleetUnit[]) {
|
||||
if (devices.length === 0) return []
|
||||
|
||||
const warningDevices = devices.filter((unit) => unit.status === DEVICE_STATUS.WARNING)
|
||||
const powerAttentionDevices = devices.filter(
|
||||
(unit) => unit.riskFactors.includes('充电中') || unit.riskFactors.includes('低电量'),
|
||||
)
|
||||
const missingPredictionDevices = devices.filter((unit) => unit.soh === null)
|
||||
|
||||
return [
|
||||
{
|
||||
name: '优先处理预警设备',
|
||||
impact: `当前有 ${warningDevices.length} 台设备处于预警状态,建议先复核供电、连接与预测结果。`,
|
||||
scope: warningDevices.length > 0 ? `${warningDevices.length} 台预警设备` : '当前设备',
|
||||
eta: '本次巡检周期内',
|
||||
},
|
||||
{
|
||||
name: '提升预测覆盖',
|
||||
impact:
|
||||
missingPredictionDevices.length > 0
|
||||
? `当前有 ${missingPredictionDevices.length} 台设备暂无健康预测,建议在下次同步后复查。`
|
||||
: `当前已有 ${devices.length} 台设备具备预测结果,可继续观察健康变化。`,
|
||||
scope:
|
||||
powerAttentionDevices.length > 0
|
||||
? `${powerAttentionDevices.length} 台充电中或低电量设备`
|
||||
: missingPredictionDevices.length > 0
|
||||
? `${missingPredictionDevices.length} 台缺失预测设备`
|
||||
: '当前设备',
|
||||
eta: '下次同步后复查',
|
||||
},
|
||||
] satisfies DashboardSnapshot['strategies']
|
||||
}
|
||||
|
||||
export function createDashboardSnapshot(
|
||||
items: BatteryInfo[],
|
||||
now = new Date(),
|
||||
predictions: ReadonlyMap<string, BatteryPrediction> = new Map(),
|
||||
): DashboardSnapshot {
|
||||
const devices = items.map((item) => toFleetUnit(item, predictions.get(item.mac)))
|
||||
|
||||
return {
|
||||
devices,
|
||||
soh: createSohResponse(devices),
|
||||
events: createEvents(devices, now),
|
||||
strategies: createStrategies(devices),
|
||||
summary: createSummary(devices, now),
|
||||
}
|
||||
}
|
||||
@@ -3,18 +3,12 @@ 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),
|
||||
DATABASE_URL: z.url(),
|
||||
},
|
||||
clientPrefix: 'VITE_',
|
||||
client: {},
|
||||
client: {
|
||||
VITE_APP_TITLE: z.string().min(1).optional(),
|
||||
},
|
||||
runtimeEnv: process.env,
|
||||
emptyStringAsUndefined: true,
|
||||
})
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { TanStackDevtoolsReactPlugin } from '@tanstack/react-devtools'
|
||||
import { ReactQueryDevtoolsPanel } from '@tanstack/react-query-devtools'
|
||||
|
||||
export const devtools = {
|
||||
name: 'TanStack Query',
|
||||
render: <ReactQueryDevtoolsPanel />,
|
||||
} satisfies TanStackDevtoolsReactPlugin
|
||||
@@ -0,0 +1 @@
|
||||
export * from './devtools'
|
||||
@@ -0,0 +1,7 @@
|
||||
import type { TanStackDevtoolsReactPlugin } from '@tanstack/react-devtools'
|
||||
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
|
||||
|
||||
export const devtools = {
|
||||
name: 'TanStack Router',
|
||||
render: <TanStackRouterDevtoolsPanel />,
|
||||
} satisfies TanStackDevtoolsReactPlugin
|
||||
@@ -0,0 +1 @@
|
||||
export * from './devtools'
|
||||
@@ -0,0 +1,53 @@
|
||||
import { createORPCClient } from '@orpc/client'
|
||||
import { RPCLink } from '@orpc/client/fetch'
|
||||
import { createRouterClient } from '@orpc/server'
|
||||
import { createTanstackQueryUtils } from '@orpc/tanstack-query'
|
||||
import { createIsomorphicFn } from '@tanstack/react-start'
|
||||
import { getRequestHeaders } from '@tanstack/react-start/server'
|
||||
import { router } from './router'
|
||||
import type { RouterClient } from './types'
|
||||
|
||||
const getORPCClient = createIsomorphicFn()
|
||||
.server(() =>
|
||||
createRouterClient(router, {
|
||||
context: () => ({
|
||||
headers: getRequestHeaders(),
|
||||
}),
|
||||
}),
|
||||
)
|
||||
.client(() => {
|
||||
const link = new RPCLink({
|
||||
url: `${window.location.origin}/api/rpc`,
|
||||
})
|
||||
return createORPCClient<RouterClient>(link)
|
||||
})
|
||||
|
||||
const client: RouterClient = getORPCClient()
|
||||
|
||||
export const orpc = createTanstackQueryUtils(client, {
|
||||
experimental_defaults: {
|
||||
todo: {
|
||||
create: {
|
||||
mutationOptions: {
|
||||
onSuccess: (_, __, ___, ctx) => {
|
||||
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
},
|
||||
},
|
||||
},
|
||||
update: {
|
||||
mutationOptions: {
|
||||
onSuccess: (_, __, ___, ctx) => {
|
||||
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
},
|
||||
},
|
||||
},
|
||||
remove: {
|
||||
mutationOptions: {
|
||||
onSuccess: (_, __, ___, ctx) => {
|
||||
ctx.client.invalidateQueries({ queryKey: orpc.todo.list.key() })
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,5 @@
|
||||
import * as todo from './contracts/todo'
|
||||
|
||||
export const contract = {
|
||||
todo,
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { oc } from '@orpc/contract'
|
||||
import {
|
||||
createInsertSchema,
|
||||
createSelectSchema,
|
||||
createUpdateSchema,
|
||||
} from 'drizzle-zod'
|
||||
import { z } from 'zod'
|
||||
import { todoTable } from '@/db/schema'
|
||||
|
||||
const selectSchema = createSelectSchema(todoTable)
|
||||
|
||||
const insertSchema = createInsertSchema(todoTable).omit({
|
||||
id: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
})
|
||||
|
||||
const updateSchema = createUpdateSchema(todoTable).omit({
|
||||
id: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
})
|
||||
|
||||
export const list = oc.input(z.void()).output(z.array(selectSchema))
|
||||
|
||||
export const create = oc.input(insertSchema).output(selectSchema)
|
||||
|
||||
export const update = oc
|
||||
.input(
|
||||
z.object({
|
||||
id: z.uuid(),
|
||||
data: updateSchema,
|
||||
}),
|
||||
)
|
||||
.output(selectSchema)
|
||||
|
||||
export const remove = oc
|
||||
.input(
|
||||
z.object({
|
||||
id: z.uuid(),
|
||||
}),
|
||||
)
|
||||
.output(z.void())
|
||||
@@ -0,0 +1,48 @@
|
||||
import { ORPCError } from '@orpc/server'
|
||||
import { eq } from 'drizzle-orm'
|
||||
import { todoTable } from '@/db/schema'
|
||||
import { baseProcedure } from '@/orpc/procedures'
|
||||
|
||||
export const list = baseProcedure.todo.list.handler(async ({ context }) => {
|
||||
const todos = await context.db.query.todoTable.findMany({
|
||||
orderBy: (todos, { desc }) => [desc(todos.createdAt)],
|
||||
})
|
||||
return todos
|
||||
})
|
||||
|
||||
export const create = baseProcedure.todo.create.handler(
|
||||
async ({ context, input }) => {
|
||||
const [newTodo] = await context.db
|
||||
.insert(todoTable)
|
||||
.values(input)
|
||||
.returning()
|
||||
|
||||
if (!newTodo) {
|
||||
throw new ORPCError('NOT_FOUND')
|
||||
}
|
||||
|
||||
return newTodo
|
||||
},
|
||||
)
|
||||
|
||||
export const update = baseProcedure.todo.update.handler(
|
||||
async ({ context, input }) => {
|
||||
const [updatedTodo] = await context.db
|
||||
.update(todoTable)
|
||||
.set(input.data)
|
||||
.where(eq(todoTable.id, input.id))
|
||||
.returning()
|
||||
|
||||
if (!updatedTodo) {
|
||||
throw new ORPCError('NOT_FOUND')
|
||||
}
|
||||
|
||||
return updatedTodo
|
||||
},
|
||||
)
|
||||
|
||||
export const remove = baseProcedure.todo.remove.handler(
|
||||
async ({ context, input }) => {
|
||||
await context.db.delete(todoTable).where(eq(todoTable.id, input.id))
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,2 @@
|
||||
export { orpc } from './client'
|
||||
export * from './types'
|
||||
@@ -0,0 +1,17 @@
|
||||
import { createDb } from '@/db'
|
||||
import { os } from '@/orpc/server'
|
||||
|
||||
export type Database = ReturnType<typeof createDb>
|
||||
|
||||
const globalForDb = globalThis as { __db?: Database }
|
||||
|
||||
function getDb(): Database {
|
||||
globalForDb.__db ??= createDb()
|
||||
return globalForDb.__db
|
||||
}
|
||||
|
||||
export const dbProvider = os.middleware(async ({ context, next }) => {
|
||||
return next({
|
||||
context: { ...context, db: getDb() },
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
export * from './db'
|
||||
@@ -0,0 +1,4 @@
|
||||
import { dbProvider } from './middlewares/db'
|
||||
import { os } from './server'
|
||||
|
||||
export const baseProcedure = os.use(dbProvider)
|
||||
@@ -0,0 +1,6 @@
|
||||
import * as todo from './handlers/todo'
|
||||
import { os } from './server'
|
||||
|
||||
export const router = os.router({
|
||||
todo,
|
||||
})
|
||||
@@ -0,0 +1,8 @@
|
||||
import { implement } from '@orpc/server'
|
||||
import { contract } from './contract'
|
||||
|
||||
export type ORPCContext = {
|
||||
headers?: Headers
|
||||
}
|
||||
|
||||
export const os = implement(contract).$context<ORPCContext>()
|
||||
@@ -0,0 +1,11 @@
|
||||
import type {
|
||||
ContractRouterClient,
|
||||
InferContractRouterInputs,
|
||||
InferContractRouterOutputs,
|
||||
} from '@orpc/contract'
|
||||
import type { contract } from './contract'
|
||||
|
||||
export type Contract = typeof contract
|
||||
export type RouterClient = ContractRouterClient<Contract>
|
||||
export type RouterInputs = InferContractRouterInputs<Contract>
|
||||
export type RouterOutputs = InferContractRouterOutputs<Contract>
|
||||
@@ -9,32 +9,14 @@
|
||||
// Additionally, you should also exclude this file from your linter and/or formatter to prevent it from being checked or modified.
|
||||
|
||||
import { Route as rootRouteImport } from './routes/__root'
|
||||
import { Route as HealthRouteImport } from './routes/health'
|
||||
import { Route as BatteriesRouteImport } from './routes/batteries'
|
||||
import { Route as IndexRouteImport } from './routes/index'
|
||||
import { Route as ApiSplatRouteImport } from './routes/api/$'
|
||||
import { Route as ApiRpcSplatRouteImport } from './routes/api/rpc.$'
|
||||
|
||||
const HealthRoute = HealthRouteImport.update({
|
||||
id: '/health',
|
||||
path: '/health',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const BatteriesRoute = BatteriesRouteImport.update({
|
||||
id: '/batteries',
|
||||
path: '/batteries',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const IndexRoute = IndexRouteImport.update({
|
||||
id: '/',
|
||||
path: '/',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ApiSplatRoute = ApiSplatRouteImport.update({
|
||||
id: '/api/$',
|
||||
path: '/api/$',
|
||||
getParentRoute: () => rootRouteImport,
|
||||
} as any)
|
||||
const ApiRpcSplatRoute = ApiRpcSplatRouteImport.update({
|
||||
id: '/api/rpc/$',
|
||||
path: '/api/rpc/$',
|
||||
@@ -43,58 +25,32 @@ const ApiRpcSplatRoute = ApiRpcSplatRouteImport.update({
|
||||
|
||||
export interface FileRoutesByFullPath {
|
||||
'/': typeof IndexRoute
|
||||
'/batteries': typeof BatteriesRoute
|
||||
'/health': typeof HealthRoute
|
||||
'/api/$': typeof ApiSplatRoute
|
||||
'/api/rpc/$': typeof ApiRpcSplatRoute
|
||||
}
|
||||
export interface FileRoutesByTo {
|
||||
'/': typeof IndexRoute
|
||||
'/batteries': typeof BatteriesRoute
|
||||
'/health': typeof HealthRoute
|
||||
'/api/$': typeof ApiSplatRoute
|
||||
'/api/rpc/$': typeof ApiRpcSplatRoute
|
||||
}
|
||||
export interface FileRoutesById {
|
||||
__root__: typeof rootRouteImport
|
||||
'/': typeof IndexRoute
|
||||
'/batteries': typeof BatteriesRoute
|
||||
'/health': typeof HealthRoute
|
||||
'/api/$': typeof ApiSplatRoute
|
||||
'/api/rpc/$': typeof ApiRpcSplatRoute
|
||||
}
|
||||
export interface FileRouteTypes {
|
||||
fileRoutesByFullPath: FileRoutesByFullPath
|
||||
fullPaths: '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
|
||||
fullPaths: '/' | '/api/rpc/$'
|
||||
fileRoutesByTo: FileRoutesByTo
|
||||
to: '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
|
||||
id: '__root__' | '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
|
||||
to: '/' | '/api/rpc/$'
|
||||
id: '__root__' | '/' | '/api/rpc/$'
|
||||
fileRoutesById: FileRoutesById
|
||||
}
|
||||
export interface RootRouteChildren {
|
||||
IndexRoute: typeof IndexRoute
|
||||
BatteriesRoute: typeof BatteriesRoute
|
||||
HealthRoute: typeof HealthRoute
|
||||
ApiSplatRoute: typeof ApiSplatRoute
|
||||
ApiRpcSplatRoute: typeof ApiRpcSplatRoute
|
||||
}
|
||||
|
||||
declare module '@tanstack/react-router' {
|
||||
interface FileRoutesByPath {
|
||||
'/health': {
|
||||
id: '/health'
|
||||
path: '/health'
|
||||
fullPath: '/health'
|
||||
preLoaderRoute: typeof HealthRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/batteries': {
|
||||
id: '/batteries'
|
||||
path: '/batteries'
|
||||
fullPath: '/batteries'
|
||||
preLoaderRoute: typeof BatteriesRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/': {
|
||||
id: '/'
|
||||
path: '/'
|
||||
@@ -102,13 +58,6 @@ declare module '@tanstack/react-router' {
|
||||
preLoaderRoute: typeof IndexRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/api/$': {
|
||||
id: '/api/$'
|
||||
path: '/api/$'
|
||||
fullPath: '/api/$'
|
||||
preLoaderRoute: typeof ApiSplatRouteImport
|
||||
parentRoute: typeof rootRouteImport
|
||||
}
|
||||
'/api/rpc/$': {
|
||||
id: '/api/rpc/$'
|
||||
path: '/api/rpc/$'
|
||||
@@ -121,9 +70,6 @@ declare module '@tanstack/react-router' {
|
||||
|
||||
const rootRouteChildren: RootRouteChildren = {
|
||||
IndexRoute: IndexRoute,
|
||||
BatteriesRoute: BatteriesRoute,
|
||||
HealthRoute: HealthRoute,
|
||||
ApiSplatRoute: ApiSplatRoute,
|
||||
ApiRpcSplatRoute: ApiRpcSplatRoute,
|
||||
}
|
||||
export const routeTree = rootRouteImport
|
||||
|
||||
@@ -5,14 +5,7 @@ import type { RouterContext } from './routes/__root'
|
||||
import { routeTree } from './routeTree.gen'
|
||||
|
||||
export const getRouter = () => {
|
||||
const queryClient = new QueryClient({
|
||||
defaultOptions: {
|
||||
queries: {
|
||||
staleTime: 30 * 1000,
|
||||
retry: 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
const queryClient = new QueryClient()
|
||||
|
||||
const router = createRouter({
|
||||
routeTree,
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
import { TanStackDevtools } from '@tanstack/react-devtools'
|
||||
import type { QueryClient } from '@tanstack/react-query'
|
||||
import { ReactQueryDevtoolsPanel } from '@tanstack/react-query-devtools'
|
||||
import { createRootRouteWithContext, HeadContent, Scripts } from '@tanstack/react-router'
|
||||
import { TanStackRouterDevtoolsPanel } from '@tanstack/react-router-devtools'
|
||||
import {
|
||||
createRootRouteWithContext,
|
||||
HeadContent,
|
||||
Scripts,
|
||||
} from '@tanstack/react-router'
|
||||
import type { ReactNode } from 'react'
|
||||
import { name } from '#package'
|
||||
import { ErrorComponent } from '@/components/Error'
|
||||
import { NotFoundComponent } from '@/components/NotFound'
|
||||
import { devtools as queryDevtools } from '@/integrations/tanstack-query'
|
||||
import { devtools as routerDevtools } from '@/integrations/tanstack-router'
|
||||
import appCss from '@/styles.css?url'
|
||||
|
||||
export interface RouterContext {
|
||||
@@ -24,7 +27,7 @@ export const Route = createRootRouteWithContext<RouterContext>()({
|
||||
content: 'width=device-width, initial-scale=1',
|
||||
},
|
||||
{
|
||||
title: name,
|
||||
title: 'Fullstack Starter',
|
||||
},
|
||||
],
|
||||
links: [
|
||||
@@ -35,8 +38,8 @@ export const Route = createRootRouteWithContext<RouterContext>()({
|
||||
],
|
||||
}),
|
||||
shellComponent: RootDocument,
|
||||
errorComponent: ErrorComponent,
|
||||
notFoundComponent: NotFoundComponent,
|
||||
errorComponent: () => <ErrorComponent />,
|
||||
notFoundComponent: () => <NotFoundComponent />,
|
||||
})
|
||||
|
||||
function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
|
||||
@@ -47,23 +50,12 @@ function RootDocument({ children }: Readonly<{ children: ReactNode }>) {
|
||||
</head>
|
||||
<body>
|
||||
{children}
|
||||
{import.meta.env.DEV && (
|
||||
<TanStackDevtools
|
||||
config={{
|
||||
position: 'bottom-right',
|
||||
}}
|
||||
plugins={[
|
||||
{
|
||||
name: 'TanStack Router',
|
||||
render: <TanStackRouterDevtoolsPanel />,
|
||||
},
|
||||
{
|
||||
name: 'TanStack Query',
|
||||
render: <ReactQueryDevtoolsPanel />,
|
||||
},
|
||||
]}
|
||||
/>
|
||||
)}
|
||||
<TanStackDevtools
|
||||
config={{
|
||||
position: 'bottom-right',
|
||||
}}
|
||||
plugins={[routerDevtools, queryDevtools]}
|
||||
/>
|
||||
<Scripts />
|
||||
</body>
|
||||
</html>
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
import { OpenAPIHandler } from '@orpc/openapi/fetch'
|
||||
import { OpenAPIReferencePlugin } from '@orpc/openapi/plugins'
|
||||
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: 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)],
|
||||
})
|
||||
|
||||
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: {
|
||||
headers: request.headers,
|
||||
},
|
||||
})
|
||||
|
||||
return response ?? new Response('Not Found', { status: 404 })
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -1,12 +1,46 @@
|
||||
import { onError } from '@orpc/server'
|
||||
import { ORPCError, onError, ValidationError } from '@orpc/server'
|
||||
import { RPCHandler } from '@orpc/server/fetch'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { handleValidationError, logError } from '@/server/api/interceptors'
|
||||
import { router } from '@/server/api/routers'
|
||||
import { z } from 'zod'
|
||||
import { router } from '@/orpc/router'
|
||||
|
||||
const handler = new RPCHandler(router, {
|
||||
interceptors: [onError(logError)],
|
||||
clientInterceptors: [onError(handleValidationError)],
|
||||
interceptors: [
|
||||
onError((error) => {
|
||||
console.error(error)
|
||||
}),
|
||||
],
|
||||
clientInterceptors: [
|
||||
onError((error) => {
|
||||
if (
|
||||
error instanceof ORPCError &&
|
||||
error.code === 'BAD_REQUEST' &&
|
||||
error.cause instanceof ValidationError
|
||||
) {
|
||||
// If you only use Zod you can safely cast to ZodIssue[]
|
||||
const zodError = new z.ZodError(
|
||||
error.cause.issues as z.core.$ZodIssue[],
|
||||
)
|
||||
|
||||
throw new ORPCError('INPUT_VALIDATION_FAILED', {
|
||||
status: 422,
|
||||
message: z.prettifyError(zodError),
|
||||
data: z.flattenError(zodError),
|
||||
cause: error.cause,
|
||||
})
|
||||
}
|
||||
|
||||
if (
|
||||
error instanceof ORPCError &&
|
||||
error.code === 'INTERNAL_SERVER_ERROR' &&
|
||||
error.cause instanceof ValidationError
|
||||
) {
|
||||
throw new ORPCError('OUTPUT_VALIDATION_FAILED', {
|
||||
cause: error.cause,
|
||||
})
|
||||
}
|
||||
}),
|
||||
],
|
||||
})
|
||||
|
||||
export const Route = createFileRoute('/api/rpc/$')({
|
||||
@@ -15,9 +49,7 @@ export const Route = createFileRoute('/api/rpc/$')({
|
||||
ANY: async ({ request }) => {
|
||||
const { response } = await handler.handle(request, {
|
||||
prefix: '/api/rpc',
|
||||
context: {
|
||||
headers: request.headers,
|
||||
},
|
||||
context: {},
|
||||
})
|
||||
|
||||
return response ?? new Response('Not Found', { status: 404 })
|
||||
|
||||
@@ -1,530 +0,0 @@
|
||||
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, X, Zap } from 'lucide-react'
|
||||
import { useEffect, useMemo, useState } from 'react'
|
||||
import { z } from 'zod'
|
||||
import { orpc } from '@/client/orpc'
|
||||
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')({
|
||||
validateSearch: (search) => searchSchema.parse(search),
|
||||
component: BatteriesPage,
|
||||
errorComponent: () => (
|
||||
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
|
||||
<div className="text-center">
|
||||
<p className="text-lg text-red-400">数据加载失败</p>
|
||||
<p className="mt-2 text-sm text-zinc-500">请检查筛选条件后重试。</p>
|
||||
</div>
|
||||
</main>
|
||||
),
|
||||
})
|
||||
|
||||
const powerStatusLabel: Record<PowerStatus, string> = {
|
||||
[POWER_STATUS.NOT_CHARGING]: '未充电',
|
||||
[POWER_STATUS.CHARGING]: '充电中',
|
||||
[POWER_STATUS.FULL]: '已充满',
|
||||
}
|
||||
|
||||
const powerStatusVariant: Record<PowerStatus, 'muted' | 'info' | 'success'> = {
|
||||
[POWER_STATUS.NOT_CHARGING]: 'muted',
|
||||
[POWER_STATUS.CHARGING]: 'info',
|
||||
[POWER_STATUS.FULL]: 'success',
|
||||
}
|
||||
|
||||
function powerBarColor(power: number, isLowPower: boolean): string {
|
||||
if (isLowPower || power <= 20) return 'bg-red-500'
|
||||
if (power <= 50) return 'bg-amber-500'
|
||||
return 'bg-teal-500'
|
||||
}
|
||||
|
||||
const columnHelper = createColumnHelper<BatteryInfo>()
|
||||
|
||||
function parseSort(value: string): BatteryListSort {
|
||||
return BATTERY_LIST_SORT_VALUES.find((option) => option === value) ?? BATTERY_LIST_SORT.CREATED_AT_DESC
|
||||
}
|
||||
|
||||
function parsePowerStatus(value: string): PowerStatus | undefined {
|
||||
if (value === allPowerStatusValue) return undefined
|
||||
|
||||
const parsed = Number(value)
|
||||
|
||||
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() {
|
||||
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({
|
||||
input: {
|
||||
search: search.search,
|
||||
lowPower: search.lowPower,
|
||||
powerStatus: search.powerStatus,
|
||||
sort: search.sort,
|
||||
pageSize: search.pageSize,
|
||||
cursor: search.cursor,
|
||||
},
|
||||
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) {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
|
||||
<div className="text-center">
|
||||
<p className="text-lg text-red-400">数据加载失败</p>
|
||||
<p className="mt-2 text-sm text-zinc-500">请稍后重试,或联系管理员检查数据源连接。</p>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-[#09090B] text-zinc-100">
|
||||
{/* Background gradient */}
|
||||
<div className="pointer-events-none fixed inset-0 z-0 flex justify-center">
|
||||
<div className="h-[600px] w-[1000px] -translate-y-1/2 rounded-full bg-teal-900/5 blur-[100px]" />
|
||||
</div>
|
||||
|
||||
<div className="relative z-10 mx-auto max-w-7xl px-6 py-8">
|
||||
<MotionHeader>
|
||||
<div className="flex flex-col gap-5 lg:flex-row lg:items-end lg:justify-between">
|
||||
<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>
|
||||
|
||||
<dl className="mt-8 grid grid-cols-1 gap-4 sm:grid-cols-3">
|
||||
<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>
|
||||
</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>
|
||||
)
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
|
||||
export const Route = createFileRoute('/health')({
|
||||
server: {
|
||||
handlers: {
|
||||
GET: () => new Response('ok', { status: 200, headers: { 'content-type': 'text/plain' } }),
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -1,670 +1,215 @@
|
||||
import { useQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute, Link } from '@tanstack/react-router'
|
||||
import { Activity, AlertTriangle, ArrowRight, ShieldCheck, Tags, TrendingDown } from 'lucide-react'
|
||||
import {
|
||||
Area,
|
||||
CartesianGrid,
|
||||
ComposedChart,
|
||||
Line,
|
||||
ReferenceLine,
|
||||
ResponsiveContainer,
|
||||
Tooltip,
|
||||
XAxis,
|
||||
YAxis,
|
||||
} from 'recharts'
|
||||
import type { NameType, ValueType } from 'recharts/types/component/DefaultTooltipContent'
|
||||
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 { BATTERY_LIST_SORT, DEVICE_STATUS } from '@/domain/battery'
|
||||
import { useMutation, useSuspenseQuery } from '@tanstack/react-query'
|
||||
import { createFileRoute } from '@tanstack/react-router'
|
||||
import { isTauri } from '@tauri-apps/api/core'
|
||||
import { getCurrentWindow } from '@tauri-apps/api/window'
|
||||
import type { ChangeEventHandler, FormEventHandler } from 'react'
|
||||
import { useEffect, useState } from 'react'
|
||||
import { orpc } from '@/orpc'
|
||||
|
||||
export const Route = createFileRoute('/')({
|
||||
component: Dashboard,
|
||||
errorComponent: ({ error }) => (
|
||||
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
|
||||
<div className="text-center">
|
||||
<p className="text-lg text-red-400">数据加载失败</p>
|
||||
<p className="mt-2 text-sm text-[#71717A]">{error.message}</p>
|
||||
</div>
|
||||
</main>
|
||||
),
|
||||
component: Todos,
|
||||
loader: async ({ context }) => {
|
||||
await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions())
|
||||
},
|
||||
})
|
||||
|
||||
function buildChartData(soh: DashboardSnapshot['soh']) {
|
||||
const chartData: { month: string; history?: number; forecast?: number }[] = soh.history.map((h) => ({
|
||||
month: h.month,
|
||||
history: h.value,
|
||||
forecast: undefined,
|
||||
}))
|
||||
function Todos() {
|
||||
const [newTodoTitle, setNewTodoTitle] = useState('')
|
||||
|
||||
if (chartData.length > 0 && soh.forecast.length > 0) {
|
||||
// Overlap: last history point is also first forecast point
|
||||
const last = chartData[chartData.length - 1]
|
||||
if (last) {
|
||||
last.forecast = soh.forecast[0]?.value
|
||||
const listQuery = useSuspenseQuery(orpc.todo.list.queryOptions())
|
||||
const createMutation = useMutation(orpc.todo.create.mutationOptions())
|
||||
const updateMutation = useMutation(orpc.todo.update.mutationOptions())
|
||||
const deleteMutation = useMutation(orpc.todo.remove.mutationOptions())
|
||||
|
||||
useEffect(() => {
|
||||
if (!isTauri()) return
|
||||
getCurrentWindow().setTitle('待办事项')
|
||||
}, [])
|
||||
|
||||
const handleCreateTodo: FormEventHandler<HTMLFormElement> = (e) => {
|
||||
e.preventDefault()
|
||||
if (newTodoTitle.trim()) {
|
||||
createMutation.mutate({ title: newTodoTitle.trim() })
|
||||
setNewTodoTitle('')
|
||||
}
|
||||
}
|
||||
|
||||
const forecastStart = chartData.length > 0 ? 1 : 0
|
||||
|
||||
for (let i = forecastStart; i < soh.forecast.length; i++) {
|
||||
const f = soh.forecast[i]
|
||||
if (f) {
|
||||
chartData.push({
|
||||
month: f.month,
|
||||
history: undefined,
|
||||
forecast: f.value,
|
||||
})
|
||||
}
|
||||
const handleInputChange: ChangeEventHandler<HTMLInputElement> = (e) => {
|
||||
setNewTodoTitle(e.target.value)
|
||||
}
|
||||
|
||||
return chartData
|
||||
}
|
||||
|
||||
const statusVariantMap: Record<DeviceStatus, 'success' | 'warning' | 'danger'> = {
|
||||
[DEVICE_STATUS.HEALTHY]: 'success',
|
||||
[DEVICE_STATUS.WATCH]: 'warning',
|
||||
[DEVICE_STATUS.WARNING]: 'danger',
|
||||
}
|
||||
|
||||
const severityVariantMap: Record<DashboardSnapshot['events'][number]['severity'], 'danger' | 'warning' | 'muted'> = {
|
||||
高: 'danger',
|
||||
中: 'warning',
|
||||
低: 'muted',
|
||||
}
|
||||
|
||||
function formatChartTooltip(value: ValueType | undefined, name: NameType | undefined) {
|
||||
const numericValue = typeof value === 'number' ? value : Number(value)
|
||||
|
||||
return [
|
||||
`${Number.isFinite(numericValue) ? numericValue.toFixed(1) : (value ?? '-')}%`,
|
||||
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() {
|
||||
const { data, error, isPending } = useQuery(orpc.battery.dashboard.queryOptions())
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
|
||||
<div className="text-center">
|
||||
<p className="text-lg text-red-400">数据加载失败</p>
|
||||
<p className="mt-2 text-sm text-[#71717A]">{error.message}</p>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
const handleToggleTodo = (id: string, currentCompleted: boolean) => {
|
||||
updateMutation.mutate({
|
||||
id,
|
||||
data: { completed: !currentCompleted },
|
||||
})
|
||||
}
|
||||
|
||||
if (isPending || !data) {
|
||||
return (
|
||||
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
|
||||
<p className="text-[#71717A]">加载中…</p>
|
||||
</main>
|
||||
)
|
||||
const handleDeleteTodo = (id: string) => {
|
||||
deleteMutation.mutate({ id })
|
||||
}
|
||||
|
||||
const { devices, soh, events, strategies, summary } = data
|
||||
const {
|
||||
totalDevices,
|
||||
avgSoh,
|
||||
avgSoh30d,
|
||||
avgSoh90d,
|
||||
warningCount,
|
||||
watchCount,
|
||||
healthyCount,
|
||||
batchPerformance,
|
||||
riskFactorCounts,
|
||||
firmwareHealth,
|
||||
updatedAt,
|
||||
executiveSummary,
|
||||
} = summary
|
||||
const chartData = buildChartData(soh)
|
||||
const todos = listQuery.data
|
||||
const completedCount = todos.filter((todo) => todo.completed).length
|
||||
const totalCount = todos.length
|
||||
const progress = totalCount > 0 ? (completedCount / totalCount) * 100 : 0
|
||||
|
||||
return (
|
||||
<main className="min-h-screen w-full bg-[#09090B] font-sans text-[#F4F4F5]">
|
||||
{/* Background gradient */}
|
||||
<div className="pointer-events-none fixed inset-0 z-0 flex justify-center">
|
||||
<div className="h-[800px] w-[1200px] -translate-y-1/2 rounded-full bg-teal-900/10 blur-[120px]" />
|
||||
</div>
|
||||
|
||||
<div className="relative z-10 mx-auto max-w-[1400px] px-6 pb-24 pt-12 lg:px-12">
|
||||
<div className="min-h-screen bg-slate-50 py-12 px-4 sm:px-6 font-sans">
|
||||
<div className="max-w-2xl mx-auto space-y-8">
|
||||
{/* Header */}
|
||||
<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" /> 实时数据与健康预测
|
||||
</Badge>
|
||||
<h1 className="text-4xl font-light tracking-tight text-white sm:text-5xl">电池健康与风险洞察</h1>
|
||||
</div>
|
||||
<div className="flex flex-col items-end gap-3 text-right">
|
||||
<Badge variant="muted">基于当前可用数据生成</Badge>
|
||||
<p className="text-xs tabular-nums text-[#71717A]">数据更新时间: {updatedAt}</p>
|
||||
<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>
|
||||
</div>
|
||||
</MotionHeader>
|
||||
|
||||
{/* Executive Summary */}
|
||||
<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>
|
||||
</MotionSection>
|
||||
|
||||
{/* Primary KPI Row */}
|
||||
<MotionSection delay={0.2} className="mb-12 grid grid-cols-1 gap-4 md:grid-cols-2 lg:grid-cols-5">
|
||||
{/* Hero KPI */}
|
||||
<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">
|
||||
<h2 className="text-6xl font-light tabular-nums text-white">{formatPercent(avgSoh)}</h2>
|
||||
{avgSoh !== null && <span className="text-2xl text-[#71717A]">%</span>}
|
||||
</div>
|
||||
<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="h-1.5 w-1.5 rounded-full bg-emerald-400" />
|
||||
{avgSoh === null ? '健康预测暂不可用' : '预测已返回'}
|
||||
</span>
|
||||
<span className="text-[#71717A]">|</span>
|
||||
<span className="text-[#A1A1AA]">共 {totalDevices} 台设备</span>
|
||||
</div>
|
||||
</MotionCardArticle>
|
||||
|
||||
{/* Regular KPIs */}
|
||||
<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>
|
||||
{avgSoh30d !== null && <span className="text-lg text-[#71717A]">%</span>}
|
||||
</div>
|
||||
<div className="mt-4 flex items-center gap-1.5 text-sm">
|
||||
<span className="text-red-400">↘</span>
|
||||
<span className="tabular-nums text-[#A1A1AA]">{formatDelta(avgSoh, avgSoh30d)}</span>
|
||||
</div>
|
||||
</MotionCardArticle>
|
||||
|
||||
<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>
|
||||
{avgSoh90d !== null && <span className="text-lg text-[#71717A]">%</span>}
|
||||
</div>
|
||||
<div className="mt-4 flex items-center gap-1.5 text-sm">
|
||||
<span className="text-red-400">↘</span>
|
||||
<span className="tabular-nums text-[#A1A1AA]">{formatDelta(avgSoh, avgSoh90d)}</span>
|
||||
</div>
|
||||
</MotionCardArticle>
|
||||
|
||||
<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>
|
||||
<span className="text-lg text-[#71717A]">台</span>
|
||||
</div>
|
||||
<div className="mt-4 flex items-center gap-1.5 text-sm">
|
||||
<span className="text-amber-400">↗</span>
|
||||
<span className="tabular-nums text-[#A1A1AA]">
|
||||
占比 {totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
|
||||
</span>
|
||||
</div>
|
||||
</MotionCardArticle>
|
||||
</MotionSection>
|
||||
|
||||
{/* Divider */}
|
||||
<hr className="my-12 border-white/5" />
|
||||
|
||||
{/* Health trend chart */}
|
||||
<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
|
||||
icon={<TrendingDown className="size-4" />}
|
||||
title="健康趋势预测"
|
||||
description="展示当前健康度与未来 30/90 天趋势;数据不足时保持空态,避免误导判断。"
|
||||
/>
|
||||
<div className="flex items-center gap-6 text-sm text-[#A1A1AA]">
|
||||
{soh.history.length > 0 && (
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<span className="h-2 w-4 rounded-full bg-teal-400" />
|
||||
历史观测值
|
||||
</span>
|
||||
)}
|
||||
<span className="inline-flex items-center gap-2">
|
||||
<span className="h-2 w-4 rounded-full bg-indigo-400" />
|
||||
预测趋势
|
||||
</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div className="w-full h-[320px]">
|
||||
{chartData.length > 0 ? (
|
||||
<ResponsiveContainer width="100%" height="100%">
|
||||
<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.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.25} />
|
||||
<stop offset="100%" stopColor="#818CF8" stopOpacity={0} />
|
||||
</linearGradient>
|
||||
</defs>
|
||||
<CartesianGrid stroke="#ffffff" strokeOpacity={0.05} vertical={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: '#A1A1AA', fontSize: 12 }}
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
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="当前设备数据不足以生成可靠的健康趋势预测,请等待系统收集更多数据。"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Card>
|
||||
</MotionSection>
|
||||
|
||||
{/* Two-column grid */}
|
||||
<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 */}
|
||||
<div>
|
||||
<div className="mb-6">
|
||||
<SectionTitle icon={<ShieldCheck className="size-4" />} title="健康分布" />
|
||||
</div>
|
||||
<div className="space-y-5">
|
||||
<div>
|
||||
<div className="mb-2 flex justify-between text-sm">
|
||||
<span className="text-[#A1A1AA]">健康 (> 90%)</span>
|
||||
<span className="tabular-nums text-white">
|
||||
{healthyCount} 台{' '}
|
||||
<span className="text-[#71717A]">
|
||||
/ {totalDevices > 0 ? ((healthyCount / totalDevices) * 100).toFixed(1) : 0}%
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
|
||||
<div
|
||||
className="h-full rounded-full bg-emerald-400"
|
||||
style={{ width: `${totalDevices > 0 ? (healthyCount / totalDevices) * 100 : 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 flex justify-between text-sm">
|
||||
<span className="text-[#A1A1AA]">关注 (85% - 90%)</span>
|
||||
<span className="tabular-nums text-white">
|
||||
{watchCount} 台{' '}
|
||||
<span className="text-[#71717A]">
|
||||
/ {totalDevices > 0 ? ((watchCount / totalDevices) * 100).toFixed(1) : 0}%
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
|
||||
<div
|
||||
className="h-full rounded-full bg-amber-400"
|
||||
style={{ width: `${totalDevices > 0 ? (watchCount / totalDevices) * 100 : 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<div className="mb-2 flex justify-between text-sm">
|
||||
<span className="text-[#A1A1AA]">预警 (≤ 85%)</span>
|
||||
<span className="tabular-nums text-white">
|
||||
{warningCount} 台{' '}
|
||||
<span className="text-[#71717A]">
|
||||
/ {totalDevices > 0 ? ((warningCount / totalDevices) * 100).toFixed(1) : 0}%
|
||||
</span>
|
||||
</span>
|
||||
</div>
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
|
||||
<div
|
||||
className="h-full rounded-full bg-red-400"
|
||||
style={{ width: `${totalDevices > 0 ? (warningCount / totalDevices) * 100 : 0}%` }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Regional Performance */}
|
||||
<div>
|
||||
<h3 className="mb-6 text-lg font-medium text-white">设备型号健康度概览</h3>
|
||||
<div className="space-y-4">
|
||||
{batchPerformance.length > 0 ? (
|
||||
batchPerformance.map((item) => (
|
||||
<div key={item.batch} className="flex items-center gap-4">
|
||||
<span className="w-20 text-sm text-[#A1A1AA]">{item.batch}</span>
|
||||
<div className="flex-1">
|
||||
<div className="h-1.5 overflow-hidden rounded-full bg-white/5">
|
||||
<div
|
||||
className="h-full rounded-full bg-white/20"
|
||||
style={{ width: widthPercent(item.avgSoh) }}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<span className="w-20 text-right text-sm tabular-nums text-white">
|
||||
{formatPercentWithUnit(item.avgSoh)}
|
||||
</span>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="text-sm text-[#71717A]">暂无数据</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Right Column */}
|
||||
<div className="space-y-8">
|
||||
{/* Event Timeline */}
|
||||
<div>
|
||||
<div className="mb-6">
|
||||
<SectionTitle icon={<AlertTriangle className="size-4" />} title="风险与趋势概览" />
|
||||
</div>
|
||||
<div className="relative border-l border-white/10 pl-5">
|
||||
{events.length > 0 ? (
|
||||
events.map((event) => (
|
||||
<div key={event.time + event.title} className="mb-6 last:mb-0">
|
||||
<div
|
||||
className={`absolute -left-[4px] mt-1.5 h-2 w-2 rounded-full ${
|
||||
event.severity === '高' ? 'bg-red-400' : 'bg-amber-400'
|
||||
}`}
|
||||
/>
|
||||
<div className="mb-1 flex items-center gap-3">
|
||||
<span className="text-xs font-medium tabular-nums text-[#71717A]">{event.time}</span>
|
||||
<Badge variant={severityVariantMap[event.severity]}>{event.severity}风险</Badge>
|
||||
</div>
|
||||
<h4 className="text-sm font-medium text-[#F4F4F5]">{event.title}</h4>
|
||||
<p className="mt-1 text-sm leading-relaxed text-[#A1A1AA]">{event.detail}</p>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="text-sm text-[#71717A]">暂无数据</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Risk Factor Frequency */}
|
||||
<div>
|
||||
<div className="mb-6">
|
||||
<SectionTitle icon={<Tags className="size-4" />} title="主要风险因子分布" />
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-2">
|
||||
{riskFactorCounts.length > 0 ? (
|
||||
riskFactorCounts.map((item) => (
|
||||
<Badge key={item.factor} variant={item.factor.includes('不可用') ? 'warning' : 'default'}>
|
||||
{item.factor}
|
||||
<span className="rounded-full bg-white/10 px-1.5 py-0.5 tabular-nums text-white">
|
||||
{item.count}
|
||||
</span>
|
||||
</Badge>
|
||||
))
|
||||
) : (
|
||||
<div className="text-sm text-[#71717A]">暂无数据</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</MotionSection>
|
||||
|
||||
{/* Divider */}
|
||||
<hr className="my-12 border-white/5" />
|
||||
|
||||
{/* Device Table */}
|
||||
<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>
|
||||
<p className="mt-1 text-sm text-[#A1A1AA]">按风险优先级展示当前健康度与未来 30/90 天趋势。</p>
|
||||
</div>
|
||||
</div>
|
||||
<Card className="overflow-hidden">
|
||||
<div className="overflow-x-auto">
|
||||
<table className="w-full min-w-[1000px] border-collapse text-left text-sm">
|
||||
<thead>
|
||||
<tr className="border-b border-white/10 bg-white/[0.02] text-zinc-400">
|
||||
<th className="px-6 py-4 font-medium whitespace-nowrap">设备标识</th>
|
||||
<th className="px-6 py-4 font-medium whitespace-nowrap">设备型号</th>
|
||||
<th className="px-6 py-4 font-medium whitespace-nowrap">当前健康度</th>
|
||||
<th className="px-6 py-4 font-medium whitespace-nowrap">30天预测</th>
|
||||
<th className="px-6 py-4 font-medium whitespace-nowrap">90天预测</th>
|
||||
<th className="px-6 py-4 font-medium whitespace-nowrap">风险评分</th>
|
||||
<th className="px-6 py-4 font-medium whitespace-nowrap">状态</th>
|
||||
<th className="px-6 py-4 font-medium whitespace-nowrap">主要风险因子</th>
|
||||
</tr>
|
||||
</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.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 */}
|
||||
<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) => (
|
||||
<MotionCardDiv
|
||||
key={item.name}
|
||||
className="relative overflow-hidden rounded-xl border border-white/[0.06] bg-white/[0.02] p-5"
|
||||
>
|
||||
<div
|
||||
className={`absolute bottom-0 left-0 top-0 w-1 ${index === 0 ? 'bg-red-400' : index === 1 ? 'bg-amber-400' : 'bg-teal-400'}`}
|
||||
/>
|
||||
<h4 className="font-medium text-white">{item.name}</h4>
|
||||
<p className="mt-2 text-sm text-[#A1A1AA]">{item.impact}</p>
|
||||
<div className="mt-4 flex flex-wrap gap-4 text-xs text-[#71717A]">
|
||||
<span>范围: {item.scope}</span>
|
||||
<span>时效: {item.eta}</span>
|
||||
</div>
|
||||
</MotionCardDiv>
|
||||
))
|
||||
) : (
|
||||
<div className="text-sm text-[#71717A] col-span-2">暂无策略建议</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Firmware Comparison */}
|
||||
<div className="flex items-end justify-between">
|
||||
<div>
|
||||
<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="space-y-4">
|
||||
{firmwareHealth.length > 0 ? (
|
||||
firmwareHealth.map((item) => (
|
||||
<div key={item.firmware} className="flex items-center justify-between">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-white">{item.firmware}</div>
|
||||
<div className="text-xs text-[#71717A]">{item.count} 台设备</div>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-sm tabular-nums text-white">{formatPercentWithUnit(item.avgSoh)}</div>
|
||||
<div className="text-xs text-[#71717A]">平均健康度</div>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
) : (
|
||||
<div className="text-sm text-[#71717A]">暂无数据</div>
|
||||
)}
|
||||
</div>
|
||||
<h1 className="text-3xl font-bold text-slate-900 tracking-tight">
|
||||
我的待办
|
||||
</h1>
|
||||
<p className="text-slate-500 mt-1">保持专注,逐个击破</p>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<div className="text-2xl font-semibold text-slate-900">
|
||||
{completedCount}
|
||||
<span className="text-slate-400 text-lg">/{totalCount}</span>
|
||||
</div>
|
||||
<div className="text-xs font-medium text-slate-400 uppercase tracking-wider">
|
||||
已完成
|
||||
</div>
|
||||
</div>
|
||||
</MotionSection>
|
||||
</div>
|
||||
|
||||
{/* Add Todo Form */}
|
||||
<form onSubmit={handleCreateTodo} className="relative group z-10">
|
||||
<div className="relative transform transition-all duration-200 focus-within:-translate-y-1">
|
||||
<input
|
||||
type="text"
|
||||
value={newTodoTitle}
|
||||
onChange={handleInputChange}
|
||||
placeholder="添加新任务..."
|
||||
className="w-full pl-6 pr-32 py-5 bg-white rounded-2xl shadow-[0_8px_30px_rgb(0,0,0,0.04)] border-0 ring-1 ring-slate-100 focus:ring-2 focus:ring-indigo-500/50 outline-none transition-all placeholder:text-slate-400 text-lg text-slate-700"
|
||||
disabled={createMutation.isPending}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={createMutation.isPending || !newTodoTitle.trim()}
|
||||
className="absolute right-3 top-3 bottom-3 px-6 bg-indigo-600 hover:bg-indigo-700 text-white rounded-xl font-medium transition-all shadow-md shadow-indigo-200 disabled:opacity-50 disabled:shadow-none hover:shadow-lg hover:shadow-indigo-300 active:scale-95"
|
||||
>
|
||||
{createMutation.isPending ? '添加中' : '添加'}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{/* Progress Bar (Only visible when there are tasks) */}
|
||||
{totalCount > 0 && (
|
||||
<div className="h-1.5 w-full bg-slate-200 rounded-full overflow-hidden">
|
||||
<div
|
||||
className="h-full bg-indigo-500 transition-all duration-500 ease-out rounded-full"
|
||||
style={{ width: `${progress}%` }}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Todo List */}
|
||||
<div className="space-y-3">
|
||||
{todos.length === 0 ? (
|
||||
<div className="py-20 text-center">
|
||||
<div className="inline-flex items-center justify-center w-16 h-16 rounded-full bg-slate-100 mb-4">
|
||||
<svg
|
||||
className="w-8 h-8 text-slate-400"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={1.5}
|
||||
d="M12 6v6m0 0v6m0-6h6m-6 0H6"
|
||||
/>
|
||||
</svg>
|
||||
</div>
|
||||
<p className="text-slate-500 text-lg font-medium">没有待办事项</p>
|
||||
<p className="text-slate-400 text-sm mt-1">
|
||||
输入上方内容添加您的第一个任务
|
||||
</p>
|
||||
</div>
|
||||
) : (
|
||||
todos.map((todo) => (
|
||||
<div
|
||||
key={todo.id}
|
||||
className={`group relative flex items-center p-4 bg-white rounded-xl border border-slate-100 shadow-sm transition-all duration-200 hover:shadow-md hover:border-slate-200 ${
|
||||
todo.completed ? 'bg-slate-50/50' : ''
|
||||
}`}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleToggleTodo(todo.id, todo.completed)}
|
||||
className={`flex-shrink-0 w-6 h-6 rounded-full border-2 transition-all duration-200 flex items-center justify-center mr-4 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 ${
|
||||
todo.completed
|
||||
? 'bg-indigo-500 border-indigo-500'
|
||||
: 'border-slate-300 hover:border-indigo-500 bg-white'
|
||||
}`}
|
||||
>
|
||||
{todo.completed && (
|
||||
<svg
|
||||
className="w-3.5 h-3.5 text-white"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={3}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M5 13l4 4L19 7"
|
||||
/>
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
|
||||
<div className="flex-1 min-w-0">
|
||||
<p
|
||||
className={`text-lg transition-all duration-200 truncate ${
|
||||
todo.completed
|
||||
? 'text-slate-400 line-through decoration-slate-300 decoration-2'
|
||||
: 'text-slate-700'
|
||||
}`}
|
||||
>
|
||||
{todo.title}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center opacity-0 group-hover:opacity-100 transition-opacity duration-200 absolute right-4 pl-4 bg-gradient-to-l from-white via-white to-transparent sm:static sm:bg-none">
|
||||
<span className="text-xs text-slate-400 mr-3 hidden sm:inline-block">
|
||||
{new Date(todo.createdAt).toLocaleDateString('zh-CN')}
|
||||
</span>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => handleDeleteTodo(todo.id)}
|
||||
className="p-2 text-slate-400 hover:text-red-500 hover:bg-red-50 rounded-lg transition-colors focus:outline-none"
|
||||
title="删除"
|
||||
>
|
||||
<svg
|
||||
className="w-5 h-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
aria-hidden="true"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
export interface BaseContext {
|
||||
headers: Headers
|
||||
}
|
||||
@@ -1,35 +0,0 @@
|
||||
import { oc } from '@orpc/contract'
|
||||
import { z } from 'zod'
|
||||
import {
|
||||
BATTERY_LIST_SORT,
|
||||
BATTERY_LIST_SORT_VALUES,
|
||||
batteriesResponseSchema,
|
||||
dashboardSnapshotSchema,
|
||||
POWER_STATUS,
|
||||
} from '@/domain/battery'
|
||||
|
||||
export const dashboard = oc.input(z.void()).output(dashboardSnapshotSchema)
|
||||
|
||||
const batteryListInputSchema = z.object({
|
||||
pageSize: z.number().int().min(1).max(100).default(50),
|
||||
cursor: z.string().min(1).max(1024).optional(),
|
||||
search: z.preprocess(
|
||||
(value) => (typeof value === 'string' ? value.trim() || undefined : value),
|
||||
z.string().min(1).max(100).optional(),
|
||||
),
|
||||
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).default(BATTERY_LIST_SORT.CREATED_AT_DESC),
|
||||
})
|
||||
|
||||
export const batteries = oc.input(batteryListInputSchema).output(batteriesResponseSchema)
|
||||
|
||||
export const history = oc
|
||||
.input(
|
||||
z.object({
|
||||
mac: z.string().min(1),
|
||||
}),
|
||||
)
|
||||
.output(batteriesResponseSchema)
|
||||
@@ -1,7 +0,0 @@
|
||||
import * as battery from './battery.contract'
|
||||
|
||||
export const contract = {
|
||||
battery,
|
||||
}
|
||||
|
||||
export type Contract = typeof contract
|
||||
@@ -1,32 +0,0 @@
|
||||
import { ORPCError, ValidationError } from '@orpc/server'
|
||||
import { z } from 'zod'
|
||||
import { getLogger } from '@/server/logger'
|
||||
|
||||
const logger = getLogger(['api'])
|
||||
|
||||
export const logError = (error: unknown) => {
|
||||
logger.error('Unhandled error in ORPC handler', { error })
|
||||
}
|
||||
|
||||
export const handleValidationError = (error: unknown) => {
|
||||
if (!(error instanceof ORPCError) || !(error.cause instanceof ValidationError)) return
|
||||
|
||||
if (error.code === 'BAD_REQUEST') {
|
||||
// ORPC widens issues to the Standard Schema shape; contracts here are built from Zod.
|
||||
// Rehydrate to reuse z.prettifyError / z.flattenError.
|
||||
const zodError = new z.ZodError(error.cause.issues as z.core.$ZodIssue[])
|
||||
|
||||
throw new ORPCError('INPUT_VALIDATION_FAILED', {
|
||||
status: 422,
|
||||
message: z.prettifyError(zodError),
|
||||
data: z.flattenError(zodError),
|
||||
cause: error.cause,
|
||||
})
|
||||
}
|
||||
|
||||
if (error.code === 'INTERNAL_SERVER_ERROR') {
|
||||
throw new ORPCError('OUTPUT_VALIDATION_FAILED', {
|
||||
cause: error.cause,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,72 +0,0 @@
|
||||
import { createBatteriesResponse, createDashboardSnapshot, POWER_STATUS } from '@/domain/battery'
|
||||
import { os } from '@/server/api/server'
|
||||
import {
|
||||
getBatteryHistory,
|
||||
getBatteryPredictionHistories,
|
||||
getLatestBatteryPage,
|
||||
getLatestBatteryPerDevice,
|
||||
} from '@/server/battery/mysql'
|
||||
import { isPredictionEnabled, predictSoh } from '@/server/prediction/client'
|
||||
|
||||
const dashboardPredictionConcurrency = 5
|
||||
|
||||
async function mapWithConcurrency<T, R>(
|
||||
items: T[],
|
||||
concurrency: number,
|
||||
handler: (item: T) => Promise<R>,
|
||||
): Promise<R[]> {
|
||||
const results: R[] = []
|
||||
let nextIndex = 0
|
||||
|
||||
async function worker() {
|
||||
while (nextIndex < items.length) {
|
||||
const index = nextIndex
|
||||
nextIndex += 1
|
||||
const item = items[index]
|
||||
if (item !== undefined) results[index] = await handler(item)
|
||||
}
|
||||
}
|
||||
|
||||
await Promise.all(Array.from({ length: Math.min(concurrency, items.length) }, worker))
|
||||
|
||||
return results
|
||||
}
|
||||
|
||||
export const dashboard = os.battery.dashboard.handler(async () => {
|
||||
const items = await getLatestBatteryPerDevice()
|
||||
const predictionHistories = isPredictionEnabled()
|
||||
? await getBatteryPredictionHistories(items.map((item) => item.mac))
|
||||
: new Map()
|
||||
const predictionEntries = isPredictionEnabled()
|
||||
? await mapWithConcurrency(items, dashboardPredictionConcurrency, async (item) => {
|
||||
const prediction = await predictSoh(item, predictionHistories.get(item.mac) ?? [])
|
||||
|
||||
return prediction ? ([item.mac, prediction] as const) : null
|
||||
})
|
||||
: []
|
||||
const predictions = new Map(predictionEntries.filter((entry) => entry !== null))
|
||||
|
||||
return createDashboardSnapshot(items, new Date(), predictions)
|
||||
})
|
||||
|
||||
export const batteries = os.battery.batteries.handler(async ({ input }) => {
|
||||
const page = await getLatestBatteryPage(input)
|
||||
|
||||
return createBatteriesResponse(
|
||||
page.items,
|
||||
new Date(),
|
||||
{ total: page.total, lowPower: page.lowPower, charging: page.charging },
|
||||
page.nextCursor,
|
||||
)
|
||||
})
|
||||
|
||||
export const history = os.battery.history.handler(async ({ input }) => {
|
||||
const items = await getBatteryHistory(input.mac)
|
||||
|
||||
// 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,
|
||||
})
|
||||
})
|
||||
@@ -1,6 +0,0 @@
|
||||
import { os } from '@/server/api/server'
|
||||
import * as battery from './battery.router'
|
||||
|
||||
export const router = os.router({
|
||||
battery,
|
||||
})
|
||||
@@ -1,5 +0,0 @@
|
||||
import { implement } from '@orpc/server'
|
||||
import type { BaseContext } from './context'
|
||||
import { contract } from './contracts'
|
||||
|
||||
export const os = implement(contract).$context<BaseContext>()
|
||||
@@ -1,5 +0,0 @@
|
||||
import type { ContractRouterClient, InferContractRouterOutputs } from '@orpc/contract'
|
||||
import type { Contract } from './contracts'
|
||||
|
||||
export type RouterClient = ContractRouterClient<Contract>
|
||||
export type RouterOutputs = InferContractRouterOutputs<Contract>
|
||||
@@ -1,332 +0,0 @@
|
||||
import mysql, { type Pool, type RowDataPacket } from 'mysql2/promise'
|
||||
|
||||
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'
|
||||
|
||||
const historyLimit = 500
|
||||
const predictionHistoryLimit = 10
|
||||
type BatteryInfoMysqlRow = RowDataPacket & BatteryInfoSourceRow
|
||||
type CountMysqlRow = RowDataPacket & {
|
||||
total: number
|
||||
lowPower: number | string | null
|
||||
charging: number | string | null
|
||||
}
|
||||
|
||||
export type LatestBatteryPageInput = {
|
||||
pageSize: number
|
||||
cursor?: string
|
||||
search?: string
|
||||
lowPower?: boolean
|
||||
powerStatus?: PowerStatus
|
||||
sort?: BatteryListSort
|
||||
}
|
||||
|
||||
export type LatestBatteryPage = {
|
||||
items: BatteryInfo[]
|
||||
nextCursor: string | null
|
||||
total?: number
|
||||
lowPower?: number
|
||||
charging?: number
|
||||
}
|
||||
|
||||
type PageCursor = {
|
||||
sort: BatteryListSort
|
||||
createTime: string
|
||||
id: number
|
||||
power?: number
|
||||
}
|
||||
|
||||
let pool: Pool | undefined
|
||||
|
||||
function getBatteryPool() {
|
||||
pool ??= mysql.createPool({
|
||||
uri: env.DATABASE_URL,
|
||||
waitForConnections: true,
|
||||
connectionLimit: 5,
|
||||
namedPlaceholders: true,
|
||||
dateStrings: true,
|
||||
})
|
||||
|
||||
return pool
|
||||
}
|
||||
|
||||
export async function closeBatteryPool() {
|
||||
if (!pool) return
|
||||
|
||||
await pool.end()
|
||||
pool = undefined
|
||||
}
|
||||
|
||||
const sourceColumns = `
|
||||
id,
|
||||
user_id AS userId,
|
||||
mac,
|
||||
dev_model AS devModel,
|
||||
dev_name AS devName,
|
||||
is_low_power AS isLowPower,
|
||||
power_status AS powerStatus,
|
||||
power,
|
||||
create_time AS createTime,
|
||||
remark
|
||||
`
|
||||
|
||||
const normalizedColumns = `
|
||||
id,
|
||||
userId,
|
||||
mac,
|
||||
devModel,
|
||||
devName,
|
||||
isLowPower,
|
||||
powerStatus,
|
||||
power,
|
||||
createTime,
|
||||
remark
|
||||
`
|
||||
|
||||
const latestRecordPredicate = `
|
||||
NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM ls_battery_info AS newer_record
|
||||
WHERE newer_record.mac = current_record.mac
|
||||
AND (
|
||||
newer_record.create_time > current_record.create_time
|
||||
OR (newer_record.create_time = current_record.create_time AND newer_record.id > current_record.id)
|
||||
)
|
||||
)
|
||||
`
|
||||
|
||||
const orderByBySort: Record<BatteryListSort, string> = {
|
||||
[BATTERY_LIST_SORT.CREATED_AT_DESC]: 'current_record.create_time DESC, current_record.id DESC',
|
||||
[BATTERY_LIST_SORT.CREATED_AT_ASC]: 'current_record.create_time ASC, current_record.id ASC',
|
||||
[BATTERY_LIST_SORT.POWER_DESC]: 'current_record.power DESC, 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) {
|
||||
if (value === null || value === undefined) return 0
|
||||
return Number(value)
|
||||
}
|
||||
|
||||
function encodeCursor(item: BatteryInfo, sort: BatteryListSort) {
|
||||
const cursor: PageCursor = {
|
||||
sort,
|
||||
createTime: item.createTime,
|
||||
id: item.id,
|
||||
power: sort === BATTERY_LIST_SORT.POWER_ASC || sort === BATTERY_LIST_SORT.POWER_DESC ? item.power : undefined,
|
||||
}
|
||||
|
||||
return Buffer.from(JSON.stringify(cursor)).toString('base64url')
|
||||
}
|
||||
|
||||
function decodeCursor(value: string | undefined, sort: BatteryListSort): PageCursor | null {
|
||||
if (!value) return null
|
||||
|
||||
try {
|
||||
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 (
|
||||
(sort === BATTERY_LIST_SORT.POWER_ASC || sort === BATTERY_LIST_SORT.POWER_DESC) &&
|
||||
typeof decoded.power !== 'number'
|
||||
) {
|
||||
return null
|
||||
}
|
||||
|
||||
return decoded as PageCursor
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
function escapeLike(value: string) {
|
||||
return value.replace(/[\\%_]/g, (match) => `\\${match}`)
|
||||
}
|
||||
|
||||
function normalizeCursorDateTime(value: string) {
|
||||
return value.includes('T') ? value.slice(0, 19).replace('T', ' ') : value
|
||||
}
|
||||
|
||||
function createLatestWhere(input: LatestBatteryPageInput, cursor: PageCursor | null) {
|
||||
const clauses = [latestRecordPredicate]
|
||||
const params: Record<string, string | number> = {}
|
||||
|
||||
if (input.search) {
|
||||
clauses.push(
|
||||
"(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)}%`
|
||||
}
|
||||
|
||||
if (input.lowPower !== undefined) {
|
||||
clauses.push('LOWER(TRIM(current_record.is_low_power)) = :lowPower')
|
||||
params.lowPower = toMysqlBoolean(input.lowPower)
|
||||
}
|
||||
|
||||
if (input.powerStatus !== undefined) {
|
||||
clauses.push('current_record.power_status = :powerStatus')
|
||||
params.powerStatus = input.powerStatus
|
||||
}
|
||||
|
||||
if (cursor) {
|
||||
params.cursorCreateTime = normalizeCursorDateTime(cursor.createTime)
|
||||
params.cursorId = cursor.id
|
||||
|
||||
switch (input.sort ?? BATTERY_LIST_SORT.CREATED_AT_DESC) {
|
||||
case BATTERY_LIST_SORT.CREATED_AT_ASC:
|
||||
clauses.push(
|
||||
'(current_record.create_time > :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id > :cursorId))',
|
||||
)
|
||||
break
|
||||
case BATTERY_LIST_SORT.POWER_DESC:
|
||||
params.cursorPower = cursor.power ?? 0
|
||||
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))))',
|
||||
)
|
||||
break
|
||||
case BATTERY_LIST_SORT.POWER_ASC:
|
||||
params.cursorPower = cursor.power ?? 0
|
||||
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))))',
|
||||
)
|
||||
break
|
||||
case BATTERY_LIST_SORT.CREATED_AT_DESC:
|
||||
clauses.push(
|
||||
'(current_record.create_time < :cursorCreateTime OR (current_record.create_time = :cursorCreateTime AND current_record.id < :cursorId))',
|
||||
)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
return { whereSql: clauses.map((clause) => `(${clause})`).join(' AND '), params }
|
||||
}
|
||||
|
||||
export async function getBatteryHistory(mac: string): Promise<BatteryInfo[]> {
|
||||
const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>(
|
||||
`
|
||||
SELECT ${sourceColumns}
|
||||
FROM ls_battery_info
|
||||
WHERE mac = :mac
|
||||
ORDER BY create_time DESC, id DESC
|
||||
LIMIT :limit
|
||||
`,
|
||||
{ mac, limit: historyLimit },
|
||||
)
|
||||
|
||||
return rows.map(toBatteryInfo)
|
||||
}
|
||||
|
||||
export async function getBatteryPredictionHistory(mac: string): Promise<BatteryInfo[]> {
|
||||
const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>(
|
||||
`
|
||||
SELECT ${sourceColumns}
|
||||
FROM ls_battery_info
|
||||
WHERE mac = :mac
|
||||
ORDER BY create_time DESC, id DESC
|
||||
LIMIT :limit
|
||||
`,
|
||||
{ mac, limit: predictionHistoryLimit },
|
||||
)
|
||||
|
||||
return rows.map(toBatteryInfo).reverse()
|
||||
}
|
||||
|
||||
export async function getBatteryPredictionHistories(macAddresses: string[]): Promise<Map<string, BatteryInfo[]>> {
|
||||
if (macAddresses.length === 0) return new Map()
|
||||
|
||||
const params = Object.fromEntries(macAddresses.map((mac, index) => [`mac${index}`, mac]))
|
||||
const placeholders = macAddresses.map((_, index) => `:mac${index}`).join(', ')
|
||||
const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>(
|
||||
`
|
||||
SELECT ${normalizedColumns}
|
||||
FROM (
|
||||
SELECT
|
||||
${sourceColumns},
|
||||
ROW_NUMBER() OVER (PARTITION BY mac ORDER BY create_time DESC, id DESC) AS history_rank
|
||||
FROM ls_battery_info
|
||||
WHERE mac IN (${placeholders})
|
||||
) AS ranked_history
|
||||
WHERE ranked_history.history_rank <= :limit
|
||||
ORDER BY ranked_history.mac ASC, ranked_history.createTime ASC, ranked_history.id ASC
|
||||
`,
|
||||
{ ...params, limit: predictionHistoryLimit },
|
||||
)
|
||||
|
||||
const histories = new Map<string, BatteryInfo[]>()
|
||||
for (const item of rows.map(toBatteryInfo)) {
|
||||
histories.set(item.mac, [...(histories.get(item.mac) ?? []), item])
|
||||
}
|
||||
|
||||
return histories
|
||||
}
|
||||
|
||||
export async function getLatestBatteryPage(input: LatestBatteryPageInput): Promise<LatestBatteryPage> {
|
||||
const sort = input.sort ?? BATTERY_LIST_SORT.CREATED_AT_DESC
|
||||
const pageSize = Math.min(Math.max(input.pageSize, 1), 100)
|
||||
const cursor = decodeCursor(input.cursor, sort)
|
||||
const { whereSql, params } = createLatestWhere({ ...input, sort, pageSize }, cursor)
|
||||
const countWhere = createLatestWhere({ ...input, sort, pageSize }, null)
|
||||
const queryLimit = pageSize + 1
|
||||
|
||||
const [rows] = await getBatteryPool().query<BatteryInfoMysqlRow[]>(
|
||||
`
|
||||
SELECT ${sourceColumns}
|
||||
FROM ls_battery_info AS current_record
|
||||
WHERE ${whereSql}
|
||||
ORDER BY ${orderByBySort[sort]}
|
||||
LIMIT :limit
|
||||
`,
|
||||
{ ...params, limit: queryLimit },
|
||||
)
|
||||
|
||||
const pageItems = rows.slice(0, pageSize).map(toBatteryInfo)
|
||||
const lastPageItem = pageItems.at(-1)
|
||||
const nextCursor = rows.length > pageSize && lastPageItem ? encodeCursor(lastPageItem, sort) : null
|
||||
|
||||
const [countRows] = await getBatteryPool().query<CountMysqlRow[]>(
|
||||
`
|
||||
SELECT
|
||||
COUNT(*) AS total,
|
||||
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}
|
||||
`,
|
||||
countWhere.params,
|
||||
)
|
||||
const counts = countRows[0]
|
||||
|
||||
return {
|
||||
items: pageItems,
|
||||
nextCursor,
|
||||
total: toNumber(counts?.total),
|
||||
lowPower: toNumber(counts?.lowPower),
|
||||
charging: toNumber(counts?.charging),
|
||||
}
|
||||
}
|
||||
|
||||
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${limitSql}
|
||||
`,
|
||||
queryParams,
|
||||
)
|
||||
|
||||
return rows.map(toBatteryInfo)
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
import { configureSync, getConfig, getConsoleSink, getJsonLinesFormatter } from '@logtape/logtape'
|
||||
import { prettyFormatter } from '@logtape/pretty'
|
||||
import { env } from '@/env'
|
||||
|
||||
if (getConfig() === null) {
|
||||
const format = env.LOG_FORMAT ?? (process.stdout.isTTY ? 'pretty' : 'json')
|
||||
|
||||
configureSync({
|
||||
sinks: {
|
||||
console: getConsoleSink({ formatter: format === 'pretty' ? prettyFormatter : getJsonLinesFormatter() }),
|
||||
},
|
||||
loggers: [
|
||||
{ category: [], lowestLevel: env.LOG_LEVEL, sinks: ['console'] },
|
||||
{ category: ['logtape', 'meta'], lowestLevel: 'warning', sinks: ['console'], parentSinks: 'override' },
|
||||
],
|
||||
})
|
||||
}
|
||||
|
||||
export { getLogger } from '@logtape/logtape'
|
||||
@@ -1,30 +0,0 @@
|
||||
import { closeBatteryPool } from '@/server/battery/mysql'
|
||||
import { getLogger } from '@/server/logger'
|
||||
|
||||
export default () => {
|
||||
if (import.meta.dev) return
|
||||
|
||||
const logger = getLogger(['shutdown'])
|
||||
let exiting = false
|
||||
|
||||
const shutdown = async (signal: NodeJS.Signals) => {
|
||||
if (exiting) {
|
||||
logger.warn('Forcing exit on repeated signal', { signal })
|
||||
process.exit(0)
|
||||
}
|
||||
exiting = true
|
||||
logger.info('Draining for shutdown', { signal, graceMs: 500 })
|
||||
|
||||
await Bun.sleep(500)
|
||||
try {
|
||||
await closeBatteryPool()
|
||||
logger.info('Battery MySQL pool closed, exiting')
|
||||
} catch (error) {
|
||||
logger.error('DB pool close failed during shutdown', { error })
|
||||
}
|
||||
process.exit(0)
|
||||
}
|
||||
|
||||
process.on('SIGINT', () => void shutdown('SIGINT'))
|
||||
process.on('SIGTERM', () => void shutdown('SIGTERM'))
|
||||
}
|
||||
@@ -1,97 +0,0 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -1,225 +0,0 @@
|
||||
import { LRUCache } from 'lru-cache'
|
||||
import { z } from 'zod'
|
||||
import { type BatteryInfo, type BatteryPrediction, type PowerStatus, toMysqlBoolean } from '@/domain/battery'
|
||||
import { env } from '@/env'
|
||||
import { getLogger } from '@/server/logger'
|
||||
|
||||
export const sohPredictionSchema = z.object({
|
||||
batteryId: z.number().int(),
|
||||
mac: z.string(),
|
||||
nowSoh: z.number(),
|
||||
monthSoh: z.number(),
|
||||
trmonthSoh: z.number(),
|
||||
riskScore: z.number().nullable(),
|
||||
riskLevel: z.string().nullable(),
|
||||
status: z.string().nullable(),
|
||||
modelName: z.string().nullable(),
|
||||
cyclesUsed: z.number().int().nullable(),
|
||||
updatedAt: z.string().nullable(),
|
||||
})
|
||||
export type SohPrediction = BatteryPrediction & z.infer<typeof sohPredictionSchema>
|
||||
|
||||
type PredictionHistoryItem = {
|
||||
cycle: number
|
||||
charge_capacity_ah: number
|
||||
discharge_capacity_ah: number
|
||||
timestamp: string
|
||||
}
|
||||
|
||||
type PredictionRequest = {
|
||||
battery: {
|
||||
id: number
|
||||
user_id: number
|
||||
mac: string
|
||||
dev_model: string
|
||||
dev_name: string
|
||||
is_low_power: string
|
||||
power_status: PowerStatus
|
||||
power: number
|
||||
create_time: string
|
||||
remark: string
|
||||
}
|
||||
history: PredictionHistoryItem[]
|
||||
}
|
||||
|
||||
const predictionResponseSchema = z.object({
|
||||
now_soh: z.number(),
|
||||
month_soh: z.number(),
|
||||
trmonth_soh: z.number(),
|
||||
risk_score: z.number().nullable().optional(),
|
||||
risk_level: z.string().nullable().optional(),
|
||||
status: z.string().nullable().optional(),
|
||||
battery_id: z.number().int(),
|
||||
mac: z.string(),
|
||||
model_name: z.string().nullable().optional(),
|
||||
cycles_used: z.number().int().nullable().optional(),
|
||||
updated_at: z.string().nullable().optional(),
|
||||
})
|
||||
|
||||
const logger = getLogger(['prediction'])
|
||||
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
|
||||
|
||||
function normalizeMysqlDateTime(value: string) {
|
||||
if (!value.includes('T')) return value
|
||||
|
||||
return value.slice(0, 19).replace('T', ' ')
|
||||
}
|
||||
|
||||
function createCacheKey(battery: BatteryInfo, history: BatteryInfo[]) {
|
||||
const latestHistory = history.at(-1)
|
||||
const latestId = latestHistory?.id ?? battery.id
|
||||
const latestTime = latestHistory?.createTime ?? battery.createTime
|
||||
|
||||
return `${battery.mac}:${latestId}:${latestTime}`
|
||||
}
|
||||
|
||||
function createHistoryItem(item: BatteryInfo, index: number): PredictionHistoryItem {
|
||||
const observedCapacityRatio = Math.max(0.5, Math.min(1, item.power / 100))
|
||||
const chargeCapacityAh = round2(nominalCapacityAh * observedCapacityRatio)
|
||||
|
||||
return {
|
||||
cycle: index + 1,
|
||||
charge_capacity_ah: chargeCapacityAh,
|
||||
discharge_capacity_ah: round2(chargeCapacityAh * 0.96),
|
||||
timestamp: normalizeMysqlDateTime(item.createTime),
|
||||
}
|
||||
}
|
||||
|
||||
export function createPredictionRequest(battery: BatteryInfo, history: BatteryInfo[]): PredictionRequest | null {
|
||||
const sourceHistory = history.length > 0 ? history : [battery]
|
||||
|
||||
if (sourceHistory.length < 5) return null
|
||||
|
||||
return {
|
||||
battery: {
|
||||
id: battery.id,
|
||||
user_id: battery.userId,
|
||||
mac: battery.mac,
|
||||
dev_model: battery.devModel,
|
||||
dev_name: battery.devName,
|
||||
is_low_power: toMysqlBoolean(battery.isLowPower),
|
||||
power_status: battery.powerStatus,
|
||||
power: battery.power,
|
||||
create_time: normalizeMysqlDateTime(battery.createTime),
|
||||
remark: battery.remark ?? '',
|
||||
},
|
||||
history: sourceHistory.map(createHistoryItem),
|
||||
}
|
||||
}
|
||||
|
||||
export function normalizePrediction(response: z.infer<typeof predictionResponseSchema>): SohPrediction {
|
||||
return {
|
||||
batteryId: response.battery_id,
|
||||
mac: response.mac,
|
||||
nowSoh: response.now_soh,
|
||||
monthSoh: response.month_soh,
|
||||
trmonthSoh: response.trmonth_soh,
|
||||
riskScore: response.risk_score ?? null,
|
||||
riskLevel: response.risk_level ?? null,
|
||||
status: response.status ?? null,
|
||||
modelName: response.model_name ?? null,
|
||||
cyclesUsed: response.cycles_used ?? null,
|
||||
updatedAt: response.updated_at ?? null,
|
||||
}
|
||||
}
|
||||
|
||||
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 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)
|
||||
if (pendingRequest) return pendingRequest
|
||||
|
||||
const requestPromise = requestPrediction(cacheKey, battery, request)
|
||||
inFlightRequests.set(cacheKey, requestPromise)
|
||||
|
||||
return requestPromise
|
||||
}
|
||||
|
||||
async function requestPrediction(
|
||||
cacheKey: string,
|
||||
battery: BatteryInfo,
|
||||
request: PredictionRequest,
|
||||
): Promise<SohPrediction | null> {
|
||||
const controller = new AbortController()
|
||||
const timeout = setTimeout(() => controller.abort(), env.SOH_PREDICTION_TIMEOUT_MS)
|
||||
const baseUrl = env.SOH_PREDICTION_API_BASE_URL.endsWith('/')
|
||||
? env.SOH_PREDICTION_API_BASE_URL
|
||||
: `${env.SOH_PREDICTION_API_BASE_URL}/`
|
||||
const endpoint = new URL('predict', baseUrl)
|
||||
|
||||
try {
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
headers: { 'content-type': 'application/json' },
|
||||
body: JSON.stringify(request),
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
logger.warn('SOH prediction request failed', { mac: battery.mac, status: response.status })
|
||||
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 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()
|
||||
}
|
||||