Compare commits

...

58 Commits

Author SHA1 Message Date
imbytecat 7b2ae856b7 fix(prediction): 适配预测服务最小请求字段 2026-05-12 01:49:19 +08:00
imbytecat c00e04dfb0 fix(prediction): 跳过缺少遥测字段的预测请求 2026-05-12 01:43:46 +08:00
imbytecat 305ed1b692 fix(domain): 使用空值表示缺失业务指标 2026-05-12 01:09:10 +08:00
imbytecat 1126fad2c2 fix(prediction): 使用真实历史字段请求预测 2026-05-12 01:09:09 +08:00
imbytecat 76854fe23b fix(api): 禁用未启用的 OpenAPI 端点 2026-05-12 01:09:09 +08:00
imbytecat e6b351e39c feat(ui): 优化看板和设备列表体验 2026-05-12 01:01:15 +08:00
imbytecat 6014af2690 feat(ui): 添加空态和骨架组件 2026-05-12 01:01:15 +08:00
imbytecat 4147d15a42 chore(pkg): 更新项目包元数据 2026-05-12 00:57:20 +08:00
imbytecat 282fdbc2a6 fix(ui): 完整遵守减少动态效果偏好 2026-05-12 00:56:33 +08:00
imbytecat ad32500121 fix(dashboard): 使用稳定设备标识 2026-05-12 00:56:33 +08:00
imbytecat 9fb37b29c2 fix(data): 统一 MySQL 时间和布尔规范化 2026-05-12 00:56:33 +08:00
imbytecat 2d068fa66b docs(api): 说明接口文档启用方式 2026-05-12 00:52:43 +08:00
imbytecat 779c9c2338 fix(prediction): 缓存不可用预测结果 2026-05-12 00:52:43 +08:00
imbytecat fad890abe1 fix(api): 默认关闭接口文档 2026-05-12 00:52:43 +08:00
imbytecat 11cf298332 fix(ui): 限制分页游标历史长度 2026-05-12 00:48:16 +08:00
imbytecat 25d7f1c315 fix(api): 修正看板和历史统计口径 2026-05-12 00:48:16 +08:00
imbytecat 58b615a327 style(ui): 移除过期原生下拉样式 2026-05-12 00:45:00 +08:00
imbytecat 8f953cd6a1 feat(ui): 替换原生下拉控件 2026-05-12 00:39:44 +08:00
imbytecat 84e3f02752 chore(deps): 添加 Radix Select 依赖 2026-05-12 00:39:44 +08:00
imbytecat 2dabbd1281 feat(ui): 添加克制页面动效 2026-05-12 00:30:16 +08:00
imbytecat 602f969117 chore(deps): 添加 Motion 动效依赖 2026-05-12 00:30:16 +08:00
imbytecat 32946b25fa docs: 优化交付文档表达 2026-05-12 00:18:00 +08:00
imbytecat 50e8e32bac fix(ui): 修复充电状态筛选重置 2026-05-12 00:18:00 +08:00
imbytecat 4571cee2a1 feat(ui): 优化电池实时状态筛选体验 2026-05-12 00:07:15 +08:00
imbytecat 38943f239f feat(ui): 增强电池看板状态表达 2026-05-12 00:07:15 +08:00
imbytecat 5d9aa660d8 fix(domain): 移除虚构 SoH 趋势语义 2026-05-12 00:07:15 +08:00
imbytecat e9568bca8c chore(dev): 统一 Compose 环境变量格式 2026-05-11 23:42:28 +08:00
imbytecat ba4aa96baf docs(prediction): 明确 SoH 预测必填依赖 2026-05-11 23:38:38 +08:00
imbytecat 8a3d5fd947 fix(env): 要求配置 SoH 预测服务 2026-05-11 23:38:38 +08:00
imbytecat a131bb845b fix(dashboard): 正确展示 SoH 预测不可用 2026-05-11 23:38:37 +08:00
imbytecat 99d9cd1e1d refactor(api): 复用电池业务常量 2026-05-11 23:38:37 +08:00
imbytecat dc8a595d0a refactor(domain): 集中电池业务常量 2026-05-11 23:38:37 +08:00
imbytecat a8e3cf5f4b docs(api): 更新电池分页接口说明 2026-05-11 23:16:59 +08:00
imbytecat c533113229 feat(ui): 重构电池列表分页表格 2026-05-11 23:16:59 +08:00
imbytecat 69c4a2e9eb fix(api): 收紧电池列表查询输入 2026-05-11 23:16:59 +08:00
imbytecat dd4a447dcd style: 格式化后端改造代码 2026-05-11 23:16:59 +08:00
imbytecat cf6f91651d feat(api): 支持电池分页和安全预测 2026-05-11 22:39:05 +08:00
imbytecat 29e70fea9a refactor(domain): 标注 SoH 来源语义 2026-05-11 22:39:05 +08:00
imbytecat 6ff9dbe772 chore(deps): 添加表格和缓存依赖 2026-05-11 22:39:05 +08:00
imbytecat c936167fc8 docs(prediction): 说明 AI 预测服务配置 2026-05-11 22:21:57 +08:00
imbytecat 1a2ff19cf4 feat(dashboard): 接入预测结果聚合 2026-05-11 22:21:57 +08:00
imbytecat b11d37e9d8 feat(prediction): 新增 AI SoH 预测客户端 2026-05-11 22:21:57 +08:00
imbytecat c8ea9330e1 chore(ignore): 忽略本地 MySQL 数据目录 2026-05-11 21:58:23 +08:00
imbytecat 8824db8019 chore(dev): 改用 Compose named volume 2026-05-11 21:58:23 +08:00
imbytecat 158d4007e4 feat(ui): 使用 Recharts 并改为客户端 API 请求 2026-05-11 21:58:23 +08:00
imbytecat 749697634a chore(env): 更新本地环境示例 2026-05-11 20:51:43 +08:00
imbytecat 6f627fe776 docs: 更新 MySQL 展示系统说明 2026-05-11 20:51:43 +08:00
imbytecat ddd077eb37 chore(dev): 添加本地 MySQL seed 环境 2026-05-11 20:51:43 +08:00
imbytecat 3040608959 refactor(db): 移除嵌入式迁移链路 2026-05-11 20:51:43 +08:00
imbytecat bec1026a94 refactor(db): 移除 PostgreSQL 运行时层 2026-05-11 20:51:43 +08:00
imbytecat e722913468 refactor(todo): 移除 Todo API 示例 2026-05-11 20:51:34 +08:00
imbytecat 334e387765 refactor(todo): 移除 Todo 前端示例 2026-05-11 20:51:34 +08:00
imbytecat b722799ca3 feat(ui): 新增电池实时状态页 2026-05-11 20:51:34 +08:00
imbytecat df7b58c2f8 feat(ui): 重建 SoH 看板首页 2026-05-11 20:51:34 +08:00
imbytecat 4e5ba4b599 feat(api): 实现电池 ORPC 路由 2026-05-11 20:51:24 +08:00
imbytecat 657c7317f7 feat(api): 暴露电池 ORPC 契约 2026-05-11 20:51:24 +08:00
imbytecat ebe0970df1 feat(mysql): 接入只读电池数据源 2026-05-11 20:51:24 +08:00
imbytecat 8b6339f34b feat(domain): 新增电池领域模型与聚合逻辑 2026-05-11 20:51:24 +08:00
49 changed files with 3615 additions and 995 deletions
+12 -3
View File
@@ -1,6 +1,15 @@
DATABASE_URL=postgres://postgres:postgres@localhost:5432/postgres
DATABASE_URL=mysql://user:password@localhost:3306/database
# Optional logging knobs (defaults are usually fine):
# 默认关闭公开 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 # true to log every Drizzle SQL query
# LOG_DB=false # reserved for database query logging if enabled later
+1
View File
@@ -6,6 +6,7 @@ node_modules/
.tanstack/
.vite/
out/
volumes/
*.bun-build
*.tsbuildinfo
vite.config.js.timestamp-*
+76 -199
View File
@@ -1,232 +1,109 @@
# AGENTS.md
Compact, repo-specific notes for AI agents. Generic language/framework knowledge is omitted — only things that will bite you if you don't know. Pair this with `README.md` (user-facing quick-start + add-a-feature checklist + deploy flow).
Repo-specific notes for AI agents.
## Stack & runtime
## Stack
- **Bun-only** (`mise.toml` pins `bun = 1.3.13`). Never invoke `npm`/`npx`/`node`/`yarn`/`pnpm`. Use `bun run <script>` (bare `bun <script>` can collide with Bun built-in subcommands).
- **Prefer Bun-native APIs over external packages and `node:*` polyfills.** UUIDv7 in app code → `Bun.randomUUIDv7()` (not the `uuid` package); DB primary keys are a separate matter — those go through PG18's `uuidv7()`, see "Drizzle" section. SHA-256 → `Bun.CryptoHasher.hash('sha256', s, 'hex')` (not `node:crypto.createHash`); short sleeps → `Bun.sleep(ms)` (not raw `setTimeout` with promise wrapping); file I/O in build scripts → `Bun.file` / `Bun.write` are fine. The runtime is Bun, the deployment target is Bun, the test runner is Bun — there is no "portability" concern that would justify dragging in npm packages or Node compat shims for things Bun ships natively.
- TanStack Start (React 19 SSR, file-routed) + Vite 8 + Nitro (nightly, preset `bun`). Dev server defaults to Vite's port (3000); not pinned, override via `vite dev --port <n>` if you need to.
- **PostgreSQL 18+ only** (`compose.yaml` pins `postgres:18-alpine`). The starter relies on PG18's built-in `uuidv7()` function for primary-key generation — see "Drizzle" section. Do not soften this to support older PG; if you need PG <18 compatibility, fork and reintroduce app-side UUIDv7 (e.g. `Bun.randomUUIDv7()` or the `uuid` package) yourself.
- **Drizzle ORM `0.45.2` (0.x, NOT 1.0 beta)** — see "Drizzle" section, this matters a lot.
- ORPC (contract-first), TanStack Query v5, Tailwind v4.
- **Logging via [LogTape](https://logtape.org/)** (zero-dep, runtime-agnostic) — see "Logging" section. `console.*` is forbidden in business code.
- 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.
## Scripts
```bash
bun run dev # bunx --bun vite dev (localhost:3000)
bun run build # bunx --bun vite build → .output/
bun run compile # bun scripts/compile.ts → out/server-<target> (standalone CLI binary)
bun run cli <cmd> # bun src/bin.ts <cmd> — run a CLI subcommand in source (dev)
bun run typecheck # tsc --noEmit
bun run test # bun test — runs all *.test.ts files (colocated with source)
bun run fix # biome check --write (lint + format + organize imports)
bun run db:push # dev only — push schema to DB, no migration file
bun run db:generate # drizzle-kit generate && scripts/embed-migrations.ts (regenerates migrations.gen.ts)
bun run db:embed # scripts/embed-migrations.ts only — regenerate migrations.gen.ts from ./drizzle/
bun run db:migrate # apply migrations via drizzle-kit (local dev convenience; prod uses ./server migrate)
bun run db:studio # Drizzle Studio
bun run dev
bun run build
bun run compile
bun run seed
bun run typecheck
bun run test
bun run fix
```
Cross-compile targets live under `compile:{linux,darwin,windows}[:arch]`. `scripts/compile.ts` accepts `--target bun-<os>-<arch>`; default derives from host.
Before shipping: `bun run fix && bun run typecheck && bun run test && bun run build`.
Before committing: `bun run fix && bun run typecheck && bun run test`. No CI, no pre-commit hooks, no lint-staged — so these are on you.
## MySQL Source
## Drizzle (v0.x — critical)
Environment variable:
**Why it matters:** the project was on 1.0 beta and was rolled back. Online docs default to 1.0 beta APIs that do NOT exist here. If typecheck complains, you are probably importing a 1.0 beta API.
- Driver: `drizzle-orm/postgres-js`. Do NOT use `drizzle-orm/bun-sql`.
- `drizzle()` is called with `{ connection, schema }` where `schema = import * as schema from '@/server/db/schema'`. There is **no `relations.ts`** and **no `defineRelations`** in 0.x.
- Zod generators live in the separate `drizzle-zod` package (`^0.8.3`). Import from `drizzle-zod`, **not** `drizzle-orm/zod` (that subpath only exists in 1.0 beta).
- Relational queries use **RQB v1 callback syntax**:
```ts
db.query.todoTable.findMany({
orderBy: (t, { desc }) => desc(t.createdAt),
})
```
Do NOT use the v2 object form (`orderBy: { createdAt: 'desc' }`, `where: { id }`) — it won't type-check.
- To add relations later: declare per-table with `relations()` from `drizzle-orm` and export them from the same file as the table; they get picked up automatically because `index.ts` does `drizzle({ schema })` via `import *`.
- Every table must spread `...generatedFields` from `src/server/db/fields.ts` (`id uuid PRIMARY KEY DEFAULT uuidv7() NOT NULL` — **Postgres-side generation**, requires PG18+; `createdAt`, `updatedAt` with `$onUpdateFn`). The DB is the single source of UUIDv7 truth: monotonic per cluster, uses DB clock, no app-side round-trip. **Do not reintroduce `$defaultFn(() => Bun.randomUUIDv7())`** — the SQL default is what the migration emits and what `drizzle-zod` reads as "optional in insert schema". `generatedFieldKeys` is hand-written and uses `satisfies Record<keyof typeof generatedFields, true>` so any field-key drift fails typecheck; it feeds `createInsertSchema(...).omit(...)` / `createUpdateSchema(...).omit(...)`.
- `src/server/db/index.ts` exports a module-level `const db = drizzle(...)` — not a lazy singleton. On Bun this is a long-lived process, so top-level side effects are fine and requested. Don't reintroduce `getDB/closeDB` ceremony; the Nitro shutdown plugin calls `db.$client.end()` directly. (Cloudflare Workers would need per-request init — we don't support that deployment target.)
- `drizzle.config.ts` runs outside Vite — `@/*` path aliases do NOT resolve there. It currently does `import { env } from './src/env'` (relative). Preserve that.
- **Migrations are embedded in the binary, not read from disk.** `bun run db:generate` chains `drizzle-kit generate && bun scripts/embed-migrations.ts`, which regenerates `src/server/db/migrations.gen.ts` (committed, AUTO-GENERATED header) by `import sql_<idx> from '#drizzle/<tag>.sql' with { type: 'text' }`. `src/cli/migrate.ts` reads `embeddedMigrations`, **validates SHA-256 hash of every already-applied migration against the embedded SQL** (rejects schema drift if anyone edited an applied migration), then applies pending entries via `db.execute(sql\`...\`)` + `db.transaction(...)` against the `drizzle.__drizzle_migrations` book-keeping table — public APIs only, no `db.dialect`/`db.session` (those are `@internal`). Each migration is split on `--> statement-breakpoint`; empty fragments are trimmed and skipped. Dev helpers `db:push` / `drizzle-kit migrate` still read `./drizzle/`.
## CLI & single-binary deploy
`bun run compile` produces a single executable that dispatches subcommands via [citty](https://github.com/unjs/citty). Entry is `src/bin.ts`; subcommands live in `src/cli/`.
```
./server [serve] # default — start the HTTP server
./server migrate # apply embedded migrations
./server --help
```bash
DATABASE_URL=mysql://user:password@host:3306/database
```
**Nitro side-effect pitfall (important).** Under the `bun` preset, `.output/server/index.mjs` has a top-level `serve(...)` call — merely importing it starts the HTTP server. `src/bin.ts` therefore must not eager-import any subcommand module, and `src/cli/serve.ts` reaches `.output/server/index.mjs` through the `src/cli/_serve-nitro.mjs` bridge (with `_serve-nitro.d.mts` for types, since `.output/` doesn't exist at typecheck time). Citty's `subCommands: { x: () => import('...') }` lazy-loader is what keeps `--help` and `migrate` from booting the server.
Required AI prediction service:
**Citty eager-loads subcommand modules for `--help`** to read each subcommand's `meta`. So every `src/cli/*.ts` module body must be side-effect-free: do NOT static-import `@/env`, `@/server/db/*`, or anything that reads env at module-load time. Use `await import('@/env')` inside `run()`. Otherwise `./server --help` (or any subcommand's help) will fail with env validation errors before printing.
Add a subcommand: drop a file in `src/cli/` that default-exports `defineCommand({...})`, then register it in `src/bin.ts`'s `subCommands` with a `() => import(...)` thunk. Keep top-level imports limited to `citty` + Node built-ins; pull env / db / etc. via `await import(...)` inside `run()`.
**Deploy flow is always migrate-then-serve.** Migrations are embedded in the binary (see "Drizzle" section), so the binary is the only artifact — no `./drizzle/` directory at runtime. Dockerfile copies just `./server`. `compose.yaml` models the pattern with a one-shot `migrate` service that `app` `depends_on: service_completed_successfully`. On k8s, run `./server migrate` as an initContainer or a Helm `pre-upgrade` Job; run `./server` (= `./server serve`) as the main container.
## Compile flags
`scripts/compile.ts` builds with `--minify --bytecode --sourcemap=inline`:
- **`bytecode`** — pre-compiles JS to bytecode and embeds it in the binary; ~2x startup on app-sized binaries (Bun docs benchmark). Requires `--compile`; top-level `await` must live inside `async` functions (it already does in this repo).
- **`minify`** — shrinks the binary and the bytecode it derives from.
- **`sourcemap: 'inline'`** — embeds the source map in the binary so error stack traces stay decodable. Bun also writes a residual `out/bin.js.map` next to the output; `scripts/compile.ts` removes it so the binary is the only artifact.
## ORPC
Contract → Router → Handler → Client, all type-safe from a single contract.
- `os` is built in `src/server/api/server.ts` via `implement(contract).$context<BaseContext>()`. **Always import `os` from `@/server/api/server`**, never from `@orpc/server` directly. `ORPCError`, `onError`, `ValidationError` come from `@orpc/server`.
- Contracts (`src/server/api/contracts/*.contract.ts`) generate Zod from Drizzle tables via `drizzle-zod`:
```ts
const insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)
```
Barrel-aggregated in `contracts/index.ts` as `export const contract = { todo }`.
- Routers (`src/server/api/routers/*.router.ts`) import `db` directly from `@/server/db` in their handlers. There is **no `middlewares/` directory** by default — `db` doesn't need one (module-level const). When you actually need per-request context (auth, tenant, rate-limit), create `src/server/api/middlewares/<name>.middleware.ts` with `os.middleware(...)` and extend `BaseContext` in `context.ts`.
- **Interceptors are attached at the handler level, not in `server.ts` and not on `os`.** Both `src/routes/api/rpc.$.ts` (`RPCHandler`) and `src/routes/api/$.ts` (`OpenAPIHandler`) register `[onError(logError)]` (server) and `[onError(handleValidationError)]` (client). The validation interceptor rewrites `BAD_REQUEST + ValidationError` into `INPUT_VALIDATION_FAILED` (422) and output validation errors into `OUTPUT_VALIDATION_FAILED`. `logError` resolves a `getLogger(['api'])` LogTape category — never `console.*` directly. See "Logging" section.
- OpenAPI/Scalar: docs at `/api/docs`, spec at `/api/spec.json` (handler prefix `/api`, plugin paths `/docs` and `/spec.json`).
- **SSR isomorphism** (`src/client/orpc.ts`): `createIsomorphicFn().server(createRouterClient(...)).client(new RPCLink(...))`. Server branch reads `getRequestHeaders()` for context; client branch POSTs to `${origin}/api/rpc`.
- **Mutation invalidation is colocated at the call site** via `mutationOptions({ onSuccess })`, not in `src/client/orpc.ts`. `orpc` in `src/client/orpc.ts` is a plain `createTanstackQueryUtils(client)` — no `experimental_defaults`. Per-feature query helpers live in `src/client/queries/<feature>.ts` (e.g. `useInvalidateTodos`); routes/components compose those hooks rather than holding query keys inline. See `src/client/queries/todo.ts` + `src/routes/index.tsx` for the canonical shape.
- SSR prefetch in route loaders: `await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions())`. Components use `useSuspenseQuery(orpc.feature.list.queryOptions())`.
## Code style (Biome)
- 2-space, LF, single quotes, **semicolons as-needed** (omitted unless required), 120-col, arrow parens always, `useArrowFunction: "error"` (covers function *expressions* only). Also `noReactPropAssignments: "error"`.
- Lint domains enabled (Biome 2.4): `types: "all"` (catches `noFloatingPromises`, `noMisusedPromises`, `useAwaitThenable`, `noUnnecessaryConditions` — TS-aware async/promise traps), `drizzle: "recommended"`, `react: "recommended"`. `noImportCycles` is on under `suspicious`.
- **Route components use `function Foo()` declarations**, placed below the `Route` config so the file reads top-down (route on top, component below). This is the official TanStack Router/Start pattern and relies on hoisting — `const Foo = () => {}` would TDZ-error when referenced from `createFileRoute({ component: Foo })` above it. Inline arrows are fine for trivial leaf components (e.g. plain redirect routes). Non-route components (UI primitives in `src/components/`) use `const Foo = () => {}`.
- Imports are auto-organized into two groups (external, then `@/*`), each alphabetical, with `import type` interleaved (NOT a separate group). `bun run fix` handles this; don't hand-sort.
- Files: utils `kebab-case.ts`, components `PascalCase.tsx`.
- `routeTree.gen.ts` is generated — ignored by Biome, never edit.
## Testing
`bun test` runs all `*.test.ts` files. Tests are colocated next to the source they exercise (e.g. `src/server/api/contracts/todo.contract.test.ts`). Use `import { describe, expect, test } from 'bun:test'`. The `@/*` alias resolves in tests via tsconfig paths. No Vitest, no Jest, no separate test config — keep it that way unless you need a browser/JSDOM environment.
## Endpoints
- `/` — Todos UI (file route).
- `/health` — bare `GET` returning `ok` (200, `text/plain`). Liveness only — no DB check, so it stays green even when Postgres is down. Add a separate `/ready` if you ever need readiness.
- `/api/rpc` — ORPC RPC handler (POST).
- `/api/*` — ORPC OpenAPI handler. Docs at `/api/docs`, spec at `/api/spec.json`.
## TypeScript
Strict mode, plus `noUncheckedIndexedAccess`, `verbatimModuleSyntax`, `erasableSyntaxOnly`, `noImplicitOverride`. No `as any` / `@ts-ignore` / `@ts-expect-error`.
Path alias: `@/* → src/*`. For files outside `src/` use `@/../<file>` (example in the codebase: `src/routes/api/$.ts` imports `name, version` from `@/../package.json`).
## Env
`src/env.ts` via `@t3-oss/env-core`. Server: `DATABASE_URL` (required, `z.url()`), `LOG_LEVEL` (`trace|debug|info|warning|error|fatal`, default `info`), `LOG_FORMAT` (`pretty|json`, default = TTY ? `pretty` : `json`), `LOG_DB` (`stringbool`, default `false` — flips on Drizzle SQL query logging). `client: {}` is empty by default — any client-side env must be `VITE_`-prefixed. Never commit `.env`.
## Logging
All server-side logging goes through `src/server/logger.ts`, a thin wrapper over [LogTape](https://logtape.org/). The module configures LogTape on import (via `configureSync`, no top-level await — works under `--bytecode`) and re-exports `getLogger`.
```ts
import { getLogger } from '@/server/logger'
const logger = getLogger(['feature', 'subsystem'])
logger.info('Created todo {id}', { id })
logger.error('DB write failed', { error })
```bash
SOH_PREDICTION_API_BASE_URL=http://127.0.0.1:8000
SOH_PREDICTION_CACHE_TTL_SECONDS=86400
SOH_PREDICTION_TIMEOUT_MS=10000
```
- Categories are hierarchical arrays — they show up as dot-paths in JSON output (`"logger":"feature.subsystem"`) and let you filter by prefix when shipping logs.
- The `{name}` placeholders are for **primitive** values you want rendered inline (numbers, short strings, IDs). For objects, errors, and anything multi-field, omit the placeholder and just pass the value in properties — `logger.error('Auth failed', { error, userId })` keeps the message clean while properties stay structured. Never string-concatenate or template-literal — that defeats structured logging.
- Format is `pretty` (icons + ANSI) on TTY, `json` (one-line JSON) when piped — perfect for Loki/Datadog/CloudWatch ingestion. Override with `LOG_FORMAT`.
- Drizzle SQL queries are logged at `info` under category `['db']` when `LOG_DB=true`, via `@logtape/drizzle-orm`'s `DrizzleLogger` adapter (constructed in `src/server/db/index.ts`). The `info` level is intentional: flipping `LOG_DB=true` alone is enough — no need to also lower `LOG_LEVEL`.
- `src/server/api/interceptors.ts` calls `getLogger(['api']).error(...)` from `logError`. CLI subcommands lazy-import the logger inside `run()` — they are still required to be side-effect-free at module top (citty eager-loads for `--help`).
- Bun-specific: `process.env.NODE_ENV` is **inlined at build time** by `bun build --minify` — do NOT branch on it for logger config (use `process.stdout.isTTY` or `LOG_FORMAT` instead). pino is unusable here because its worker-thread transports crash inside the `/$bunfs/` virtual filesystem of compiled binaries; LogTape has zero workers and zero dynamic require, so it ships cleanly into the single binary.
Customer table: `ls_battery_info`.
## Docker / deploy
| 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 |
- Multi-stage: `oven/bun:1.3.13` builds and runs `bun scripts/compile.ts`, then `gcr.io/distroless/cc-debian13:nonroot` runs the single `./server` binary. The `cc` (glibc) distroless variant is required because Bun's compiled binary links glibc.
- `compose.yaml`: one-shot `migrate` service runs `./server migrate` with `restart: "no"`, then `app` starts (`depends_on: migrate: service_completed_successfully`). `DATABASE_URL=postgres://postgres:postgres@db:5432/postgres` for both.
- Distroless has no shell, so any init-then-serve pattern must use exec-form `command: [...]`, not `sh -c`.
Rules:
## Layout (non-obvious parts only)
- 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/
├── bin.ts # citty entry — keep imports minimal (see "CLI" section)
├── client/
│ ├── orpc.ts # isomorphic ORPC client + TanStack Query utils (no global invalidation defaults)
│ └── queries/ # per-feature query hooks: keys, options, `useInvalidate<Feature>` helpers
├── cli/ # CLI subcommands (loaded lazily by src/bin.ts via citty)
│ ├── serve.ts # `./server serve` — imports the Nitro bridge on demand
│ ├── migrate.ts # `./server migrate` — applies embedded migrations via public `db.execute(sql)` + `db.transaction()`
│ ├── _serve-nitro.mjs # bridge: `import('#server')` (subpath import → .output/server/index.mjs)
│ └── _serve-nitro.d.mts # types for the bridge (build output has no .d.ts)
├── routes/
│ ├── __root.tsx # root route + RootDocument shell
│ ├── index.tsx # Todos UI
── health.ts # GET /health → "ok" (no DB)
│ └── api/
│ ├── $.ts # OpenAPI + Scalar; interceptors registered here
│ └── rpc.$.ts # RPC; interceptors registered here
│ ├── index.tsx # SoH dashboard
│ ├── batteries.tsx # battery monitor page
── api/ # ORPC handlers
├── server/
│ ├── logger.ts # LogTape `configureSync` + `getLogger` re-export — the only log entrypoint
│ ├── api/
│ ├── server.ts # the ONLY place to build `os`
│ │ ├── context.ts # BaseContext (add per-request fields when you add middlewares)
│ │ ├── interceptors.ts # logError (→ logger), handleValidationError
│ │ ├── types.ts # Router{Client,Inputs,Outputs} derived from Contract
│ │ ├── contracts/ # Zod schemas from Drizzle tables (barrel: contract); colocated *.test.ts
│ │ └── routers/ # os.* handlers (barrel: router) — import db directly
│ ├── db/
│ │ ├── index.ts # module-level `export const db = drizzle({...})`
│ │ ├── fields.ts # generatedFields (id/createdAt/updatedAt) + generatedFieldKeys
│ │ ├── migrations.gen.ts # AUTO-GENERATED by `bun run db:embed`; embeds ./drizzle/*.sql via `with { type: 'text' }`
│ │ ├── sql.d.ts # ambient `declare module '*.sql'` — load-bearing for `with { type: 'text' }` imports in migrations.gen.ts
│ │ └── schema/ # pgTable definitions; also put `relations()` here when adding
│ └── plugins/
│ └── shutdown.ts # SIGINT/SIGTERM → db.$client.end() with 500ms delay (prod only)
├── components/ # non-route UI primitives (PascalCase, arrow const)
├── env.ts # t3-oss env validation
├── router.tsx # QueryClient + setupRouterSsrQueryIntegration
├── styles.css # Tailwind v4 entry
└── routeTree.gen.ts # auto-generated, do not edit
scripts/
├── compile.ts # `bun build --compile` driver; resolves --target; sets minify/bytecode/sourcemap
└── embed-migrations.ts # codegen: scans ./drizzle/meta/_journal.json → src/server/db/migrations.gen.ts
drizzle/ # SQL migrations (source of truth for `db:generate`; not shipped in binary)
│ ├── api/ # contracts / routers / interceptors
│ ├── battery/mysql.ts
└── prediction/client.ts
├── domain/battery.ts
├── client/orpc.ts
── styles.css
```
Nitro plugins are wired in `vite.config.ts` (`nitro({ plugins: [...] })`), not via a Nitro config file.
## ORPC
## Don'ts (specific, non-obvious)
- 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`
- **Don't run `bun run db:generate` (or `drizzle-kit generate`) as an AI agent.** Migration generation is reserved for the human. Make schema changes in `src/server/db/schema/*` + `src/server/db/fields.ts`, push the code changes, and stop — the human will run `bun run db:generate` and commit the resulting `drizzle/*.sql` + `src/server/db/migrations.gen.ts` themselves. (`bun run db:embed` is also off-limits because it's the codegen tail of `db:generate`.)
- Don't edit `routeTree.gen.ts` or `src/server/db/migrations.gen.ts`.
- Don't eager-import anything from `.output/` in `src/bin.ts` or any module it statically imports — it starts the HTTP server as a side effect. Subcommands must be lazy via citty's `() => import(...)` thunks.
- Don't re-add an auto-migrate Nitro plugin. Migrations are an explicit deploy step via `./server migrate`.
- Don't reach into `db.dialect`/`db.session` from `migrate.ts` — they're `@internal`. The current implementation uses public `db.execute(sql)` + `db.transaction(...)` against the documented `drizzle.__drizzle_migrations` schema.
- Don't add `./drizzle/` back to the runtime image — migrations are embedded into the binary.
- Don't reintroduce `getDB/closeDB` or any "lazy DB init" pattern — that's a Cloudflare Workers shape; we deploy on Bun processes.
- Don't import `os` from `@orpc/server` in middleware/routers — always `@/server/api/server`.
- Don't import from `drizzle-orm/zod` (1.0 beta only). Use `drizzle-zod`.
- Don't use RQB v2 object syntax, `defineRelations`, or pass `relations` to `drizzle()`. All are 1.0 beta.
- Don't use `drizzle-orm/bun-sql`.
- Don't use `@/*` aliases in `drizzle.config.ts`.
- Don't commit `.env`.
## CLI And Deploy
## Room-to-grow rules (discipline for the first real feature)
- `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.
These keep the starter from setting bad precedents as it grows. Append, don't restructure.
## Code Style
1. Per-feature client query code — keys, options, `useInvalidate<Feature>` helpers — lives in `src/client/queries/<feature>.ts`. Routes/components compose these hooks; they don't hold query keys inline.
2. Mutation invalidation stays explicit at the mutation call site (`mutationOptions({ onSuccess })`) or in a feature query helper. Do not reintroduce global `experimental_defaults` or any implicit cache policy.
3. Client state defaults to route/component local state. Create a store (zustand or equivalent) only when state is shared across routes or needs persistence.
4. Middlewares (`src/server/api/middlewares/<name>.middleware.ts`) derive request-scoped context or gate access. They do NOT orchestrate business flow, hold side effects, or replace handlers/services.
5. Interceptors (`src/server/api/interceptors.ts`) do cross-cutting error logging, transport normalization, and validation rewrites. They do NOT read business data.
6. One file per Drizzle table. Relations live in the same file and are exported as `<entity>Relations`. No global `relations.ts`.
7. One router file per feature (`routers/<feature>.router.ts`). Only introduce `routers/<domain>/index.ts` when a domain grows past ~5 router files or needs shared domain helpers.
8. All server-side logging goes through `getLogger([...])` from `@/server/logger`. Use a hierarchical category (`['api']`, `['db']`, `['cli', 'migrate']`, etc.) — these become dot-paths in JSON output and let you filter by prefix. Use the `{name}` placeholder + properties form, not string interpolation. `console.*` is forbidden in business code.
9. CLI subcommand modules keep top-level imports to `citty` + Node built-ins. Env, db, and server code are `await import(...)`-ed inside `run()` (see `src/bin.ts` comment for why).
10. Every new business feature ships with at least one `bun test` covering a contract schema, a pure helper, or a router behavior.
- 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.
+4 -1
View File
@@ -1,4 +1,4 @@
FROM oven/bun:1.3.13 AS build
FROM oven/bun:1.3.13 AS source
WORKDIR /app
@@ -6,6 +6,9 @@ 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
+114 -83
View File
@@ -1,112 +1,143 @@
# fullstack-starter
# battery-soh
一个**单二进制**的全栈应用 starter——`bun run compile` 出来的 `./server` 文件就是你要部署的全部产物,自带 HTTP 服务、SSR、API、嵌入式 SQL 迁移,运行时不依赖 Node、不依赖源码、不依赖外部 migration 目录
电池健康运营看板,用于接入客户现有设备数据,持续呈现电量状态、健康预测、风险分布与维护建议。系统以只读方式连接客户数据库,不改动生产数据;当健康预测暂不可用时,页面会明确显示不可用状态,避免用误导性数值替代真实结果
技术栈:Bun · TanStack Start (React 19 SSR) · ORPC(契约优先 API)· Drizzle ORM · PostgreSQL 18+ · Tailwind v4 · Biome。
## 产品能力
## 为什么用这个
- **健康总览**:聚合展示设备规模、平均健康度、30/90 天趋势与预警设备占比。
- **风险识别**:按健康度、低电量、充电状态与预测风险生成重点关注设备清单。
- **实时明细**:支持按设备名称、编号、电量与充电状态筛选设备,快速定位需要排查的对象。
- **维护建议**:基于当前可用数据给出巡检、复查与优先处理建议。
- **可信展示**:缺少预测结果时显示“预测不可用”,不会将缺失值渲染为 `0%`
- **部署最简**:发布只拷一个二进制文件。先 `./server migrate``./server`,完事。
- **契约优先**:在 `*.contract.ts` 用 Zod 定义一次,前端、后端、OpenAPI 文档自动同步。
- **类型严格**TypeScript strict,杜绝 `any` / `@ts-ignore` / `as any` 等类型逃逸。
- **开箱可跑**:路径别名、文件路由、ORPC 接线、Tailwind、热重载、错误页全部预接好。
## 数据接入
系统接入客户现有 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` 不受此开关影响。
## 快速开始
> **需要 PostgreSQL 18+**——schema 用 PG 原生的 `uuidv7()` 生成主键(`compose.yaml` 已锁 `postgres:18-alpine`)。要兼容更老的 PG,把 `src/server/db/fields.ts` 里的 `default(sql\`uuidv7()\`)` 换成 `$defaultFn(() => Bun.randomUUIDv7())`,再跑 `bun run db:generate`。
```bash
cp .env.example .env # 把里面的 DATABASE_URL 改成你的 Postgres
cp .env.example .env
bun install
bun run db:push # 开发期:把 schema 直接同步到 DB(不写 migration 文件)
bun run dev # http://localhost:3000
bun run dev
```
打开浏览器:
- `http://localhost:3000/` — Todo 示例页
- `http://localhost:3000/api/docs` — Scalar 渲染的 API 文档
- `http://localhost:3000/`:设备健康运营看板
- `http://localhost:3000/batteries`:设备状态明细
- `http://localhost:3000/api/docs`:接口文档(需设置 `ENABLE_API_DOCS=true`
## 目录结构(你需要关心的部分)
## 本地演示环境
```
src/
├── routes/ # 文件路由:页面 + API 端点
├── server/
│ ├── api/
│ │ ├── contracts/ # Zod 契约(client / server 共享)
│ │ └── routers/ # 业务实现
│ └── db/ # Drizzle schema + 嵌入式 migrations
├── client/ # 前端 hooks、ORPC 客户端
└── components/ # UI 组件
```
## 加一个功能(以 `post` 为例)
每一步都很短,按顺序填即可:
1. **建表**`src/server/db/schema/post.ts` 定义 `postTable`,记得展开 `...generatedFields`(自动注入 `id` / `createdAt` / `updatedAt`)。
2. **导出表**:在 `src/server/db/schema/index.ts``export * from './post'`
3. **写契约**`src/server/api/contracts/post.contract.ts``drizzle-zod` 从表派生 Zod schema。
4. **挂契约**:在 `src/server/api/contracts/index.ts``post` 加进 `contract` 对象。
5. **写实现**`src/server/api/routers/post.router.ts` 实现 `os.post.*.handler(...)`
6. **挂路由**:在 `src/server/api/routers/index.ts``post` 加进 `router` 对象。
7. **写前端 hook**`src/client/queries/post.ts` 导出 `useInvalidatePosts` 等失效辅助。
8. **写页面**`src/routes/<page>.tsx``useSuspenseQuery` 读、`mutate` 写;mutation 的 `onSuccess` 调用第 7 步的 helper。
9. **生成 migration**`bun run db:generate` 把 SQL 写到 `./drizzle/` 并嵌入二进制。
完工。`bun run dev` 已自动热重载。
## 部署
**永远先 migrate 再 serve**。Migration 已嵌入二进制;部署只发一个 `./server` 文件。
```bash
./server migrate # 应用嵌入式 migration(用 $DATABASE_URL
./server # 启动 HTTP 服务(默认子命令)
./server --help # 列出所有子命令
```
仓库自带 `compose.yaml`(一次性 `migrate` 服务先跑完,再启动 `app`):
如果暂时没有生产数据库连接,可以使用 Docker Compose 启动本地 MySQL 并填充演示数据:
```bash
docker compose up --build
```
Kubernetes 上:把 `./server migrate` 放进 initContainer 或 Helm `pre-upgrade` Job,主容器跑 `./server`
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` | Vite 开发服务器(默认端口 3000) |
| `bun run build` | 构建`.output/``bun run compile` 会用到) |
| `bun run compile` | 生成单二进制 `out/server-<target>` |
| `bun run dev` | 启动开发服务 |
| `bun run build` | 构建应用 |
| `bun run compile` | 生成单二进制产物 |
| `bun run seed` | 初始化本地演示数据 |
| `bun run typecheck` | TypeScript 类型检查 |
| `bun run test` | 运行所有 `*.test.ts` |
| `bun run fix` | Biome 格式化 + lint + 整理 imports |
| `bun run db:push` | 开发期:直接同步 schema 到 DB(不写 migration 文件) |
| `bun run db:generate` | 写 SQL migration 到 `./drizzle/` 并嵌入二进制 |
| `bun run db:embed` | 仅重生 `migrations.gen.ts`(手改了 `./drizzle/*.sql` 后用) |
| `bun run db:migrate` | 通过 drizzle-kit 在本地应用 migration(开发便利) |
| `bun run db:studio` | Drizzle Studio(可视化 DB |
| `bun run test` | 运行测试 |
| `bun run fix` | 格式化与静态检查 |
跨平台编译:`bun run compile:{linux,darwin,windows}[:arch]`
## 端点
| 路径 | 用途 |
| --- | --- |
| `/` | Todo 示例 UI |
| `/health` | 存活探针(不查 DB,纯文本 `ok` |
| `/api/rpc` | ORPC RPC 端点(client 直连) |
| `/api/docs` | Scalar 渲染的 API 文档 |
| `/api/spec.json` | OpenAPI spec |
## 提交前
交付前验证:
```bash
bun run fix && bun run typecheck && bun run test
bun run fix && bun run typecheck && bun run test && bun run build
```
没有 CI、没有 pre-commit hook——上面三条由你自觉跑。
+1 -2
View File
@@ -7,7 +7,7 @@
},
"files": {
"ignoreUnknown": false,
"includes": ["**", "!**/routeTree.gen.ts", "!**/migrations.gen.ts"]
"includes": ["**", "!**/routeTree.gen.ts", "!**/migrations.gen.ts", "!volumes"]
},
"formatter": {
"enabled": true,
@@ -18,7 +18,6 @@
"linter": {
"enabled": true,
"domains": {
"drizzle": "recommended",
"react": "recommended",
"types": "all"
},
+204 -67
View File
@@ -5,7 +5,6 @@
"": {
"name": "fullstack-starter",
"dependencies": {
"@logtape/drizzle-orm": "^2.0.5",
"@logtape/logtape": "^2.0.5",
"@logtape/pretty": "^2.0.5",
"@orpc/client": "^1.14.0",
@@ -14,17 +13,23 @@
"@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",
"drizzle-orm": "0.45.2",
"drizzle-zod": "^0.8.3",
"postgres": "^3.4.9",
"drizzle-orm": "^0.45.2",
"lru-cache": "^11.3.6",
"lucide-react": "^1.14.0",
"motion": "^12.38.0",
"mysql2": "^3.22.3",
"react": "^19.2.5",
"react-dom": "^19.2.5",
"recharts": "^3.8.1",
"zod": "^4.3.6",
},
"devDependencies": {
@@ -36,7 +41,7 @@
"@tanstack/react-router-devtools": "^1.166.13",
"@types/bun": "^1.3.13",
"@vitejs/plugin-react": "^6.0.1",
"drizzle-kit": "0.31.10",
"drizzle-seed": "^0.3.1",
"nitro": "npm:nitro-nightly@3.0.1-20260424-182106-f8cf6ccc",
"tailwindcss": "^4.2.4",
"typescript": "^6.0.3",
@@ -101,18 +106,12 @@
"@biomejs/cli-win32-x64": ["@biomejs/cli-win32-x64@2.4.13", "", { "os": "win32", "cpu": "x64" }, "sha512-tTcMkXyBrmHi9BfrD2VNHs/5rYIUKETqsBlYOvSAABwBkJhSDVb5e7wPukftsQbO3WzQkXe6kaztC6WtUOXSoQ=="],
"@drizzle-team/brocli": ["@drizzle-team/brocli@0.10.2", "", {}, "sha512-z33Il7l5dKjUgGULTqBsQBQwckHh5AbIuxhdsIxDDiZAzBOrZO6q9ogcWC65kU382AfynTfgNumVcNIjuIua6w=="],
"@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" } }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],
"@emnapi/runtime": ["@emnapi/runtime@1.10.0", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA=="],
"@emnapi/wasi-threads": ["@emnapi/wasi-threads@1.2.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w=="],
"@esbuild-kit/core-utils": ["@esbuild-kit/core-utils@3.3.2", "", { "dependencies": { "esbuild": "~0.18.20", "source-map-support": "^0.5.21" } }, "sha512-sPRAnw9CdSsRmEtnsl2WXWdyquogVpB3yZ3dgwJfe8zrOzTsV7cJvmwrKVa+0ma5BoiGJ+BoqkMvawbayKUsqQ=="],
"@esbuild-kit/esm-loader": ["@esbuild-kit/esm-loader@2.6.5", "", { "dependencies": { "@esbuild-kit/core-utils": "^3.3.2", "get-tsconfig": "^4.7.0" } }, "sha512-FxEMIkJKnodyA1OaCUoEvbYRkoZlLZ4d/eXFu9Fh8CbBBgP5EmZxrfTRyN0qpXZ4vOvqnE5YdRdcrmUUXuU+dA=="],
"@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.25.12", "", { "os": "aix", "cpu": "ppc64" }, "sha512-Hhmwd6CInZ3dwpuGTF8fJG6yoWmsToE+vYgD4nytZVxcu1ulHpUQRAB1UJ8+N1Am3Mz4+xOByoQoSZf4D+CpkA=="],
"@esbuild/android-arm": ["@esbuild/android-arm@0.25.12", "", { "os": "android", "cpu": "arm" }, "sha512-VJ+sKvNA/GE7Ccacc9Cha7bpS8nyzVv0jdVgwNDaR4gDMC/2TTRc33Ip8qrNYUcpkOHUT5OZ0bUcNNVZQ9RLlg=="],
@@ -165,6 +164,14 @@
"@esbuild/win32-x64": ["@esbuild/win32-x64@0.25.12", "", { "os": "win32", "cpu": "x64" }, "sha512-alJC0uCZpTFrSL0CCDjcgleBXPnCrEAhTBILpeAp7M/OFgoqtAetfBzX0xM00MUsVVPpVjlPuMbREqnZCXaTnA=="],
"@floating-ui/core": ["@floating-ui/core@1.7.5", "", { "dependencies": { "@floating-ui/utils": "^0.2.11" } }, "sha512-1Ih4WTWyw0+lKyFMcBHGbb5U5FtuHJuujoyyr5zTaWS5EYMeT6Jb2AuDeftsCsEuchO+mM2ij5+q9crhydzLhQ=="],
"@floating-ui/dom": ["@floating-ui/dom@1.7.6", "", { "dependencies": { "@floating-ui/core": "^1.7.5", "@floating-ui/utils": "^0.2.11" } }, "sha512-9gZSAI5XM36880PPMm//9dfiEngYoC6Am2izES1FF406YFsjvyBMmeJ2g4SAju3xWwtuynNRFL2s9hgxpLI5SQ=="],
"@floating-ui/react-dom": ["@floating-ui/react-dom@2.1.8", "", { "dependencies": { "@floating-ui/dom": "^1.7.6" }, "peerDependencies": { "react": ">=16.8.0", "react-dom": ">=16.8.0" } }, "sha512-cC52bHwM/n/CxS87FH0yWdngEZrjdtLW/qVruo68qg+prK7ZQ4YGdut2GyDVpoGeAYe/h899rVeOVm6Oi40k2A=="],
"@floating-ui/utils": ["@floating-ui/utils@0.2.11", "", {}, "sha512-RiB/yIh78pcIxl6lLMG0CgBXAZ2Y0eVHqMPYugu+9U0AeT6YBeiJpf7lbdJNIugFP5SIjwNRgo4DhR1Qxi26Gg=="],
"@jridgewell/gen-mapping": ["@jridgewell/gen-mapping@0.3.13", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.0", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA=="],
"@jridgewell/remapping": ["@jridgewell/remapping@2.3.5", "", { "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.24" } }, "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ=="],
@@ -175,8 +182,6 @@
"@jridgewell/trace-mapping": ["@jridgewell/trace-mapping@0.3.31", "", { "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" } }, "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw=="],
"@logtape/drizzle-orm": ["@logtape/drizzle-orm@2.0.5", "", { "peerDependencies": { "@logtape/logtape": "^2.0.5" } }, "sha512-woM4x9J7B4XzoQTY1bzR6uJVlqezn6oY6flV+rDD6lsuwP2llNVvptgCOGjRutDye+6WZldSUIGe7UFK/faBzA=="],
"@logtape/logtape": ["@logtape/logtape@2.0.5", "", {}, "sha512-UizDkh20ZPJVOddRxG1F77WhHdlNl/sbQgoO8T534R7XvUBMAJ9En9f35u+meW2tRsNLvjz6R87Zanwf53tspQ=="],
"@logtape/pretty": ["@logtape/pretty@2.0.5", "", { "peerDependencies": { "@logtape/logtape": "^2.0.5" } }, "sha512-jU5pYL0CW0tFmxBS5umMF5VEMq1vXLvkqKrj7KRHnSlb5SrBOSCYl0w4q7FmPPFVADmgTmzVVr6IcIWwK/2Nig=="],
@@ -225,6 +230,60 @@
"@oxc-project/types": ["@oxc-project/types@0.127.0", "", {}, "sha512-aIYXQBo4lCbO4z0R3FHeucQHpF46l2LbMdxRvqvuRuW2OxdnSkcng5B8+K12spgLDj93rtN3+J2Vac/TIO+ciQ=="],
"@radix-ui/number": ["@radix-ui/number@1.1.1", "", {}, "sha512-MkKCwxlXTgz6CFoJx3pCwn07GKp36+aZyu/u2Ln2VrA5DcdyCZkASEDBTd8x5whTQQL5CiYf4prXKLcgQdv29g=="],
"@radix-ui/primitive": ["@radix-ui/primitive@1.1.3", "", {}, "sha512-JTF99U/6XIjCBo0wqkU5sK10glYe27MRRsfwoiq5zzOEZLHU3A3KCMa5X/azekYRCJ0HlwI0crAXS/5dEHTzDg=="],
"@radix-ui/react-arrow": ["@radix-ui/react-arrow@1.1.7", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-F+M1tLhO+mlQaOWspE8Wstg+z6PwxwRd8oQ8IXceWz92kfAmalTRf0EjrouQeo7QssEPfCn05B4Ihs1K9WQ/7w=="],
"@radix-ui/react-collection": ["@radix-ui/react-collection@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Fh9rGN0MoI4ZFUNyfFVNU4y9LUz93u9/0K+yLgA2bwRojxM8JU1DyvvMBabnZPBgMWREAJvU2jjVzq+LrFUglw=="],
"@radix-ui/react-compose-refs": ["@radix-ui/react-compose-refs@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-z4eqJvfiNnFMHIIvXP3CY57y2WJs5g2v3X0zm9mEJkrkNv4rDxu+sg9Jh8EkXyeqBkB7SOcboo9dMVqhyrACIg=="],
"@radix-ui/react-context": ["@radix-ui/react-context@1.1.2", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jCi/QKUM2r1Ju5a3J64TH2A5SpKAgh0LpknyqdQ4m6DCV0xJ2HG1xARRwNGPQfi1SLdLWZ1OJz6F4OMBBNiGJA=="],
"@radix-ui/react-direction": ["@radix-ui/react-direction@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-1UEWRX6jnOA2y4H5WczZ44gOOjTEmlqv1uNW4GAJEO5+bauCBhv8snY65Iw5/VOS/ghKN9gr2KjnLKxrsvoMVw=="],
"@radix-ui/react-dismissable-layer": ["@radix-ui/react-dismissable-layer@1.1.11", "", { "dependencies": { "@radix-ui/primitive": "1.1.3", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-escape-keydown": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-Nqcp+t5cTB8BinFkZgXiMJniQH0PsUt2k51FUhbdfeKvc4ACcG2uQniY/8+h1Yv6Kza4Q7lD7PQV0z0oicE0Mg=="],
"@radix-ui/react-focus-guards": ["@radix-ui/react-focus-guards@1.1.3", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-0rFg/Rj2Q62NCm62jZw0QX7a3sz6QCQU0LpZdNrJX8byRGaGVTqbrW9jAoIAHyMQqsNpeZ81YgSizOt5WXq0Pw=="],
"@radix-ui/react-focus-scope": ["@radix-ui/react-focus-scope@1.1.7", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-t2ODlkXBQyn7jkl6TNaw/MtVEVvIGelJDCG41Okq/KwUsJBwQ4XVZsHAVUkK4mBv3ewiAS3PGuUWuY2BoK4ZUw=="],
"@radix-ui/react-id": ["@radix-ui/react-id@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-kGkGegYIdQsOb4XjsfM97rXsiHaBwco+hFI66oO4s9LU+PLAC5oJ7khdOVFxkhsmlbpUqDAvXw11CluXP+jkHg=="],
"@radix-ui/react-popper": ["@radix-ui/react-popper@1.2.8", "", { "dependencies": { "@floating-ui/react-dom": "^2.0.0", "@radix-ui/react-arrow": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-rect": "1.1.1", "@radix-ui/react-use-size": "1.1.1", "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-0NJQ4LFFUuWkE7Oxf0htBKS6zLkkjBH+hM1uk7Ng705ReR8m/uelduy1DBo0PyBXPKVnBA6YBlU94MBGXrSBCw=="],
"@radix-ui/react-portal": ["@radix-ui/react-portal@1.1.9", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-bpIxvq03if6UNwXZ+HTK71JLh4APvnXntDc6XOX8UVq4XQOVl7lwok0AvIl+b8zgCw3fSaVTZMpAPPagXbKmHQ=="],
"@radix-ui/react-primitive": ["@radix-ui/react-primitive@2.1.3", "", { "dependencies": { "@radix-ui/react-slot": "1.2.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-m9gTwRkhy2lvCPe6QJp4d3G1TYEUHn/FzJUtq9MjH46an1wJU+GdoGC5VLof8RX8Ft/DlpshApkhswDLZzHIcQ=="],
"@radix-ui/react-select": ["@radix-ui/react-select@2.2.6", "", { "dependencies": { "@radix-ui/number": "1.1.1", "@radix-ui/primitive": "1.1.3", "@radix-ui/react-collection": "1.1.7", "@radix-ui/react-compose-refs": "1.1.2", "@radix-ui/react-context": "1.1.2", "@radix-ui/react-direction": "1.1.1", "@radix-ui/react-dismissable-layer": "1.1.11", "@radix-ui/react-focus-guards": "1.1.3", "@radix-ui/react-focus-scope": "1.1.7", "@radix-ui/react-id": "1.1.1", "@radix-ui/react-popper": "1.2.8", "@radix-ui/react-portal": "1.1.9", "@radix-ui/react-primitive": "2.1.3", "@radix-ui/react-slot": "1.2.3", "@radix-ui/react-use-callback-ref": "1.1.1", "@radix-ui/react-use-controllable-state": "1.2.2", "@radix-ui/react-use-layout-effect": "1.1.1", "@radix-ui/react-use-previous": "1.1.1", "@radix-ui/react-visually-hidden": "1.2.3", "aria-hidden": "^1.2.4", "react-remove-scroll": "^2.6.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-I30RydO+bnn2PQztvo25tswPH+wFBjehVGtmagkU78yMdwTwVf12wnAOF+AeP8S2N8xD+5UPbGhkUfPyvT+mwQ=="],
"@radix-ui/react-slot": ["@radix-ui/react-slot@1.2.3", "", { "dependencies": { "@radix-ui/react-compose-refs": "1.1.2" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-aeNmHnBxbi2St0au6VBVC7JXFlhLlOnvIIlePNniyUNAClzmtAUEY8/pBiK3iHjufOlwA+c20/8jngo7xcrg8A=="],
"@radix-ui/react-use-callback-ref": ["@radix-ui/react-use-callback-ref@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-FkBMwD+qbGQeMu1cOHnuGB6x4yzPjho8ap5WtbEJ26umhgqVXbhekKUQO+hZEL1vU92a3wHwdp0HAcqAUF5iDg=="],
"@radix-ui/react-use-controllable-state": ["@radix-ui/react-use-controllable-state@1.2.2", "", { "dependencies": { "@radix-ui/react-use-effect-event": "0.0.2", "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-BjasUjixPFdS+NKkypcyyN5Pmg83Olst0+c6vGov0diwTEo6mgdqVR6hxcEgFuh4QrAs7Rc+9KuGJ9TVCj0Zzg=="],
"@radix-ui/react-use-effect-event": ["@radix-ui/react-use-effect-event@0.0.2", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Qp8WbZOBe+blgpuUT+lw2xheLP8q0oatc9UpmiemEICxGvFLYmHm9QowVZGHtJlGbS6A6yJ3iViad/2cVjnOiA=="],
"@radix-ui/react-use-escape-keydown": ["@radix-ui/react-use-escape-keydown@1.1.1", "", { "dependencies": { "@radix-ui/react-use-callback-ref": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Il0+boE7w/XebUHyBjroE+DbByORGR9KKmITzbR7MyQ4akpORYP/ZmbhAr0DG7RmmBqoOnZdy2QlvajJ2QA59g=="],
"@radix-ui/react-use-layout-effect": ["@radix-ui/react-use-layout-effect@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-RbJRS4UWQFkzHTTwVymMTUv8EqYhOp8dOOviLj2ugtTiXRaRQS7GLGxZTLL1jWhMeoSCf5zmcZkqTl9IiYfXcQ=="],
"@radix-ui/react-use-previous": ["@radix-ui/react-use-previous@1.1.1", "", { "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-2dHfToCj/pzca2Ck724OZ5L0EVrr3eHRNsG/b3xQJLA2hZpVCS99bLAX+hm1IHXDEnzU6by5z/5MIY794/a8NQ=="],
"@radix-ui/react-use-rect": ["@radix-ui/react-use-rect@1.1.1", "", { "dependencies": { "@radix-ui/rect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-QTYuDesS0VtuHNNvMh+CjlKJ4LJickCMUAqjlE3+j8w+RlRpwyX3apEQKGFzbZGdo7XNG1tXa+bQqIE7HIXT2w=="],
"@radix-ui/react-use-size": ["@radix-ui/react-use-size@1.1.1", "", { "dependencies": { "@radix-ui/react-use-layout-effect": "1.1.1" }, "peerDependencies": { "@types/react": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-ewrXRDTAqAXlkl6t/fkXWNAhFX9I+CkKlw6zjEwk86RSPKwZr3xpBRso655aqYafwtnbpHLj6toFzmd6xdVptQ=="],
"@radix-ui/react-visually-hidden": ["@radix-ui/react-visually-hidden@1.2.3", "", { "dependencies": { "@radix-ui/react-primitive": "2.1.3" }, "peerDependencies": { "@types/react": "*", "@types/react-dom": "*", "react": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc", "react-dom": "^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react", "@types/react-dom"] }, "sha512-pzJq12tEaaIhqjbzpCuv/OypJY/BPavOofm+dbab+MHLajy277+1lLm6JFcGgF5eskJ6mquGirhXY2GD/8u8Ug=="],
"@radix-ui/rect": ["@radix-ui/rect@1.1.1", "", {}, "sha512-HPwpGIzkl28mWyZqG52jiqDJ12waP11Pa1lGoiyUkIEuMLBP0oeK/C89esbXrxsky5we7dfd8U58nm0SgAWpVw=="],
"@reduxjs/toolkit": ["@reduxjs/toolkit@2.11.2", "", { "dependencies": { "@standard-schema/spec": "^1.0.0", "@standard-schema/utils": "^0.3.0", "immer": "^11.0.0", "redux": "^5.0.1", "redux-thunk": "^3.1.0", "reselect": "^5.1.0" }, "peerDependencies": { "react": "^16.9.0 || ^17.0.0 || ^18 || ^19", "react-redux": "^7.2.1 || ^8.1.3 || ^9.0.0" }, "optionalPeers": ["react", "react-redux"] }, "sha512-Kd6kAHTA6/nUpp8mySPqj3en3dm0tdMIgbttnQ1xFMVpufoj+ADi8pXLBsd4xzTRHQa7t/Jv8W5UnCuW4kuWMQ=="],
"@rolldown/binding-android-arm64": ["@rolldown/binding-android-arm64@1.0.0-rc.17", "", { "os": "android", "cpu": "arm64" }, "sha512-s70pVGhw4zqGeFnXWvAzJDlvxhlRollagdCCKRgOsgUOH3N1l0LIxf83AtGzmb5SiVM4Hjl5HyarMRfdfj3DaQ=="],
"@rolldown/binding-darwin-arm64": ["@rolldown/binding-darwin-arm64@1.0.0-rc.17", "", { "os": "darwin", "cpu": "arm64" }, "sha512-4ksWc9n0mhlZpZ9PMZgTGjeOPRu8MB1Z3Tz0Mo02eWfWCHMW1zN82Qz/pL/rC+yQa+8ZnutMF0JjJe7PjwasYw=="],
@@ -271,6 +330,8 @@
"@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="],
"@standard-schema/utils": ["@standard-schema/utils@0.3.0", "", {}, "sha512-e7Mew686owMaPJVNNLs55PUvgz371nKgwsc4vxE49zsODpJEnxgxRo2y/OKrqueavXgZNMDVj3DdHFlaSAeU8g=="],
"@t3-oss/env-core": ["@t3-oss/env-core@0.13.11", "", { "peerDependencies": { "arktype": "^2.1.0", "typescript": ">=5.0.0", "valibot": "^1.0.0-beta.7 || ^1.0.0", "zod": "^3.24.0 || ^4.0.0" }, "optionalPeers": ["arktype", "typescript", "valibot", "zod"] }, "sha512-sM7GYY+KL7H/Hl0BE0inWfk3nRHZOLhmVn7sHGxaZt9FAR6KqREXAE+6TqKfiavfXmpRxO/OZ2QgKRd+oiBYRQ=="],
"@tailwindcss/node": ["@tailwindcss/node@4.2.4", "", { "dependencies": { "@jridgewell/remapping": "^2.3.5", "enhanced-resolve": "^5.19.0", "jiti": "^2.6.1", "lightningcss": "1.32.0", "magic-string": "^0.30.21", "source-map-js": "^1.2.1", "tailwindcss": "4.2.4" } }, "sha512-Ai7+yQPxz3ddrDQzFfBKdHEVBg0w3Zl83jnjuwxnZOsnH9pGn93QHQtpU0p/8rYWxvbFZHneni6p1BSLK4DkGA=="],
@@ -343,6 +404,10 @@
"@tanstack/react-store": ["@tanstack/react-store@0.9.3", "", { "dependencies": { "@tanstack/store": "0.9.3", "use-sync-external-store": "^1.6.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-y2iHd/N9OkoQbFJLUX1T9vbc2O9tjH0pQRgTcx1/Nz4IlwLvkgpuglXUx+mXt0g5ZDFrEeDnONPqkbfxXJKwRg=="],
"@tanstack/react-table": ["@tanstack/react-table@8.21.3", "", { "dependencies": { "@tanstack/table-core": "8.21.3" }, "peerDependencies": { "react": ">=16.8", "react-dom": ">=16.8" } }, "sha512-5nNMTSETP4ykGegmVkhjcS8tTLW6Vl4axfEGQN3v0zdHYbK4UfoqfPChclTrJ4EoK9QynqAu9oUf8VEmrpZ5Ww=="],
"@tanstack/react-virtual": ["@tanstack/react-virtual@3.13.24", "", { "dependencies": { "@tanstack/virtual-core": "3.14.0" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-aIJvz5OSkhNIhZIpYivrxrPTKYsjW9Uzy+sP/mx0S3sev2HyvPb7xmjbYvokzEpfgYHy/HjzJ2zFAETuUfgCpg=="],
"@tanstack/router-core": ["@tanstack/router-core@1.168.15", "", { "dependencies": { "@tanstack/history": "1.161.6", "cookie-es": "^3.0.0", "seroval": "^1.5.0", "seroval-plugins": "^1.5.0" }, "bin": { "intent": "bin/intent.js" } }, "sha512-Wr0424NDtD8fT/uALobMZ9DdcfsTyXtW5IPR++7zvW8/7RaIOeaqXpVDId8ywaGtqPWLWOfaUg2zUtYtukoXYA=="],
"@tanstack/router-devtools-core": ["@tanstack/router-devtools-core@1.167.3", "", { "dependencies": { "clsx": "^2.1.1", "goober": "^2.1.16" }, "peerDependencies": { "@tanstack/router-core": "^1.168.11", "csstype": "^3.0.10" }, "optionalPeers": ["csstype"] }, "sha512-fJ1VMhyQgnoashTrP763c2HRc9kofgF61L7Jb3F6eTHAmCKtGVx8BRtiFt37sr3U0P0jmaaiiSPGP6nT5JtVNg=="],
@@ -367,18 +432,42 @@
"@tanstack/store": ["@tanstack/store@0.9.3", "", {}, "sha512-8reSzl/qGWGGVKhBoxXPMWzATSbZLZFWhwBAFO9NAyp0TxzfBP0mIrGb8CP8KrQTmvzXlR/vFPPUrHTLBGyFyw=="],
"@tanstack/table-core": ["@tanstack/table-core@8.21.3", "", {}, "sha512-ldZXEhOBb8Is7xLs01fR3YEc3DERiz5silj8tnGkFZytt1abEvl/GhUmCE0PMLaMPTa3Jk4HbKmRlHmu+gCftg=="],
"@tanstack/virtual-core": ["@tanstack/virtual-core@3.14.0", "", {}, "sha512-JLANqGy/D6k4Ujmh8Tr25lGimuOXNiaVyXaCAZS0W+1390sADdGnyUdSWNIfd49gebtIxGMij4IktRVzrdr12Q=="],
"@tanstack/virtual-file-routes": ["@tanstack/virtual-file-routes@1.161.7", "", { "bin": { "intent": "bin/intent.js" } }, "sha512-olW33+Cn+bsCsZKPwEGhlkqS6w3M2slFv11JIobdnCFKMLG97oAI2kWKdx5/zsywTL8flpnoIgaZZPlQTFYhdQ=="],
"@tybys/wasm-util": ["@tybys/wasm-util@0.10.1", "", { "dependencies": { "tslib": "^2.4.0" } }, "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg=="],
"@types/bun": ["@types/bun@1.3.13", "", { "dependencies": { "bun-types": "1.3.13" } }, "sha512-9fqXWk5YIHGGnUau9TEi+qdlTYDAnOj+xLCmSTwXfAIqXr2x4tytJb43E9uCvt09zJURKXwAtkoH4nLQfzeTXw=="],
"@types/d3-array": ["@types/d3-array@3.2.2", "", {}, "sha512-hOLWVbm7uRza0BYXpIIW5pxfrKe0W+D5lrFiAEYR+pb6w3N2SwSMaJbXdUfSEv+dT4MfHBLtn5js0LAWaO6otw=="],
"@types/d3-color": ["@types/d3-color@3.1.3", "", {}, "sha512-iO90scth9WAbmgv7ogoq57O9YpKmFBbmoEoCHDB2xMBY0+/KVrqAaCDyCE16dUspeOvIxFFRI+0sEtqDqy2b4A=="],
"@types/d3-ease": ["@types/d3-ease@3.0.2", "", {}, "sha512-NcV1JjO5oDzoK26oMzbILE6HW7uVXOHLQvHshBUW4UMdZGfiY6v5BeQwh9a9tCzv+CeefZQHJt5SRgK154RtiA=="],
"@types/d3-interpolate": ["@types/d3-interpolate@3.0.4", "", { "dependencies": { "@types/d3-color": "*" } }, "sha512-mgLPETlrpVV1YRJIglr4Ez47g7Yxjl1lj7YKsiMCb27VJH9W8NVM6Bb9d8kkpG/uAQS5AmbA48q2IAolKKo1MA=="],
"@types/d3-path": ["@types/d3-path@3.1.1", "", {}, "sha512-VMZBYyQvbGmWyWVea0EHs/BwLgxc+MKi1zLDCONksozI4YJMcTt8ZEuIR4Sb1MMTE8MMW49v0IwI5+b7RmfWlg=="],
"@types/d3-scale": ["@types/d3-scale@4.0.9", "", { "dependencies": { "@types/d3-time": "*" } }, "sha512-dLmtwB8zkAeO/juAMfnV+sItKjlsw2lKdZVVy6LRr0cBmegxSABiLEpGVmSJJ8O08i4+sGR6qQtb6WtuwJdvVw=="],
"@types/d3-shape": ["@types/d3-shape@3.1.8", "", { "dependencies": { "@types/d3-path": "*" } }, "sha512-lae0iWfcDeR7qt7rA88BNiqdvPS5pFVPpo5OfjElwNaT2yyekbM0C9vK+yqBqEmHr6lDkRnYNoTBYlAgJa7a4w=="],
"@types/d3-time": ["@types/d3-time@3.0.4", "", {}, "sha512-yuzZug1nkAAaBlBBikKZTgzCeA+k1uy4ZFwWANOfKw5z5LRhV0gNA7gNkKm7HoK+HRN0wX3EkxGk0fpbWhmB7g=="],
"@types/d3-timer": ["@types/d3-timer@3.0.2", "", {}, "sha512-Ps3T8E8dZDam6fUyNiMkekK3XUsaUEik+idO9/YjPtfj2qruF8tFBXS7XhtE4iIXBLxhmLjP3SXpLhVf21I9Lw=="],
"@types/node": ["@types/node@25.6.0", "", { "dependencies": { "undici-types": "~7.19.0" } }, "sha512-+qIYRKdNYJwY3vRCZMdJbPLJAtGjQBudzZzdzwQYkEPQd+PJGixUL5QfvCLDaULoLv+RhT3LDkwEfKaAkgSmNQ=="],
"@types/react": ["@types/react@19.2.14", "", { "dependencies": { "csstype": "^3.2.2" } }, "sha512-ilcTH/UniCkMdtexkoCN0bI7pMcJDvmQFPvuPvmEaYA/NSfFTAgdUSLAoVjaRJm7+6PvcM+q1zYOwS4wTYMF9w=="],
"@types/react-dom": ["@types/react-dom@19.2.3", "", { "peerDependencies": { "@types/react": "^19.2.0" } }, "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ=="],
"@types/use-sync-external-store": ["@types/use-sync-external-store@0.0.6", "", {}, "sha512-zFDAD+tlpf2r4asuHEj0XH6pY6i0g5NeAHPn+15wk3BV6JA69eERFXC1gyGThDkVa1zCyKr5jox1+2LbV/AMLg=="],
"@vitejs/plugin-react": ["@vitejs/plugin-react@6.0.1", "", { "dependencies": { "@rolldown/pluginutils": "1.0.0-rc.7" }, "peerDependencies": { "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", "babel-plugin-react-compiler": "^1.0.0", "vite": "^8.0.0" }, "optionalPeers": ["@rolldown/plugin-babel", "babel-plugin-react-compiler"] }, "sha512-l9X/E3cDb+xY3SWzlG1MOGt2usfEHGMNIaegaUGFsLkb3RCn/k8/TOXBcab+OndDI4TBtktT8/9BwwW8Vi9KUQ=="],
"ansis": ["ansis@4.2.0", "", {}, "sha512-HqZ5rWlFjGiV0tDm3UxxgNRqsOTniqoKZu0pIAfh7TZQMGuZK+hH0drySty0si0QXj1ieop4+SkSfPZBPPkHig=="],
@@ -387,6 +476,10 @@
"argparse": ["argparse@2.0.1", "", {}, "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q=="],
"aria-hidden": ["aria-hidden@1.2.6", "", { "dependencies": { "tslib": "^2.0.0" } }, "sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA=="],
"aws-ssl-profiles": ["aws-ssl-profiles@1.1.2", "", {}, "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g=="],
"babel-dead-code-elimination": ["babel-dead-code-elimination@1.0.12", "", { "dependencies": { "@babel/core": "^7.23.7", "@babel/parser": "^7.23.6", "@babel/traverse": "^7.23.7", "@babel/types": "^7.23.6" } }, "sha512-GERT7L2TiYcYDtYk1IpD+ASAYXjKbLTDPhBtYj7X1NuRMDTMtAx9kyBenub1Ev41lo91OHCKdmP+egTDmfQ7Ig=="],
"baseline-browser-mapping": ["baseline-browser-mapping@2.10.21", "", { "bin": { "baseline-browser-mapping": "dist/cli.cjs" } }, "sha512-Q+rUQ7Uz8AHM7DEaNdwvfFCTq7a43lNTzuS94eiWqwyxfV/wJv+oUivef51T91mmRY4d4A1u9rcSvkeufCVXlA=="],
@@ -399,8 +492,6 @@
"browserslist": ["browserslist@4.28.2", "", { "dependencies": { "baseline-browser-mapping": "^2.10.12", "caniuse-lite": "^1.0.30001782", "electron-to-chromium": "^1.5.328", "node-releases": "^2.0.36", "update-browserslist-db": "^1.2.3" }, "bin": { "browserslist": "cli.js" } }, "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg=="],
"buffer-from": ["buffer-from@1.1.2", "", {}, "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ=="],
"bun-types": ["bun-types@1.3.13", "", { "dependencies": { "@types/node": "*" } }, "sha512-QXKeHLlOLqQX9LgYaHJfzdBaV21T63HhFJnvuRCcjZiaUDpbs5ED1MgxbMra71CsryN/1dAoXuJJJwIv/2drVA=="],
"caniuse-lite": ["caniuse-lite@1.0.30001790", "", {}, "sha512-bOoxfJPyYo+ds6W0YfptaCWbFnJYjh2Y1Eow5lRv+vI2u8ganPZqNm1JwNh0t2ELQCqIWg4B3dWEusgAmsoyOw=="],
@@ -433,14 +524,42 @@
"csstype": ["csstype@3.2.3", "", {}, "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ=="],
"d3-array": ["d3-array@3.2.4", "", { "dependencies": { "internmap": "1 - 2" } }, "sha512-tdQAmyA18i4J7wprpYq8ClcxZy3SC31QMeByyCFyRt7BVHdREQZ5lpzoe5mFEYZUWe+oq8HBvk9JjpibyEV4Jg=="],
"d3-color": ["d3-color@3.1.0", "", {}, "sha512-zg/chbXyeBtMQ1LbD/WSoW2DpC3I0mpmPdW+ynRTj/x2DAWYrIY7qeZIHidozwV24m4iavr15lNwIwLxRmOxhA=="],
"d3-ease": ["d3-ease@3.0.1", "", {}, "sha512-wR/XK3D3XcLIZwpbvQwQ5fK+8Ykds1ip7A2Txe0yxncXSdq1L9skcG7blcedkOX+ZcgxGAmLX1FrRGbADwzi0w=="],
"d3-format": ["d3-format@3.1.2", "", {}, "sha512-AJDdYOdnyRDV5b6ArilzCPPwc1ejkHcoyFarqlPqT7zRYjhavcT3uSrqcMvsgh2CgoPbK3RCwyHaVyxYcP2Arg=="],
"d3-interpolate": ["d3-interpolate@3.0.1", "", { "dependencies": { "d3-color": "1 - 3" } }, "sha512-3bYs1rOD33uo8aqJfKP3JWPAibgw8Zm2+L9vBKEHJ2Rg+viTR7o5Mmv5mZcieN+FRYaAOWX5SJATX6k1PWz72g=="],
"d3-path": ["d3-path@3.1.0", "", {}, "sha512-p3KP5HCf/bvjBSSKuXid6Zqijx7wIfNW+J/maPs+iwR35at5JCbLUT0LzF1cnjbCHWhqzQTIN2Jpe8pRebIEFQ=="],
"d3-scale": ["d3-scale@4.0.2", "", { "dependencies": { "d3-array": "2.10.0 - 3", "d3-format": "1 - 3", "d3-interpolate": "1.2.0 - 3", "d3-time": "2.1.1 - 3", "d3-time-format": "2 - 4" } }, "sha512-GZW464g1SH7ag3Y7hXjf8RoUuAFIqklOAq3MRl4OaWabTFJY9PN/E1YklhXLh+OQ3fM9yS2nOkCoS+WLZ6kvxQ=="],
"d3-shape": ["d3-shape@3.2.0", "", { "dependencies": { "d3-path": "^3.1.0" } }, "sha512-SaLBuwGm3MOViRq2ABk3eLoxwZELpH6zhl3FbAoJ7Vm1gofKx6El1Ib5z23NUEhF9AsGl7y+dzLe5Cw2AArGTA=="],
"d3-time": ["d3-time@3.1.0", "", { "dependencies": { "d3-array": "2 - 3" } }, "sha512-VqKjzBLejbSMT4IgbmVgDjpkYrNWUYJnbCGo874u7MMKIWsILRX+OpX/gTk8MqjpT1A/c6HY2dCA77ZN0lkQ2Q=="],
"d3-time-format": ["d3-time-format@4.1.0", "", { "dependencies": { "d3-time": "1 - 3" } }, "sha512-dJxPBlzC7NugB2PDLwo9Q8JiTR3M3e4/XANkreKSUxF8vvXKqm1Yfq4Q5dl8budlunRVlUUaDUgFt7eA8D6NLg=="],
"d3-timer": ["d3-timer@3.0.1", "", {}, "sha512-ndfJ/JxxMd3nw31uyKoY2naivF+r29V+Lc0svZxe1JvvIRmi8hUsrMvdOwgS1o6uBHmiz91geQ0ylPP0aj1VUA=="],
"dayjs": ["dayjs@1.11.20", "", {}, "sha512-YbwwqR/uYpeoP4pu043q+LTDLFBLApUP6VxRihdfNTqu4ubqMlGDLd6ErXhEgsyvY0K6nCs7nggYumAN+9uEuQ=="],
"db0": ["db0@0.3.4", "", { "peerDependencies": { "@electric-sql/pglite": "*", "@libsql/client": "*", "better-sqlite3": "*", "drizzle-orm": "*", "mysql2": "*", "sqlite3": "*" }, "optionalPeers": ["@electric-sql/pglite", "@libsql/client", "better-sqlite3", "drizzle-orm", "mysql2", "sqlite3"] }, "sha512-RiXXi4WaNzPTHEOu8UPQKMooIbqOEyqA1t7Z6MsdxSCeb8iUC9ko3LcmsLmeUt2SM5bctfArZKkRQggKZz7JNw=="],
"debug": ["debug@4.4.3", "", { "dependencies": { "ms": "^2.1.3" } }, "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA=="],
"decimal.js-light": ["decimal.js-light@2.5.1", "", {}, "sha512-qIMFpTMZmny+MMIitAB6D7iVPEorVw6YQRWkvarTkT4tBeSLLiHzcwj6q0MmYSFCiVpiqPJTJEYIrpcPzVEIvg=="],
"denque": ["denque@2.1.0", "", {}, "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw=="],
"detect-libc": ["detect-libc@2.1.2", "", {}, "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ=="],
"detect-node-es": ["detect-node-es@1.1.0", "", {}, "sha512-ypdmJU/TbBby2Dxibuv7ZLW3Bs1QEmM7nHjEANfohJLvE0XVujisn1qPJcZxg+qDucsr+bP6fLD1rPS3AhJ7EQ=="],
"diff": ["diff@8.0.4", "", {}, "sha512-DPi0FmjiSU5EvQV0++GFDOJ9ASQUVFh5kD+OzOnYdi7n3Wpm9hWWGfB/O2blfHcMVTL5WkQXSnRiK9makhrcnw=="],
"dom-serializer": ["dom-serializer@2.0.0", "", { "dependencies": { "domelementtype": "^2.3.0", "domhandler": "^5.0.2", "entities": "^4.2.0" } }, "sha512-wIkAryiqt/nV5EQKqQpo3SToSOV9J0DnbJqwK7Wv/Trc92zIAYZ4FlMu+JPFW1DfGFt81ZTCGgDEabffXeLyJg=="],
@@ -451,11 +570,9 @@
"domutils": ["domutils@3.2.2", "", { "dependencies": { "dom-serializer": "^2.0.0", "domelementtype": "^2.3.0", "domhandler": "^5.0.3" } }, "sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw=="],
"drizzle-kit": ["drizzle-kit@0.31.10", "", { "dependencies": { "@drizzle-team/brocli": "^0.10.2", "@esbuild-kit/esm-loader": "^2.5.5", "esbuild": "^0.25.4", "tsx": "^4.21.0" }, "bin": { "drizzle-kit": "bin.cjs" } }, "sha512-7OZcmQUrdGI+DUNNsKBn1aW8qSoKuTH7d0mYgSP8bAzdFzKoovxEFnoGQp2dVs82EOJeYycqRtciopszwUf8bw=="],
"drizzle-orm": ["drizzle-orm@0.45.2", "", { "peerDependencies": { "@aws-sdk/client-rds-data": ">=3", "@cloudflare/workers-types": ">=4", "@electric-sql/pglite": ">=0.2.0", "@libsql/client": ">=0.10.0", "@libsql/client-wasm": ">=0.10.0", "@neondatabase/serverless": ">=0.10.0", "@op-engineering/op-sqlite": ">=2", "@opentelemetry/api": "^1.4.1", "@planetscale/database": ">=1.13", "@prisma/client": "*", "@tidbcloud/serverless": "*", "@types/better-sqlite3": "*", "@types/pg": "*", "@types/sql.js": "*", "@upstash/redis": ">=1.34.7", "@vercel/postgres": ">=0.8.0", "@xata.io/client": "*", "better-sqlite3": ">=7", "bun-types": "*", "expo-sqlite": ">=14.0.0", "gel": ">=2", "knex": "*", "kysely": "*", "mysql2": ">=2", "pg": ">=8", "postgres": ">=3", "sql.js": ">=1", "sqlite3": ">=5" }, "optionalPeers": ["@aws-sdk/client-rds-data", "@cloudflare/workers-types", "@electric-sql/pglite", "@libsql/client", "@libsql/client-wasm", "@neondatabase/serverless", "@op-engineering/op-sqlite", "@opentelemetry/api", "@planetscale/database", "@prisma/client", "@tidbcloud/serverless", "@types/better-sqlite3", "@types/pg", "@types/sql.js", "@upstash/redis", "@vercel/postgres", "@xata.io/client", "better-sqlite3", "bun-types", "expo-sqlite", "gel", "knex", "kysely", "mysql2", "pg", "postgres", "sql.js", "sqlite3"] }, "sha512-kY0BSaTNYWnoDMVoyY8uxmyHjpJW1geOmBMdSSicKo9CIIWkSxMIj2rkeSR51b8KAPB7m+qysjuHme5nKP+E5Q=="],
"drizzle-zod": ["drizzle-zod@0.8.3", "", { "peerDependencies": { "drizzle-orm": ">=0.36.0", "zod": "^3.25.0 || ^4.0.0" } }, "sha512-66yVOuvGhKJnTdiqj1/Xaaz9/qzOdRJADpDa68enqS6g3t0kpNkwNYjUuaeXgZfO/UWuIM9HIhSlJ6C5ZraMww=="],
"drizzle-seed": ["drizzle-seed@0.3.1", "", { "dependencies": { "pure-rand": "^6.1.0" }, "peerDependencies": { "drizzle-orm": ">=0.36.4" }, "optionalPeers": ["drizzle-orm"] }, "sha512-F/0lgvfOAsqlYoHM/QAGut4xXIOXoE5VoAdv2FIl7DpGYVXlAzKuJO+IphkKUFK3Dz+rFlOsQLnMNrvoQ0cx7g=="],
"electron-to-chromium": ["electron-to-chromium@1.5.344", "", {}, "sha512-4MxfbmNDm+KPh066EZy+eUnkcDPcZ35wNmOWzFuh/ijvHsve6kbLTLURy88uCNK5FbpN+yk2nQY6BYh1GEt+wg=="],
@@ -467,22 +584,32 @@
"env-runner": ["env-runner@0.1.7", "", { "dependencies": { "crossws": "^0.4.4", "exsolve": "^1.0.8", "httpxy": "^0.5.0", "srvx": "^0.11.13" }, "peerDependencies": { "@netlify/runtime": "^4", "miniflare": "^4.20260317.3" }, "optionalPeers": ["@netlify/runtime", "miniflare"], "bin": { "env-runner": "dist/cli.mjs" } }, "sha512-i7h96jxETJYhXy5grgHNJ9xNzCzWIn9Ck/VkkYgOlE4gOqknsLX3CmlVb5LmwNex8sOoLFVZLz+TIw/+b5rktA=="],
"es-toolkit": ["es-toolkit@1.46.1", "", {}, "sha512-5eNtXOs3tbfxXOj04tjjseeWkRWaoCjdEI+96DgwzZoe6c9juL49pXlzAFTI72aWC9Y8p7168g6XIKjh7k6pyQ=="],
"esbuild": ["esbuild@0.25.12", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.25.12", "@esbuild/android-arm": "0.25.12", "@esbuild/android-arm64": "0.25.12", "@esbuild/android-x64": "0.25.12", "@esbuild/darwin-arm64": "0.25.12", "@esbuild/darwin-x64": "0.25.12", "@esbuild/freebsd-arm64": "0.25.12", "@esbuild/freebsd-x64": "0.25.12", "@esbuild/linux-arm": "0.25.12", "@esbuild/linux-arm64": "0.25.12", "@esbuild/linux-ia32": "0.25.12", "@esbuild/linux-loong64": "0.25.12", "@esbuild/linux-mips64el": "0.25.12", "@esbuild/linux-ppc64": "0.25.12", "@esbuild/linux-riscv64": "0.25.12", "@esbuild/linux-s390x": "0.25.12", "@esbuild/linux-x64": "0.25.12", "@esbuild/netbsd-arm64": "0.25.12", "@esbuild/netbsd-x64": "0.25.12", "@esbuild/openbsd-arm64": "0.25.12", "@esbuild/openbsd-x64": "0.25.12", "@esbuild/openharmony-arm64": "0.25.12", "@esbuild/sunos-x64": "0.25.12", "@esbuild/win32-arm64": "0.25.12", "@esbuild/win32-ia32": "0.25.12", "@esbuild/win32-x64": "0.25.12" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg=="],
"escalade": ["escalade@3.2.0", "", {}, "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA=="],
"escape-string-regexp": ["escape-string-regexp@5.0.0", "", {}, "sha512-/veY75JbMK4j1yjvuUxuVsiS/hr/4iHs9FTT6cgTexxdE0Ly/glccBAkloH/DofkjRbZU3bnoj38mOmhkZ0lHw=="],
"eventemitter3": ["eventemitter3@5.0.4", "", {}, "sha512-mlsTRyGaPBjPedk6Bvw+aqbsXDtoAyAzm5MO7JgU+yVRyMQ5O8bD4Kcci7BS85f93veegeCPkL8R4GLClnjLFw=="],
"exsolve": ["exsolve@1.0.8", "", {}, "sha512-LmDxfWXwcTArk8fUEnOfSZpHOJ6zOMUJKOtFLFqJLoKJetuQG874Uc7/Kki7zFLzYybmZhp1M7+98pfMqeX8yA=="],
"fdir": ["fdir@6.5.0", "", { "peerDependencies": { "picomatch": "^3 || ^4" }, "optionalPeers": ["picomatch"] }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="],
"fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="],
"framer-motion": ["framer-motion@12.38.0", "", { "dependencies": { "motion-dom": "^12.38.0", "motion-utils": "^12.36.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-rFYkY/pigbcswl1XQSb7q424kSTQ8q6eAC+YUsSKooHQYuLdzdHjrt6uxUC+PRAO++q5IS7+TamgIw1AphxR+g=="],
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
"generate-function": ["generate-function@2.3.1", "", { "dependencies": { "is-property": "^1.0.2" } }, "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ=="],
"gensync": ["gensync@1.0.0-beta.2", "", {}, "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg=="],
"get-nonce": ["get-nonce@1.0.1", "", {}, "sha512-FJhYRoDaiatfEkUK8HKlicmu/3SGFD51q3itKDGoSTysQJBnfOcxU5GxnhE1E6soB76MbT0MBtnKJuXyAx+96Q=="],
"get-tsconfig": ["get-tsconfig@4.14.0", "", { "dependencies": { "resolve-pkg-maps": "^1.0.0" } }, "sha512-yTb+8DXzDREzgvYmh6s9vHsSVCHeC0G3PI5bEXNBHtmshPnO+S5O7qgLEOn0I5QvMy6kpZN8K1NKGyilLb93wA=="],
"glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
@@ -501,7 +628,11 @@
"httpxy": ["httpxy@0.5.1", "", {}, "sha512-JPhqYiixe1A1I+MXDewWDZqeudBGU8Q9jCHYN8ML+779RQzLjTi78HBvWz4jMxUD6h2/vUL12g4q/mFM0OUw1A=="],
"iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
"iconv-lite": ["iconv-lite@0.7.2", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-im9DjEDQ55s9fL4EYzOAv0yMqmMBSZp6G0VvFyTMPKWxiSBHUj9NW/qqLmXUwXrrM7AvqSlTCfvqRb0cM8yYqw=="],
"immer": ["immer@10.2.0", "", {}, "sha512-d/+XTN3zfODyjr89gM3mPq1WNX2B8pYsu7eORitdwyA2sBubnTl3laYlBk4sXY5FUa5qTZGBDPJICVbvqzjlbw=="],
"internmap": ["internmap@2.0.3", "", {}, "sha512-5Hh7Y1wQbvY5ooGgPbDaL5iYLAPzMTUrjMulskHLH6wnv/A+1q5rgEaiuqEjB+oxGXIVZs1FF+R/KPN3ZSQYYg=="],
"is-binary-path": ["is-binary-path@2.1.0", "", { "dependencies": { "binary-extensions": "^2.0.0" } }, "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw=="],
@@ -511,6 +642,8 @@
"is-number": ["is-number@7.0.0", "", {}, "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng=="],
"is-property": ["is-property@1.0.2", "", {}, "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g=="],
"isbot": ["isbot@5.1.39", "", {}, "sha512-obH0yYahGXdzNxo+djmHhBYThUKDkz565cxkIlt2L9hXfv1NlaLKoDBHo6KxXsYrIXx2RK3x5vY36CfZcobxEw=="],
"jiti": ["jiti@2.6.1", "", { "bin": { "jiti": "lib/jiti-cli.mjs" } }, "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ=="],
@@ -551,12 +684,28 @@
"lightningcss-win32-x64-msvc": ["lightningcss-win32-x64-msvc@1.32.0", "", { "os": "win32", "cpu": "x64" }, "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q=="],
"lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
"long": ["long@5.3.2", "", {}, "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA=="],
"lru-cache": ["lru-cache@11.3.6", "", {}, "sha512-Gf/KoL3C/MlI7Bt0PGI9I+TeTC/I6r/csU58N4BSNc4lppLBeKsOdFYkK+dX0ABDUMJNfCHTyPpzwwO21Awd3A=="],
"lru.min": ["lru.min@1.1.4", "", {}, "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA=="],
"lucide-react": ["lucide-react@1.14.0", "", { "peerDependencies": { "react": "^16.5.1 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-+1mdWcfSJVUsaTIjN9zoezmUhfXo5l0vP7ekBMPo3jcS/aIkxHnXqAPsByszMZx/Y8oQBRJxJx5xg+RH3urzxA=="],
"magic-string": ["magic-string@0.30.21", "", { "dependencies": { "@jridgewell/sourcemap-codec": "^1.5.5" } }, "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ=="],
"motion": ["motion@12.38.0", "", { "dependencies": { "framer-motion": "^12.38.0", "tslib": "^2.4.0" }, "peerDependencies": { "@emotion/is-prop-valid": "*", "react": "^18.0.0 || ^19.0.0", "react-dom": "^18.0.0 || ^19.0.0" }, "optionalPeers": ["@emotion/is-prop-valid", "react", "react-dom"] }, "sha512-uYfXzeHlgThchzwz5Te47dlv5JOUC7OB4rjJ/7XTUgtBZD8CchMN8qEJ4ZVsUmTyYA44zjV0fBwsiktRuFnn+w=="],
"motion-dom": ["motion-dom@12.38.0", "", { "dependencies": { "motion-utils": "^12.36.0" } }, "sha512-pdkHLD8QYRp8VfiNLb8xIBJis1byQ9gPT3Jnh2jqfFtAsWUA3dEepDlsWe/xMpO8McV+VdpKVcp+E+TGJEtOoA=="],
"motion-utils": ["motion-utils@12.36.0", "", {}, "sha512-eHWisygbiwVvf6PZ1vhaHCLamvkSbPIeAYxWUuL3a2PD/TROgE7FvfHWTIH4vMl798QLfMw15nRqIaRDXTlYRg=="],
"ms": ["ms@2.1.3", "", {}, "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA=="],
"mysql2": ["mysql2@3.22.3", "", { "dependencies": { "aws-ssl-profiles": "^1.1.2", "denque": "^2.1.0", "generate-function": "^2.3.1", "iconv-lite": "^0.7.2", "long": "^5.3.2", "lru.min": "^1.1.4", "named-placeholders": "^1.1.6", "sql-escaper": "^1.3.3" }, "peerDependencies": { "@types/node": ">= 8" } }, "sha512-uWWxvZSRvRhtBdh2CdcuK83YcOfPdmEeEYB069bAmPnV93QApDGVPuvCQOLjlh7tYHEWdgQPrn6kosDxHBVLkA=="],
"named-placeholders": ["named-placeholders@1.1.6", "", { "dependencies": { "lru.min": "^1.1.0" } }, "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w=="],
"nanoid": ["nanoid@3.3.11", "", { "bin": { "nanoid": "bin/nanoid.cjs" } }, "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w=="],
"nf3": ["nf3@0.3.16", "", {}, "sha512-Gs0xRPpUm2nDkqbi40NJ9g7qDIcjcJzgExiydnq6LAyqhI2jfno8wG3NKTL+IiJsx799UHOb1CnSd4Wg4SG4Pw=="],
@@ -595,14 +744,34 @@
"prettier": ["prettier@3.8.3", "", { "bin": { "prettier": "bin/prettier.cjs" } }, "sha512-7igPTM53cGHMW8xWuVTydi2KO233VFiTNyF5hLJqpilHfmn8C8gPf+PS7dUT64YcXFbiMGZxS9pCSxL/Dxm/Jw=="],
"pure-rand": ["pure-rand@6.1.0", "", {}, "sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA=="],
"radash": ["radash@12.1.1", "", {}, "sha512-h36JMxKRqrAxVD8201FrCpyeNuUY9Y5zZwujr20fFO77tpUtGa6EZzfKw/3WaiBX95fq7+MpsuMLNdSnORAwSA=="],
"react": ["react@19.2.5", "", {}, "sha512-llUJLzz1zTUBrskt2pwZgLq59AemifIftw4aB7JxOqf1HY2FDaGDxgwpAPVzHU1kdWabH7FauP4i1oEeer2WCA=="],
"react-dom": ["react-dom@19.2.5", "", { "dependencies": { "scheduler": "^0.27.0" }, "peerDependencies": { "react": "^19.2.5" } }, "sha512-J5bAZz+DXMMwW/wV3xzKke59Af6CHY7G4uYLN1OvBcKEsWOs4pQExj86BBKamxl/Ik5bx9whOrvBlSDfWzgSag=="],
"react-is": ["react-is@19.2.6", "", {}, "sha512-XjBR15BhXuylgWGuslhDKqlSayuqvqBX91BP8pauG8kd1zY8kotkNWbXksTCNRarse4kuGbe2kIY05ARtwNIvw=="],
"react-redux": ["react-redux@9.2.0", "", { "dependencies": { "@types/use-sync-external-store": "^0.0.6", "use-sync-external-store": "^1.4.0" }, "peerDependencies": { "@types/react": "^18.2.25 || ^19", "react": "^18.0 || ^19", "redux": "^5.0.0" }, "optionalPeers": ["@types/react", "redux"] }, "sha512-ROY9fvHhwOD9ySfrF0wmvu//bKCQ6AeZZq1nJNtbDC+kk5DuSuNX/n6YWYF/SYy7bSba4D4FSz8DJeKY/S/r+g=="],
"react-remove-scroll": ["react-remove-scroll@2.7.2", "", { "dependencies": { "react-remove-scroll-bar": "^2.3.7", "react-style-singleton": "^2.2.3", "tslib": "^2.1.0", "use-callback-ref": "^1.3.3", "use-sidecar": "^1.1.3" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Iqb9NjCCTt6Hf+vOdNIZGdTiH1QSqr27H/Ek9sv/a97gfueI/5h1s3yRi1nngzMUaOOToin5dI1dXKdXiF+u0Q=="],
"react-remove-scroll-bar": ["react-remove-scroll-bar@2.3.8", "", { "dependencies": { "react-style-singleton": "^2.2.2", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" }, "optionalPeers": ["@types/react"] }, "sha512-9r+yi9+mgU33AKcj6IbT9oRCO78WriSj6t/cF8DWBZJ9aOGPOTEDvdUDz1FwKim7QXWwmHqtdHnRJfhAxEG46Q=="],
"react-style-singleton": ["react-style-singleton@2.2.3", "", { "dependencies": { "get-nonce": "^1.0.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-b6jSvxvVnyptAiLjbkWLE/lOnR4lfTtDAl+eUC7RZy+QQWc6wRzIV2CE6xBuMmDxc2qIihtDCZD5NPOFl7fRBQ=="],
"readdirp": ["readdirp@3.6.0", "", { "dependencies": { "picomatch": "^2.2.1" } }, "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA=="],
"recharts": ["recharts@3.8.1", "", { "dependencies": { "@reduxjs/toolkit": "^1.9.0 || 2.x.x", "clsx": "^2.1.1", "decimal.js-light": "^2.5.1", "es-toolkit": "^1.39.3", "eventemitter3": "^5.0.1", "immer": "^10.1.1", "react-redux": "8.x.x || 9.x.x", "reselect": "5.1.1", "tiny-invariant": "^1.3.3", "use-sync-external-store": "^1.2.2", "victory-vendor": "^37.0.2" }, "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-dom": "^16.0.0 || ^17.0.0 || ^18.0.0 || ^19.0.0", "react-is": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-mwzmO1s9sFL0TduUpwndxCUNoXsBw3u3E/0+A+cLcrSfQitSG62L32N69GhqUrrT5qKcAE3pCGVINC6pqkBBQg=="],
"redux": ["redux@5.0.1", "", {}, "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w=="],
"redux-thunk": ["redux-thunk@3.1.0", "", { "peerDependencies": { "redux": "^5.0.0" } }, "sha512-NW2r5T6ksUKXCabzhL9z+h206HQw/NJkcLm1GPImRQ8IzfXwRGqjVhKJGauHirT0DAuyy6hjdnMZaRoAcy0Klw=="],
"reselect": ["reselect@5.1.1", "", {}, "sha512-K/BG6eIky/SBpzfHZv/dd+9JBFiS4SWV7FIujVyJRux6e45+73RaUHXLmIR1f7WOMaQ0U1km6qwklRQxpJJY0w=="],
"resolve-pkg-maps": ["resolve-pkg-maps@1.0.0", "", {}, "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw=="],
"rolldown": ["rolldown@1.0.0-rc.17", "", { "dependencies": { "@oxc-project/types": "=0.127.0", "@rolldown/pluginutils": "1.0.0-rc.17" }, "optionalDependencies": { "@rolldown/binding-android-arm64": "1.0.0-rc.17", "@rolldown/binding-darwin-arm64": "1.0.0-rc.17", "@rolldown/binding-darwin-x64": "1.0.0-rc.17", "@rolldown/binding-freebsd-x64": "1.0.0-rc.17", "@rolldown/binding-linux-arm-gnueabihf": "1.0.0-rc.17", "@rolldown/binding-linux-arm64-gnu": "1.0.0-rc.17", "@rolldown/binding-linux-arm64-musl": "1.0.0-rc.17", "@rolldown/binding-linux-ppc64-gnu": "1.0.0-rc.17", "@rolldown/binding-linux-s390x-gnu": "1.0.0-rc.17", "@rolldown/binding-linux-x64-gnu": "1.0.0-rc.17", "@rolldown/binding-linux-x64-musl": "1.0.0-rc.17", "@rolldown/binding-openharmony-arm64": "1.0.0-rc.17", "@rolldown/binding-wasm32-wasi": "1.0.0-rc.17", "@rolldown/binding-win32-arm64-msvc": "1.0.0-rc.17", "@rolldown/binding-win32-x64-msvc": "1.0.0-rc.17" }, "bin": { "rolldown": "bin/cli.mjs" } }, "sha512-ZrT53oAKrtA4+YtBWPQbtPOxIbVDbxT0orcYERKd63VJTF13zPcgXTvD4843L8pcsI7M6MErt8QtON6lrB9tyA=="],
@@ -627,7 +796,7 @@
"source-map-js": ["source-map-js@1.2.1", "", {}, "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA=="],
"source-map-support": ["source-map-support@0.5.21", "", { "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" } }, "sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w=="],
"sql-escaper": ["sql-escaper@1.3.3", "", {}, "sha512-BsTCV265VpTp8tm1wyIm1xqQCS+Q9NHx2Sr+WcnUrgLrQ6yiDIvHYJV5gHxsj1lMBy2zm5twLaZao8Jd+S8JJw=="],
"srvx": ["srvx@0.11.15", "", { "bin": { "srvx": "bin/srvx.mjs" } }, "sha512-iXsux0UcOjdvs0LCMa2Ws3WwcDUozA3JN3BquNXkaFPP7TpRqgunKdEgoZ/uwb1J6xaYHfxtz9Twlh6yzwM6Tg=="],
@@ -637,6 +806,8 @@
"tapable": ["tapable@2.3.3", "", {}, "sha512-uxc/zpqFg6x7C8vOE7lh6Lbda8eEL9zmVm/PLeTPBRhh1xCgdWaQ+J1CUieGpIfm2HdtsUpRv+HshiasBMcc6A=="],
"tiny-invariant": ["tiny-invariant@1.3.3", "", {}, "sha512-+FbBPE1o9QAYvviau/qC5SE3caw21q3xkvWKBtja5vgqOWIHHJ3ioaq1VPfn/Szqctz2bU/oYeKd9/z5BL+PVg=="],
"tinyglobby": ["tinyglobby@0.2.16", "", { "dependencies": { "fdir": "^6.5.0", "picomatch": "^4.0.4" } }, "sha512-pn99VhoACYR8nFHhxqix+uvsbXineAasWm5ojXoN8xEwK5Kd3/TrhNn1wByuD52UxWRLy8pu+kRMniEi6Eq9Zg=="],
"to-regex-range": ["to-regex-range@5.0.1", "", { "dependencies": { "is-number": "^7.0.0" } }, "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ=="],
@@ -663,8 +834,14 @@
"update-browserslist-db": ["update-browserslist-db@1.2.3", "", { "dependencies": { "escalade": "^3.2.0", "picocolors": "^1.1.1" }, "peerDependencies": { "browserslist": ">= 4.21.0" }, "bin": { "update-browserslist-db": "cli.js" } }, "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w=="],
"use-callback-ref": ["use-callback-ref@1.3.3", "", { "dependencies": { "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-jQL3lRnocaFtu3V00JToYz/4QkNWswxijDaCVNZRiRTO3HQDLsdu1ZtmIUvV4yPp+rvWm5j0y0TG/S61cuijTg=="],
"use-sidecar": ["use-sidecar@1.1.3", "", { "dependencies": { "detect-node-es": "^1.1.0", "tslib": "^2.0.0" }, "peerDependencies": { "@types/react": "*", "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0 || ^19.0.0-rc" }, "optionalPeers": ["@types/react"] }, "sha512-Fedw0aZvkhynoPYlA5WXrMCAMm+nSWdZt6lzJQ7Ok8S6Q+VsHmHpRWndVRJ8Be0ZbkfPc5LRYH+5XrzXcEeLRQ=="],
"use-sync-external-store": ["use-sync-external-store@1.6.0", "", { "peerDependencies": { "react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0" } }, "sha512-Pp6GSwGP/NrPIrxVFAIkOQeyw8lFenOHijQWkUTrDvrF4ALqylP2C/KCkeS9dpUM3KvYRQhna5vt7IL95+ZQ9w=="],
"victory-vendor": ["victory-vendor@37.3.6", "", { "dependencies": { "@types/d3-array": "^3.0.3", "@types/d3-ease": "^3.0.0", "@types/d3-interpolate": "^3.0.1", "@types/d3-scale": "^4.0.2", "@types/d3-shape": "^3.1.0", "@types/d3-time": "^3.0.0", "@types/d3-timer": "^3.0.0", "d3-array": "^3.1.6", "d3-ease": "^3.0.1", "d3-interpolate": "^3.0.1", "d3-scale": "^4.0.2", "d3-shape": "^3.1.0", "d3-time": "^3.0.0", "d3-timer": "^3.0.1" } }, "sha512-SbPDPdDBYp+5MJHhBCAyI7wKM3d5ivekigc2Dk2s7pgbZ9wIgIBYGVw4zGHBml/qTFbexrofXW6Gu4noGxrOwQ=="],
"vite": ["vite@8.0.10", "", { "dependencies": { "lightningcss": "^1.32.0", "picomatch": "^4.0.4", "postcss": "^8.5.10", "rolldown": "1.0.0-rc.17", "tinyglobby": "^0.2.16" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.1.0", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@types/node", "@vitejs/devtools", "esbuild", "jiti", "less", "sass", "sass-embedded", "stylus", "sugarss", "terser", "tsx", "yaml"], "bin": { "vite": "bin/vite.js" } }, "sha512-rZuUu9j6J5uotLDs+cAA4O5H4K1SfPliUlQwqa6YEwSrWDZzP4rhm00oJR5snMewjxF5V/K3D4kctsUTsIU9Mw=="],
"vitefu": ["vitefu@1.1.3", "", { "peerDependencies": { "vite": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0" }, "optionalPeers": ["vite"] }, "sha512-ub4okH7Z5KLjb6hDyjqrGXqWtWvoYdU3IGm/NorpgHncKoLTCfRIbvlhBm7r0YstIaQRYlp4yEbFqDcKSzXSSg=="],
@@ -685,7 +862,9 @@
"zod": ["zod@4.3.6", "", {}, "sha512-rftlrkhHZOcjDwkGlnUtZZkvaPHCsDATp4pGpuOOMDaTdDDXF91wuVDJoWoPsKX/3YPQ5fHuF3STjcYyKr+Qhg=="],
"@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
"@babel/helper-compilation-targets/lru-cache": ["lru-cache@5.1.1", "", { "dependencies": { "yallist": "^3.0.2" } }, "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w=="],
"@reduxjs/toolkit/immer": ["immer@11.1.8", "", {}, "sha512-/tbkHMW7y10Lx6i1crLjD4/OhNkRG+Fo7byZHtah0547nIeXYcpIXaUh0IAQY6gO5459qpGGYapcEOHtFXkIuA=="],
"@tailwindcss/oxide-wasm32-wasi/@emnapi/core": ["@emnapi/core@1.10.0", "", { "dependencies": { "@emnapi/wasi-threads": "1.2.1", "tslib": "^2.4.0" }, "bundled": true }, "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw=="],
@@ -731,6 +910,8 @@
"anymatch/picomatch": ["picomatch@2.3.2", "", {}, "sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA=="],
"encoding-sniffer/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
"h3/rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="],
"h3-v2/rou3": ["rou3@0.8.1", "", {}, "sha512-ePa+XGk00/3HuCqrEnK3LxJW7I0SdNg6EFzKUJG73hMAdDcOUC/i/aSz7LSDwLrGr33kal/rqOGydzwl6U7zBA=="],
@@ -743,53 +924,9 @@
"rolldown/@rolldown/pluginutils": ["@rolldown/pluginutils@1.0.0-rc.17", "", {}, "sha512-n8iosDOt6Ig1UhJ2AYqoIhHWh/isz0xpicHTzpKBeotdVsTEcxsSA/i3EVM7gQAj0rU27OLAxCjzlj15IWY7bg=="],
"source-map-support/source-map": ["source-map@0.6.1", "", {}, "sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g=="],
"tsx/esbuild": ["esbuild@0.27.7", "", { "optionalDependencies": { "@esbuild/aix-ppc64": "0.27.7", "@esbuild/android-arm": "0.27.7", "@esbuild/android-arm64": "0.27.7", "@esbuild/android-x64": "0.27.7", "@esbuild/darwin-arm64": "0.27.7", "@esbuild/darwin-x64": "0.27.7", "@esbuild/freebsd-arm64": "0.27.7", "@esbuild/freebsd-x64": "0.27.7", "@esbuild/linux-arm": "0.27.7", "@esbuild/linux-arm64": "0.27.7", "@esbuild/linux-ia32": "0.27.7", "@esbuild/linux-loong64": "0.27.7", "@esbuild/linux-mips64el": "0.27.7", "@esbuild/linux-ppc64": "0.27.7", "@esbuild/linux-riscv64": "0.27.7", "@esbuild/linux-s390x": "0.27.7", "@esbuild/linux-x64": "0.27.7", "@esbuild/netbsd-arm64": "0.27.7", "@esbuild/netbsd-x64": "0.27.7", "@esbuild/openbsd-arm64": "0.27.7", "@esbuild/openbsd-x64": "0.27.7", "@esbuild/openharmony-arm64": "0.27.7", "@esbuild/sunos-x64": "0.27.7", "@esbuild/win32-arm64": "0.27.7", "@esbuild/win32-ia32": "0.27.7", "@esbuild/win32-x64": "0.27.7" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-IxpibTjyVnmrIQo5aqNpCgoACA/dTKLTlhMHihVHhdkxKyPO1uBBthumT0rdHmcsk9uMonIWS0m4FljWzILh3w=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/android-x64": ["@esbuild/android-x64@0.18.20", "", { "os": "android", "cpu": "x64" }, "sha512-8GDdlePJA8D6zlZYJV/jnrRAi6rOiNaCC/JclcXpB+KIuvfBN4owLtgzY2bsxnx666XjJx2kDPUmnTtR8qKQUg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/darwin-arm64": ["@esbuild/darwin-arm64@0.18.20", "", { "os": "darwin", "cpu": "arm64" }, "sha512-bxRHW5kHU38zS2lPTPOyuyTm+S+eobPUnTNkdJEfAddYgEcll4xkT8DB9d2008DtTbl7uJag2HuE5NZAZgnNEA=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/darwin-x64": ["@esbuild/darwin-x64@0.18.20", "", { "os": "darwin", "cpu": "x64" }, "sha512-pc5gxlMDxzm513qPGbCbDukOdsGtKhfxD1zJKXjCCcU7ju50O7MeAZ8c4krSJcOIJGFR+qx21yMMVYwiQvyTyQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/freebsd-arm64": ["@esbuild/freebsd-arm64@0.18.20", "", { "os": "freebsd", "cpu": "arm64" }, "sha512-yqDQHy4QHevpMAaxhhIwYPMv1NECwOvIpGCZkECn8w2WFHXjEwrBn3CeNIYsibZ/iZEUemj++M26W3cNR5h+Tw=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/freebsd-x64": ["@esbuild/freebsd-x64@0.18.20", "", { "os": "freebsd", "cpu": "x64" }, "sha512-tgWRPPuQsd3RmBZwarGVHZQvtzfEBOreNuxEMKFcd5DaDn2PbBxfwLcj4+aenoh7ctXcbXmOQIn8HI6mCSw5MQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-arm": ["@esbuild/linux-arm@0.18.20", "", { "os": "linux", "cpu": "arm" }, "sha512-/5bHkMWnq1EgKr1V+Ybz3s1hWXok7mDFUMQ4cG10AfW3wL02PSZi5kFpYKrptDsgb2WAJIvRcDm+qIvXf/apvg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-arm64": ["@esbuild/linux-arm64@0.18.20", "", { "os": "linux", "cpu": "arm64" }, "sha512-2YbscF+UL7SQAVIpnWvYwM+3LskyDmPhe31pE7/aoTMFKKzIc9lLbyGUpmmb8a8AixOL61sQ/mFh3jEjHYFvdA=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-ia32": ["@esbuild/linux-ia32@0.18.20", "", { "os": "linux", "cpu": "ia32" }, "sha512-P4etWwq6IsReT0E1KHU40bOnzMHoH73aXp96Fs8TIT6z9Hu8G6+0SHSw9i2isWrD2nbx2qo5yUqACgdfVGx7TA=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-loong64": ["@esbuild/linux-loong64@0.18.20", "", { "os": "linux", "cpu": "none" }, "sha512-nXW8nqBTrOpDLPgPY9uV+/1DjxoQ7DoB2N8eocyq8I9XuqJ7BiAMDMf9n1xZM9TgW0J8zrquIb/A7s3BJv7rjg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-mips64el": ["@esbuild/linux-mips64el@0.18.20", "", { "os": "linux", "cpu": "none" }, "sha512-d5NeaXZcHp8PzYy5VnXV3VSd2D328Zb+9dEq5HE6bw6+N86JVPExrA6O68OPwobntbNJ0pzCpUFZTo3w0GyetQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-ppc64": ["@esbuild/linux-ppc64@0.18.20", "", { "os": "linux", "cpu": "ppc64" }, "sha512-WHPyeScRNcmANnLQkq6AfyXRFr5D6N2sKgkFo2FqguP44Nw2eyDlbTdZwd9GYk98DZG9QItIiTlFLHJHjxP3FA=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-riscv64": ["@esbuild/linux-riscv64@0.18.20", "", { "os": "linux", "cpu": "none" }, "sha512-WSxo6h5ecI5XH34KC7w5veNnKkju3zBRLEQNY7mv5mtBmrP/MjNBCAlsM2u5hDBlS3NGcTQpoBvRzqBcRtpq1A=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-s390x": ["@esbuild/linux-s390x@0.18.20", "", { "os": "linux", "cpu": "s390x" }, "sha512-+8231GMs3mAEth6Ja1iK0a1sQ3ohfcpzpRLH8uuc5/KVDFneH6jtAJLFGafpzpMRO6DzJ6AvXKze9LfFMrIHVQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/linux-x64": ["@esbuild/linux-x64@0.18.20", "", { "os": "linux", "cpu": "x64" }, "sha512-UYqiqemphJcNsFEskc73jQ7B9jgwjWrSayxawS6UVFZGWrAAtkzjxSqnoclCXxWtfwLdzU+vTpcNYhpn43uP1w=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/netbsd-x64": ["@esbuild/netbsd-x64@0.18.20", "", { "os": "none", "cpu": "x64" }, "sha512-iO1c++VP6xUBUmltHZoMtCUdPlnPGdBom6IrO4gyKPFFVBKioIImVooR5I83nTew5UOYrk3gIJhbZh8X44y06A=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/openbsd-x64": ["@esbuild/openbsd-x64@0.18.20", "", { "os": "openbsd", "cpu": "x64" }, "sha512-e5e4YSsuQfX4cxcygw/UCPIEP6wbIL+se3sxPdCiMbFLBWu0eiZOJ7WoD+ptCLrmjZBK1Wk7I6D/I3NglUGOxg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/sunos-x64": ["@esbuild/sunos-x64@0.18.20", "", { "os": "sunos", "cpu": "x64" }, "sha512-kDbFRFp0YpTQVVrqUd5FTYmWo45zGaXe0X8E1G/LKFC0v8x0vWrhOWSLITcCn63lmZIxfOMXtCfti/RxN/0wnQ=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/win32-arm64": ["@esbuild/win32-arm64@0.18.20", "", { "os": "win32", "cpu": "arm64" }, "sha512-ddYFR6ItYgoaq4v4JmQQaAI5s7npztfV4Ag6NrhiaW0RrnOXqBkgwZLofVTlq1daVTQNhtI5oieTvkRPfZrePg=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/win32-ia32": ["@esbuild/win32-ia32@0.18.20", "", { "os": "win32", "cpu": "ia32" }, "sha512-Wv7QBi3ID/rROT08SABTS7eV4hX26sVduqDOTe1MvGMjNd3EjOz4b7zeexIR62GTIEKrfJXKL9LFxTYgkyeu7g=="],
"@esbuild-kit/core-utils/esbuild/@esbuild/win32-x64": ["@esbuild/win32-x64@0.18.20", "", { "os": "win32", "cpu": "x64" }, "sha512-kTdfRcSiDfQca/y9QIkng02avJ+NCaQvrMejlsB3RRv5sE9rRoeBPISaZpKxHELzRxZyLvNts1P27W3wV+8geQ=="],
"whatwg-encoding/iconv-lite": ["iconv-lite@0.6.3", "", { "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" } }, "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw=="],
"tsx/esbuild/@esbuild/aix-ppc64": ["@esbuild/aix-ppc64@0.27.7", "", { "os": "aix", "cpu": "ppc64" }, "sha512-EKX3Qwmhz1eMdEJokhALr0YiD0lhQNwDqkPYyPhiSwKrh7/4KRjQc04sZ8db+5DVVnZ1LmbNDI1uAMPEUBnQPg=="],
+32 -24
View File
@@ -1,39 +1,47 @@
services:
migrate:
build: .
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=postgres://postgres:postgres@db:5432/postgres
command: ["./server", "migrate"]
restart: "no"
- 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:
db:
condition: service_healthy
migrate:
seed:
condition: service_completed_successfully
extra_hosts:
- "host.docker.internal:host-gateway"
ports:
- "3000:3000"
environment:
- DATABASE_URL=postgres://postgres:postgres@db:5432/postgres
db:
image: postgres:18-alpine
volumes:
- postgres_data:/var/lib/postgresql
environment:
POSTGRES_USER: postgres
POSTGRES_PASSWORD: postgres
POSTGRES_DB: postgres
healthcheck:
test: [ "CMD", "pg_isready", "-U", "postgres" ]
interval: 10s
timeout: 5s
retries: 5
- DATABASE_URL=mysql://battery:battery@db:3306/battery_soh
- SOH_PREDICTION_API_BASE_URL=http://host.docker.internal:8000
- ENABLE_API_DOCS=true
volumes:
postgres_data:
mysql_data:
-11
View File
@@ -1,11 +0,0 @@
import { defineConfig } from 'drizzle-kit'
import { env } from './src/env'
export default defineConfig({
out: './drizzle',
schema: './src/server/db/schema/index.ts',
dialect: 'postgresql',
dbCredentials: {
url: env.DATABASE_URL,
},
})
-7
View File
@@ -1,7 +0,0 @@
CREATE TABLE "todo" (
"id" uuid PRIMARY KEY NOT NULL,
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
"title" text NOT NULL,
"completed" boolean DEFAULT false NOT NULL
);
-65
View File
@@ -1,65 +0,0 @@
{
"id": "4ece5479-57bf-473d-b806-c1176c972e7f",
"prevId": "00000000-0000-0000-0000-000000000000",
"version": "7",
"dialect": "postgresql",
"tables": {
"public.todo": {
"name": "todo",
"schema": "",
"columns": {
"id": {
"name": "id",
"type": "uuid",
"primaryKey": true,
"notNull": true
},
"created_at": {
"name": "created_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"updated_at": {
"name": "updated_at",
"type": "timestamp with time zone",
"primaryKey": false,
"notNull": true,
"default": "now()"
},
"title": {
"name": "title",
"type": "text",
"primaryKey": false,
"notNull": true
},
"completed": {
"name": "completed",
"type": "boolean",
"primaryKey": false,
"notNull": true,
"default": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"policies": {},
"checkConstraints": {},
"isRLSEnabled": false
}
},
"enums": {},
"schemas": {},
"sequences": {},
"roles": {},
"policies": {},
"views": {},
"_meta": {
"columns": {},
"schemas": {},
"tables": {}
}
}
-13
View File
@@ -1,13 +0,0 @@
{
"version": "7",
"dialect": "postgresql",
"entries": [
{
"idx": 0,
"version": "7",
"when": 1777096386609,
"tag": "0000_loving_thunderbird",
"breakpoints": true
}
]
}
+12 -12
View File
@@ -1,10 +1,9 @@
{
"name": "fullstack-starter",
"name": "battery-soh",
"version": "1.0.0",
"private": true,
"type": "module",
"imports": {
"#drizzle/*.sql": "./drizzle/*.sql",
"#package": "./package.json",
"#server": "./.output/server/index.mjs"
},
@@ -20,18 +19,13 @@
"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",
"db:embed": "bun scripts/embed-migrations.ts",
"db:generate": "drizzle-kit generate && bun scripts/embed-migrations.ts",
"db:migrate": "drizzle-kit migrate",
"db:push": "drizzle-kit push",
"db:studio": "drizzle-kit studio",
"dev": "bunx --bun vite dev",
"fix": "biome check --write",
"seed": "bun scripts/seed.ts",
"test": "bun test",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@logtape/drizzle-orm": "^2.0.5",
"@logtape/logtape": "^2.0.5",
"@logtape/pretty": "^2.0.5",
"@orpc/client": "^1.14.0",
@@ -40,17 +34,22 @@
"@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",
"drizzle-orm": "0.45.2",
"drizzle-zod": "^0.8.3",
"postgres": "^3.4.9",
"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",
"zod": "^4.3.6"
},
"devDependencies": {
@@ -62,7 +61,8 @@
"@tanstack/react-router-devtools": "^1.166.13",
"@types/bun": "^1.3.13",
"@vitejs/plugin-react": "^6.0.1",
"drizzle-kit": "0.31.10",
"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",
-51
View File
@@ -1,51 +0,0 @@
import { existsSync } from 'node:fs'
import { readFile, writeFile } from 'node:fs/promises'
import { z } from 'zod'
const JOURNAL = './drizzle/meta/_journal.json'
const OUTPUT = './src/server/db/migrations.gen.ts'
const journalEntrySchema = z.object({
idx: z.number().int().nonnegative(),
tag: z.string().regex(/^\d{4}_[a-z0-9_]+$/),
when: z.number().int().nonnegative(),
breakpoints: z.boolean(),
})
const journalSchema = z.object({ entries: z.array(journalEntrySchema).default([]) })
type JournalEntry = z.infer<typeof journalEntrySchema>
const readJournalEntries = async (): Promise<JournalEntry[]> => {
if (!existsSync(JOURNAL)) {
return []
}
const raw: unknown = JSON.parse(await readFile(JOURNAL, 'utf-8'))
return journalSchema.parse(raw).entries.sort((a, b) => a.idx - b.idx)
}
const main = async () => {
const entries = await readJournalEntries()
const imports = entries
.map((e) => `import sql_${e.idx} from '#drizzle/${e.tag}.sql' with { type: 'text' }`)
.join('\n')
const arrayBody = entries.length
? `[\n${entries.map((e) => ` { tag: '${e.tag}', sql: sql_${e.idx}, when: ${e.when}, breakpoints: ${e.breakpoints} },`).join('\n')}\n]`
: '[]'
const out = `// AUTO-GENERATED by \`bun run db:embed\`. Do not edit.
${imports ? `${imports}\n` : ''}
export type EmbeddedMigration = { tag: string; sql: string; when: number; breakpoints: boolean }
export const embeddedMigrations: readonly EmbeddedMigration[] = ${arrayBody}
`
await writeFile(OUTPUT, out)
console.log(`${OUTPUT} (${entries.length} migration${entries.length === 1 ? '' : 's'})`)
}
main().catch((err) => {
console.error('❌', err instanceof Error ? err.message : err)
process.exit(1)
})
+138
View File
@@ -0,0 +1,138 @@
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()
}
+1 -2
View File
@@ -4,7 +4,7 @@ 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
// `migrate` or `--help`. All subcommands are lazy-loaded via citty.
// `--help`. All subcommands are lazy-loaded via citty.
const main = defineCommand({
meta: {
name,
@@ -14,7 +14,6 @@ const main = defineCommand({
default: 'serve',
subCommands: {
serve: () => import('@/cli/serve').then((m) => m.default),
migrate: () => import('@/cli/migrate').then((m) => m.default),
},
})
-84
View File
@@ -1,84 +0,0 @@
import { defineCommand } from 'citty'
export default defineCommand({
meta: {
name: 'migrate',
description: 'Apply pending database migrations',
},
async run() {
const [{ env }, { drizzle }, { sql }, { embeddedMigrations }, { getLogger }] = await Promise.all([
import('@/env'),
import('drizzle-orm/postgres-js'),
import('drizzle-orm'),
import('@/server/db/migrations.gen'),
import('@/server/logger'),
])
const logger = getLogger(['cli', 'migrate'])
if (embeddedMigrations.length === 0) {
logger.info('No migrations bundled into this binary.')
return
}
const sha256 = (s: string) => Bun.CryptoHasher.hash('sha256', s, 'hex')
const db = drizzle({
connection: {
url: env.DATABASE_URL,
max: 1,
onnotice: (n) => logger.debug('pg notice', { notice: n.message }),
},
})
try {
await db.execute(sql`CREATE SCHEMA IF NOT EXISTS "drizzle"`)
await db.execute(sql`
CREATE TABLE IF NOT EXISTS "drizzle"."__drizzle_migrations" (
id SERIAL PRIMARY KEY,
hash text NOT NULL,
created_at bigint
)
`)
const applied = await db.execute<{ hash: string; created_at: string | null }>(
sql`SELECT hash, created_at FROM "drizzle"."__drizzle_migrations" ORDER BY created_at ASC`,
)
// Reject schema drift: any applied migration whose embedded SQL has changed (or is missing) is fatal.
for (const row of applied) {
const when = Number(row.created_at)
const m = embeddedMigrations.find((e) => e.when === when)
if (!m) {
throw new Error(`Applied migration when=${when} is not in this binary; do not roll back applied migrations.`)
}
if (sha256(m.sql) !== row.hash) {
throw new Error(`Migration hash mismatch at when=${when}; do not edit migrations after they are applied.`)
}
}
const appliedWhens = new Set(applied.map((r) => Number(r.created_at)))
const pending = embeddedMigrations.filter((m) => !appliedWhens.has(m.when))
if (pending.length === 0) {
logger.info('Database is up to date.')
return
}
logger.info('Applying {count} migration(s)...', { count: pending.length })
await db.transaction(async (tx) => {
for (const m of pending) {
for (const rawStmt of m.sql.split('--> statement-breakpoint')) {
const stmt = rawStmt.trim()
if (!stmt) continue
await tx.execute(sql.raw(stmt))
}
await tx.execute(
sql`INSERT INTO "drizzle"."__drizzle_migrations" ("hash", "created_at") VALUES (${sha256(m.sql)}, ${m.when})`,
)
}
})
logger.info('Migrations applied.')
} finally {
await db.$client.end()
}
},
})
-7
View File
@@ -1,7 +0,0 @@
import { useQueryClient } from '@tanstack/react-query'
import { orpc } from '@/client/orpc'
export const useInvalidateTodos = () => {
const queryClient = useQueryClient()
return () => queryClient.invalidateQueries({ queryKey: orpc.todo.list.key() })
}
-41
View File
@@ -1,41 +0,0 @@
import type { SubmitEventHandler } from 'react'
import { useState } from 'react'
interface TodoFormProps {
onSubmit: (title: string) => void
isPending: boolean
}
export const TodoForm = ({ onSubmit, isPending }: TodoFormProps) => {
const [title, setTitle] = useState('')
const handleSubmit: SubmitEventHandler<HTMLFormElement> = (e) => {
e.preventDefault()
if (title.trim()) {
onSubmit(title.trim())
setTitle('')
}
}
return (
<form onSubmit={handleSubmit} className="relative group z-10">
<div className="relative transform transition-all duration-200 focus-within:-translate-y-1">
<input
type="text"
value={title}
onChange={(e) => setTitle(e.target.value)}
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={isPending}
/>
<button
type="submit"
disabled={isPending || !title.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"
>
{isPending ? '添加中' : '添加'}
</button>
</div>
</form>
)
}
-77
View File
@@ -1,77 +0,0 @@
import type { RouterOutputs } from '@/server/api/types'
type Todo = RouterOutputs['todo']['list'][number]
interface TodoItemProps {
todo: Todo
onToggle: (id: string, completed: boolean) => void
onDelete: (id: string) => void
}
export const TodoItem = ({ todo, onToggle, onDelete }: TodoItemProps) => {
return (
<div
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={() => onToggle(todo.id, todo.completed)}
className={`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-linear-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={() => onDelete(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>
)
}
+128
View File
@@ -0,0 +1,128 @@
import { motion, useReducedMotion } from 'motion/react'
import type { ComponentPropsWithoutRef, ReactNode } from 'react'
export function useMotionConfig() {
const shouldReduceMotion = useReducedMotion()
return { shouldReduceMotion }
}
export function MotionHeader({
children,
delay = 0,
className,
...props
}: { children: ReactNode; delay?: number } & ComponentPropsWithoutRef<typeof motion.header>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.header
initial={shouldReduceMotion ? false : { opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay, ease: [0.25, 0.1, 0.25, 1] }}
className={className}
{...props}
>
{children}
</motion.header>
)
}
export function MotionSection({
children,
delay = 0,
className,
...props
}: { children: ReactNode; delay?: number } & ComponentPropsWithoutRef<typeof motion.section>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.section
initial={shouldReduceMotion ? false : { opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay, ease: [0.25, 0.1, 0.25, 1] }}
className={className}
{...props}
>
{children}
</motion.section>
)
}
export function MotionDiv({
children,
delay = 0,
className,
...props
}: { children: ReactNode; delay?: number } & ComponentPropsWithoutRef<typeof motion.div>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.div
initial={shouldReduceMotion ? false : { opacity: 0, y: 10 }}
animate={{ opacity: 1, y: 0 }}
transition={{ duration: 0.5, delay, ease: [0.25, 0.1, 0.25, 1] }}
className={className}
{...props}
>
{children}
</motion.div>
)
}
export function MotionCardArticle({
children,
className,
...props
}: { children: ReactNode } & ComponentPropsWithoutRef<typeof motion.article>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.article
whileHover={shouldReduceMotion ? {} : { y: -2 }}
transition={{ duration: 0.2, ease: 'easeOut' }}
className={className}
{...props}
>
{children}
</motion.article>
)
}
export function MotionCardDiv({
children,
className,
...props
}: { children: ReactNode } & ComponentPropsWithoutRef<typeof motion.div>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.div
whileHover={shouldReduceMotion ? {} : { y: -2 }}
transition={{ duration: 0.2, ease: 'easeOut' }}
className={className}
{...props}
>
{children}
</motion.div>
)
}
export function MotionTableRow({
children,
className,
...props
}: { children: ReactNode } & ComponentPropsWithoutRef<typeof motion.tr>) {
const { shouldReduceMotion } = useMotionConfig()
return (
<motion.tr
initial={shouldReduceMotion ? false : { opacity: 0 }}
animate={{ opacity: 1 }}
transition={{ duration: 0.3 }}
className={className}
{...props}
>
{children}
</motion.tr>
)
}
+181
View File
@@ -0,0 +1,181 @@
import * as RadixSelect from '@radix-ui/react-select'
import { Check, ChevronDown } from 'lucide-react'
import type { ComponentPropsWithoutRef, ReactNode } from 'react'
type Variant = 'default' | 'muted' | 'success' | 'warning' | 'danger' | 'info'
function cn(...classes: Array<string | false | null | undefined>) {
return classes.filter(Boolean).join(' ')
}
const variantClass: Record<Variant, string> = {
default: 'border-white/10 bg-white/[0.04] text-zinc-100',
muted: 'border-white/10 bg-zinc-900/70 text-zinc-400',
success: 'border-emerald-400/20 bg-emerald-400/10 text-emerald-300',
warning: 'border-amber-400/20 bg-amber-400/10 text-amber-300',
danger: 'border-red-400/20 bg-red-400/10 text-red-300',
info: 'border-teal-400/20 bg-teal-400/10 text-teal-300',
}
export function Badge({
className,
variant = 'default',
children,
...props
}: ComponentPropsWithoutRef<'span'> & { variant?: Variant }) {
return (
<span
className={cn(
'inline-flex items-center gap-1.5 rounded-full border px-2.5 py-1 text-xs font-medium leading-none',
variantClass[variant],
className,
)}
{...props}
>
{children}
</span>
)
}
export function Card({ className, children, ...props }: ComponentPropsWithoutRef<'div'>) {
return (
<div
className={cn('rounded-2xl border border-white/[0.08] bg-zinc-950/60 shadow-2xl shadow-black/20', className)}
{...props}
>
{children}
</div>
)
}
export function Button({ className, children, ...props }: ComponentPropsWithoutRef<'button'>) {
return (
<button
className={cn(
'inline-flex items-center justify-center gap-2 rounded-lg border border-white/10 bg-white/[0.05] px-4 py-2 text-sm font-medium text-zinc-100 transition-colors hover:border-white/20 hover:bg-white/[0.09] disabled:cursor-not-allowed disabled:opacity-35 disabled:hover:bg-white/[0.05]',
className,
)}
{...props}
>
{children}
</button>
)
}
export function Input({ className, ...props }: ComponentPropsWithoutRef<'input'>) {
return (
<input
className={cn(
'h-10 w-full rounded-lg border border-white/10 bg-zinc-950/80 px-3 py-2 text-sm text-zinc-100 placeholder:text-zinc-600 outline-none transition-colors focus:border-teal-400/60 focus:ring-2 focus:ring-teal-400/10',
className,
)}
{...props}
/>
)
}
export function Select({
value,
onValueChange,
children,
className,
id,
}: {
value?: string | number
onValueChange?: (value: string) => void
children: ReactNode
className?: string
id?: string
}) {
return (
<RadixSelect.Root value={value?.toString()} onValueChange={onValueChange}>
<RadixSelect.Trigger
id={id}
className={cn(
'flex h-10 w-full items-center justify-between gap-2 rounded-lg border border-white/10 bg-zinc-950/95 px-3 py-2 text-sm text-zinc-100 outline-none transition-colors focus:border-teal-400/60 focus:ring-2 focus:ring-teal-400/10 data-[placeholder]:text-zinc-500',
className,
)}
>
<RadixSelect.Value />
<RadixSelect.Icon asChild>
<ChevronDown className="size-4 opacity-50" />
</RadixSelect.Icon>
</RadixSelect.Trigger>
<RadixSelect.Portal>
<RadixSelect.Content
className="relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-lg border border-white/10 bg-zinc-950 text-zinc-100 shadow-xl shadow-black/40"
position="popper"
sideOffset={4}
>
<RadixSelect.Viewport className="p-1">{children}</RadixSelect.Viewport>
</RadixSelect.Content>
</RadixSelect.Portal>
</RadixSelect.Root>
)
}
export function SelectOption({
value,
children,
className,
}: {
value: string | number
children: ReactNode
className?: string
}) {
return (
<RadixSelect.Item
value={value.toString()}
className={cn(
'relative flex w-full cursor-default select-none items-center rounded-md py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-white/10 focus:text-zinc-50 data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
className,
)}
>
<span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
<RadixSelect.ItemIndicator>
<Check className="size-4" />
</RadixSelect.ItemIndicator>
</span>
<RadixSelect.ItemText>{children}</RadixSelect.ItemText>
</RadixSelect.Item>
)
}
export function SectionTitle({ icon, title, description }: { icon?: ReactNode; title: string; description?: string }) {
return (
<div className="flex items-start gap-3">
{icon && <div className="mt-0.5 rounded-lg border border-white/10 bg-white/[0.04] p-2 text-teal-300">{icon}</div>}
<div>
<h3 className="text-lg font-medium text-white">{title}</h3>
{description && <p className="mt-1 text-sm text-zinc-400">{description}</p>}
</div>
</div>
)
}
export function Skeleton({ className, ...props }: ComponentPropsWithoutRef<'div'>) {
return <div className={cn('rounded-md bg-white/5 motion-safe:animate-pulse', className)} {...props} />
}
export function EmptyState({
icon,
title,
description,
action,
className,
}: {
icon?: ReactNode
title: string
description?: string
action?: ReactNode
className?: string
}) {
return (
<div className={cn('flex flex-col items-center justify-center py-12 text-center', className)}>
{icon && <div className="mb-4 text-zinc-500">{icon}</div>}
<h3 className="text-sm font-medium text-zinc-200">{title}</h3>
{description && <p className="mt-1 text-sm text-zinc-500 max-w-sm">{description}</p>}
{action && <div className="mt-6">{action}</div>}
</div>
)
}
+63
View File
@@ -0,0 +1,63 @@
export const POWER_STATUS = {
NOT_CHARGING: 0,
CHARGING: 1,
FULL: 2,
} as const
export type PowerStatus = (typeof POWER_STATUS)[keyof typeof POWER_STATUS]
export const POWER_STATUS_VALUES = [POWER_STATUS.NOT_CHARGING, POWER_STATUS.CHARGING, POWER_STATUS.FULL] as const
export const BATTERY_LIST_SORT = {
CREATED_AT_DESC: 'createdAtDesc',
CREATED_AT_ASC: 'createdAtAsc',
POWER_DESC: 'powerDesc',
POWER_ASC: 'powerAsc',
} as const
export type BatteryListSort = (typeof BATTERY_LIST_SORT)[keyof typeof BATTERY_LIST_SORT]
export const BATTERY_LIST_SORT_VALUES = [
BATTERY_LIST_SORT.CREATED_AT_DESC,
BATTERY_LIST_SORT.CREATED_AT_ASC,
BATTERY_LIST_SORT.POWER_DESC,
BATTERY_LIST_SORT.POWER_ASC,
] as const
export const MYSQL_BOOLEAN = {
TRUE: 'true',
FALSE: 'false',
} as const
export function toMysqlBoolean(value: boolean) {
return value ? MYSQL_BOOLEAN.TRUE : MYSQL_BOOLEAN.FALSE
}
export function fromMysqlBoolean(value: string | boolean) {
if (typeof value === 'boolean') return value
return value.trim().toLowerCase() === MYSQL_BOOLEAN.TRUE
}
export const DEVICE_STATUS = {
HEALTHY: '健康',
WATCH: '关注',
WARNING: '预警',
} as const
export type DeviceStatus = (typeof DEVICE_STATUS)[keyof typeof DEVICE_STATUS]
export const EVENT_SEVERITY = {
HIGH: '高',
MEDIUM: '中',
LOW: '低',
} as const
export type EventSeverity = (typeof EVENT_SEVERITY)[keyof typeof EVENT_SEVERITY]
export const SOH_THRESHOLDS = {
WARNING: 85,
WATCH: 90,
LOW_POWER: 20,
HIGH_RISK_SCORE: 70,
WATCH_RISK_SCORE: 40,
} as const
+151
View File
@@ -0,0 +1,151 @@
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 })
})
})
+475
View File
@@ -0,0 +1,475 @@
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),
}
}
+6 -1
View File
@@ -3,10 +3,15 @@ import { z } from 'zod'
export const env = createEnv({
server: {
DATABASE_URL: z.url({ protocol: /^postgres(ql)?$/ }),
DATABASE_URL: z.url({ protocol: /^mysql$/ }),
ENABLE_API_DOCS: z.stringbool().default(false),
LOG_DB: z.stringbool().default(false),
LOG_FORMAT: z.enum(['pretty', 'json']).optional(),
LOG_LEVEL: z.enum(['trace', 'debug', 'info', 'warning', 'error', 'fatal']).default('info'),
SOH_PREDICTION_API_BASE_URL: z.url({ protocol: /^https?$/ }),
SOH_PREDICTION_CACHE_TTL_SECONDS: z.coerce.number().int().positive().default(86_400),
SOH_PREDICTION_NEGATIVE_CACHE_TTL_SECONDS: z.coerce.number().int().positive().default(300),
SOH_PREDICTION_TIMEOUT_MS: z.coerce.number().int().positive().default(10_000),
},
clientPrefix: 'VITE_',
client: {},
+21 -3
View File
@@ -10,6 +10,7 @@
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.$'
@@ -19,6 +20,11 @@ const HealthRoute = HealthRouteImport.update({
path: '/health',
getParentRoute: () => rootRouteImport,
} as any)
const BatteriesRoute = BatteriesRouteImport.update({
id: '/batteries',
path: '/batteries',
getParentRoute: () => rootRouteImport,
} as any)
const IndexRoute = IndexRouteImport.update({
id: '/',
path: '/',
@@ -37,12 +43,14 @@ 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
@@ -50,20 +58,22 @@ export interface FileRoutesByTo {
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: '/' | '/health' | '/api/$' | '/api/rpc/$'
fullPaths: '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
fileRoutesByTo: FileRoutesByTo
to: '/' | '/health' | '/api/$' | '/api/rpc/$'
id: '__root__' | '/' | '/health' | '/api/$' | '/api/rpc/$'
to: '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
id: '__root__' | '/' | '/batteries' | '/health' | '/api/$' | '/api/rpc/$'
fileRoutesById: FileRoutesById
}
export interface RootRouteChildren {
IndexRoute: typeof IndexRoute
BatteriesRoute: typeof BatteriesRoute
HealthRoute: typeof HealthRoute
ApiSplatRoute: typeof ApiSplatRoute
ApiRpcSplatRoute: typeof ApiRpcSplatRoute
@@ -78,6 +88,13 @@ declare module '@tanstack/react-router' {
preLoaderRoute: typeof HealthRouteImport
parentRoute: typeof rootRouteImport
}
'/batteries': {
id: '/batteries'
path: '/batteries'
fullPath: '/batteries'
preLoaderRoute: typeof BatteriesRouteImport
parentRoute: typeof rootRouteImport
}
'/': {
id: '/'
path: '/'
@@ -104,6 +121,7 @@ declare module '@tanstack/react-router' {
const rootRouteChildren: RootRouteChildren = {
IndexRoute: IndexRoute,
BatteriesRoute: BatteriesRoute,
HealthRoute: HealthRoute,
ApiSplatRoute: ApiSplatRoute,
ApiRpcSplatRoute: ApiRpcSplatRoute,
+7 -2
View File
@@ -4,11 +4,13 @@ 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: [
plugins: env.ENABLE_API_DOCS
? [
new OpenAPIReferencePlugin({
docsProvider: 'scalar',
schemaConverters: [new ZodToJsonSchemaConverter()],
@@ -21,7 +23,8 @@ const handler = new OpenAPIHandler(router, {
docsPath: '/docs',
specPath: '/spec.json',
}),
],
]
: [],
interceptors: [onError(logError)],
clientInterceptors: [onError(handleValidationError)],
})
@@ -30,6 +33,8 @@ export const Route = createFileRoute('/api/$')({
server: {
handlers: {
ANY: async ({ request }) => {
if (!env.ENABLE_API_DOCS) return new Response('Not Found', { status: 404 })
const { response } = await handler.handle(request, {
prefix: '/api',
context: {
+530
View File
@@ -0,0 +1,530 @@
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>
)
}
+649 -66
View File
@@ -1,87 +1,670 @@
import { useMutation, useSuspenseQuery } from '@tanstack/react-query'
import { createFileRoute } from '@tanstack/react-router'
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 { useInvalidateTodos } from '@/client/queries/todo'
import { TodoForm } from '@/components/TodoForm'
import { TodoItem } from '@/components/TodoItem'
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'
export const Route = createFileRoute('/')({
component: Todos,
loader: async ({ context }) => {
await context.queryClient.ensureQueryData(orpc.todo.list.queryOptions())
},
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>
),
})
function Todos() {
const listQuery = useSuspenseQuery(orpc.todo.list.queryOptions())
const invalidateTodos = useInvalidateTodos()
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,
}))
const createMutation = useMutation(orpc.todo.create.mutationOptions({ onSuccess: invalidateTodos }))
const updateMutation = useMutation(orpc.todo.update.mutationOptions({ onSuccess: invalidateTodos }))
const deleteMutation = useMutation(orpc.todo.remove.mutationOptions({ onSuccess: invalidateTodos }))
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 todos = listQuery.data
const completedCount = todos.filter((todo) => todo.completed).length
const totalCount = todos.length
const progress = totalCount > 0 ? (completedCount / totalCount) * 100 : 0
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,
})
}
}
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>
)
}
if (isPending || !data) {
return (
<main className="flex min-h-screen items-center justify-center bg-[#09090B]">
<p className="text-[#71717A]"></p>
</main>
)
}
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)
return (
<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">
<div className="flex items-end justify-between">
<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">
{/* 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>
<h1 className="text-3xl font-bold text-slate-900 tracking-tight"></h1>
<p className="text-slate-500 mt-1"></p>
<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]"> (&gt; 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]"> (&le; 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>
<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-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 className="text-sm tabular-nums text-white">{formatPercentWithUnit(item.avgSoh)}</div>
<div className="text-xs text-[#71717A]"></div>
</div>
</div>
<TodoForm onSubmit={(title) => createMutation.mutate({ title })} isPending={createMutation.isPending} />
{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>
)}
<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) => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={(id, completed) => updateMutation.mutate({ id, data: { completed: !completed } })}
onDelete={(id) => deleteMutation.mutate({ id })}
/>
))
) : (
<div className="text-sm text-[#71717A]"></div>
)}
</div>
</div>
</div>
</MotionSection>
</div>
</main>
)
}
@@ -0,0 +1,35 @@
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)
+2 -2
View File
@@ -1,7 +1,7 @@
import * as todo from './todo.contract'
import * as battery from './battery.contract'
export const contract = {
todo,
battery,
}
export type Contract = typeof contract
@@ -1,20 +0,0 @@
import { describe, expect, test } from 'bun:test'
import { createInsertSchema } from 'drizzle-zod'
import { generatedFieldKeys } from '@/server/db/fields'
import { todoTable } from '@/server/db/schema'
describe('todo insert schema', () => {
const insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)
test('accepts a minimal valid input', () => {
expect(insertSchema.safeParse({ title: 'buy milk' }).success).toBe(true)
})
test('rejects missing title', () => {
expect(insertSchema.safeParse({}).success).toBe(false)
})
test('rejects non-string title', () => {
expect(insertSchema.safeParse({ title: 42 }).success).toBe(false)
})
})
-34
View File
@@ -1,34 +0,0 @@
import { oc } from '@orpc/contract'
import { createInsertSchema, createSelectSchema, createUpdateSchema } from 'drizzle-zod'
import { z } from 'zod'
import { generatedFieldKeys } from '@/server/db/fields'
import { todoTable } from '@/server/db/schema'
const selectSchema = createSelectSchema(todoTable)
const insertSchema = createInsertSchema(todoTable).omit(generatedFieldKeys)
const updateSchema = createUpdateSchema(todoTable)
.omit(generatedFieldKeys)
.refine((data) => Object.keys(data).length > 0, { message: 'At least one field is required' })
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())
+2 -2
View File
@@ -12,8 +12,8 @@ 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; every contract here is built from Zod/drizzle-zod,
// so the runtime objects are Zod issues. Rehydrate to reuse z.prettifyError / z.flattenError.
// 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', {
+72
View File
@@ -0,0 +1,72 @@
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,
})
})
+2 -2
View File
@@ -1,6 +1,6 @@
import { os } from '@/server/api/server'
import * as todo from './todo.router'
import * as battery from './battery.router'
export const router = os.router({
todo,
battery,
})
-39
View File
@@ -1,39 +0,0 @@
import { ORPCError } from '@orpc/server'
import { eq } from 'drizzle-orm'
import { os } from '@/server/api/server'
import { db } from '@/server/db'
import { todoTable } from '@/server/db/schema'
export const list = os.todo.list.handler(async () => {
return db.query.todoTable.findMany({
orderBy: (table, { desc }) => desc(table.createdAt),
})
})
export const create = os.todo.create.handler(async ({ input }) => {
const [newTodo] = await db.insert(todoTable).values(input).returning()
if (!newTodo) {
throw new ORPCError('INTERNAL_SERVER_ERROR', { message: 'Failed to create todo' })
}
return newTodo
})
export const update = os.todo.update.handler(async ({ input }) => {
const [updatedTodo] = await 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 = os.todo.remove.handler(async ({ input }) => {
const [deleted] = await db.delete(todoTable).where(eq(todoTable.id, input.id)).returning({ id: todoTable.id })
if (!deleted) {
throw new ORPCError('NOT_FOUND')
}
})
+332
View File
@@ -0,0 +1,332 @@
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)
}
-19
View File
@@ -1,19 +0,0 @@
import { sql } from 'drizzle-orm'
import { timestamp, uuid } from 'drizzle-orm/pg-core'
export const generatedFields = {
id: uuid('id').primaryKey().default(sql`uuidv7()`),
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
updatedAt: timestamp('updated_at', { withTimezone: true })
.notNull()
.defaultNow()
.$onUpdateFn(() => new Date()),
}
type GeneratedFieldKey = keyof typeof generatedFields
export const generatedFieldKeys = {
id: true,
createdAt: true,
updatedAt: true,
} satisfies Record<GeneratedFieldKey, true>
-11
View File
@@ -1,11 +0,0 @@
import { DrizzleLogger } from '@logtape/drizzle-orm'
import { drizzle } from 'drizzle-orm/postgres-js'
import { env } from '@/env'
import * as schema from '@/server/db/schema'
import { getLogger } from '@/server/logger'
export const db = drizzle({
connection: env.DATABASE_URL,
schema,
logger: env.LOG_DB ? new DrizzleLogger(getLogger(['db']), 'info') : false,
})
-8
View File
@@ -1,8 +0,0 @@
// AUTO-GENERATED by `bun run db:embed`. Do not edit.
import sql_0 from '#drizzle/0000_loving_thunderbird.sql' with { type: 'text' }
export type EmbeddedMigration = { tag: string; sql: string; when: number; breakpoints: boolean }
export const embeddedMigrations: readonly EmbeddedMigration[] = [
{ tag: '0000_loving_thunderbird', sql: sql_0, when: 1777096386609, breakpoints: true },
]
-1
View File
@@ -1 +0,0 @@
export * from './todo'
-8
View File
@@ -1,8 +0,0 @@
import { boolean, pgTable, text } from 'drizzle-orm/pg-core'
import { generatedFields } from '../fields'
export const todoTable = pgTable('todo', {
...generatedFields,
title: text('title').notNull(),
completed: boolean('completed').notNull().default(false),
})
-4
View File
@@ -1,4 +0,0 @@
declare module '*.sql' {
const content: string
export default content
}
+3 -3
View File
@@ -1,4 +1,4 @@
import { db } from '@/server/db'
import { closeBatteryPool } from '@/server/battery/mysql'
import { getLogger } from '@/server/logger'
export default () => {
@@ -17,8 +17,8 @@ export default () => {
await Bun.sleep(500)
try {
await db.$client.end()
logger.info('DB pool closed, exiting')
await closeBatteryPool()
logger.info('Battery MySQL pool closed, exiting')
} catch (error) {
logger.error('DB pool close failed during shutdown', { error })
}
+97
View File
@@ -0,0 +1,97 @@
import { beforeAll, describe, expect, test } from 'bun:test'
import type { BatteryInfo } from '@/domain/battery'
import { MYSQL_BOOLEAN, POWER_STATUS, toBatteryInfo } from '@/domain/battery'
import type { normalizePrediction as normalizePredictionType } from './client'
type PredictionClientModule = typeof import('./client')
const battery = toBatteryInfo({
id: 10,
userId: 7,
mac: 'RING-A03',
devModel: '2401-A',
devName: 'RING-A03',
isLowPower: MYSQL_BOOLEAN.FALSE,
powerStatus: POWER_STATUS.FULL,
power: 94,
createTime: '2026-05-10 23:00:00',
remark: null,
})
const predictionResponse = {
battery_id: 10,
mac: 'RING-A03',
now_soh: 91,
month_soh: 89,
trmonth_soh: 84,
risk_score: null,
risk_level: null,
status: null,
model_name: 'xgboost',
cycles_used: 6,
updated_at: '2026-05-11T00:00:00.000Z',
}
let createPredictionRequest: PredictionClientModule['createPredictionRequest']
let isPredictionForBattery: PredictionClientModule['isPredictionForBattery']
let normalizePrediction: typeof normalizePredictionType
beforeAll(async () => {
process.env.DATABASE_URL = 'mysql://user:password@localhost:3306/database'
process.env.SOH_PREDICTION_API_BASE_URL = 'http://127.0.0.1:8000'
const client = await import('./client')
createPredictionRequest = client.createPredictionRequest
isPredictionForBattery = client.isPredictionForBattery
normalizePrediction = client.normalizePrediction
})
describe('prediction client helpers', () => {
test('normalizes prediction response shape without fake fallback values', () => {
const prediction = normalizePrediction(predictionResponse)
expect(prediction).toEqual({
batteryId: 10,
mac: 'RING-A03',
nowSoh: 91,
monthSoh: 89,
trmonthSoh: 84,
riskScore: null,
riskLevel: null,
status: null,
modelName: 'xgboost',
cyclesUsed: 6,
updatedAt: '2026-05-11T00:00:00.000Z',
})
})
test('requires prediction responses to belong to the requested battery', () => {
expect(isPredictionForBattery(normalizePrediction(predictionResponse), battery)).toBe(true)
expect(isPredictionForBattery({ batteryId: 11, mac: battery.mac }, battery as BatteryInfo)).toBe(false)
expect(isPredictionForBattery({ batteryId: battery.id, mac: 'RING-B11' }, battery as BatteryInfo)).toBe(false)
})
test('returns null for history-insufficient prediction requests', () => {
expect(createPredictionRequest(battery, [battery, battery, battery, battery])).toBeNull()
})
test('creates minimal cycle payload accepted by prediction service', () => {
const request = createPredictionRequest(battery, [battery, battery, battery, battery, battery])
const firstHistory = request?.history[0]
expect(request?.battery).toMatchObject({
id: battery.id,
user_id: battery.userId,
mac: battery.mac,
power: battery.power,
})
expect(firstHistory).toEqual({
cycle: 1,
charge_capacity_ah: 3.01,
discharge_capacity_ah: 2.89,
timestamp: battery.createTime,
})
expect(Object.hasOwn(firstHistory ?? {}, 'charge_energy_wh')).toBe(false)
expect(Object.hasOwn(firstHistory ?? {}, 'coulombic_efficiency_pct')).toBe(false)
})
})
+225
View File
@@ -0,0 +1,225 @@
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()
}
+18
View File
@@ -1 +1,19 @@
@import "tailwindcss";
:root {
color-scheme: dark;
background: #09090b;
}
html {
background: #09090b;
}
body {
min-width: 320px;
margin: 0;
background:
radial-gradient(circle at top, rgba(20, 184, 166, 0.08), transparent 34rem),
linear-gradient(180deg, #09090b 0%, #0b0f12 100%);
color: #f4f4f5;
}