Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 92d033f053 | |||
| bf96aef624 | |||
| ebf4308ec7 | |||
| 5d6fef71e3 | |||
| a580422100 | |||
| 515a118dba | |||
| 87e7a3aeb3 | |||
| 15f672e10d |
+3
-3
@@ -1,6 +1,6 @@
|
|||||||
# role-user Agent Skills
|
# role-user Agent Skills
|
||||||
|
|
||||||
本目录存放 `role-user` 的项目级 Agent skill。规则参考 SeaCloud 项目的 agent skill 组织方式,并按当前员工端 Next.js、TypeScript、移动端工作台场景保留最小必要规范。
|
本目录存放 `role-user` 的项目级 Agent skill。规则参考 SeaCloud 项目的 agent skill 组织方式,并按当前数字人 H5 的 Next.js、TypeScript 和移动端场景保留最小必要规范。
|
||||||
|
|
||||||
## 使用入口
|
## 使用入口
|
||||||
|
|
||||||
@@ -11,9 +11,9 @@
|
|||||||
|
|
||||||
## 当前项目事实
|
## 当前项目事实
|
||||||
|
|
||||||
- 应用类型:员工端 C 端移动优先工作台。
|
- 应用类型:个人数字人 C 端 H5,移动优先。
|
||||||
- 技术栈:Next.js App Router、React、TypeScript。
|
- 技术栈:Next.js App Router、React、TypeScript。
|
||||||
- 关键边界:BFF Route Handlers 负责会话与后端转发,前端不持久化 JWT 或明文密码。
|
- 关键边界:BFF Route Handlers 负责会话与后端转发,Firebase Google 登录换取 HttpOnly 会话。
|
||||||
|
|
||||||
## Skill 索引
|
## Skill 索引
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -1,4 +1,4 @@
|
|||||||
ACCESS_MANAGE_API_BASE_URL=http://localhost:3500/api
|
ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:13501/api
|
||||||
ROLE_USER_SESSION_COOKIE=role_user_session_local
|
ROLE_USER_SESSION_COOKIE=role_user_session_local
|
||||||
APP_ENV=local
|
APP_ENV=local
|
||||||
APP_ENV_LABEL=本地环境
|
APP_ENV_LABEL=本地环境
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
# role-user
|
# personal-digital-human-web
|
||||||
|
|
||||||
星港 H5/Web 数字人空间,基于现有 `access-manage` 后端和 `role-admin` 管理后台改造。
|
个人数字人 H5/Web,基于现有 `access-manage` 后端和 `role-admin` 管理后台改造。
|
||||||
|
|
||||||
采用 React + Next.js App Router + TypeScript,移动优先并适配桌面,保留原工作台兼容路由。
|
采用 React + Next.js App Router + TypeScript,移动优先并适配桌面。
|
||||||
|
|
||||||
## 启动
|
## 启动
|
||||||
|
|
||||||
@@ -12,21 +12,12 @@ cp .env.example .env.local
|
|||||||
pnpm dev
|
pnpm dev
|
||||||
```
|
```
|
||||||
|
|
||||||
默认访问:
|
默认访问 http://localhost:3210/login,登录后进入数字人空间。
|
||||||
|
|
||||||
- 登录页:http://localhost:3210/login
|
|
||||||
- 数字人空间:http://localhost:3210/discover
|
|
||||||
- 原工作台兼容入口:http://localhost:3210/dashboard
|
|
||||||
- 任务:http://localhost:3210/tasks
|
|
||||||
- 排班:http://localhost:3210/schedule
|
|
||||||
- 公告:http://localhost:3210/announcements
|
|
||||||
- 门店:http://localhost:3210/store
|
|
||||||
- 我的:http://localhost:3210/me
|
|
||||||
|
|
||||||
## 环境变量
|
## 环境变量
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
ACCESS_MANAGE_API_BASE_URL=http://localhost:3500/api
|
ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:13501/api
|
||||||
ROLE_USER_SESSION_COOKIE=role_user_session_local
|
ROLE_USER_SESSION_COOKIE=role_user_session_local
|
||||||
APP_ENV=local
|
APP_ENV=local
|
||||||
APP_ENV_LABEL=本地环境
|
APP_ENV_LABEL=本地环境
|
||||||
@@ -34,7 +25,9 @@ PORT=3210
|
|||||||
HOSTNAME=0.0.0.0
|
HOSTNAME=0.0.0.0
|
||||||
```
|
```
|
||||||
|
|
||||||
`ACCESS_MANAGE_API_BASE_URL` 指向 `access-manage` 服务端 API 根路径。数字人登录调用后端 `POST /api/auth/digital/login`,仅接受后台开通的独立 C 端账号,登录成功后只把 JWT 写入 Next.js 服务端 HttpOnly Cookie,不写入 `localStorage`。
|
`ACCESS_MANAGE_API_BASE_URL` 指向 `access-manage` 服务端 API 根路径。本地前端可用 SSH 转发连接远程测试后端,例如 `ssh -N -L 127.0.0.1:13501:127.0.0.1:3501 <测试服务器>`。
|
||||||
|
|
||||||
|
Google 登录从 `src/lib/firebase-google.ts` 取得 Firebase ID token,经 `src/app/api/auth/firebase/route.ts` 交给 `access-manage` 的 `POST /api/auth/digital/firebase`。Web 使用独立命名的 HttpOnly Cookie,Firebase 凭据仅在兑换期间保留于内存。测试后端需应用迁移 021 并配置 `FIREBASE_PROJECT_ID=personal-digital-human`,Firebase 授权域名需包含本地使用的 `localhost` 和实际 Web 部署域名。
|
||||||
|
|
||||||
环境标识按 `APP_ENV` 区分:
|
环境标识按 `APP_ENV` 区分:
|
||||||
|
|
||||||
@@ -57,68 +50,12 @@ pnpm start:develop
|
|||||||
pnpm start:prod
|
pnpm start:prod
|
||||||
```
|
```
|
||||||
|
|
||||||
## 当前实现范围
|
## 页面与接口
|
||||||
|
|
||||||
- Next.js App Router 项目结构、TypeScript、ESLint、`@/*` 路径别名和基础样式。
|
- `/login` 提供 Google 登录,成功后恢复数字人站内深链。
|
||||||
- BFF Route Handlers:
|
- `/discover`、`/chats`、`/library` 和 `/profile` 提供数字人业务页面。
|
||||||
- `POST /api/auth/login`
|
- BFF 使用 `POST /api/auth/firebase` 建立会话,使用 `/api/auth/logout` 退出,通过 `/api/digital/*` 转发数字人业务请求。
|
||||||
- `POST|GET /api/auth/logout`
|
- `access-manage` 提供业务 API,`role-admin` 提供管理后台。
|
||||||
- `GET /api/auth/me`
|
|
||||||
- `PATCH /api/auth/me/password`
|
|
||||||
- `GET /api/permissions/me`
|
|
||||||
- `GET /api/mobile/tasks`
|
|
||||||
- `GET /api/mobile/tasks/:id`
|
|
||||||
- `POST /api/mobile/tasks/:id/start`
|
|
||||||
- `POST /api/mobile/tasks/:id/complete`
|
|
||||||
- `POST /api/mobile/tasks/:id/comment`
|
|
||||||
- `GET /api/mobile/announcements`
|
|
||||||
- `GET /api/mobile/announcements/:id`
|
|
||||||
- `POST /api/mobile/announcements/:id/read`
|
|
||||||
- `GET /api/mobile/shifts`
|
|
||||||
- `GET /api/mobile/shifts/today`
|
|
||||||
- `GET /api/mobile/store`
|
|
||||||
- `GET /api/mobile/store/employees`
|
|
||||||
- 页面:
|
|
||||||
- `/login`
|
|
||||||
- `/dashboard`
|
|
||||||
- `/tasks`
|
|
||||||
- `/tasks/:id`
|
|
||||||
- `/schedule`
|
|
||||||
- `/announcements`
|
|
||||||
- `/announcements/:id`
|
|
||||||
- `/store`
|
|
||||||
- `/me`
|
|
||||||
- 首页已消费正式 `mobile/bootstrap` 的 `latestAnnouncements`、`tasks`、`overdueTaskCount`、`todayShift/todayShifts`。
|
|
||||||
- `/announcements` 支持全部、未读、已读筛选;公告详情进入后通过 BFF 标记已读。
|
|
||||||
- `/tasks` 支持全部、待处理、处理中、已完成筛选;任务详情支持开始、完成和追加备注。
|
|
||||||
- `/schedule` 支持今日、未来、全部排班筛选。
|
|
||||||
- `/me` 已接入本人修改密码表单,前端不持久化密码或 token。
|
|
||||||
- `/dashboard`、`/tasks`、`/announcements`、`/schedule` 会在后端临时不可用或 5xx 时保持基础资料和业务空态。
|
|
||||||
- `/store` 会尝试读取当前门店详情和本店员工列表;后端权限或接口不可用时保持门店基础信息和空态。
|
|
||||||
- 移动端底部导航、加载态、空态、会话缺失跳登录、401 清理 Cookie 的服务端路径。
|
|
||||||
- PWA manifest、应用图标、基础 service worker、安全响应头和参照 SeaCloud 的移动端工作台视觉系统。
|
|
||||||
|
|
||||||
## 文档
|
|
||||||
|
|
||||||
- `.agents/README.md`: 本项目 Agent skill 索引和使用入口。
|
|
||||||
- `.agents/skills/chinese-commit-message/SKILL.md`: 中文提交信息规范。
|
|
||||||
- `.agents/skills/header-comment-sync/SKILL.md`: 中文文件头和注释同步规范。
|
|
||||||
- `docs/C_EMPLOYEE_APP_REQUIREMENTS.md`: C 端员工工作台需求文档。
|
|
||||||
- `docs/FULLSTACK_BACKEND_GAP_ANALYSIS.md`: C 端员工工作台三端缺口与改动范围分析。
|
|
||||||
- `AGENTS.md`: Codex/Agent 入口规则,转到 `RTK.md` 并登记本地 skill。
|
|
||||||
- `RTK.md`: 本项目 Codex/Agent 协作规则。
|
|
||||||
|
|
||||||
## 关联项目
|
|
||||||
|
|
||||||
- `/Users/mac033/Desktop/my-project/access-manage`: 服务端 API。
|
|
||||||
- `/Users/mac033/Desktop/my-project/role-admin`: 管理后台。
|
|
||||||
|
|
||||||
## 安全边界
|
|
||||||
|
|
||||||
- 不展示任何明文密码。
|
|
||||||
- 不把密码、JWT 或权限 token 持久化到前端存储。
|
|
||||||
- 员工端修改密码已通过 BFF 接入后端 `PATCH /api/auth/me/password`。
|
|
||||||
- 公告、任务、排班已按正式后端接口接入列表、筛选、详情和员工端操作;后端临时不可用时页面保留业务空态。
|
|
||||||
|
|
||||||
## 数字人空间
|
## 数字人空间
|
||||||
|
|
||||||
@@ -156,13 +93,13 @@ NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成
|
|||||||
|
|
||||||
### 独立 C 端登录
|
### 独立 C 端登录
|
||||||
|
|
||||||
前台通过 `/api/auth/digital/login` 使用独立 C 端账号,由后台「用户管理」开通;不再使用管理员/员工身份。已有数字人业务账号由迁移复制密码哈希并保留会话,之后两套账号密码和状态独立。登录令牌保存在 HttpOnly Cookie,密码重置/账号停用会撤销旧登录状态。
|
H5 仅支持 Google 登录,按 Firebase 项目与 UID 识别数字人账号。旧会话失效后需重新登录。历史账号及聊天记录保留在后端,首次 Google 登录按 UID 建立账号。
|
||||||
|
|
||||||
对话设置的世界书与叙事风格使用平面列表;选中只保留轻底色和一个勾选标记,键盘焦点仍显示明确轮廓。
|
对话设置的世界书与叙事风格使用平面列表;选中只保留轻底色和一个勾选标记,键盘焦点仍显示明确轮廓。
|
||||||
|
|
||||||
### NSFW 账号偏好
|
### NSFW 账号偏好
|
||||||
|
|
||||||
「我的」提供 NSFW 成人内容开关,登录账号未保存偏好时默认开启,已保存的关闭选择继续保留。保存后对已有及新会话的后续回复生效,包括发送、继续、重生成与回复灵感;游客仍须先登录。偏好由 `access-manage` 保存在本人资料中,前台不使用本地存储伪造保存结果。前后端需配套发布。
|
「我的」提供 NSFW 成人内容开关,登录账号未保存偏好时默认开启,已保存的关闭选择继续保留。保存后对已有及新会话的后续回复生效,包括发送、继续、重生成与回复灵感。偏好由 `access-manage` 保存在本人资料中,前台不使用本地存储伪造保存结果。前后端需配套发布。
|
||||||
|
|
||||||
### 对白与叙述排版
|
### 对白与叙述排版
|
||||||
|
|
||||||
@@ -186,7 +123,7 @@ NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成
|
|||||||
| `/library/:id` | 世界书或风格详情 |
|
| `/library/:id` | 世界书或风格详情 |
|
||||||
| `/profile` | 数字人个人身份与内容偏好 |
|
| `/profile` | 数字人个人身份与内容偏好 |
|
||||||
|
|
||||||
页面入口位于 `src/app/(digital)/`,共享布局追踪站内历史。`src/components/digital-page.tsx` 并行加载私有首屏,`src/lib/digital-routes.ts` 集中维护资源地址和登录回跳边界。原工作台 `/me` 保持兼容。
|
页面入口位于 `src/app/(digital)/`,共享布局追踪站内历史。`src/components/digital-page.tsx` 并行加载私有首屏,`src/lib/digital-routes.ts` 集中维护资源地址和登录回跳边界。
|
||||||
|
|
||||||
导航和详情使用真实链接,浏览器后退/前进还原实际上一页;页面内返回优先使用已有站内历史,从新标签页或外站直接打开时回到对应列表。搜索筛选替换当前历史条目,不为每次输入增加返回步骤。删除当前聊天后替换为列表地址,旧链接显示资源不存在。
|
导航和详情使用真实链接,浏览器后退/前进还原实际上一页;页面内返回优先使用已有站内历史,从新标签页或外站直接打开时回到对应列表。搜索筛选替换当前历史条目,不为每次输入增加返回步骤。删除当前聊天后替换为列表地址,旧链接显示资源不存在。
|
||||||
|
|
||||||
@@ -195,3 +132,28 @@ NPC 尚未出字就停止或失败时,“继续”仍可接续此前已完成
|
|||||||
路由与深链回归:`node --experimental-strip-types --test tests/*.test.mjs`;类型检查和构建按上面的项目命令执行。
|
路由与深链回归:`node --experimental-strip-types --test tests/*.test.mjs`;类型检查和构建按上面的项目命令执行。
|
||||||
|
|
||||||
`pnpm typecheck` 会先清理生产路由类型目录 `.next/types` 并执行 `next typegen`,再运行 TypeScript。这样 CI 在迁移页面目录或新增路由后不会复用上一版的路由声明;不清理整个构建产物目录。
|
`pnpm typecheck` 会先清理生产路由类型目录 `.next/types` 并执行 `next typegen`,再运行 TypeScript。这样 CI 在迁移页面目录或新增路由后不会复用上一版的路由声明;不清理整个构建产物目录。
|
||||||
|
|
||||||
|
## 聊天体验与会话管理
|
||||||
|
|
||||||
|
- `src/components/conversation-list.tsx` 提供服务端历史标题/消息搜索、置顶与重命名;`conversation-dialogs.tsx` 统一命名和分支确认的居中表单。
|
||||||
|
- 前台删除可在 30 秒内撤销,后台可恢复历史删除。分支保存名称、父会话和消息锚点,可跳回原故事。
|
||||||
|
- `use-chat-reading.ts` 按会话保存本标签页的消息锚点和偏移;上翻时新回复只提示,点击后才回到底部。
|
||||||
|
- `src/lib/digital-stream.ts` 必须收到 SSE done 才确认结束,异常断流保留部分内容。发送前保存请求标识,重试复用同一标识;刷新先对照服务端记录,避免重复发送。
|
||||||
|
- 发现页区分最近聊天、收藏和新角色;详情可展开备用开场全文。账号身份为新会话默认值,当前会话设定仅影响自己的后续回复,NSFW 是账号范围。
|
||||||
|
|
||||||
|
以上管理功能需要配套后端 `019_conversation_management.sql` 迁移及接口;不要只发布前台。
|
||||||
|
|
||||||
|
## C端增长体验
|
||||||
|
|
||||||
|
需配套后端迁移 `020_digital_growth.sql` 和 `021_digital_firebase_identity.sql`。同源校验位于 `src/lib/auth-origin.ts`,`src/lib/auth-input.ts` 将登录请求体限制为 8 KB。
|
||||||
|
|
||||||
|
- `growth-journey.tsx`:读取站内运营卡片后上报本次访问,实际可见时才确认曝光,不向外部渠道发消息。
|
||||||
|
- `growth-recommendations.tsx`:展示服务端推荐及原因、支持跳过,推荐回执随独立详情路由承接,避免普通入口误用旧推荐来源。
|
||||||
|
- `growth-profile.tsx`:选择最多12个兴趣、查看真实剩余额度,明确开启或关闭自动记忆。会员权益由后台授予,前台没有虚构购买或支付成功状态。
|
||||||
|
- `growth-chat.tsx`:故事内查看/更正/移除记忆、手动添加背景,提供回答点赞与原因反馈;评价按具体回复保存。
|
||||||
|
- `growth-analytics.ts`:事件队列按账号隔离,最多200条,单批20条,保留UUID重试,过期事件不补报;仅上报事件和资源ID,不采集正文、密码或设备指纹。
|
||||||
|
- `growth.ts`:个人权益协议、反馈合并读取与推荐来源工具,避免每条消息各发一条评价查询。
|
||||||
|
|
||||||
|
自动记忆是用户明确事实提取和历史原文摘录,不是额外调用模型生成的智能总结。删除的同一来源不会被后台任务重新加入。每日次数与字符预算分别展示和计算,字符数不是供应商Token账单;空失败释放次数,部分回复计次,灵感也消耗一次。推荐实验与现有UI实验独立;前端不自行决定分组、发放权益或计算扣减结果。
|
||||||
|
|
||||||
|
验证新增 `tests/growth-analytics.test.mjs`,覆盖账号切换、UUID重试、批次上限、请求期间新事件保留及反向代理同源校验。真机、真实数据库并发和支付验收不能被这些测试替代。
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
# role-user Project Notes
|
# role-user Project Notes
|
||||||
|
|
||||||
This project is the employee-facing C-side app for the `access-manage` backend and the `role-admin` management console.
|
This project is the personal digital human H5 for the `access-manage` backend and the `role-admin` management console.
|
||||||
|
|
||||||
When working in this repository:
|
When working in this repository:
|
||||||
|
|
||||||
- Prefer Chinese for project notes, PRDs, comments, and delivery summaries.
|
- Prefer Chinese for project notes, PRDs, comments, and delivery summaries.
|
||||||
- Use React + Next.js App Router + TypeScript as the default frontend stack.
|
- Use React + Next.js App Router + TypeScript as the default frontend stack.
|
||||||
- Keep the app mobile-first and PWA-friendly; desktop should work, but the primary user is a store employee using a phone.
|
- Keep the app mobile-first and PWA-friendly; desktop should work, but the primary user accesses the digital human app on a phone.
|
||||||
- Treat `access-manage/docs/ROLE_USER_BACKEND_REQUIREMENTS.md` as the backend contract source and `docs/C_EMPLOYEE_APP_REQUIREMENTS.md` as the frontend product source.
|
- Use Firebase Google sign-in for digital human identity.
|
||||||
- Do not store or expose plaintext passwords in the frontend. Password operations must use reset/change flows, temporary one-time passwords, and audit logs.
|
|
||||||
- Use a Backend-for-Frontend layer in Next.js Route Handlers when it improves session safety. Prefer HttpOnly cookies over localStorage for tokens.
|
- Use a Backend-for-Frontend layer in Next.js Route Handlers when it improves session safety. Prefer HttpOnly cookies over localStorage for tokens.
|
||||||
- Keep business API types and request helpers centralized under `src/lib/` once the app is scaffolded.
|
- Keep business API types and request helpers centralized under `src/lib/` once the app is scaffolded.
|
||||||
- When files or directories are added, removed, renamed, or reorganized, update `README.md` in the same change once a README exists.
|
- When files or directories are added, removed, renamed, or reorganized, update `README.md` in the same change once a README exists.
|
||||||
|
|||||||
+3
-2
@@ -1,9 +1,9 @@
|
|||||||
{
|
{
|
||||||
"name": "role-user",
|
"name": "personal-digital-human-web",
|
||||||
"version": "0.1.0",
|
"version": "0.1.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "APP_ENV=local APP_ENV_LABEL=本地环境 ACCESS_MANAGE_API_BASE_URL=http://localhost:3500/api ROLE_USER_SESSION_COOKIE=role_user_session_local next dev -p 3210",
|
"dev": "APP_ENV=local APP_ENV_LABEL=本地环境 ROLE_USER_SESSION_COOKIE=role_user_session_local next dev -p 3210",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"build:develop": "APP_ENV=develop APP_ENV_LABEL=测试环境 ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3501/api ROLE_USER_SESSION_COOKIE=role_user_session_develop next build",
|
"build:develop": "APP_ENV=develop APP_ENV_LABEL=测试环境 ACCESS_MANAGE_API_BASE_URL=http://127.0.0.1:3501/api ROLE_USER_SESSION_COOKIE=role_user_session_develop next build",
|
||||||
"build:test": "pnpm build:develop",
|
"build:test": "pnpm build:develop",
|
||||||
@@ -15,6 +15,7 @@
|
|||||||
"typecheck": "node -e \"require('node:fs').rmSync('.next/types', { recursive: true, force: true })\" && next typegen && tsc --noEmit --incremental false"
|
"typecheck": "node -e \"require('node:fs').rmSync('.next/types', { recursive: true, force: true })\" && next typegen && tsc --noEmit --incremental false"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
|
"firebase": "^13.3.0",
|
||||||
"lucide-react": "^0.511.0",
|
"lucide-react": "^0.511.0",
|
||||||
"next": "latest",
|
"next": "latest",
|
||||||
"react": "latest",
|
"react": "latest",
|
||||||
|
|||||||
Generated
+1278
-5
File diff suppressed because it is too large
Load Diff
@@ -1,68 +0,0 @@
|
|||||||
import Link from "next/link";
|
|
||||||
import { notFound } from "next/navigation";
|
|
||||||
import { ArrowLeft, Bell } from "lucide-react";
|
|
||||||
|
|
||||||
import { AnnouncementReadMarker } from "@/components/announcement-read-marker";
|
|
||||||
import { PageHeader } from "@/components/page-header";
|
|
||||||
import { StatusPill } from "@/components/status-pill";
|
|
||||||
import { BackendError } from "@/lib/backend";
|
|
||||||
import { formatDateTime } from "@/lib/format";
|
|
||||||
import { getAnnouncementDetail } from "@/lib/mobile-data";
|
|
||||||
import type { AnnouncementSummary } from "@/lib/types";
|
|
||||||
|
|
||||||
type AnnouncementDetailPageProps = {
|
|
||||||
params: Promise<{ id: string }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const levelText: Record<AnnouncementSummary["level"], string> = {
|
|
||||||
normal: "普通",
|
|
||||||
important: "重要",
|
|
||||||
urgent: "紧急"
|
|
||||||
};
|
|
||||||
|
|
||||||
const levelTone: Record<AnnouncementSummary["level"], "default" | "warning" | "danger"> = {
|
|
||||||
normal: "default",
|
|
||||||
important: "warning",
|
|
||||||
urgent: "danger"
|
|
||||||
};
|
|
||||||
|
|
||||||
export default async function AnnouncementDetailPage({ params }: AnnouncementDetailPageProps) {
|
|
||||||
const { id } = await params;
|
|
||||||
let announcement: Awaited<ReturnType<typeof getAnnouncementDetail>>;
|
|
||||||
|
|
||||||
try {
|
|
||||||
announcement = await getAnnouncementDetail(id);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof BackendError && error.status === 404) {
|
|
||||||
notFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="page-stack">
|
|
||||||
<Link className="inline-link" href="/announcements">
|
|
||||||
<ArrowLeft aria-hidden size={16} />
|
|
||||||
返回公告
|
|
||||||
</Link>
|
|
||||||
<PageHeader
|
|
||||||
eyebrow={formatDateTime(announcement.publishedAt)}
|
|
||||||
title={announcement.title}
|
|
||||||
description={announcement.summary}
|
|
||||||
/>
|
|
||||||
<AnnouncementReadMarker id={announcement.id} read={announcement.read} />
|
|
||||||
<section className="detail-card">
|
|
||||||
<div className="detail-meta">
|
|
||||||
<span>
|
|
||||||
<Bell aria-hidden size={16} />
|
|
||||||
公告级别
|
|
||||||
</span>
|
|
||||||
<StatusPill tone={levelTone[announcement.level]}>{levelText[announcement.level]}</StatusPill>
|
|
||||||
<StatusPill tone={announcement.read ? "default" : "warning"}>{announcement.read ? "已读" : "未读"}</StatusPill>
|
|
||||||
</div>
|
|
||||||
<article className="long-copy">{announcement.content}</article>
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,92 +0,0 @@
|
|||||||
import Link from "next/link";
|
|
||||||
import type { Route } from "next";
|
|
||||||
|
|
||||||
import { EmptyState } from "@/components/empty-state";
|
|
||||||
import { FilterNav } from "@/components/filter-nav";
|
|
||||||
import { PageHeader } from "@/components/page-header";
|
|
||||||
import { StatusPill } from "@/components/status-pill";
|
|
||||||
import { formatDateTime } from "@/lib/format";
|
|
||||||
import { getAnnouncements } from "@/lib/mobile-data";
|
|
||||||
|
|
||||||
type AnnouncementFilter = "all" | "unread" | "read";
|
|
||||||
|
|
||||||
type AnnouncementsPageProps = {
|
|
||||||
searchParams: Promise<{ read?: string | string[] }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
function firstSearchValue(value: string | string[] | undefined) {
|
|
||||||
return Array.isArray(value) ? value[0] : value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeFilter(value: string | string[] | undefined): AnnouncementFilter {
|
|
||||||
const read = firstSearchValue(value);
|
|
||||||
if (read === "unread" || read === "read") return read;
|
|
||||||
return "all";
|
|
||||||
}
|
|
||||||
|
|
||||||
function emptyCopy(filter: AnnouncementFilter) {
|
|
||||||
if (filter === "unread") {
|
|
||||||
return {
|
|
||||||
title: "暂无未读公告",
|
|
||||||
description: "当前没有需要你阅读的新公告。"
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
if (filter === "read") {
|
|
||||||
return {
|
|
||||||
title: "暂无已读公告",
|
|
||||||
description: "你阅读过的公告会保留在这里,方便回看。"
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
title: "暂无公告",
|
|
||||||
description: "当前没有面向你的门店公告。"
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function AnnouncementsPage({ searchParams }: AnnouncementsPageProps) {
|
|
||||||
const filter = normalizeFilter((await searchParams).read);
|
|
||||||
const allAnnouncements = await getAnnouncements();
|
|
||||||
const announcements = allAnnouncements.filter((item) => {
|
|
||||||
if (filter === "unread") return !item.read;
|
|
||||||
if (filter === "read") return item.read;
|
|
||||||
return true;
|
|
||||||
});
|
|
||||||
const empty = emptyCopy(filter);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="page-stack">
|
|
||||||
<PageHeader title="公告" description="接收管理员或店长发布给你的门店通知。" />
|
|
||||||
<FilterNav
|
|
||||||
label="公告筛选"
|
|
||||||
options={[
|
|
||||||
{ label: "全部", href: "/announcements" as Route, active: filter === "all" },
|
|
||||||
{ label: "未读", href: "/announcements?read=unread" as Route, active: filter === "unread" },
|
|
||||||
{ label: "已读", href: "/announcements?read=read" as Route, active: filter === "read" }
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
{announcements.length > 0 ? (
|
|
||||||
<section className="list-stack">
|
|
||||||
{announcements.map((item) => {
|
|
||||||
const href = `/announcements/${item.id}` as Route;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link className="list-card" href={href} key={item.id}>
|
|
||||||
<div>
|
|
||||||
<h2>{item.title}</h2>
|
|
||||||
<p>{item.summary || formatDateTime(item.publishedAt)}</p>
|
|
||||||
</div>
|
|
||||||
<StatusPill tone={item.level === "normal" ? "default" : "warning"}>
|
|
||||||
{item.read ? "已读" : "未读"}
|
|
||||||
</StatusPill>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</section>
|
|
||||||
) : (
|
|
||||||
<EmptyState title={empty.title} description={empty.description} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,168 +0,0 @@
|
|||||||
import Link from "next/link";
|
|
||||||
import type { Route } from "next";
|
|
||||||
import { Bell, CalendarDays, ChevronRight, ClipboardList } from "lucide-react";
|
|
||||||
|
|
||||||
import { EmptyState } from "@/components/empty-state";
|
|
||||||
import { StatusPill } from "@/components/status-pill";
|
|
||||||
import { formatDateTime, roleNames } from "@/lib/format";
|
|
||||||
import { getBootstrapData } from "@/lib/mobile-data";
|
|
||||||
import type { TaskStatus } from "@/lib/types";
|
|
||||||
|
|
||||||
const taskStatusText: Record<TaskStatus, string> = {
|
|
||||||
pending: "待处理",
|
|
||||||
in_progress: "处理中",
|
|
||||||
completed: "已完成",
|
|
||||||
cancelled: "已取消"
|
|
||||||
};
|
|
||||||
|
|
||||||
const taskStatusTone: Record<TaskStatus, "default" | "success" | "warning" | "danger"> = {
|
|
||||||
pending: "default",
|
|
||||||
in_progress: "warning",
|
|
||||||
completed: "success",
|
|
||||||
cancelled: "danger"
|
|
||||||
};
|
|
||||||
|
|
||||||
export default async function DashboardPage() {
|
|
||||||
const data = await getBootstrapData();
|
|
||||||
const { user } = data;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="page-stack">
|
|
||||||
<section className="dashboard-hero">
|
|
||||||
<div className="dashboard-hero__content">
|
|
||||||
<p className="hero-kicker">{user.storeName || "员工端"}</p>
|
|
||||||
<h1>你好,{user.displayName}</h1>
|
|
||||||
<p>今日工作状态已同步,先处理最重要的事项。</p>
|
|
||||||
</div>
|
|
||||||
<div className="hero-stat-strip" aria-label="今日概览">
|
|
||||||
<span>
|
|
||||||
<strong>{data.pendingTaskCount}</strong>
|
|
||||||
待办
|
|
||||||
</span>
|
|
||||||
<span>
|
|
||||||
<strong>{data.todayShifts.length}</strong>
|
|
||||||
班次
|
|
||||||
</span>
|
|
||||||
<span>
|
|
||||||
<strong>{data.unreadAnnouncementCount}</strong>
|
|
||||||
未读
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="identity-card">
|
|
||||||
<div className="identity-card__media">
|
|
||||||
<span className="avatar">{user.displayName.slice(0, 1)}</span>
|
|
||||||
</div>
|
|
||||||
<div className="identity-card__body">
|
|
||||||
<h2>{user.displayName}</h2>
|
|
||||||
<p>{user.storeName || "未绑定门店"}</p>
|
|
||||||
<div className="pill-row">
|
|
||||||
<StatusPill tone="success">账号正常</StatusPill>
|
|
||||||
<StatusPill>{roleNames(user.roles)}</StatusPill>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="metric-grid">
|
|
||||||
<Link className="metric-tile" href="/tasks">
|
|
||||||
<ClipboardList aria-hidden size={20} />
|
|
||||||
<span>{data.pendingTaskCount}</span>
|
|
||||||
<p>待办任务</p>
|
|
||||||
</Link>
|
|
||||||
<Link className="metric-tile" href="/tasks">
|
|
||||||
<Bell aria-hidden size={20} />
|
|
||||||
<span>{data.overdueTaskCount}</span>
|
|
||||||
<p>已逾期</p>
|
|
||||||
</Link>
|
|
||||||
<Link className="metric-tile" href="/announcements">
|
|
||||||
<Bell aria-hidden size={20} />
|
|
||||||
<span>{data.unreadAnnouncementCount}</span>
|
|
||||||
<p>未读公告</p>
|
|
||||||
</Link>
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="section-block">
|
|
||||||
<div className="section-title">
|
|
||||||
<h2>今日排班</h2>
|
|
||||||
<CalendarDays aria-hidden size={20} />
|
|
||||||
</div>
|
|
||||||
{data.todayShifts.length > 0 ? (
|
|
||||||
<div className="list-stack">
|
|
||||||
{data.todayShifts.map((shift) => (
|
|
||||||
<article className="list-card" key={shift.id}>
|
|
||||||
<div>
|
|
||||||
<h3>{shift.position}</h3>
|
|
||||||
<p>
|
|
||||||
{formatDateTime(shift.startAt)} - {formatDateTime(shift.endAt)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<StatusPill tone="success">已排班</StatusPill>
|
|
||||||
</article>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<EmptyState title="今日暂无排班" description="今天没有安排班次,可在排班页查看未来排班。" />
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="section-block">
|
|
||||||
<div className="section-title">
|
|
||||||
<h2>待办任务</h2>
|
|
||||||
<Link href="/tasks">
|
|
||||||
查看全部
|
|
||||||
<ChevronRight aria-hidden size={16} />
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
{data.tasks.length > 0 ? (
|
|
||||||
<div className="list-stack">
|
|
||||||
{data.tasks.map((task) => {
|
|
||||||
const href = `/tasks/${task.id}` as Route;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link className="list-card" href={href} key={task.id}>
|
|
||||||
<div>
|
|
||||||
<h3>{task.title}</h3>
|
|
||||||
<p>{task.description || `截止:${formatDateTime(task.dueAt)}`}</p>
|
|
||||||
</div>
|
|
||||||
<StatusPill tone={taskStatusTone[task.status]}>{taskStatusText[task.status]}</StatusPill>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<EmptyState title="暂无待办任务" description="待处理和处理中任务会显示在这里。" />
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
|
|
||||||
<section className="section-block">
|
|
||||||
<div className="section-title">
|
|
||||||
<h2>最新公告</h2>
|
|
||||||
<Link href="/announcements">
|
|
||||||
查看全部
|
|
||||||
<ChevronRight aria-hidden size={16} />
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
{data.latestAnnouncements.length > 0 ? (
|
|
||||||
<div className="list-stack">
|
|
||||||
{data.latestAnnouncements.map((item) => {
|
|
||||||
const href = `/announcements/${item.id}` as Route;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link className="list-card" href={href} key={item.id}>
|
|
||||||
<div>
|
|
||||||
<h3>{item.title}</h3>
|
|
||||||
<p>{item.summary || formatDateTime(item.publishedAt)}</p>
|
|
||||||
</div>
|
|
||||||
<StatusPill tone={item.read ? "default" : "warning"}>{item.read ? "已读" : "未读"}</StatusPill>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<EmptyState title="暂无公告" description="当前没有面向你的门店公告。" />
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
import { BottomNav } from "@/components/bottom-nav";
|
|
||||||
|
|
||||||
export default function AppLayout({ children }: Readonly<{ children: React.ReactNode }>) {
|
|
||||||
return (
|
|
||||||
<div className="app-shell">
|
|
||||||
<main className="app-main">{children}</main>
|
|
||||||
<BottomNav />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
export default function Loading() {
|
|
||||||
return (
|
|
||||||
<div className="page-stack">
|
|
||||||
<div className="skeleton skeleton-title" />
|
|
||||||
<div className="skeleton skeleton-card" />
|
|
||||||
<div className="skeleton skeleton-card" />
|
|
||||||
<div className="skeleton skeleton-card" />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,52 +0,0 @@
|
|||||||
import { KeyRound, ShieldCheck, UserRound } from "lucide-react";
|
|
||||||
|
|
||||||
import { LogoutButton } from "@/components/logout-button";
|
|
||||||
import { PageHeader } from "@/components/page-header";
|
|
||||||
import { PasswordChangeForm } from "@/components/password-change-form";
|
|
||||||
import { StatusPill } from "@/components/status-pill";
|
|
||||||
import { roleNames } from "@/lib/format";
|
|
||||||
import { getCurrentUser } from "@/lib/mobile-data";
|
|
||||||
|
|
||||||
export default async function MePage() {
|
|
||||||
const user = await getCurrentUser();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="page-stack">
|
|
||||||
<PageHeader title="我的" description="个人资料、账号安全和退出登录。" />
|
|
||||||
<section className="profile-card">
|
|
||||||
<span className="avatar large">{user.displayName.slice(0, 1)}</span>
|
|
||||||
<h2>{user.displayName}</h2>
|
|
||||||
<p>{user.username}</p>
|
|
||||||
<div className="pill-row">
|
|
||||||
<StatusPill tone="success">员工账号</StatusPill>
|
|
||||||
<StatusPill>{roleNames(user.roles)}</StatusPill>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
<section className="info-list">
|
|
||||||
<div>
|
|
||||||
<UserRound aria-hidden size={18} />
|
|
||||||
<span>所属门店</span>
|
|
||||||
<strong>{user.storeName || "未绑定门店"}</strong>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<ShieldCheck aria-hidden size={18} />
|
|
||||||
<span>权限数量</span>
|
|
||||||
<strong>{user.permissions.includes("*") ? "全部权限" : `${user.permissions.length} 项`}</strong>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<KeyRound aria-hidden size={18} />
|
|
||||||
<span>修改密码</span>
|
|
||||||
<strong>旧密码 + 新密码</strong>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
<section className="section-block">
|
|
||||||
<div className="section-title">
|
|
||||||
<h2>账号安全</h2>
|
|
||||||
</div>
|
|
||||||
<p className="muted-copy">本应用不展示明文密码,也不会在前端持久化 token 或密码。</p>
|
|
||||||
<PasswordChangeForm />
|
|
||||||
</section>
|
|
||||||
<LogoutButton />
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,87 +0,0 @@
|
|||||||
import { EmptyState } from "@/components/empty-state";
|
|
||||||
import { FilterNav } from "@/components/filter-nav";
|
|
||||||
import { PageHeader } from "@/components/page-header";
|
|
||||||
import { StatusPill } from "@/components/status-pill";
|
|
||||||
import { formatDateTime } from "@/lib/format";
|
|
||||||
import { getShifts } from "@/lib/mobile-data";
|
|
||||||
import type { Route } from "next";
|
|
||||||
|
|
||||||
type ScheduleRange = "today" | "upcoming" | "all";
|
|
||||||
|
|
||||||
type SchedulePageProps = {
|
|
||||||
searchParams: Promise<{ range?: string | string[] }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const statusText = {
|
|
||||||
scheduled: "已排班",
|
|
||||||
cancelled: "已取消",
|
|
||||||
completed: "已完成"
|
|
||||||
} as const;
|
|
||||||
|
|
||||||
function firstSearchValue(value: string | string[] | undefined) {
|
|
||||||
return Array.isArray(value) ? value[0] : value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function toDateString(date: Date) {
|
|
||||||
const year = date.getFullYear();
|
|
||||||
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
||||||
const day = String(date.getDate()).padStart(2, "0");
|
|
||||||
return `${year}-${month}-${day}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeRange(value: string | string[] | undefined): ScheduleRange {
|
|
||||||
const range = firstSearchValue(value);
|
|
||||||
if (range === "upcoming" || range === "all") return range;
|
|
||||||
return "today";
|
|
||||||
}
|
|
||||||
|
|
||||||
function rangeFilter(range: ScheduleRange) {
|
|
||||||
const today = toDateString(new Date());
|
|
||||||
if (range === "today") return { startDate: today, endDate: today };
|
|
||||||
if (range === "upcoming") return { startDate: today };
|
|
||||||
return {};
|
|
||||||
}
|
|
||||||
|
|
||||||
function emptyCopy(range: ScheduleRange) {
|
|
||||||
if (range === "today") return "今天没有安排班次。";
|
|
||||||
if (range === "upcoming") return "当前没有未来班次。";
|
|
||||||
return "当前没有你的排班记录。";
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function SchedulePage({ searchParams }: SchedulePageProps) {
|
|
||||||
const range = normalizeRange((await searchParams).range);
|
|
||||||
const shifts = await getShifts(rangeFilter(range));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="page-stack">
|
|
||||||
<PageHeader title="排班" description="查看本周和未来班次,第一版仅支持查看。" />
|
|
||||||
<FilterNav
|
|
||||||
label="排班筛选"
|
|
||||||
options={[
|
|
||||||
{ label: "今日", href: "/schedule" as Route, active: range === "today" },
|
|
||||||
{ label: "未来", href: "/schedule?range=upcoming" as Route, active: range === "upcoming" },
|
|
||||||
{ label: "全部", href: "/schedule?range=all" as Route, active: range === "all" }
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
{shifts.length > 0 ? (
|
|
||||||
<section className="list-stack">
|
|
||||||
{shifts.map((shift) => (
|
|
||||||
<article className="list-card" key={shift.id}>
|
|
||||||
<div>
|
|
||||||
<h2>{shift.position}</h2>
|
|
||||||
<p>
|
|
||||||
{formatDateTime(shift.startAt)} - {formatDateTime(shift.endAt)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<StatusPill tone={shift.status === "cancelled" ? "danger" : "success"}>
|
|
||||||
{statusText[shift.status]}
|
|
||||||
</StatusPill>
|
|
||||||
</article>
|
|
||||||
))}
|
|
||||||
</section>
|
|
||||||
) : (
|
|
||||||
<EmptyState title="暂无排班" description={emptyCopy(range)} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,71 +0,0 @@
|
|||||||
import { MapPin, Phone, Store } from "lucide-react";
|
|
||||||
|
|
||||||
import { EmptyState } from "@/components/empty-state";
|
|
||||||
import { PageHeader } from "@/components/page-header";
|
|
||||||
import { StatusPill } from "@/components/status-pill";
|
|
||||||
import { getCurrentStore, getCurrentStoreEmployees, getCurrentUser, getPermissionPayload } from "@/lib/mobile-data";
|
|
||||||
|
|
||||||
export default async function StorePage() {
|
|
||||||
const [user, permissions] = await Promise.all([getCurrentUser(), getPermissionPayload()]);
|
|
||||||
const canViewStoreEmployees =
|
|
||||||
permissions.permissions.includes("*") ||
|
|
||||||
permissions.permissions.includes("employee:view:store") ||
|
|
||||||
permissions.permissions.includes("employee:view:all");
|
|
||||||
const [store, employees] = await Promise.all([
|
|
||||||
getCurrentStore(user),
|
|
||||||
canViewStoreEmployees ? getCurrentStoreEmployees(user) : Promise.resolve([])
|
|
||||||
]);
|
|
||||||
const storeName = store?.name || user.storeName || "未绑定门店";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="page-stack">
|
|
||||||
<PageHeader title="门店" description="当前登录员工所属门店信息。" />
|
|
||||||
<section className="store-panel">
|
|
||||||
<Store aria-hidden size={28} />
|
|
||||||
<div>
|
|
||||||
<h2>{storeName}</h2>
|
|
||||||
<p>门店 ID:{store?.id ?? user.storeId ?? "暂无"}</p>
|
|
||||||
</div>
|
|
||||||
<StatusPill tone={store?.status === "INACTIVE" ? "warning" : "success"}>
|
|
||||||
{store?.status === "INACTIVE" ? "停用" : "正常"}
|
|
||||||
</StatusPill>
|
|
||||||
</section>
|
|
||||||
<section className="info-list">
|
|
||||||
<div>
|
|
||||||
<MapPin aria-hidden size={18} />
|
|
||||||
<span>地址</span>
|
|
||||||
<strong>{store?.address || "暂无"}</strong>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Phone aria-hidden size={18} />
|
|
||||||
<span>电话</span>
|
|
||||||
<strong>{store?.phone || "暂无"}</strong>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
{canViewStoreEmployees && employees.length > 0 ? (
|
|
||||||
<section className="section-block">
|
|
||||||
<div className="section-title">
|
|
||||||
<h2>本店员工</h2>
|
|
||||||
</div>
|
|
||||||
<div className="list-stack">
|
|
||||||
{employees.map((employee) => (
|
|
||||||
<article className="list-card" key={employee.id}>
|
|
||||||
<div>
|
|
||||||
<h3>{employee.name}</h3>
|
|
||||||
<p>{employee.phone || employee.roles.map((role) => role.name).join("、") || "未分配角色"}</p>
|
|
||||||
</div>
|
|
||||||
<StatusPill tone={employee.status === "INACTIVE" ? "warning" : "success"}>
|
|
||||||
{employee.status === "INACTIVE" ? "停用" : "在职"}
|
|
||||||
</StatusPill>
|
|
||||||
</article>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
) : canViewStoreEmployees ? (
|
|
||||||
<EmptyState title="暂无本店员工" description="有查看权限,但当前接口没有返回员工数据。" />
|
|
||||||
) : (
|
|
||||||
<EmptyState title="仅展示门店资料" description="当前账号没有查看本店员工列表的权限。" />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,114 +0,0 @@
|
|||||||
import Link from "next/link";
|
|
||||||
import { notFound } from "next/navigation";
|
|
||||||
import { ArrowLeft, CalendarClock, ClipboardList, Store, UsersRound } from "lucide-react";
|
|
||||||
|
|
||||||
import { PageHeader } from "@/components/page-header";
|
|
||||||
import { StatusPill } from "@/components/status-pill";
|
|
||||||
import { TaskActionPanel } from "@/components/task-action-panel";
|
|
||||||
import { BackendError } from "@/lib/backend";
|
|
||||||
import { formatDateTime } from "@/lib/format";
|
|
||||||
import { getTaskDetail } from "@/lib/mobile-data";
|
|
||||||
import type { TaskEvent, TaskStatus } from "@/lib/types";
|
|
||||||
|
|
||||||
type TaskDetailPageProps = {
|
|
||||||
params: Promise<{ id: string }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
const statusText: Record<TaskStatus, string> = {
|
|
||||||
pending: "待处理",
|
|
||||||
in_progress: "处理中",
|
|
||||||
completed: "已完成",
|
|
||||||
cancelled: "已取消"
|
|
||||||
};
|
|
||||||
|
|
||||||
const statusTone: Record<TaskStatus, "default" | "success" | "warning" | "danger"> = {
|
|
||||||
pending: "warning",
|
|
||||||
in_progress: "warning",
|
|
||||||
completed: "success",
|
|
||||||
cancelled: "danger"
|
|
||||||
};
|
|
||||||
|
|
||||||
const eventText: Record<string, string> = {
|
|
||||||
CREATED: "创建任务",
|
|
||||||
UPDATED: "更新任务",
|
|
||||||
STARTED: "开始处理",
|
|
||||||
COMPLETED: "完成任务",
|
|
||||||
CANCELLED: "取消任务",
|
|
||||||
COMMENTED: "追加备注"
|
|
||||||
};
|
|
||||||
|
|
||||||
function eventDescription(event: TaskEvent) {
|
|
||||||
const label = eventText[event.eventType] ?? event.eventType;
|
|
||||||
if (event.comment) return `${label}:${event.comment}`;
|
|
||||||
if (event.fromStatus && event.toStatus) return `${label}:${event.fromStatus} -> ${event.toStatus}`;
|
|
||||||
return label;
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function TaskDetailPage({ params }: TaskDetailPageProps) {
|
|
||||||
const { id } = await params;
|
|
||||||
let task: Awaited<ReturnType<typeof getTaskDetail>>;
|
|
||||||
|
|
||||||
try {
|
|
||||||
task = await getTaskDetail(id);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof BackendError && error.status === 404) {
|
|
||||||
notFound();
|
|
||||||
}
|
|
||||||
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="page-stack">
|
|
||||||
<Link className="inline-link" href="/tasks">
|
|
||||||
<ArrowLeft aria-hidden size={16} />
|
|
||||||
返回任务
|
|
||||||
</Link>
|
|
||||||
<PageHeader eyebrow={task.storeName || "任务详情"} title={task.title} description={task.description} />
|
|
||||||
<section className="detail-card">
|
|
||||||
<div className="detail-meta">
|
|
||||||
<span>
|
|
||||||
<ClipboardList aria-hidden size={16} />
|
|
||||||
当前状态
|
|
||||||
</span>
|
|
||||||
<StatusPill tone={statusTone[task.status]}>{statusText[task.status]}</StatusPill>
|
|
||||||
</div>
|
|
||||||
<div className="info-list compact">
|
|
||||||
<div>
|
|
||||||
<CalendarClock aria-hidden size={18} />
|
|
||||||
<span>截止时间</span>
|
|
||||||
<strong>{formatDateTime(task.dueAt)}</strong>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<Store aria-hidden size={18} />
|
|
||||||
<span>所属门店</span>
|
|
||||||
<strong>{task.storeName || "未指定"}</strong>
|
|
||||||
</div>
|
|
||||||
<div>
|
|
||||||
<UsersRound aria-hidden size={18} />
|
|
||||||
<span>处理人</span>
|
|
||||||
<strong>{task.assignees.map((item) => item.name).join("、") || task.assigneeName || "未指定"}</strong>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</section>
|
|
||||||
<TaskActionPanel initialStatus={task.status} taskId={task.id} />
|
|
||||||
<section className="section-block">
|
|
||||||
<div className="section-title">
|
|
||||||
<h2>处理记录</h2>
|
|
||||||
</div>
|
|
||||||
{task.events.length > 0 ? (
|
|
||||||
<div className="timeline">
|
|
||||||
{task.events.map((event) => (
|
|
||||||
<article className="timeline-item" key={event.id}>
|
|
||||||
<strong>{eventDescription(event)}</strong>
|
|
||||||
<span>{formatDateTime(event.createdAt)}</span>
|
|
||||||
</article>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
) : (
|
|
||||||
<p className="muted-copy">暂无处理记录。</p>
|
|
||||||
)}
|
|
||||||
</section>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,88 +0,0 @@
|
|||||||
import Link from "next/link";
|
|
||||||
import type { Route } from "next";
|
|
||||||
|
|
||||||
import { EmptyState } from "@/components/empty-state";
|
|
||||||
import { FilterNav } from "@/components/filter-nav";
|
|
||||||
import { PageHeader } from "@/components/page-header";
|
|
||||||
import { StatusPill } from "@/components/status-pill";
|
|
||||||
import { formatDateTime } from "@/lib/format";
|
|
||||||
import { getTasks } from "@/lib/mobile-data";
|
|
||||||
import type { TaskStatus } from "@/lib/types";
|
|
||||||
|
|
||||||
const statusText: Record<TaskStatus, string> = {
|
|
||||||
pending: "待处理",
|
|
||||||
in_progress: "处理中",
|
|
||||||
completed: "已完成",
|
|
||||||
cancelled: "已取消"
|
|
||||||
};
|
|
||||||
|
|
||||||
const statusTone: Record<TaskStatus, "success" | "warning" | "danger"> = {
|
|
||||||
pending: "warning",
|
|
||||||
in_progress: "warning",
|
|
||||||
completed: "success",
|
|
||||||
cancelled: "danger"
|
|
||||||
};
|
|
||||||
|
|
||||||
type TasksPageProps = {
|
|
||||||
searchParams: Promise<{ status?: string | string[] }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
function firstSearchValue(value: string | string[] | undefined) {
|
|
||||||
return Array.isArray(value) ? value[0] : value;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeStatus(value: string | string[] | undefined): TaskStatus | "all" {
|
|
||||||
const status = firstSearchValue(value);
|
|
||||||
if (status === "pending" || status === "in_progress" || status === "completed" || status === "cancelled") {
|
|
||||||
return status;
|
|
||||||
}
|
|
||||||
|
|
||||||
return "all";
|
|
||||||
}
|
|
||||||
|
|
||||||
function emptyCopy(status: TaskStatus | "all") {
|
|
||||||
if (status === "pending") return "当前没有待处理任务。";
|
|
||||||
if (status === "in_progress") return "当前没有处理中的任务。";
|
|
||||||
if (status === "completed") return "当前没有已完成任务。";
|
|
||||||
if (status === "cancelled") return "当前没有已取消任务。";
|
|
||||||
return "当前没有分配给你的任务。";
|
|
||||||
}
|
|
||||||
|
|
||||||
export default async function TasksPage({ searchParams }: TasksPageProps) {
|
|
||||||
const status = normalizeStatus((await searchParams).status);
|
|
||||||
const tasks = await getTasks(status === "all" ? {} : { status });
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="page-stack">
|
|
||||||
<PageHeader title="任务" description="查看个人和门店分配给你的事项。" />
|
|
||||||
<FilterNav
|
|
||||||
label="任务筛选"
|
|
||||||
options={[
|
|
||||||
{ label: "全部", href: "/tasks" as Route, active: status === "all" },
|
|
||||||
{ label: "待处理", href: "/tasks?status=pending" as Route, active: status === "pending" },
|
|
||||||
{ label: "处理中", href: "/tasks?status=in_progress" as Route, active: status === "in_progress" },
|
|
||||||
{ label: "已完成", href: "/tasks?status=completed" as Route, active: status === "completed" }
|
|
||||||
]}
|
|
||||||
/>
|
|
||||||
{tasks.length > 0 ? (
|
|
||||||
<section className="list-stack">
|
|
||||||
{tasks.map((task) => {
|
|
||||||
const href = `/tasks/${task.id}` as Route;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link className="list-card" href={href} key={task.id}>
|
|
||||||
<div>
|
|
||||||
<h2>{task.title}</h2>
|
|
||||||
<p>{task.description || `截止:${formatDateTime(task.dueAt)}`}</p>
|
|
||||||
</div>
|
|
||||||
<StatusPill tone={statusTone[task.status]}>{statusText[task.status]}</StatusPill>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</section>
|
|
||||||
) : (
|
|
||||||
<EmptyState title="暂无任务" description={emptyCopy(status)} />
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,4 +1,4 @@
|
|||||||
/** 星港登录页,使用独立用户账号,无公开注册。 */
|
/** 个人数字人登录页,使用 Google 登录。 */
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { safeDigitalReturnTo } from "@/lib/digital-routes";
|
import { safeDigitalReturnTo } from "@/lib/digital-routes";
|
||||||
import { LoginForm } from "@/components/login-form";
|
import { LoginForm } from "@/components/login-form";
|
||||||
@@ -19,7 +19,7 @@ export default async function LoginPage({
|
|||||||
<Link href="/" className="stellar-login-brand">
|
<Link href="/" className="stellar-login-brand">
|
||||||
✦{" "}
|
✦{" "}
|
||||||
<span>
|
<span>
|
||||||
星港 <small>STELLAR</small>
|
个人数字人
|
||||||
</span>
|
</span>
|
||||||
</Link>
|
</Link>
|
||||||
<div>
|
<div>
|
||||||
@@ -39,10 +39,9 @@ export default async function LoginPage({
|
|||||||
</section>
|
</section>
|
||||||
<section className="stellar-login-panel">
|
<section className="stellar-login-panel">
|
||||||
<span className="stellar-login-star">✧</span>
|
<span className="stellar-login-star">✧</span>
|
||||||
<h2>欢迎回到星港</h2>
|
<h2>登录个人数字人</h2>
|
||||||
<p>使用你的星港账号,继续未完的故事。</p>
|
<p>使用 Google 账号继续。</p>
|
||||||
<LoginForm returnTo={returnTo} />
|
<LoginForm returnTo={returnTo} />
|
||||||
<small>账号由管理员开通 · 与后台账号独立</small>
|
|
||||||
</section>
|
</section>
|
||||||
</main>
|
</main>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { DigitalPage } from "@/components/digital-page";
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
/** 独立详情页面名称。 */
|
/** 独立详情页面名称。 */
|
||||||
export const metadata = { title: "角色详情 · 星港" };
|
export const metadata = { title: "角色详情 · 个人数字人" };
|
||||||
|
|
||||||
/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */
|
/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */
|
||||||
export default async function Page({
|
export default async function Page({
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { DigitalPage } from "@/components/digital-page";
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
/** 独立详情页面名称。 */
|
/** 独立详情页面名称。 */
|
||||||
export const metadata = { title: "聊天 · 星港" };
|
export const metadata = { title: "聊天 · 个人数字人" };
|
||||||
|
|
||||||
/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */
|
/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */
|
||||||
export default async function Page({
|
export default async function Page({
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { DigitalPage } from "@/components/digital-page";
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
||||||
export const metadata = { title: "我的对话 · 星港" };
|
export const metadata = { title: "我的对话 · 个人数字人" };
|
||||||
|
|
||||||
/** 读取本页面的私有首屏数据。 */
|
/** 读取本页面的私有首屏数据。 */
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { DigitalPage } from "@/components/digital-page";
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
||||||
export const metadata = { title: "发现角色 · 星港" };
|
export const metadata = { title: "发现角色 · 个人数字人" };
|
||||||
|
|
||||||
/** 读取本页面的私有首屏数据。 */
|
/** 读取本页面的私有首屏数据。 */
|
||||||
export default async function Page({
|
export default async function Page({
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { DigitalPage } from "@/components/digital-page";
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
/** 独立详情页面名称。 */
|
/** 独立详情页面名称。 */
|
||||||
export const metadata = { title: "内容详情 · 星港" };
|
export const metadata = { title: "内容详情 · 个人数字人" };
|
||||||
|
|
||||||
/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */
|
/** 路径参数由统一数据入口校验,不存在或已删除的资源返回不存在页面。 */
|
||||||
export default async function Page({
|
export default async function Page({
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { DigitalPage } from "@/components/digital-page";
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
||||||
export const metadata = { title: "灵感书架 · 星港" };
|
export const metadata = { title: "灵感书架 · 个人数字人" };
|
||||||
|
|
||||||
/** 读取本页面的私有首屏数据。 */
|
/** 读取本页面的私有首屏数据。 */
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
import { DigitalPage } from "@/components/digital-page";
|
import { DigitalPage } from "@/components/digital-page";
|
||||||
|
|
||||||
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
/** 当前页面标题,切换路由时同步浏览器与辅助技术的页面名称。 */
|
||||||
export const metadata = { title: "我的身份 · 星港" };
|
export const metadata = { title: "我的身份 · 个人数字人" };
|
||||||
|
|
||||||
/** 读取本页面的私有首屏数据。 */
|
/** 读取本页面的私有首屏数据。 */
|
||||||
export default function Page() {
|
export default function Page() {
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
/** 同源兑换 Firebase 凭据,业务 JWT 仅写入现有 HttpOnly Cookie。 */
|
||||||
|
import { readLoginInput } from "@/lib/auth-input";
|
||||||
|
import { sameOriginRequest } from "@/lib/auth-origin";
|
||||||
|
import { BackendError, backendRequest } from "@/lib/backend";
|
||||||
|
import { setSessionToken } from "@/lib/session";
|
||||||
|
|
||||||
|
/** 将 Firebase ID token 交给账号服务。 */
|
||||||
|
export async function POST(request: Request) {
|
||||||
|
if (!sameOriginRequest(request)) {
|
||||||
|
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const { idToken } = await readLoginInput(request);
|
||||||
|
if (typeof idToken !== "string" || !idToken || idToken.length > 6000) {
|
||||||
|
return Response.json({ message: "Google 登录凭据不合法" }, { status: 400 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const { token } = await backendRequest<{ token: string }>("/auth/digital/firebase", {
|
||||||
|
method: "POST",
|
||||||
|
body: JSON.stringify({ idToken }),
|
||||||
|
token: "",
|
||||||
|
});
|
||||||
|
if (!token) {
|
||||||
|
return Response.json({ message: "Google 登录暂不可用" }, { status: 502 });
|
||||||
|
}
|
||||||
|
await setSessionToken(token);
|
||||||
|
return Response.json({ success: true });
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof BackendError) {
|
||||||
|
if (error.status === 404 || error.status >= 500) {
|
||||||
|
return Response.json({ message: "Google 登录暂不可用" }, { status: 503 });
|
||||||
|
}
|
||||||
|
return Response.json({ message: error.message }, { status: error.status });
|
||||||
|
}
|
||||||
|
if (error instanceof SyntaxError || error instanceof RangeError) {
|
||||||
|
return Response.json({ message: "登录内容不合法" }, { status: 400 });
|
||||||
|
}
|
||||||
|
return Response.json({ message: "Google 登录暂不可用" }, { status: 502 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,34 +0,0 @@
|
|||||||
/** 数字人登录 BFF,令牌仅写入 HttpOnly Cookie,不返回浏览器。 */
|
|
||||||
import { setSessionToken } from "@/lib/session";
|
|
||||||
import { BackendError, backendRequest } from "@/lib/backend";
|
|
||||||
import type { LoginResponse } from "@/lib/types";
|
|
||||||
|
|
||||||
export async function POST(request: Request) {
|
|
||||||
try {
|
|
||||||
const body = await request.json();
|
|
||||||
const result = await backendRequest<LoginResponse>("/auth/digital/login", {
|
|
||||||
method: "POST",
|
|
||||||
body: JSON.stringify({
|
|
||||||
username: body.username,
|
|
||||||
password: body.password,
|
|
||||||
}),
|
|
||||||
token: "",
|
|
||||||
});
|
|
||||||
|
|
||||||
await setSessionToken(result.token);
|
|
||||||
|
|
||||||
return Response.json({
|
|
||||||
success: true,
|
|
||||||
data: {
|
|
||||||
user: result.user,
|
|
||||||
tokenType: result.tokenType,
|
|
||||||
expiresIn: result.expiresIn,
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
const status = error instanceof BackendError ? error.status : 500;
|
|
||||||
const message = error instanceof Error ? error.message : "登录失败";
|
|
||||||
|
|
||||||
return Response.json({ success: false, data: null, message }, { status });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { AuthUser } from "@/lib/types";
|
|
||||||
|
|
||||||
export async function PATCH(request: Request) {
|
|
||||||
const body = await request.text();
|
|
||||||
|
|
||||||
return proxyBackendJson<AuthUser>("/auth/me/password", {
|
|
||||||
method: "PATCH",
|
|
||||||
body: body || undefined
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { AuthUser } from "@/lib/types";
|
|
||||||
|
|
||||||
export async function GET() {
|
|
||||||
return proxyBackendJson<AuthUser>("/auth/me");
|
|
||||||
}
|
|
||||||
@@ -33,7 +33,7 @@ async function proxy(
|
|||||||
const { path } = await context.params;
|
const { path } = await context.params;
|
||||||
const joined = path.join("/");
|
const joined = path.join("/");
|
||||||
if (
|
if (
|
||||||
!/^(bootstrap|profile|exposure|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|suggestions|style-policy|messages\/[a-zA-Z0-9_-]+))?)?)$/.test(
|
!/^(bootstrap|profile|exposure|growth(?:\/(?:preferences|recommendations|events|inbox\/[a-zA-Z0-9_-]+))?|decisions\/[a-zA-Z0-9_-]+|conversations(?:\/[a-zA-Z0-9_-]+(?:\/(?:stream|stop|branch|restore|suggestions|feedback|memories(?:\/[a-zA-Z0-9_-]+)?|style-policy|messages\/[a-zA-Z0-9_-]+))?)?)$/.test(
|
||||||
joined,
|
joined,
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
@@ -55,6 +55,12 @@ async function proxy(
|
|||||||
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
return Response.json({ message: "请求来源不合法" }, { status: 403 });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
const search =
|
||||||
|
request.method === "GET" && joined === "conversations"
|
||||||
|
? new URL(request.url).searchParams.get("q")
|
||||||
|
: null;
|
||||||
|
const query =
|
||||||
|
search === null ? "" : `?q=${encodeURIComponent(search.slice(0, 100))}`;
|
||||||
const token = await getSessionToken();
|
const token = await getSessionToken();
|
||||||
if (!token) return Response.json({ message: "请先登录" }, { status: 401 });
|
if (!token) return Response.json({ message: "请先登录" }, { status: 401 });
|
||||||
const headers = new Headers({
|
const headers = new Headers({
|
||||||
@@ -63,7 +69,7 @@ async function proxy(
|
|||||||
});
|
});
|
||||||
try {
|
try {
|
||||||
const response = await fetch(
|
const response = await fetch(
|
||||||
`${getBackendBaseUrl().replace(/\/$/, "")}/digital/${joined}`,
|
`${getBackendBaseUrl().replace(/\/$/, "")}/digital/${joined}${query}`,
|
||||||
{
|
{
|
||||||
method: request.method,
|
method: request.method,
|
||||||
headers,
|
headers,
|
||||||
|
|||||||
@@ -1,13 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { AnnouncementDetail } from "@/lib/types";
|
|
||||||
|
|
||||||
type Params = {
|
|
||||||
params: Promise<{ id: string }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function POST(_request: Request, { params }: Params) {
|
|
||||||
const { id } = await params;
|
|
||||||
return proxyBackendJson<AnnouncementDetail>(`/mobile/announcements/${encodeURIComponent(id)}/read`, {
|
|
||||||
method: "POST"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { AnnouncementDetail } from "@/lib/types";
|
|
||||||
|
|
||||||
type Params = {
|
|
||||||
params: Promise<{ id: string }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function GET(_request: Request, { params }: Params) {
|
|
||||||
const { id } = await params;
|
|
||||||
return proxyBackendJson<AnnouncementDetail>(`/mobile/announcements/${encodeURIComponent(id)}`);
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
|
|
||||||
export async function GET(request: Request) {
|
|
||||||
const search = new URL(request.url).search;
|
|
||||||
return proxyBackendJson<unknown>(`/mobile/announcements${search}`);
|
|
||||||
}
|
|
||||||
@@ -1,7 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { ShiftSummary } from "@/lib/types";
|
|
||||||
|
|
||||||
export async function GET(request: Request) {
|
|
||||||
const search = new URL(request.url).search;
|
|
||||||
return proxyBackendJson<ShiftSummary[]>(`/mobile/shifts${search}`);
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { ShiftSummary } from "@/lib/types";
|
|
||||||
|
|
||||||
export async function GET() {
|
|
||||||
return proxyBackendJson<ShiftSummary | null>("/mobile/shifts/today");
|
|
||||||
}
|
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
import { backendErrorResponse, BackendError, backendRequest } from "@/lib/backend";
|
|
||||||
import type { ApiEnvelope, AuthUser, StoreEmployee } from "@/lib/types";
|
|
||||||
|
|
||||||
export async function GET() {
|
|
||||||
try {
|
|
||||||
const user = await backendRequest<AuthUser>("/auth/me");
|
|
||||||
|
|
||||||
if (!user.storeId) {
|
|
||||||
return Response.json({ success: true, data: [] } satisfies ApiEnvelope<StoreEmployee[]>);
|
|
||||||
}
|
|
||||||
|
|
||||||
const search = new URLSearchParams({
|
|
||||||
storeId: String(user.storeId),
|
|
||||||
page: "1",
|
|
||||||
pageSize: "100"
|
|
||||||
});
|
|
||||||
|
|
||||||
try {
|
|
||||||
const employees = await backendRequest<unknown>(`/employees?${search.toString()}`);
|
|
||||||
return Response.json({ success: true, data: employees } satisfies ApiEnvelope<unknown>);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof BackendError && [403, 404].includes(error.status)) {
|
|
||||||
return Response.json({ success: true, data: [] } satisfies ApiEnvelope<StoreEmployee[]>);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
return backendErrorResponse(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,38 +0,0 @@
|
|||||||
import { backendErrorResponse, BackendError, backendRequest } from "@/lib/backend";
|
|
||||||
import type { ApiEnvelope, AuthUser, StoreDetail } from "@/lib/types";
|
|
||||||
|
|
||||||
function fallbackStore(user: AuthUser): StoreDetail | null {
|
|
||||||
if (!user.storeId) return null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: user.storeId,
|
|
||||||
name: user.storeName ?? "当前门店",
|
|
||||||
address: null,
|
|
||||||
phone: null,
|
|
||||||
status: undefined,
|
|
||||||
employees: []
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function GET() {
|
|
||||||
try {
|
|
||||||
const user = await backendRequest<AuthUser>("/auth/me");
|
|
||||||
|
|
||||||
if (!user.storeId) {
|
|
||||||
return Response.json({ success: true, data: null } satisfies ApiEnvelope<StoreDetail | null>);
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const store = await backendRequest<StoreDetail>(`/stores/${user.storeId}`);
|
|
||||||
return Response.json({ success: true, data: store } satisfies ApiEnvelope<StoreDetail>);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof BackendError && [403, 404].includes(error.status)) {
|
|
||||||
return Response.json({ success: true, data: fallbackStore(user) } satisfies ApiEnvelope<StoreDetail | null>);
|
|
||||||
}
|
|
||||||
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
return backendErrorResponse(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { TaskDetail } from "@/lib/types";
|
|
||||||
|
|
||||||
type Params = {
|
|
||||||
params: Promise<{ id: string }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function POST(request: Request, { params }: Params) {
|
|
||||||
const { id } = await params;
|
|
||||||
const body = await request.text();
|
|
||||||
|
|
||||||
return proxyBackendJson<TaskDetail>(`/mobile/tasks/${encodeURIComponent(id)}/comment`, {
|
|
||||||
method: "POST",
|
|
||||||
body: body || undefined
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { TaskDetail } from "@/lib/types";
|
|
||||||
|
|
||||||
type Params = {
|
|
||||||
params: Promise<{ id: string }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function POST(_request: Request, { params }: Params) {
|
|
||||||
const { id } = await params;
|
|
||||||
return proxyBackendJson<TaskDetail>(`/mobile/tasks/${encodeURIComponent(id)}/complete`, {
|
|
||||||
method: "POST"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,11 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { TaskDetail } from "@/lib/types";
|
|
||||||
|
|
||||||
type Params = {
|
|
||||||
params: Promise<{ id: string }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function GET(_request: Request, { params }: Params) {
|
|
||||||
const { id } = await params;
|
|
||||||
return proxyBackendJson<TaskDetail>(`/mobile/tasks/${encodeURIComponent(id)}`);
|
|
||||||
}
|
|
||||||
@@ -1,13 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { TaskDetail } from "@/lib/types";
|
|
||||||
|
|
||||||
type Params = {
|
|
||||||
params: Promise<{ id: string }>;
|
|
||||||
};
|
|
||||||
|
|
||||||
export async function POST(_request: Request, { params }: Params) {
|
|
||||||
const { id } = await params;
|
|
||||||
return proxyBackendJson<TaskDetail>(`/mobile/tasks/${encodeURIComponent(id)}/start`, {
|
|
||||||
method: "POST"
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
|
|
||||||
export async function GET(request: Request) {
|
|
||||||
const search = new URL(request.url).search;
|
|
||||||
return proxyBackendJson<unknown>(`/mobile/tasks${search}`);
|
|
||||||
}
|
|
||||||
@@ -1,6 +0,0 @@
|
|||||||
import { proxyBackendJson } from "@/lib/backend";
|
|
||||||
import type { PermissionPayload } from "@/lib/types";
|
|
||||||
|
|
||||||
export async function GET() {
|
|
||||||
return proxyBackendJson<PermissionPayload>("/permissions/me");
|
|
||||||
}
|
|
||||||
+3
-3
@@ -5,9 +5,9 @@ import { connection } from "next/server";
|
|||||||
import { getAppEnvLabel } from "@/lib/environment";
|
import { getAppEnvLabel } from "@/lib/environment";
|
||||||
import "./globals.css";
|
import "./globals.css";
|
||||||
|
|
||||||
/** 星港品牌与安装元数据。 */
|
/** 个人数字人品牌与安装元数据。 */
|
||||||
export const metadata: Metadata = {
|
export const metadata: Metadata = {
|
||||||
title: "星港 · 数字人空间",
|
title: "个人数字人",
|
||||||
description: "与有故事的人相遇,让每一段对话继续生长",
|
description: "与有故事的人相遇,让每一段对话继续生长",
|
||||||
manifest: "/manifest.webmanifest",
|
manifest: "/manifest.webmanifest",
|
||||||
icons: {
|
icons: {
|
||||||
@@ -19,7 +19,7 @@ export const metadata: Metadata = {
|
|||||||
},
|
},
|
||||||
appleWebApp: {
|
appleWebApp: {
|
||||||
capable: true,
|
capable: true,
|
||||||
title: "星港 · 数字人空间",
|
title: "个人数字人",
|
||||||
statusBarStyle: "default",
|
statusBarStyle: "default",
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|||||||
+3
-2
@@ -1,10 +1,11 @@
|
|||||||
/** 数字人空间 PWA 元数据,保留原有安装机制。 */
|
/** 数字人空间 PWA 元数据,保留原有安装机制。 */
|
||||||
import type { MetadataRoute } from "next";
|
import type { MetadataRoute } from "next";
|
||||||
|
|
||||||
|
/** 提供浏览器安装时展示的应用名称和图标。 */
|
||||||
export default function manifest(): MetadataRoute.Manifest {
|
export default function manifest(): MetadataRoute.Manifest {
|
||||||
return {
|
return {
|
||||||
name: "星港 · 数字人空间",
|
name: "个人数字人",
|
||||||
short_name: "星港",
|
short_name: "个人数字人",
|
||||||
description: "你的私人数字人空间",
|
description: "你的私人数字人空间",
|
||||||
start_url: "/discover",
|
start_url: "/discover",
|
||||||
scope: "/",
|
scope: "/",
|
||||||
|
|||||||
@@ -1,27 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { useEffect, useRef } from "react";
|
|
||||||
|
|
||||||
type AnnouncementReadMarkerProps = {
|
|
||||||
id: string;
|
|
||||||
read: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function AnnouncementReadMarker({ id, read }: AnnouncementReadMarkerProps) {
|
|
||||||
const router = useRouter();
|
|
||||||
const sentRef = useRef(false);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (read || sentRef.current) return;
|
|
||||||
|
|
||||||
sentRef.current = true;
|
|
||||||
void fetch(`/api/mobile/announcements/${encodeURIComponent(id)}/read`, { method: "POST" }).then((response) => {
|
|
||||||
if (response.ok) {
|
|
||||||
router.refresh();
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}, [id, read, router]);
|
|
||||||
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
@@ -1,33 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import Link from "next/link";
|
|
||||||
import { usePathname } from "next/navigation";
|
|
||||||
import { Bell, CalendarDays, ClipboardList, Home, UserRound } from "lucide-react";
|
|
||||||
|
|
||||||
const items = [
|
|
||||||
{ href: "/dashboard", label: "工作台", icon: Home },
|
|
||||||
{ href: "/tasks", label: "任务", icon: ClipboardList },
|
|
||||||
{ href: "/schedule", label: "排班", icon: CalendarDays },
|
|
||||||
{ href: "/announcements", label: "公告", icon: Bell },
|
|
||||||
{ href: "/me", label: "我的", icon: UserRound }
|
|
||||||
] as const;
|
|
||||||
|
|
||||||
export function BottomNav() {
|
|
||||||
const pathname = usePathname();
|
|
||||||
|
|
||||||
return (
|
|
||||||
<nav className="bottom-nav" aria-label="主要导航">
|
|
||||||
{items.map((item) => {
|
|
||||||
const Icon = item.icon;
|
|
||||||
const active = pathname === item.href || pathname.startsWith(`${item.href}/`);
|
|
||||||
|
|
||||||
return (
|
|
||||||
<Link className={`bottom-nav__item${active ? " is-active" : ""}`} href={item.href} key={item.href}>
|
|
||||||
<Icon aria-hidden size={20} strokeWidth={active ? 2.6 : 2} />
|
|
||||||
<span>{item.label}</span>
|
|
||||||
</Link>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,81 @@
|
|||||||
|
"use client";
|
||||||
|
/** 会话命名和分支确认共用居中表单,失败时保留输入并允许重试。 */
|
||||||
|
import { useEffect, useId, useRef, useState, type ReactNode } from "react";
|
||||||
|
|
||||||
|
/** 提交过程锁定重复操作,Escape 与取消均保留原会话。 */
|
||||||
|
export function ConversationTitleDialog({
|
||||||
|
heading,
|
||||||
|
initialTitle,
|
||||||
|
preview,
|
||||||
|
onCancel,
|
||||||
|
onSubmit,
|
||||||
|
}: {
|
||||||
|
heading: string;
|
||||||
|
initialTitle: string;
|
||||||
|
preview?: ReactNode;
|
||||||
|
onCancel: () => void;
|
||||||
|
onSubmit: (title: string) => Promise<void>;
|
||||||
|
}) {
|
||||||
|
const ref = useRef<HTMLDialogElement>(null),
|
||||||
|
lock = useRef(false),
|
||||||
|
id = useId();
|
||||||
|
const [title, setTitle] = useState(initialTitle),
|
||||||
|
[busy, setBusy] = useState(false),
|
||||||
|
[error, setError] = useState("");
|
||||||
|
useEffect(() => {
|
||||||
|
const dialog = ref.current;
|
||||||
|
dialog?.showModal();
|
||||||
|
return () => dialog?.close();
|
||||||
|
}, []);
|
||||||
|
return (
|
||||||
|
<dialog
|
||||||
|
ref={ref}
|
||||||
|
className="dh-delete-dialog dh-title-dialog"
|
||||||
|
aria-labelledby={id}
|
||||||
|
onCancel={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!lock.current) onCancel();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<form
|
||||||
|
onSubmit={async (e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
if (lock.current || !title.trim()) return;
|
||||||
|
lock.current = true;
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await onSubmit(title.trim());
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "保存失败,请重试");
|
||||||
|
} finally {
|
||||||
|
lock.current = false;
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<h2 id={id}>{heading}</h2>
|
||||||
|
{preview}
|
||||||
|
<label>
|
||||||
|
对话名称
|
||||||
|
<input
|
||||||
|
autoFocus
|
||||||
|
value={title}
|
||||||
|
maxLength={120}
|
||||||
|
required
|
||||||
|
onChange={(e) => setTitle(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{error && <p role="alert">{error}</p>}
|
||||||
|
<div className="dh-delete-actions">
|
||||||
|
<button type="button" disabled={busy} onClick={onCancel}>
|
||||||
|
取消
|
||||||
|
</button>
|
||||||
|
<button type="submit" disabled={busy || !title.trim()}>
|
||||||
|
{busy ? "正在保存…" : "确认"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,153 @@
|
|||||||
|
"use client";
|
||||||
|
/** 会话列表的服务端搜索、命名和置顶;删除仍通过独立确认流程处理。 */
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { digital, type Card, type Summary } from "@/lib/digital";
|
||||||
|
import { ConversationRow } from "./conversation-row";
|
||||||
|
import { ConversationTitleDialog } from "./conversation-dialogs";
|
||||||
|
|
||||||
|
/** 搜索覆盖历史标题和消息;迟到查询不能覆盖新关键词或恢复全部列表。 */
|
||||||
|
export function ConversationList({
|
||||||
|
summaries,
|
||||||
|
cards,
|
||||||
|
disabled,
|
||||||
|
onDelete,
|
||||||
|
onRefresh,
|
||||||
|
onNotice,
|
||||||
|
}: {
|
||||||
|
summaries: Summary[];
|
||||||
|
cards: Card[];
|
||||||
|
disabled: boolean;
|
||||||
|
onDelete: (summary: Summary) => void;
|
||||||
|
onRefresh: () => Promise<void>;
|
||||||
|
onNotice: (message: string) => void;
|
||||||
|
}) {
|
||||||
|
const [query, setQuery] = useState(""),
|
||||||
|
[results, setResults] = useState<Summary[]>([]),
|
||||||
|
[resultQuery, setResultQuery] = useState(""),
|
||||||
|
[loading, setLoading] = useState(false),
|
||||||
|
[error, setError] = useState(""),
|
||||||
|
[swiped, setSwiped] = useState<string | null>(null),
|
||||||
|
[renaming, setRenaming] = useState<Summary | null>(null),
|
||||||
|
[pending, setPending] = useState<string | null>(null);
|
||||||
|
const lock = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!query.trim()) return;
|
||||||
|
const controller = new AbortController();
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setLoading(true);
|
||||||
|
setError("");
|
||||||
|
digital<Summary[]>(
|
||||||
|
`conversations?q=${encodeURIComponent(query.trim())}`,
|
||||||
|
"GET",
|
||||||
|
undefined,
|
||||||
|
controller.signal,
|
||||||
|
)
|
||||||
|
.then((items) => {
|
||||||
|
if (!controller.signal.aborted) {
|
||||||
|
setResults(items);
|
||||||
|
setResultQuery(query.trim());
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch((e) => {
|
||||||
|
if (!controller.signal.aborted)
|
||||||
|
setError(e instanceof Error ? e.message : "搜索失败");
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!controller.signal.aborted) setLoading(false);
|
||||||
|
});
|
||||||
|
}, 250);
|
||||||
|
return () => {
|
||||||
|
clearTimeout(timer);
|
||||||
|
controller.abort();
|
||||||
|
};
|
||||||
|
}, [query, summaries]);
|
||||||
|
async function save(
|
||||||
|
summary: Summary,
|
||||||
|
patch: { title?: string; pinned?: boolean },
|
||||||
|
) {
|
||||||
|
await digital(`conversations/${summary.id}`, "PATCH", patch);
|
||||||
|
setResults((items) =>
|
||||||
|
items.map((item) =>
|
||||||
|
item.id === summary.id ? { ...item, ...patch } : item,
|
||||||
|
),
|
||||||
|
);
|
||||||
|
await onRefresh();
|
||||||
|
}
|
||||||
|
const items = [...(query.trim() ? resultQuery === query.trim() ? results : [] : summaries)].sort((a,b) => Number(!!b.pinned)-Number(!!a.pinned) || Date.parse(b.updatedAt)-Date.parse(a.updatedAt));
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<label className="dh-conversation-search">
|
||||||
|
搜索对话或消息
|
||||||
|
<input
|
||||||
|
type="search"
|
||||||
|
value={query}
|
||||||
|
maxLength={100}
|
||||||
|
placeholder="输入对话名称或聊天内容…"
|
||||||
|
onChange={(e) => setQuery(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
{query.trim() && !error && (loading || resultQuery !== query.trim()) && (
|
||||||
|
<p role="status">正在搜索…</p>
|
||||||
|
)}
|
||||||
|
{query.trim() && error && <p role="alert">{error}</p>}
|
||||||
|
<div className="dh-conversation-list">
|
||||||
|
{items.map((summary) => (
|
||||||
|
<div key={summary.id}>
|
||||||
|
<ConversationRow
|
||||||
|
summary={summary}
|
||||||
|
card={cards.find((card) => card.id === summary.characterId)}
|
||||||
|
revealed={swiped === summary.id}
|
||||||
|
disabled={disabled || pending === summary.id}
|
||||||
|
onReveal={setSwiped}
|
||||||
|
onDelete={() => onDelete(summary)}
|
||||||
|
/>
|
||||||
|
<div className="dh-conversation-tools">
|
||||||
|
<button
|
||||||
|
disabled={disabled || !!pending}
|
||||||
|
onClick={async () => {
|
||||||
|
if (lock.current) return;
|
||||||
|
lock.current = true;
|
||||||
|
setPending(summary.id);
|
||||||
|
try {
|
||||||
|
await save(summary, { pinned: !summary.pinned });
|
||||||
|
onNotice(summary.pinned ? "已取消置顶" : "对话已置顶");
|
||||||
|
} catch (e) {
|
||||||
|
onNotice(e instanceof Error ? e.message : "操作失败");
|
||||||
|
} finally {
|
||||||
|
setPending(null);
|
||||||
|
lock.current = false;
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{summary.pinned ? "取消置顶" : "置顶"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
disabled={disabled || !!pending}
|
||||||
|
onClick={() => setRenaming(summary)}
|
||||||
|
>
|
||||||
|
重命名
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
{query.trim() &&
|
||||||
|
resultQuery === query.trim() &&
|
||||||
|
!loading &&
|
||||||
|
!error &&
|
||||||
|
!items.length && <p className="dh-form-note">没有找到匹配的对话。</p>}
|
||||||
|
{renaming && (
|
||||||
|
<ConversationTitleDialog
|
||||||
|
heading="重命名对话"
|
||||||
|
initialTitle={renaming.title}
|
||||||
|
onCancel={() => setRenaming(null)}
|
||||||
|
onSubmit={async (title) => {
|
||||||
|
await save(renaming, { title });
|
||||||
|
setRenaming(null);
|
||||||
|
onNotice("对话名称已保存");
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -126,8 +126,13 @@ export function ConversationRow({
|
|||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img src={card?.cover || "/icon.svg"} alt="" draggable={false} />
|
<img src={card?.cover || "/icon.svg"} alt="" draggable={false} />
|
||||||
<div>
|
<div>
|
||||||
<h3>{summary.title}</h3>
|
<h3>
|
||||||
<p>{card?.description || "继续这段私人对话"}</p>
|
{summary.pinned ? "置顶 · " : ""}
|
||||||
|
{summary.title}
|
||||||
|
</h3>
|
||||||
|
<p>
|
||||||
|
{summary.lastMessage || card?.description || "继续这段私人对话"}
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<small>
|
<small>
|
||||||
{new Date(summary.updatedAt).toLocaleDateString("zh-CN", {
|
{new Date(summary.updatedAt).toLocaleDateString("zh-CN", {
|
||||||
|
|||||||
+475
-80
@@ -1,6 +1,6 @@
|
|||||||
"use client";
|
"use client";
|
||||||
/* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */
|
/* eslint-disable @next/next/no-img-element -- 本地封面直接读取,避免在小型服务器上运行图片转换。 */
|
||||||
/** 星港数字人空间:探索、会话、世界书、身份资料和账号内容偏好。 */
|
/** 个人数字人空间:探索、会话、世界书、身份资料和账号内容偏好。 */
|
||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { useRouter, useSearchParams } from "next/navigation";
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import {
|
import {
|
||||||
@@ -10,6 +10,12 @@ import {
|
|||||||
expiredDigitalSessionPath,
|
expiredDigitalSessionPath,
|
||||||
type DigitalTab,
|
type DigitalTab,
|
||||||
} from "@/lib/digital-routes";
|
} from "@/lib/digital-routes";
|
||||||
|
import { GrowthJourney } from "./growth-journey";
|
||||||
|
import { GrowthRecommendations } from "./growth-recommendations";
|
||||||
|
import { GrowthProfile } from "./growth-profile";
|
||||||
|
import { GrowthChat, ReplyFeedback } from "./growth-chat";
|
||||||
|
import { trackGrowth, flushGrowth, recommendationReceipt } from "@/lib/growth";
|
||||||
|
import { mergeConversationSnapshot } from "@/lib/digital-recovery";
|
||||||
import { useDigitalBack } from "./digital-route-history";
|
import { useDigitalBack } from "./digital-route-history";
|
||||||
import {
|
import {
|
||||||
useCallback,
|
useCallback,
|
||||||
@@ -57,7 +63,10 @@ import {
|
|||||||
type Summary,
|
type Summary,
|
||||||
type Bootstrap,
|
type Bootstrap,
|
||||||
} from "@/lib/digital";
|
} from "@/lib/digital";
|
||||||
import { ConversationRow, ConversationDeleteDialog } from "./conversation-row";
|
import { ConversationDeleteDialog } from "./conversation-row";
|
||||||
|
import { ConversationList } from "./conversation-list";
|
||||||
|
import { ConversationTitleDialog } from "./conversation-dialogs";
|
||||||
|
import { useChatReading } from "./use-chat-reading";
|
||||||
import { DigitalMessage } from "./digital-message";
|
import { DigitalMessage } from "./digital-message";
|
||||||
import "./digital.css";
|
import "./digital.css";
|
||||||
type Tab = DigitalTab;
|
type Tab = DigitalTab;
|
||||||
@@ -105,6 +114,22 @@ export function DigitalHome({
|
|||||||
initialConversation ?? null,
|
initialConversation ?? null,
|
||||||
);
|
);
|
||||||
const [draftReady, setDraftReady] = useState(false);
|
const [draftReady, setDraftReady] = useState(false);
|
||||||
|
const [branchTarget, setBranchTarget] = useState<Message | null>(null);
|
||||||
|
const [undo, setUndo] = useState<{
|
||||||
|
id: string;
|
||||||
|
title: string;
|
||||||
|
until: number;
|
||||||
|
} | null>(null);
|
||||||
|
const [undoBusy, setUndoBusy] = useState(false);
|
||||||
|
const undoLock = useRef(false);
|
||||||
|
const [interrupted, setInterrupted] = useState(false);
|
||||||
|
const [canRetryRequest, setCanRetryRequest] = useState(false);
|
||||||
|
const undoKey = `dh-undo:${initial.account}`;
|
||||||
|
const pendingSend = useRef<{
|
||||||
|
id: string;
|
||||||
|
requestId: string;
|
||||||
|
content: string;
|
||||||
|
} | null>(null);
|
||||||
const [draft, setDraft] = useState(""),
|
const [draft, setDraft] = useState(""),
|
||||||
[busy, setBusy] = useState(initialConversation?.busy ?? false),
|
[busy, setBusy] = useState(initialConversation?.busy ?? false),
|
||||||
[opening, setOpening] = useState(false),
|
[opening, setOpening] = useState(false),
|
||||||
@@ -129,9 +154,6 @@ export function DigitalHome({
|
|||||||
bookIds: string[];
|
bookIds: string[];
|
||||||
}>({ bookIds: [] });
|
}>({ bookIds: [] });
|
||||||
const selectionTrigger = useRef<HTMLElement | null>(null);
|
const selectionTrigger = useRef<HTMLElement | null>(null);
|
||||||
const [swipedConversation, setSwipedConversation] = useState<string | null>(
|
|
||||||
null,
|
|
||||||
);
|
|
||||||
const [deleteTarget, setDeleteTarget] = useState<Summary | null>(null),
|
const [deleteTarget, setDeleteTarget] = useState<Summary | null>(null),
|
||||||
[deleting, setDeleting] = useState(false),
|
[deleting, setDeleting] = useState(false),
|
||||||
[deleteError, setDeleteError] = useState("");
|
[deleteError, setDeleteError] = useState("");
|
||||||
@@ -275,36 +297,36 @@ export function DigitalHome({
|
|||||||
const timer = setTimeout(() => setNotice(""), 3500);
|
const timer = setTimeout(() => setNotice(""), 3500);
|
||||||
return () => clearTimeout(timer);
|
return () => clearTimeout(timer);
|
||||||
}, [notice]);
|
}, [notice]);
|
||||||
|
const unread = useChatReading(
|
||||||
|
conversationId,
|
||||||
|
viewport,
|
||||||
|
messagesElement,
|
||||||
|
atBottom,
|
||||||
|
draggingScroll,
|
||||||
|
setShowJump,
|
||||||
|
);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const el = messagesElement.current,
|
const timer = setTimeout(() => {
|
||||||
view = viewport.current;
|
try {
|
||||||
if (!el || !view) return;
|
const stored = JSON.parse(sessionStorage.getItem(undoKey) ?? "null");
|
||||||
let frame = 0;
|
if (stored?.until > Date.now()) setUndo(stored);
|
||||||
const follow = () => {
|
} catch {}
|
||||||
cancelAnimationFrame(frame);
|
}, 0);
|
||||||
frame = requestAnimationFrame(() => {
|
return () => clearTimeout(timer);
|
||||||
if (!atBottom.current) return;
|
}, [undoKey]);
|
||||||
view.scrollTo({ top: view.scrollHeight, behavior: "instant" });
|
useEffect(() => {
|
||||||
setShowJump(false);
|
if (!undo) return;
|
||||||
});
|
const timer = setTimeout(
|
||||||
};
|
() => {
|
||||||
// 同时观察内容与可视区:视觉打字、结束后的操作栏、输入框和软键盘都会改变底部位置。
|
setUndo(null);
|
||||||
const observer = new ResizeObserver(follow);
|
try {
|
||||||
observer.observe(el);
|
sessionStorage.removeItem(undoKey);
|
||||||
observer.observe(view);
|
} catch {}
|
||||||
const endDrag = () => {
|
},
|
||||||
draggingScroll.current = false;
|
Math.max(0, undo.until - Date.now()),
|
||||||
};
|
);
|
||||||
window.addEventListener("pointerup", endDrag);
|
return () => clearTimeout(timer);
|
||||||
window.addEventListener("pointercancel", endDrag);
|
}, [undo, undoKey]);
|
||||||
follow();
|
|
||||||
return () => {
|
|
||||||
observer.disconnect();
|
|
||||||
cancelAnimationFrame(frame);
|
|
||||||
window.removeEventListener("pointerup", endDrag);
|
|
||||||
window.removeEventListener("pointercancel", endDrag);
|
|
||||||
};
|
|
||||||
}, [conversationId]);
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!conversationId) return;
|
if (!conversationId) return;
|
||||||
const root = document.documentElement;
|
const root = document.documentElement;
|
||||||
@@ -351,12 +373,35 @@ export function DigitalHome({
|
|||||||
if (!conversationId) return;
|
if (!conversationId) return;
|
||||||
const frame = requestAnimationFrame(() => {
|
const frame = requestAnimationFrame(() => {
|
||||||
try {
|
try {
|
||||||
setDraft(sessionStorage.getItem(`dh-draft:${conversationId}`) ?? "");
|
const storedDraft =
|
||||||
|
sessionStorage.getItem(`dh-draft:${conversationId}`) ?? "";
|
||||||
|
setDraft(storedDraft);
|
||||||
|
const pending = JSON.parse(
|
||||||
|
sessionStorage.getItem(`dh-pending:${conversationId}`) ?? "null",
|
||||||
|
);
|
||||||
|
if (
|
||||||
|
pending?.id === conversationId &&
|
||||||
|
typeof pending.content === "string" &&
|
||||||
|
/^[a-f0-9-]{36}$/.test(pending.requestId)
|
||||||
|
) {
|
||||||
|
if (
|
||||||
|
initialConversation?.messages.some(
|
||||||
|
(m) => m.requestId === pending.requestId,
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
sessionStorage.removeItem(`dh-pending:${conversationId}`);
|
||||||
|
if (storedDraft === pending.content) setDraft("");
|
||||||
|
} else {
|
||||||
|
pendingSend.current = pending;
|
||||||
|
setCanRetryRequest(true);
|
||||||
|
setInterrupted(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
setDraftReady(true);
|
setDraftReady(true);
|
||||||
});
|
});
|
||||||
return () => cancelAnimationFrame(frame);
|
return () => cancelAnimationFrame(frame);
|
||||||
}, [conversationId]);
|
}, [conversationId, initialConversation]);
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!conversationId || !draftReady) return;
|
if (!conversationId || !draftReady) return;
|
||||||
try {
|
try {
|
||||||
@@ -454,7 +499,9 @@ export function DigitalHome({
|
|||||||
`conversations/${conversationId}`,
|
`conversations/${conversationId}`,
|
||||||
);
|
);
|
||||||
if (!cancelled && currentId.current === conversationId) {
|
if (!cancelled && currentId.current === conversationId) {
|
||||||
setConversation(saved);
|
setConversation((current) =>
|
||||||
|
mergeConversationSnapshot(current, saved),
|
||||||
|
);
|
||||||
setBusy(saved.busy);
|
setBusy(saved.busy);
|
||||||
}
|
}
|
||||||
} catch {}
|
} catch {}
|
||||||
@@ -471,7 +518,6 @@ export function DigitalHome({
|
|||||||
}
|
}
|
||||||
closeIdeas();
|
closeIdeas();
|
||||||
imeComposing.current = false;
|
imeComposing.current = false;
|
||||||
setSwipedConversation(null);
|
|
||||||
if (streamingId.current && streamingId.current !== id) {
|
if (streamingId.current && streamingId.current !== id) {
|
||||||
setNotice("请先停止当前回复,再切换会话");
|
setNotice("请先停止当前回复,再切换会话");
|
||||||
return;
|
return;
|
||||||
@@ -509,6 +555,11 @@ export function DigitalHome({
|
|||||||
const c = await digital<{ id: string }>("conversations", "POST", {
|
const c = await digital<{ id: string }>("conversations", "POST", {
|
||||||
characterId: card.id,
|
characterId: card.id,
|
||||||
greetingIndex: index,
|
greetingIndex: index,
|
||||||
|
recommendationReceiptId:
|
||||||
|
searchParams.get("recommendation") ===
|
||||||
|
recommendationReceipt(initial.account, card.id)
|
||||||
|
? recommendationReceipt(initial.account, card.id)
|
||||||
|
: undefined,
|
||||||
uiDecisionId: boot?.decision.decisionId ?? undefined,
|
uiDecisionId: boot?.decision.decisionId ?? undefined,
|
||||||
});
|
});
|
||||||
router.push(chatPath(c.id));
|
router.push(chatPath(c.id));
|
||||||
@@ -541,18 +592,44 @@ export function DigitalHome({
|
|||||||
favoritePending.current = false;
|
favoritePending.current = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function send(mode: "send" | "regenerate" | "continue" = "send") {
|
function clearPendingSend(id: string) {
|
||||||
|
pendingSend.current = null;
|
||||||
|
setCanRetryRequest(false);
|
||||||
|
try {
|
||||||
|
sessionStorage.removeItem(`dh-pending:${id}`);
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
async function send(
|
||||||
|
mode: "send" | "regenerate" | "continue" = "send",
|
||||||
|
retryContent?: string,
|
||||||
|
) {
|
||||||
if (
|
if (
|
||||||
!conversation ||
|
!conversation ||
|
||||||
busy ||
|
busy ||
|
||||||
streamingId.current ||
|
streamingId.current ||
|
||||||
(mode === "send" && !draft.trim())
|
(mode === "send" && !(retryContent ?? draft).trim())
|
||||||
)
|
)
|
||||||
return;
|
return;
|
||||||
closeIdeas();
|
closeIdeas();
|
||||||
const id = conversation.id,
|
const id = conversation.id,
|
||||||
content = mode === "send" ? draft.trim() : "",
|
content = mode === "send" ? (retryContent ?? draft).trim() : "",
|
||||||
requestId = crypto.randomUUID();
|
requestId =
|
||||||
|
mode === "send" &&
|
||||||
|
pendingSend.current?.id === id &&
|
||||||
|
pendingSend.current.content === (retryContent ?? draft).trim()
|
||||||
|
? pendingSend.current.requestId
|
||||||
|
: crypto.randomUUID();
|
||||||
|
if (mode === "send") {
|
||||||
|
pendingSend.current = { id, requestId, content };
|
||||||
|
setCanRetryRequest(true);
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(
|
||||||
|
`dh-pending:${id}`,
|
||||||
|
JSON.stringify(pendingSend.current),
|
||||||
|
);
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
setInterrupted(false);
|
||||||
let assistantId = `pending-${requestId}`;
|
let assistantId = `pending-${requestId}`;
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
setError("");
|
setError("");
|
||||||
@@ -585,7 +662,19 @@ export function DigitalHome({
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
setConversation((c) =>
|
setConversation((c) =>
|
||||||
c && c.id === id ? { ...c, messages: [...c.messages, ...local] } : c,
|
c && c.id === id
|
||||||
|
? {
|
||||||
|
...c,
|
||||||
|
messages: [
|
||||||
|
...c.messages.filter(
|
||||||
|
(m) =>
|
||||||
|
m.id !== `user-${requestId}` &&
|
||||||
|
m.id !== `pending-${requestId}`,
|
||||||
|
),
|
||||||
|
...local,
|
||||||
|
],
|
||||||
|
}
|
||||||
|
: c,
|
||||||
);
|
);
|
||||||
setActiveMessage(assistantId);
|
setActiveMessage(assistantId);
|
||||||
const controller = new AbortController();
|
const controller = new AbortController();
|
||||||
@@ -641,7 +730,8 @@ export function DigitalHome({
|
|||||||
}
|
}
|
||||||
: c,
|
: c,
|
||||||
);
|
);
|
||||||
if (event === "done")
|
if (event === "done") {
|
||||||
|
clearPendingSend(id);
|
||||||
setConversation((c) =>
|
setConversation((c) =>
|
||||||
c && c.id === id
|
c && c.id === id
|
||||||
? {
|
? {
|
||||||
@@ -654,11 +744,25 @@ export function DigitalHome({
|
|||||||
}
|
}
|
||||||
: c,
|
: c,
|
||||||
);
|
);
|
||||||
|
}
|
||||||
if (event === "notice" || event === "error")
|
if (event === "notice" || event === "error")
|
||||||
setNotice(String(data.message ?? ""));
|
setNotice(String(data.message ?? ""));
|
||||||
});
|
});
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
if (!controller.signal.aborted) reportError(e);
|
if (!controller.signal.aborted) {
|
||||||
|
reportError(e);
|
||||||
|
setInterrupted(true);
|
||||||
|
}
|
||||||
|
setConversation((c) =>
|
||||||
|
c?.id === id
|
||||||
|
? {
|
||||||
|
...c,
|
||||||
|
messages: c.messages.map((m) =>
|
||||||
|
m.id === assistantId ? { ...m, status: "stopped" } : m,
|
||||||
|
),
|
||||||
|
}
|
||||||
|
: c,
|
||||||
|
);
|
||||||
if (!accepted && mode === "send") setDraft(content);
|
if (!accepted && mode === "send") setDraft(content);
|
||||||
} finally {
|
} finally {
|
||||||
streamingId.current = null;
|
streamingId.current = null;
|
||||||
@@ -669,8 +773,16 @@ export function DigitalHome({
|
|||||||
if (currentId.current === id)
|
if (currentId.current === id)
|
||||||
try {
|
try {
|
||||||
const saved = await digital<Conversation>(`conversations/${id}`);
|
const saved = await digital<Conversation>(`conversations/${id}`);
|
||||||
setConversation(saved);
|
setConversation((current) =>
|
||||||
|
mergeConversationSnapshot(current, saved),
|
||||||
|
);
|
||||||
setBusy(saved.busy);
|
setBusy(saved.busy);
|
||||||
|
if (
|
||||||
|
saved.messages.some(
|
||||||
|
(m) => m.requestId === pendingSend.current?.requestId,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
clearPendingSend(id);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
reportError(e);
|
reportError(e);
|
||||||
}
|
}
|
||||||
@@ -723,17 +835,17 @@ export function DigitalHome({
|
|||||||
reportError(e);
|
reportError(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
async function branch(message: Message) {
|
async function branch(message: Message, title: string) {
|
||||||
if (!conversation || busy) return;
|
if (!conversation || busy) return;
|
||||||
try {
|
try {
|
||||||
const result = await digital<{ id: string }>(
|
const result = await digital<{ id: string }>(
|
||||||
`conversations/${conversation.id}/branch`,
|
`conversations/${conversation.id}/branch`,
|
||||||
"POST",
|
"POST",
|
||||||
{ messageId: message.id },
|
{ messageId: message.id, title },
|
||||||
);
|
);
|
||||||
router.push(chatPath(result.id));
|
router.push(chatPath(result.id));
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
reportError(e);
|
throw e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function requestDelete(target: Summary) {
|
function requestDelete(target: Summary) {
|
||||||
@@ -761,9 +873,11 @@ export function DigitalHome({
|
|||||||
setDeleting(true);
|
setDeleting(true);
|
||||||
setDeleteError("");
|
setDeleteError("");
|
||||||
try {
|
try {
|
||||||
await digital(`conversations/${id}`, "DELETE");
|
const removed = await digital<{ undoUntil: number }>(
|
||||||
|
`conversations/${id}`,
|
||||||
|
"DELETE",
|
||||||
|
);
|
||||||
setSummaries((current) => current.filter((s) => s.id !== id));
|
setSummaries((current) => current.filter((s) => s.id !== id));
|
||||||
setSwipedConversation(null);
|
|
||||||
if (currentId.current === id) {
|
if (currentId.current === id) {
|
||||||
closeIdeas();
|
closeIdeas();
|
||||||
currentId.current = null;
|
currentId.current = null;
|
||||||
@@ -773,8 +887,17 @@ export function DigitalHome({
|
|||||||
try {
|
try {
|
||||||
sessionStorage.removeItem(`dh-draft:${id}`);
|
sessionStorage.removeItem(`dh-draft:${id}`);
|
||||||
} catch {}
|
} catch {}
|
||||||
|
const entry = {
|
||||||
|
id,
|
||||||
|
title: deleteTarget.title,
|
||||||
|
until: removed.undoUntil,
|
||||||
|
};
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(undoKey, JSON.stringify(entry));
|
||||||
|
} catch {}
|
||||||
|
setUndo(entry);
|
||||||
setDeleteTarget(null);
|
setDeleteTarget(null);
|
||||||
setNotice("对话已删除");
|
setNotice("对话已删除,可在 30 秒内撤销");
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
setDeleteError(e instanceof Error ? e.message : "删除失败,请重试");
|
setDeleteError(e instanceof Error ? e.message : "删除失败,请重试");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -809,7 +932,7 @@ export function DigitalHome({
|
|||||||
}>(
|
}>(
|
||||||
`conversations/${id}/suggestions`,
|
`conversations/${id}/suggestions`,
|
||||||
"POST",
|
"POST",
|
||||||
{ draft: draft.slice(0, 1000) },
|
{ draft: draft.slice(0, 1000), requestId: crypto.randomUUID() },
|
||||||
controller.signal,
|
controller.signal,
|
||||||
);
|
);
|
||||||
if (ideasRequest.current !== controller || currentId.current !== id)
|
if (ideasRequest.current !== controller || currentId.current !== id)
|
||||||
@@ -1077,8 +1200,7 @@ export function DigitalHome({
|
|||||||
>
|
>
|
||||||
<aside className="dh-sidebar">
|
<aside className="dh-sidebar">
|
||||||
<Link className="dh-brand" href="/discover">
|
<Link className="dh-brand" href="/discover">
|
||||||
<span className="dh-brand-mark">✦</span> 星港
|
<span className="dh-brand-mark">✦</span> 个人数字人
|
||||||
<span className="dh-brand-en">STELLAR</span>
|
|
||||||
</Link>
|
</Link>
|
||||||
<p className="dh-sidebar-caption">每一段相遇,都有下一章</p>
|
<p className="dh-sidebar-caption">每一段相遇,都有下一章</p>
|
||||||
<nav aria-label="主要导航">
|
<nav aria-label="主要导航">
|
||||||
@@ -1134,7 +1256,7 @@ export function DigitalHome({
|
|||||||
{!boot ? (
|
{!boot ? (
|
||||||
<div className="dh-loading">
|
<div className="dh-loading">
|
||||||
<LoaderCircle className="dh-spin" />
|
<LoaderCircle className="dh-spin" />
|
||||||
<span>正在开启你的星港…</span>
|
<span>正在加载数字人空间…</span>
|
||||||
</div>
|
</div>
|
||||||
) : conversation ? (
|
) : conversation ? (
|
||||||
<section className="dh-chat">
|
<section className="dh-chat">
|
||||||
@@ -1230,7 +1352,7 @@ export function DigitalHome({
|
|||||||
}}
|
}}
|
||||||
onScroll={() => {
|
onScroll={() => {
|
||||||
const v = viewport.current;
|
const v = viewport.current;
|
||||||
if (v) {
|
if (v?.isConnected && v.clientHeight > 0) {
|
||||||
const gap = v.scrollHeight - v.scrollTop - v.clientHeight;
|
const gap = v.scrollHeight - v.scrollTop - v.clientHeight;
|
||||||
if (gap <= 2) atBottom.current = true;
|
if (gap <= 2) atBottom.current = true;
|
||||||
else if (draggingScroll.current) atBottom.current = false;
|
else if (draggingScroll.current) atBottom.current = false;
|
||||||
@@ -1239,6 +1361,78 @@ export function DigitalHome({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div ref={messagesElement} className="dh-messages-inner">
|
<div ref={messagesElement} className="dh-messages-inner">
|
||||||
|
{conversation.parent && (
|
||||||
|
<p className="dh-branch-source">
|
||||||
|
分支自「{conversation.parent.title}」{" "}
|
||||||
|
{conversation.parent.available ? (
|
||||||
|
<Link
|
||||||
|
href={{
|
||||||
|
pathname: chatPath(
|
||||||
|
conversation.parent.conversationId,
|
||||||
|
),
|
||||||
|
hash: `message-${conversation.parent.messageId}`,
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
回到原故事
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
"(原会话已删除或不可用)"
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{interrupted && (
|
||||||
|
<div className="dh-recovery" role="status">
|
||||||
|
<strong>连接已中断,已显示的内容会保留</strong>
|
||||||
|
<p>
|
||||||
|
先同步服务器结果,避免重复发送;已有部分回复可使用“继续”,需要替换回答时再重新生成。
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
disabled={busy}
|
||||||
|
onClick={async () => {
|
||||||
|
try {
|
||||||
|
const saved = await digital<Conversation>(
|
||||||
|
`conversations/${conversation.id}`,
|
||||||
|
);
|
||||||
|
setConversation((current) =>
|
||||||
|
mergeConversationSnapshot(current, saved),
|
||||||
|
);
|
||||||
|
setBusy(saved.busy);
|
||||||
|
if (
|
||||||
|
saved.messages.some(
|
||||||
|
(m) =>
|
||||||
|
m.requestId === pendingSend.current?.requestId,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
clearPendingSend(saved.id);
|
||||||
|
if (!saved.busy) setInterrupted(false);
|
||||||
|
} catch (e) {
|
||||||
|
reportError(e);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
同步聊天记录
|
||||||
|
</button>
|
||||||
|
{canRetryRequest && (
|
||||||
|
<button
|
||||||
|
disabled={busy}
|
||||||
|
onClick={() =>
|
||||||
|
send("send", pendingSend.current?.content)
|
||||||
|
}
|
||||||
|
>
|
||||||
|
重试本次请求
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<GrowthJourney account={initial.account} page="chat" />
|
||||||
|
<GrowthChat
|
||||||
|
account={initial.account}
|
||||||
|
conversation={conversation.id}
|
||||||
|
busy={busy}
|
||||||
|
onExpanded={() => {
|
||||||
|
atBottom.current = false;
|
||||||
|
}}
|
||||||
|
/>
|
||||||
<div className="dh-chat-intro">
|
<div className="dh-chat-intro">
|
||||||
<span>✦</span>
|
<span>✦</span>
|
||||||
<p>这里是你与 {currentCard?.name} 的私人故事</p>
|
<p>这里是你与 {currentCard?.name} 的私人故事</p>
|
||||||
@@ -1246,6 +1440,9 @@ export function DigitalHome({
|
|||||||
</div>
|
</div>
|
||||||
{conversation.messages.map((m, index) => (
|
{conversation.messages.map((m, index) => (
|
||||||
<article
|
<article
|
||||||
|
id={`message-${m.id}`}
|
||||||
|
data-message-id={m.id}
|
||||||
|
data-message-length={m.content.length}
|
||||||
className={`dh-message dh-message-${m.role}`}
|
className={`dh-message dh-message-${m.role}`}
|
||||||
key={m.id}
|
key={m.id}
|
||||||
>
|
>
|
||||||
@@ -1291,7 +1488,7 @@ export function DigitalHome({
|
|||||||
<button
|
<button
|
||||||
aria-label="从此处分支"
|
aria-label="从此处分支"
|
||||||
title="从此处创建分支"
|
title="从此处创建分支"
|
||||||
onClick={() => branch(m)}
|
onClick={() => setBranchTarget(m)}
|
||||||
>
|
>
|
||||||
<GitBranch size={13} />
|
<GitBranch size={13} />
|
||||||
</button>
|
</button>
|
||||||
@@ -1325,6 +1522,16 @@ export function DigitalHome({
|
|||||||
<RefreshCw size={13} /> 重新生成
|
<RefreshCw size={13} /> 重新生成
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
{!busy &&
|
||||||
|
m.role === "assistant" &&
|
||||||
|
!!m.requestId &&
|
||||||
|
m.status !== "generating" && (
|
||||||
|
<ReplyFeedback
|
||||||
|
account={initial.account}
|
||||||
|
conversation={conversation.id}
|
||||||
|
messageId={m.id}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{m.status === "failed" && (
|
{m.status === "failed" && (
|
||||||
<small className="dh-message-status">
|
<small className="dh-message-status">
|
||||||
生成失败,可重新生成
|
生成失败,可重新生成
|
||||||
@@ -1334,7 +1541,9 @@ export function DigitalHome({
|
|||||||
<small className="dh-message-status">此前回答</small>
|
<small className="dh-message-status">此前回答</small>
|
||||||
)}
|
)}
|
||||||
{m.status === "stopped" && (
|
{m.status === "stopped" && (
|
||||||
<small className="dh-message-status">已停止</small>
|
<small className="dh-message-status">
|
||||||
|
回复已中止 · 已保留现有内容
|
||||||
|
</small>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</article>
|
</article>
|
||||||
@@ -1354,7 +1563,7 @@ export function DigitalHome({
|
|||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<ChevronDown size={16} />
|
<ChevronDown size={16} />
|
||||||
回到最新
|
{unread ? "有新回复 · 回到最新" : "回到最新"}
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
<div className="dh-composer-wrap">
|
<div className="dh-composer-wrap">
|
||||||
@@ -1520,8 +1729,57 @@ export function DigitalHome({
|
|||||||
✦
|
✦
|
||||||
</span>
|
</span>
|
||||||
</header>
|
</header>
|
||||||
|
<GrowthJourney
|
||||||
|
account={initial.account}
|
||||||
|
page={tab === "me" ? "profile" : tab}
|
||||||
|
/>
|
||||||
{tab === "discover" && (
|
{tab === "discover" && (
|
||||||
<>
|
<>
|
||||||
|
{!detail && (
|
||||||
|
<GrowthRecommendations
|
||||||
|
account={initial.account}
|
||||||
|
cards={cards}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
{summaries.length > 0 && (
|
||||||
|
<section aria-label="继续最近聊天">
|
||||||
|
<h2>继续最近聊天</h2>
|
||||||
|
<div className="dh-recent-stories">
|
||||||
|
{[...summaries]
|
||||||
|
.sort(
|
||||||
|
(a, b) =>
|
||||||
|
Date.parse(b.updatedAt) - Date.parse(a.updatedAt),
|
||||||
|
)
|
||||||
|
.slice(0, 3)
|
||||||
|
.map((item) => (
|
||||||
|
<Link key={item.id} href={chatPath(item.id)}>
|
||||||
|
{item.title}
|
||||||
|
<small>
|
||||||
|
{" "}
|
||||||
|
·{" "}
|
||||||
|
{item.lastMessage?.slice(0, 36) ||
|
||||||
|
"继续未完的故事"}
|
||||||
|
</small>
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
{!!profile?.favorites.length && (
|
||||||
|
<section aria-label="收藏角色">
|
||||||
|
<h2>收藏角色</h2>
|
||||||
|
<div className="dh-recent-stories">
|
||||||
|
{cards
|
||||||
|
.filter((card) => profile.favorites.includes(card.id))
|
||||||
|
.slice(0, 4)
|
||||||
|
.map((card) => (
|
||||||
|
<Link key={card.id} href={contentPath(card)}>
|
||||||
|
{card.name}
|
||||||
|
</Link>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
<section className="dh-hero">
|
<section className="dh-hero">
|
||||||
<div>
|
<div>
|
||||||
<span className="dh-pill">今晚,有人等你开口</span>
|
<span className="dh-pill">今晚,有人等你开口</span>
|
||||||
@@ -1600,9 +1858,17 @@ export function DigitalHome({
|
|||||||
<h2>{onlyFavorites ? "心动收藏" : "为你发现"}</h2>
|
<h2>{onlyFavorites ? "心动收藏" : "为你发现"}</h2>
|
||||||
<span>{filtered.length} 位角色 · 全部成年</span>
|
<span>{filtered.length} 位角色 · 全部成年</span>
|
||||||
</div>
|
</div>
|
||||||
|
<CatalogExposure
|
||||||
|
account={initial.account}
|
||||||
|
cardIds={filtered.map((c) => c.id).join(",")}
|
||||||
|
/>
|
||||||
<div className="dh-card-grid">
|
<div className="dh-card-grid">
|
||||||
{filtered.map((c) => (
|
{filtered.map((c) => (
|
||||||
<article className="dh-card" key={c.id}>
|
<article
|
||||||
|
className="dh-card"
|
||||||
|
data-growth-card={c.id}
|
||||||
|
key={c.id}
|
||||||
|
>
|
||||||
<Link className="dh-card-open" href={contentPath(c)}>
|
<Link className="dh-card-open" href={contentPath(c)}>
|
||||||
<img
|
<img
|
||||||
src={c.cover || "/icon.svg"}
|
src={c.cover || "/icon.svg"}
|
||||||
@@ -1672,19 +1938,14 @@ export function DigitalHome({
|
|||||||
{summaries.length > 0 && (
|
{summaries.length > 0 && (
|
||||||
<p className="dh-swipe-hint">向左滑动对话可删除</p>
|
<p className="dh-swipe-hint">向左滑动对话可删除</p>
|
||||||
)}
|
)}
|
||||||
<div className="dh-conversation-list">
|
<ConversationList
|
||||||
{summaries.map((s) => (
|
summaries={summaries}
|
||||||
<ConversationRow
|
cards={cards}
|
||||||
key={s.id}
|
disabled={deleting}
|
||||||
summary={s}
|
onDelete={requestDelete}
|
||||||
card={cards.find((c) => c.id === s.characterId)}
|
onRefresh={refreshSummaries}
|
||||||
revealed={swipedConversation === s.id}
|
onNotice={setNotice}
|
||||||
disabled={opening || deleting}
|
|
||||||
onReveal={setSwipedConversation}
|
|
||||||
onDelete={() => requestDelete(s)}
|
|
||||||
/>
|
/>
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
{!summaries.length && (
|
{!summaries.length && (
|
||||||
<div className="dh-empty">
|
<div className="dh-empty">
|
||||||
<MessageCircle />
|
<MessageCircle />
|
||||||
@@ -1745,6 +2006,9 @@ export function DigitalHome({
|
|||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
|
{tab === "me" && (
|
||||||
|
<GrowthProfile account={initial.account} cards={cards} />
|
||||||
|
)}
|
||||||
{tab === "me" && profile && profileDraft && (
|
{tab === "me" && profile && profileDraft && (
|
||||||
<form className="dh-profile-form" onSubmit={saveProfile}>
|
<form className="dh-profile-form" onSubmit={saveProfile}>
|
||||||
<div className="dh-profile-banner">
|
<div className="dh-profile-banner">
|
||||||
@@ -1776,7 +2040,7 @@ export function DigitalHome({
|
|||||||
rows={6}
|
rows={6}
|
||||||
value={profileDraft.persona}
|
value={profileDraft.persona}
|
||||||
maxLength={2000}
|
maxLength={2000}
|
||||||
placeholder="例如:独自在星港旅行的摄影师,喜欢雨天和旧唱片。"
|
placeholder="例如:独自旅行的摄影师,喜欢雨天和旧唱片。"
|
||||||
onChange={(e) =>
|
onChange={(e) =>
|
||||||
setProfileDraft({
|
setProfileDraft({
|
||||||
...profileDraft,
|
...profileDraft,
|
||||||
@@ -1786,7 +2050,8 @@ export function DigitalHome({
|
|||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<p className="dh-form-note">
|
<p className="dh-form-note">
|
||||||
此资料可在新会话的「对话设定」中使用。每个会话的设定相互独立。
|
账号称呼与身份仅作为新会话的默认值;已有会话保留自己的设定。NSFW
|
||||||
|
开关保存后影响所有会话的后续回复。
|
||||||
</p>
|
</p>
|
||||||
<label className="dh-content-preference">
|
<label className="dh-content-preference">
|
||||||
<span>
|
<span>
|
||||||
@@ -1832,12 +2097,20 @@ export function DigitalHome({
|
|||||||
</form>
|
</form>
|
||||||
)}
|
)}
|
||||||
<footer className="dh-footer">
|
<footer className="dh-footer">
|
||||||
星港 STELLAR <span>✧</span> 虚构相遇,真实灵感
|
个人数字人 <span>✧</span> 虚构相遇,真实灵感
|
||||||
</footer>
|
</footer>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{detail && (
|
{detail && (
|
||||||
<div className="dh-detail-page">
|
<div className="dh-detail-page">
|
||||||
|
<GrowthJourney account={initial.account} page="detail" />
|
||||||
|
{detail.kind === "character" && (
|
||||||
|
<CardOpenTracker
|
||||||
|
account={initial.account}
|
||||||
|
cardId={detail.id}
|
||||||
|
receipt={searchParams.get("recommendation")}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
<header className="dh-detail-nav">
|
<header className="dh-detail-nav">
|
||||||
<button className="dh-detail-back" onClick={goBack}>
|
<button className="dh-detail-back" onClick={goBack}>
|
||||||
<ArrowLeft size={18} />
|
<ArrowLeft size={18} />
|
||||||
@@ -1875,13 +2148,17 @@ export function DigitalHome({
|
|||||||
<span key={t}>{t}</span>
|
<span key={t}>{t}</span>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
<h2>故事与背景</h2>
|
||||||
<p className="dh-detail-description">{detail.description}</p>
|
<p className="dh-detail-description">{detail.description}</p>
|
||||||
{detail.greeting && (
|
{detail.greeting && (
|
||||||
|
<>
|
||||||
|
<h2>开场预览</h2>
|
||||||
<blockquote>
|
<blockquote>
|
||||||
{detail.greeting
|
{detail.greeting
|
||||||
.replaceAll("{{user}}", profile?.userName ?? "旅人")
|
.replaceAll("{{user}}", profile?.userName ?? "旅人")
|
||||||
.replaceAll("{{char}}", detail.name)}
|
.replaceAll("{{char}}", detail.name)}
|
||||||
</blockquote>
|
</blockquote>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
{detail.kind === "character" ? (
|
{detail.kind === "character" ? (
|
||||||
<>
|
<>
|
||||||
@@ -1898,15 +2175,20 @@ export function DigitalHome({
|
|||||||
开启这段故事
|
开启这段故事
|
||||||
</button>
|
</button>
|
||||||
{detail.alternateGreetings.map((g, i) => (
|
{detail.alternateGreetings.map((g, i) => (
|
||||||
|
<details className="dh-alt-greeting" key={i}>
|
||||||
|
<summary>另一种相遇 {i + 1} · 预览</summary>
|
||||||
|
<p>
|
||||||
|
{g
|
||||||
|
.replaceAll("{{user}}", profile?.userName ?? "旅人")
|
||||||
|
.replaceAll("{{char}}", detail.name)}
|
||||||
|
</p>
|
||||||
<button
|
<button
|
||||||
className="dh-alt-greeting"
|
|
||||||
key={i}
|
|
||||||
disabled={opening}
|
disabled={opening}
|
||||||
onClick={() => start(detail, i + 1)}
|
onClick={() => start(detail, i + 1)}
|
||||||
>
|
>
|
||||||
<small>另一种相遇 {i + 1}</small>
|
使用这个开场
|
||||||
<p>{g.slice(0, 110)}</p>
|
|
||||||
</button>
|
</button>
|
||||||
|
</details>
|
||||||
))}
|
))}
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
@@ -1935,6 +2217,9 @@ export function DigitalHome({
|
|||||||
<div>
|
<div>
|
||||||
<span className="dh-eyebrow">MAKE IT YOUR STORY</span>
|
<span className="dh-eyebrow">MAKE IT YOUR STORY</span>
|
||||||
<h2>对话设定</h2>
|
<h2>对话设定</h2>
|
||||||
|
<p className="dh-form-note">
|
||||||
|
只影响当前这段对话的后续回复,不修改账号身份、其他对话或已发送的消息。角色默认设定会作为未选择项目的基础。
|
||||||
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -1946,6 +2231,21 @@ export function DigitalHome({
|
|||||||
</button>
|
</button>
|
||||||
</header>
|
</header>
|
||||||
<div className="dh-settings-body">
|
<div className="dh-settings-body">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() =>
|
||||||
|
setSettings({
|
||||||
|
...settings,
|
||||||
|
userName: profile?.userName ?? "旅人",
|
||||||
|
persona: profile?.persona ?? "",
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
将账号身份填入本次设定
|
||||||
|
</button>
|
||||||
|
<p className="dh-form-note">
|
||||||
|
仅填入下方草稿,点击保存后才对当前会话生效。
|
||||||
|
</p>
|
||||||
<label>
|
<label>
|
||||||
你的称呼
|
你的称呼
|
||||||
<input
|
<input
|
||||||
@@ -2129,6 +2429,47 @@ export function DigitalHome({
|
|||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
{undo && (
|
||||||
|
<div className="dh-undo" role="status">
|
||||||
|
<span>已删除「{undo.title}」 · 30 秒内可撤销</span>
|
||||||
|
<button
|
||||||
|
disabled={undoBusy}
|
||||||
|
onClick={async () => {
|
||||||
|
if (undoLock.current) return;
|
||||||
|
undoLock.current = true;
|
||||||
|
setUndoBusy(true);
|
||||||
|
try {
|
||||||
|
await digital(`conversations/${undo.id}/restore`, "POST", {});
|
||||||
|
setUndo(null);
|
||||||
|
sessionStorage.removeItem(undoKey);
|
||||||
|
await refreshSummaries();
|
||||||
|
setNotice("对话已恢复");
|
||||||
|
} catch (e) {
|
||||||
|
reportError(e);
|
||||||
|
} finally {
|
||||||
|
undoLock.current = false;
|
||||||
|
setUndoBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{undoBusy ? "恢复中…" : "撤销删除"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{branchTarget && (
|
||||||
|
<ConversationTitleDialog
|
||||||
|
heading="从这里开启分支"
|
||||||
|
initialTitle={`${conversation?.title.slice(0, 100) ?? "故事"} · 分支`}
|
||||||
|
preview={
|
||||||
|
<>
|
||||||
|
<p>原故事会保留,新分支复制到下方这条消息为止。</p>
|
||||||
|
<blockquote>{branchTarget.content.slice(0, 240)}</blockquote>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
onCancel={() => setBranchTarget(null)}
|
||||||
|
onSubmit={(title) => branch(branchTarget, title)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{deleteTarget && (
|
{deleteTarget && (
|
||||||
<ConversationDeleteDialog
|
<ConversationDeleteDialog
|
||||||
title={deleteTarget.title}
|
title={deleteTarget.title}
|
||||||
@@ -2143,3 +2484,57 @@ export function DigitalHome({
|
|||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 独立详情路由打开也计入漏斗;推荐入口已上报的点击由回执事件去重链路承接。 */
|
||||||
|
function CardOpenTracker({
|
||||||
|
account,
|
||||||
|
cardId,
|
||||||
|
receipt,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
cardId: string;
|
||||||
|
receipt: string | null;
|
||||||
|
}) {
|
||||||
|
const seen = useRef("");
|
||||||
|
useEffect(() => {
|
||||||
|
if (seen.current === `${cardId}:${receipt}`) return;
|
||||||
|
seen.current = `${cardId}:${receipt}`;
|
||||||
|
const source =
|
||||||
|
receipt === recommendationReceipt(account, cardId) ? receipt : undefined;
|
||||||
|
if (source)
|
||||||
|
trackGrowth(account, "recommendation_exposure", undefined, source);
|
||||||
|
trackGrowth(account, "card_open", cardId, source ?? undefined);
|
||||||
|
void flushGrowth(account);
|
||||||
|
}, [account, cardId, receipt]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
/** 普通发现列表也只在可见时记曝光,筛选重渲染不会重复统计同一张卡。 */
|
||||||
|
function CatalogExposure({
|
||||||
|
account,
|
||||||
|
cardIds,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
cardIds: string;
|
||||||
|
}) {
|
||||||
|
const seen = useRef(new Set<string>());
|
||||||
|
useEffect(() => {
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
for (const entry of entries) {
|
||||||
|
const id = (entry.target as HTMLElement).dataset.growthCard;
|
||||||
|
if (entry.isIntersecting && id && !seen.current.has(id)) {
|
||||||
|
seen.current.add(id);
|
||||||
|
trackGrowth(account, "card_impression", id);
|
||||||
|
observer.unobserve(entry.target);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ threshold: 0.5 },
|
||||||
|
);
|
||||||
|
document
|
||||||
|
.querySelectorAll("[data-growth-card]")
|
||||||
|
.forEach((e) => observer.observe(e));
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [account, cardIds]);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|||||||
@@ -30,12 +30,6 @@
|
|||||||
font-size: 26px;
|
font-size: 26px;
|
||||||
color: #f4eef4;
|
color: #f4eef4;
|
||||||
}
|
}
|
||||||
.stellar-login-brand small {
|
|
||||||
font-size: 9px;
|
|
||||||
letter-spacing: 3px;
|
|
||||||
display: block;
|
|
||||||
color: #b09da9;
|
|
||||||
}
|
|
||||||
.stellar-login-story > div > p {
|
.stellar-login-story > div > p {
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
letter-spacing: 4px;
|
letter-spacing: 4px;
|
||||||
@@ -80,27 +74,6 @@
|
|||||||
.stellar-login-panel > .login-form {
|
.stellar-login-panel > .login-form {
|
||||||
gap: 20px;
|
gap: 20px;
|
||||||
}
|
}
|
||||||
.stellar-login-panel .login-form label {
|
|
||||||
color: #c5b7c9;
|
|
||||||
font-size: 12px;
|
|
||||||
}
|
|
||||||
.stellar-login-panel .input-wrap {
|
|
||||||
background: #211c25;
|
|
||||||
border: 1px solid #ffffff18;
|
|
||||||
border-radius: 10px;
|
|
||||||
color: #ac9bb2;
|
|
||||||
}
|
|
||||||
.stellar-login-panel .input-wrap:focus-within {
|
|
||||||
border-color: #e0b88888;
|
|
||||||
}
|
|
||||||
.stellar-login-panel input {
|
|
||||||
color: #f4eef4;
|
|
||||||
font-size: 16px;
|
|
||||||
background: none;
|
|
||||||
}
|
|
||||||
.stellar-login-panel input::placeholder {
|
|
||||||
color: #796d80;
|
|
||||||
}
|
|
||||||
.stellar-login-panel .primary-button {
|
.stellar-login-panel .primary-button {
|
||||||
background: #e0b888;
|
background: #e0b888;
|
||||||
color: #2b1d11;
|
color: #2b1d11;
|
||||||
@@ -118,9 +91,6 @@
|
|||||||
.stellar-login-panel .form-error {
|
.stellar-login-panel .form-error {
|
||||||
color: #ffa6a6;
|
color: #ffa6a6;
|
||||||
}
|
}
|
||||||
.stellar-login-panel .icon-button {
|
|
||||||
color: #b3a1b9;
|
|
||||||
}
|
|
||||||
@media (max-width: 767px) {
|
@media (max-width: 767px) {
|
||||||
.stellar-login {
|
.stellar-login {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
@@ -137,9 +107,6 @@
|
|||||||
.stellar-login-brand span {
|
.stellar-login-brand span {
|
||||||
font-size: 21px;
|
font-size: 21px;
|
||||||
}
|
}
|
||||||
.stellar-login-brand small {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.stellar-login-story > div {
|
.stellar-login-story > div {
|
||||||
padding-top: 30px;
|
padding-top: 30px;
|
||||||
}
|
}
|
||||||
|
|||||||
+18
-12
@@ -1,4 +1,4 @@
|
|||||||
/* 星港双方案视觉:沿用现有项目的深色金色与深色粉色基调,独立组织响应式页面。 */
|
/* 个人数字人双方案视觉:沿用现有项目的深色金色与深色粉色基调,独立组织响应式页面。 */
|
||||||
.dh-app {
|
.dh-app {
|
||||||
--dh-bg: #141218;
|
--dh-bg: #141218;
|
||||||
--dh-panel: #201c23;
|
--dh-panel: #201c23;
|
||||||
@@ -103,14 +103,6 @@
|
|||||||
font-size: 34px;
|
font-size: 34px;
|
||||||
color: var(--dh-accent);
|
color: var(--dh-accent);
|
||||||
}
|
}
|
||||||
.dh-brand-en {
|
|
||||||
font-size: 9px;
|
|
||||||
font-weight: 500;
|
|
||||||
letter-spacing: 2.5px;
|
|
||||||
color: var(--dh-muted);
|
|
||||||
align-self: flex-end;
|
|
||||||
margin-bottom: 9px;
|
|
||||||
}
|
|
||||||
.dh-sidebar-caption {
|
.dh-sidebar-caption {
|
||||||
font-size: 11px;
|
font-size: 11px;
|
||||||
color: var(--dh-muted);
|
color: var(--dh-muted);
|
||||||
@@ -1902,9 +1894,6 @@
|
|||||||
.dh-page {
|
.dh-page {
|
||||||
padding: 30px;
|
padding: 30px;
|
||||||
}
|
}
|
||||||
.dh-brand-en {
|
|
||||||
display: none;
|
|
||||||
}
|
|
||||||
.dh-card-grid {
|
.dh-card-grid {
|
||||||
grid-template-columns: repeat(3, minmax(0, 1fr));
|
grid-template-columns: repeat(3, minmax(0, 1fr));
|
||||||
gap: 14px;
|
gap: 14px;
|
||||||
@@ -2486,3 +2475,20 @@ html.dh-chat-active body {
|
|||||||
min-height: 44px;
|
min-height: 44px;
|
||||||
color: var(--dh-accent);
|
color: var(--dh-accent);
|
||||||
}
|
}
|
||||||
|
/* 会话管理与恢复操作沿用当前主题,移动端保持足够命中面积。 */
|
||||||
|
.dh-conversation-search { display: grid; gap: 8px; margin: 20px 0; color: var(--dh-muted); }
|
||||||
|
.dh-conversation-tools { display: flex; justify-content: flex-end; gap: 12px; margin: 4px 0 12px; }
|
||||||
|
.dh-conversation-tools button { min-height: 36px; padding: 4px 10px; color: var(--dh-muted); }
|
||||||
|
.dh-title-dialog label { display: grid; gap: 10px; margin-top: 20px; }
|
||||||
|
.dh-title-dialog input { width: 100%; font-size: 16px; }
|
||||||
|
.dh-title-dialog blockquote { max-height: 180px; overflow-y: auto; margin: 16px 0; padding: 12px; background: var(--dh-soft); white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||||
|
.dh-undo { position: fixed; z-index: 120; bottom: max(90px, env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); width: min(460px, calc(100% - 28px)); padding: 14px 18px; border-radius: 14px; background: var(--dh-soft); border: 1px solid var(--dh-line); display: flex; align-items: center; gap: 12px; box-shadow: 0 12px 40px #0008; }
|
||||||
|
.dh-undo span { flex: 1; overflow-wrap: anywhere; }
|
||||||
|
.dh-undo button { flex: none; min-height: 44px; color: var(--dh-accent); }
|
||||||
|
.dh-branch-source, .dh-recovery { padding: 14px; margin-bottom: 16px !important; border: 1px solid var(--dh-line); border-radius: 12px; color: var(--dh-muted); }
|
||||||
|
.dh-branch-source a, .dh-recovery button { color: var(--dh-accent); min-height: 40px; padding: 6px; }
|
||||||
|
.dh-recent-stories { display: flex; flex-wrap: wrap; gap: 10px; margin: 14px 0 28px; }
|
||||||
|
.dh-recent-stories a { border: 1px solid var(--dh-line); border-radius: 12px; padding: 12px 16px; max-width: 100%; overflow-wrap: anywhere; }
|
||||||
|
|
||||||
|
/* 增长入口沿用原有暗色界面,表单保持移动端16px,原生details减少聊天常驻操作。 */
|
||||||
|
.dh-growth-recommendations,.dh-growth-profile{margin:24px 0}.dh-growth-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.dh-growth-grid article{min-width:0;border:1px solid var(--line,#333);border-radius:16px;overflow:hidden}.dh-growth-grid a{display:flex;flex-direction:column;gap:8px;padding:12px;color:inherit;text-decoration:none}.dh-growth-grid img{width:100%;height:160px;object-fit:cover;border-radius:10px}.dh-growth-grid small{color:#aaa}.dh-growth-grid button,.dh-growth-feedback button,.dh-growth-chat button,.dh-growth-profile button{padding:9px 12px;border-radius:10px;background:#292129;color:#f3b0dc;border:1px solid #554050}.dh-growth-banner,.dh-growth-chat{padding:14px;margin:12px 0;border:1px solid #493442;border-radius:14px;background:#201a1e}.dh-growth-banner p,.dh-growth-chat p{line-height:1.7}.dh-growth-chat summary{cursor:pointer}.dh-growth-chat textarea,.dh-growth-profile input,.dh-growth-feedback select{font-size:16px}.dh-growth-chat textarea{display:block;width:100%;min-height:70px;background:#191919;color:#eee;padding:10px;border:1px solid #444;border-radius:10px}.dh-growth-memory{margin:12px 0}.dh-growth-profile fieldset{display:flex;flex-wrap:wrap;gap:12px;margin:18px 0;border:1px solid #444;border-radius:12px}.dh-growth-profile label{display:inline-flex;gap:6px;align-items:center}.dh-growth-feedback{display:flex;flex-wrap:wrap;gap:8px;margin-top:10px}.dh-growth-feedback button{font-size:12px}.dh-growth-feedback [aria-pressed=true]{border-color:#efa5d3}.dh-growth-feedback select{background:#222;color:#eee;padding:8px}.dh-growth-profile small{line-height:1.7;color:#aaa}
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
import { Inbox } from "lucide-react";
|
|
||||||
|
|
||||||
type EmptyStateProps = {
|
|
||||||
title: string;
|
|
||||||
description: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function EmptyState({ title, description }: EmptyStateProps) {
|
|
||||||
return (
|
|
||||||
<section className="empty-state">
|
|
||||||
<Inbox aria-hidden size={28} />
|
|
||||||
<h2>{title}</h2>
|
|
||||||
<p>{description}</p>
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,35 +0,0 @@
|
|||||||
import Link from "next/link";
|
|
||||||
import type { Route } from "next";
|
|
||||||
import type { CSSProperties } from "react";
|
|
||||||
|
|
||||||
type FilterNavOption = {
|
|
||||||
href: Route;
|
|
||||||
label: string;
|
|
||||||
active: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
type FilterNavProps = {
|
|
||||||
label: string;
|
|
||||||
options: FilterNavOption[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export function FilterNav({ label, options }: FilterNavProps) {
|
|
||||||
return (
|
|
||||||
<nav
|
|
||||||
aria-label={label}
|
|
||||||
className="segmented"
|
|
||||||
style={{ "--segment-count": options.length } as CSSProperties}
|
|
||||||
>
|
|
||||||
{options.map((option) => (
|
|
||||||
<Link
|
|
||||||
aria-current={option.active ? "page" : undefined}
|
|
||||||
className={option.active ? "is-active" : undefined}
|
|
||||||
href={option.href}
|
|
||||||
key={option.label}
|
|
||||||
>
|
|
||||||
{option.label}
|
|
||||||
</Link>
|
|
||||||
))}
|
|
||||||
</nav>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
"use client";
|
||||||
|
/** 会话内记忆管理和回答质量反馈,所有写入仍由后端校验消息归属与版本。 */
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { digital } from "@/lib/digital";
|
||||||
|
import {
|
||||||
|
feedbackFor,
|
||||||
|
invalidateFeedback,
|
||||||
|
type GrowthState,
|
||||||
|
} from "@/lib/growth";
|
||||||
|
type Memory = { id: string; kind: string; content: string; version: number };
|
||||||
|
/** 延迟读取记忆列表,删除保留服务端源键,后台任务不能将它重新创建。 */
|
||||||
|
export function GrowthChat({
|
||||||
|
account,
|
||||||
|
conversation,
|
||||||
|
busy,
|
||||||
|
onExpanded,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
conversation: string;
|
||||||
|
busy: boolean;
|
||||||
|
onExpanded: () => void;
|
||||||
|
}) {
|
||||||
|
const [memories, setMemories] = useState<Memory[]>([]),
|
||||||
|
[draft, setDraft] = useState(""),
|
||||||
|
[error, setError] = useState(""),
|
||||||
|
[pending, setPending] = useState(false),
|
||||||
|
[rights, setRights] = useState<GrowthState["entitlement"] | null>(null),
|
||||||
|
[open, setOpen] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
const c = new AbortController();
|
||||||
|
digital<GrowthState>("growth", "GET", undefined, c.signal)
|
||||||
|
.then((r) => setRights(r.entitlement))
|
||||||
|
.catch(() => {});
|
||||||
|
return () => c.abort();
|
||||||
|
}, [account, busy]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
const c = new AbortController();
|
||||||
|
digital<Memory[]>(
|
||||||
|
`conversations/${conversation}/memories`,
|
||||||
|
"GET",
|
||||||
|
undefined,
|
||||||
|
c.signal,
|
||||||
|
)
|
||||||
|
.then(setMemories)
|
||||||
|
.catch((e) => {
|
||||||
|
if (!c.signal.aborted) setError(e.message);
|
||||||
|
});
|
||||||
|
return () => c.abort();
|
||||||
|
}, [conversation, open]);
|
||||||
|
async function mutate(path: string, method: "POST" | "PATCH", body: unknown) {
|
||||||
|
if (pending) return;
|
||||||
|
setPending(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await digital(path, method, body);
|
||||||
|
setMemories(
|
||||||
|
await digital<Memory[]>(`conversations/${conversation}/memories`),
|
||||||
|
);
|
||||||
|
setDraft("");
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "操作失败");
|
||||||
|
} finally {
|
||||||
|
setPending(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<details
|
||||||
|
className="dh-growth-chat"
|
||||||
|
onToggle={(e) => {
|
||||||
|
setOpen(e.currentTarget.open);
|
||||||
|
if (e.currentTarget.open) onExpanded();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<summary>
|
||||||
|
故事记忆与权益 {rights ? `· 剩余 ${rights.remaining} 次` : ""}
|
||||||
|
</summary>
|
||||||
|
<p className="dh-form-note">
|
||||||
|
记忆仅用于当前故事。自动事实需要在“我的”中开启;这里可以更正为手动记忆,或移除不想继续使用的内容。
|
||||||
|
</p>
|
||||||
|
{error && <p role="alert">{error}</p>}
|
||||||
|
{memories.map((m) => (
|
||||||
|
<MemoryRow
|
||||||
|
key={`${m.id}:${m.version}`}
|
||||||
|
memory={m}
|
||||||
|
disabled={busy || pending}
|
||||||
|
onSave={(content) =>
|
||||||
|
mutate(`conversations/${conversation}/memories/${m.id}`, "PATCH", {
|
||||||
|
version: m.version,
|
||||||
|
content,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
onDelete={() =>
|
||||||
|
mutate(`conversations/${conversation}/memories/${m.id}`, "PATCH", {
|
||||||
|
version: m.version,
|
||||||
|
deleted: true,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
<label>
|
||||||
|
添加重要背景
|
||||||
|
<textarea
|
||||||
|
value={draft}
|
||||||
|
maxLength={600}
|
||||||
|
onChange={(e) => setDraft(e.target.value)}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<button
|
||||||
|
disabled={busy || pending || !draft.trim()}
|
||||||
|
onClick={() =>
|
||||||
|
mutate(`conversations/${conversation}/memories`, "POST", {
|
||||||
|
content: draft,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
>
|
||||||
|
记住这件事
|
||||||
|
</button>
|
||||||
|
</details>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
function MemoryRow({
|
||||||
|
memory,
|
||||||
|
disabled,
|
||||||
|
onSave,
|
||||||
|
onDelete,
|
||||||
|
}: {
|
||||||
|
memory: Memory;
|
||||||
|
disabled: boolean;
|
||||||
|
onSave: (value: string) => void;
|
||||||
|
onDelete: () => void;
|
||||||
|
}) {
|
||||||
|
const [text, setText] = useState(memory.content);
|
||||||
|
return (
|
||||||
|
<div className="dh-growth-memory">
|
||||||
|
<small>
|
||||||
|
{memory.kind === "summary"
|
||||||
|
? "历史摘录"
|
||||||
|
: memory.kind === "fact"
|
||||||
|
? "明确记忆"
|
||||||
|
: "手动背景"}
|
||||||
|
</small>
|
||||||
|
<textarea
|
||||||
|
aria-label="记忆内容"
|
||||||
|
value={text}
|
||||||
|
maxLength={600}
|
||||||
|
onChange={(e) => setText(e.target.value)}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
disabled={disabled || !text.trim() || text === memory.content}
|
||||||
|
onClick={() => onSave(text)}
|
||||||
|
>
|
||||||
|
保存更正
|
||||||
|
</button>
|
||||||
|
<button disabled={disabled} onClick={onDelete}>
|
||||||
|
不再使用
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
/** 点踩原因与指定回复绑定,不采集新的聊天正文。 */
|
||||||
|
export function ReplyFeedback({
|
||||||
|
account,
|
||||||
|
conversation,
|
||||||
|
messageId,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
conversation: string;
|
||||||
|
messageId: string;
|
||||||
|
}) {
|
||||||
|
const [rating, setRating] = useState<"up" | "down" | "">(""),
|
||||||
|
[reason, setReason] = useState(""),
|
||||||
|
[choosing, setChoosing] = useState(false),
|
||||||
|
[busy, setBusy] = useState(false),
|
||||||
|
[error, setError] = useState("");
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
feedbackFor(account, conversation)
|
||||||
|
.then((items) => {
|
||||||
|
const r = items.find((i) => i.messageId === messageId);
|
||||||
|
if (alive && r) {
|
||||||
|
setRating(r.rating);
|
||||||
|
setReason(r.reason);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {});
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
};
|
||||||
|
}, [account, conversation, messageId]);
|
||||||
|
async function save(value: "up" | "down", why = "") {
|
||||||
|
if (busy) return;
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
try {
|
||||||
|
await digital(`conversations/${conversation}/feedback`, "POST", {
|
||||||
|
messageId,
|
||||||
|
rating: value,
|
||||||
|
reason: why,
|
||||||
|
});
|
||||||
|
invalidateFeedback(account, conversation);
|
||||||
|
setRating(value);
|
||||||
|
setReason(why);
|
||||||
|
setChoosing(false);
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "反馈失败");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="dh-growth-feedback">
|
||||||
|
<button
|
||||||
|
disabled={busy}
|
||||||
|
aria-pressed={rating === "up"}
|
||||||
|
onClick={() => void save("up")}
|
||||||
|
>
|
||||||
|
{rating === "up" ? "已赞同" : "喜欢这个回答"}
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
disabled={busy}
|
||||||
|
aria-pressed={rating === "down"}
|
||||||
|
onClick={() => setChoosing(!choosing)}
|
||||||
|
>
|
||||||
|
{rating === "down" ? "已反馈" : "不太满意"}
|
||||||
|
</button>
|
||||||
|
{choosing && (
|
||||||
|
<label>
|
||||||
|
原因
|
||||||
|
<select value={reason} onChange={(e) => setReason(e.target.value)}>
|
||||||
|
<option value="">选择原因</option>
|
||||||
|
<option value="forgot">忘记设定</option>
|
||||||
|
<option value="repetition">重复内容</option>
|
||||||
|
<option value="slow">回复太慢</option>
|
||||||
|
<option value="off_topic">偏离故事</option>
|
||||||
|
<option value="other">其他</option>
|
||||||
|
</select>
|
||||||
|
<button
|
||||||
|
disabled={busy || !reason}
|
||||||
|
onClick={() => void save("down", reason)}
|
||||||
|
>
|
||||||
|
提交反馈
|
||||||
|
</button>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
{error && <small role="alert">{error}</small>}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
"use client";
|
||||||
|
/** 站内运营卡片与漏斗入口,先读取回访分群再上报本次访问,避免把沉默用户立即改为活跃。 */
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { digital } from "@/lib/digital";
|
||||||
|
import { trackGrowth, flushGrowth, type GrowthState } from "@/lib/growth";
|
||||||
|
/** 不向外部渠道发通知;仅实际可见的站内卡片确认曝光。 */
|
||||||
|
export function GrowthJourney({
|
||||||
|
account,
|
||||||
|
page,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
page: string;
|
||||||
|
}) {
|
||||||
|
const [cards, setCards] = useState<GrowthState["inbox"]>([]),
|
||||||
|
box = useRef<HTMLDivElement>(null),
|
||||||
|
visited = useRef("");
|
||||||
|
useEffect(() => {
|
||||||
|
let alive = true;
|
||||||
|
const controller = new AbortController();
|
||||||
|
digital<GrowthState>("growth", "GET", undefined, controller.signal)
|
||||||
|
.then((s) => {
|
||||||
|
if (alive) setCards(s.inbox);
|
||||||
|
})
|
||||||
|
.catch(() => {})
|
||||||
|
.finally(() => {
|
||||||
|
if (alive && visited.current !== `${account}:${page}`) {
|
||||||
|
visited.current = `${account}:${page}`;
|
||||||
|
trackGrowth(account, "page_view", page);
|
||||||
|
void flushGrowth(account);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
const timer = setInterval(() => void flushGrowth(account), 5000),
|
||||||
|
hide = () => void flushGrowth(account);
|
||||||
|
window.addEventListener("pagehide", hide);
|
||||||
|
return () => {
|
||||||
|
alive = false;
|
||||||
|
controller.abort();
|
||||||
|
clearInterval(timer);
|
||||||
|
window.removeEventListener("pagehide", hide);
|
||||||
|
void flushGrowth(account);
|
||||||
|
};
|
||||||
|
}, [account, page]);
|
||||||
|
useEffect(() => {
|
||||||
|
const element = box.current;
|
||||||
|
if (!element || !cards.length) return;
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
if (entries.some((e) => e.isIntersecting)) {
|
||||||
|
for (const card of cards)
|
||||||
|
void digital(`growth/inbox/${card.id}`, "POST", {
|
||||||
|
action: "exposure",
|
||||||
|
}).catch(() => {});
|
||||||
|
observer.disconnect();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ threshold: 0.5 },
|
||||||
|
);
|
||||||
|
observer.observe(element);
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [cards]);
|
||||||
|
return cards.length ? (
|
||||||
|
<aside ref={box} className="dh-growth-banner">
|
||||||
|
{cards.map((c) => (
|
||||||
|
<div key={c.id}>
|
||||||
|
<strong>{c.title}</strong>
|
||||||
|
<p>{c.content}</p>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
await digital(`growth/inbox/${c.id}`, "POST", {
|
||||||
|
action: "exposure",
|
||||||
|
})
|
||||||
|
.then(() =>
|
||||||
|
digital(`growth/inbox/${c.id}`, "POST", { action: "click" }),
|
||||||
|
)
|
||||||
|
.catch(() => {});
|
||||||
|
setCards([]);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
知道了,继续探索
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</aside>
|
||||||
|
) : null;
|
||||||
|
}
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
"use client";
|
||||||
|
/** 个人权益和主动兴趣选择,自动记忆须用户开启,关闭后不再提取和检索自动内容。 */
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { digital, type Card } from "@/lib/digital";
|
||||||
|
import type { GrowthState } from "@/lib/growth";
|
||||||
|
/** 所有额度和偏好读取服务端真实状态,不展示虚构购买按钮。 */
|
||||||
|
export function GrowthProfile({
|
||||||
|
account,
|
||||||
|
cards,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
cards: Card[];
|
||||||
|
}) {
|
||||||
|
const [state, setState] = useState<GrowthState | null>(null),
|
||||||
|
[error, setError] = useState(""),
|
||||||
|
[notice, setNotice] = useState(""),
|
||||||
|
[busy, setBusy] = useState(false);
|
||||||
|
useEffect(() => {
|
||||||
|
const c = new AbortController();
|
||||||
|
digital<GrowthState>("growth", "GET", undefined, c.signal)
|
||||||
|
.then(setState)
|
||||||
|
.catch((e) => {
|
||||||
|
if (!c.signal.aborted) setError(e.message);
|
||||||
|
});
|
||||||
|
return () => c.abort();
|
||||||
|
}, [account]);
|
||||||
|
const tags = [...new Set(cards.flatMap((c) => c.tags))].slice(0, 30);
|
||||||
|
return (
|
||||||
|
<section className="dh-growth-profile">
|
||||||
|
<h2>我的体验与偏好</h2>
|
||||||
|
{error && <p role="alert">{error}</p>}
|
||||||
|
{state && (
|
||||||
|
<>
|
||||||
|
<p>
|
||||||
|
{state.entitlement.tier === "member" ? "会员权益" : "免费权益"}{" "}
|
||||||
|
· 剩余 {state.entitlement.remaining} / {state.entitlement.limit} 次
|
||||||
|
· 生成中预占 {state.entitlement.reserved} 次
|
||||||
|
</p>
|
||||||
|
<small>
|
||||||
|
每次聊天或灵感生成消耗一次;空失败会释放,部分回复会保留并计次。
|
||||||
|
每日额度按服务器自然日重置。会员权益由后台运营授予。
|
||||||
|
</small>
|
||||||
|
<fieldset>
|
||||||
|
<legend>我感兴趣的题材(最多12项)</legend>
|
||||||
|
{tags.map((tag) => (
|
||||||
|
<label key={tag}>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={state.interests.includes(tag)}
|
||||||
|
disabled={
|
||||||
|
busy ||
|
||||||
|
(!state.interests.includes(tag) &&
|
||||||
|
state.interests.length >= 12)
|
||||||
|
}
|
||||||
|
onChange={(e) =>
|
||||||
|
setState({
|
||||||
|
...state,
|
||||||
|
interests: e.target.checked
|
||||||
|
? [...state.interests, tag]
|
||||||
|
: state.interests.filter((t) => t !== tag),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
{tag}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</fieldset>
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={state.autoMemory}
|
||||||
|
disabled={busy}
|
||||||
|
onChange={(e) =>
|
||||||
|
setState({ ...state, autoMemory: e.target.checked })
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
允许为我的故事提取记忆
|
||||||
|
</label>
|
||||||
|
<p className="dh-form-note">
|
||||||
|
仅提取你明确说“请记住”的事实,并定期生成历史原文摘录;你可以在故事内查看、更正或移除。关闭后不再使用自动记忆,手动添加的记忆继续生效。
|
||||||
|
</p>
|
||||||
|
<button
|
||||||
|
disabled={busy}
|
||||||
|
onClick={async () => {
|
||||||
|
setBusy(true);
|
||||||
|
setError("");
|
||||||
|
setNotice("");
|
||||||
|
try {
|
||||||
|
await digital("growth/preferences", "PUT", {
|
||||||
|
interests: state.interests,
|
||||||
|
autoMemory: state.autoMemory,
|
||||||
|
});
|
||||||
|
setNotice("偏好已保存,下次推荐与回复时生效");
|
||||||
|
} catch (e) {
|
||||||
|
setError(e instanceof Error ? e.message : "保存失败");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
{busy ? "保存中…" : "保存推荐与记忆偏好"}
|
||||||
|
</button>
|
||||||
|
{notice && <p role="status">{notice}</p>}
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
"use client";
|
||||||
|
/** 服务端推荐结果与真实可见曝光,默认排序、实验组和归因都由服务端决定。 */
|
||||||
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useEffect, useRef, useState } from "react";
|
||||||
|
import { digital, type Card } from "@/lib/digital";
|
||||||
|
import { contentPath } from "@/lib/digital-routes";
|
||||||
|
import { trackGrowth, flushGrowth, rememberRecommendation } from "@/lib/growth";
|
||||||
|
type Recommendation = {
|
||||||
|
receiptId: string;
|
||||||
|
items: { id: string; reason: string }[];
|
||||||
|
};
|
||||||
|
/** 兴趣偏好来自用户主动选择,跳过不会被误计为开聊。 */
|
||||||
|
export function GrowthRecommendations({
|
||||||
|
account,
|
||||||
|
cards,
|
||||||
|
}: {
|
||||||
|
account: string;
|
||||||
|
cards: Card[];
|
||||||
|
}) {
|
||||||
|
const [result, setResult] = useState<Recommendation | null>(null),
|
||||||
|
[error, setError] = useState(""),
|
||||||
|
root = useRef<HTMLElement>(null),
|
||||||
|
seen = useRef(new Set<string>());
|
||||||
|
useEffect(() => {
|
||||||
|
const c = new AbortController();
|
||||||
|
digital<Recommendation>(
|
||||||
|
"growth/recommendations",
|
||||||
|
"GET",
|
||||||
|
undefined,
|
||||||
|
c.signal,
|
||||||
|
)
|
||||||
|
.then(setResult)
|
||||||
|
.catch((e) => {
|
||||||
|
if (!c.signal.aborted)
|
||||||
|
setError(e instanceof Error ? e.message : "推荐加载失败");
|
||||||
|
});
|
||||||
|
return () => c.abort();
|
||||||
|
}, [account]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (!result || !root.current) return;
|
||||||
|
const observer = new IntersectionObserver(
|
||||||
|
(entries) => {
|
||||||
|
for (const entry of entries) {
|
||||||
|
if (!entry.isIntersecting) continue;
|
||||||
|
const id = (entry.target as HTMLElement).dataset.cardId;
|
||||||
|
if (!id) continue;
|
||||||
|
const key = `${result.receiptId}:${id}`;
|
||||||
|
if (seen.current.has(key)) continue;
|
||||||
|
seen.current.add(key);
|
||||||
|
trackGrowth(
|
||||||
|
account,
|
||||||
|
"recommendation_exposure",
|
||||||
|
undefined,
|
||||||
|
result.receiptId,
|
||||||
|
);
|
||||||
|
trackGrowth(account, "card_impression", id, result.receiptId);
|
||||||
|
void flushGrowth(account);
|
||||||
|
observer.unobserve(entry.target);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{ threshold: 0.5 },
|
||||||
|
);
|
||||||
|
root.current
|
||||||
|
.querySelectorAll("[data-card-id]")
|
||||||
|
.forEach((e) => observer.observe(e));
|
||||||
|
return () => observer.disconnect();
|
||||||
|
}, [account, result]);
|
||||||
|
return (
|
||||||
|
<section
|
||||||
|
ref={root}
|
||||||
|
className="dh-growth-recommendations"
|
||||||
|
aria-label="为你推荐"
|
||||||
|
>
|
||||||
|
<h2>为你推荐</h2>
|
||||||
|
<p>
|
||||||
|
<Link href="/profile">选择兴趣,让推荐更懂你</Link>
|
||||||
|
</p>
|
||||||
|
{error ? (
|
||||||
|
<p role="status">{error}</p>
|
||||||
|
) : !result ? (
|
||||||
|
<p>正在寻找适合你的故事…</p>
|
||||||
|
) : (
|
||||||
|
<div className="dh-growth-grid">
|
||||||
|
{result.items.map((item) => {
|
||||||
|
const card = cards.find((c) => c.id === item.id);
|
||||||
|
return card ? (
|
||||||
|
<article key={item.id} data-card-id={item.id}>
|
||||||
|
<Link
|
||||||
|
href={{
|
||||||
|
pathname: contentPath(card),
|
||||||
|
query: { recommendation: result.receiptId },
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
trackGrowth(
|
||||||
|
account,
|
||||||
|
"recommendation_exposure",
|
||||||
|
undefined,
|
||||||
|
result.receiptId,
|
||||||
|
);
|
||||||
|
rememberRecommendation(account, card.id, result.receiptId);
|
||||||
|
void flushGrowth(account);
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Image
|
||||||
|
src={card.cover || "/icon.svg"}
|
||||||
|
alt=""
|
||||||
|
width={240}
|
||||||
|
height={160}
|
||||||
|
unoptimized
|
||||||
|
/>
|
||||||
|
<strong>{card.name}</strong>
|
||||||
|
<small>{item.reason}</small>
|
||||||
|
</Link>
|
||||||
|
<button
|
||||||
|
onClick={() => {
|
||||||
|
trackGrowth(
|
||||||
|
account,
|
||||||
|
"card_skip",
|
||||||
|
card.id,
|
||||||
|
result.receiptId,
|
||||||
|
);
|
||||||
|
void flushGrowth(account);
|
||||||
|
setResult({
|
||||||
|
...result,
|
||||||
|
items: result.items.filter((i) => i.id !== card.id),
|
||||||
|
});
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
暂不感兴趣
|
||||||
|
</button>
|
||||||
|
</article>
|
||||||
|
) : null;
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,96 +1,42 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
/** 独立星港用户账号登录,成功后进入数字人空间。 */
|
/** Google 登录入口,换取数字人会话后恢复原页面。 */
|
||||||
import { useRouter } from "next/navigation";
|
import { useRouter } from "next/navigation";
|
||||||
|
import { useState } from "react";
|
||||||
import { safeDigitalReturnTo } from "@/lib/digital-routes";
|
import { safeDigitalReturnTo } from "@/lib/digital-routes";
|
||||||
import { Eye, EyeOff, LockKeyhole, Smartphone } from "lucide-react";
|
import { signInWithGoogle } from "@/lib/firebase-google";
|
||||||
import { FormEvent, useState } from "react";
|
|
||||||
|
|
||||||
/** 独立用户的登录表单,不保存明文密码。 */
|
/** 使用 Firebase Google 登录,并显示认证进度及错误。 */
|
||||||
export function LoginForm({ returnTo = "/discover" }: { returnTo?: string }) {
|
export function LoginForm({ returnTo = "/discover" }: { returnTo?: string }) {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [error, setError] = useState("");
|
const [error, setError] = useState("");
|
||||||
const [pending, setPending] = useState(false);
|
const [pending, setPending] = useState(false);
|
||||||
const [passwordVisible, setPasswordVisible] = useState(false);
|
|
||||||
|
|
||||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
async function handleGoogleLogin() {
|
||||||
event.preventDefault();
|
|
||||||
setError("");
|
setError("");
|
||||||
setPending(true);
|
setPending(true);
|
||||||
|
|
||||||
const formData = new FormData(event.currentTarget);
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch("/api/auth/login", {
|
await signInWithGoogle();
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({
|
|
||||||
username: String(formData.get("username") || "").trim(),
|
|
||||||
password: String(formData.get("password") || ""),
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
if (!response.ok) {
|
|
||||||
const payload = await response.json().catch(() => null);
|
|
||||||
throw new Error(payload?.message || "登录失败,请检查账号和密码");
|
|
||||||
}
|
|
||||||
router.replace(safeDigitalReturnTo(returnTo));
|
router.replace(safeDigitalReturnTo(returnTo));
|
||||||
router.refresh();
|
router.refresh();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
setError(
|
setError(error instanceof Error ? error.message : "Google 登录失败,请重试");
|
||||||
error instanceof TypeError
|
|
||||||
? "网络连接失败,请稍后重试"
|
|
||||||
: error instanceof Error
|
|
||||||
? error.message
|
|
||||||
: "登录失败,请重试",
|
|
||||||
);
|
|
||||||
} finally {
|
} finally {
|
||||||
setPending(false);
|
setPending(false);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<form className="login-form" onSubmit={handleSubmit}>
|
<div className="login-form">
|
||||||
<label>
|
|
||||||
<span>登录账号</span>
|
|
||||||
<div className="input-wrap">
|
|
||||||
<Smartphone aria-hidden size={18} />
|
|
||||||
<input
|
|
||||||
autoComplete="username"
|
|
||||||
inputMode="text"
|
|
||||||
name="username"
|
|
||||||
placeholder="请输入账号"
|
|
||||||
required
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<span>密码</span>
|
|
||||||
<div className="input-wrap">
|
|
||||||
<LockKeyhole aria-hidden size={18} />
|
|
||||||
<input
|
|
||||||
autoComplete="current-password"
|
|
||||||
name="password"
|
|
||||||
placeholder="请输入登录密码"
|
|
||||||
required
|
|
||||||
type={passwordVisible ? "text" : "password"}
|
|
||||||
/>
|
|
||||||
<button
|
<button
|
||||||
aria-label={passwordVisible ? "隐藏密码" : "显示密码"}
|
|
||||||
className="icon-button"
|
|
||||||
onClick={() => setPasswordVisible((visible) => !visible)}
|
|
||||||
type="button"
|
type="button"
|
||||||
|
disabled={pending}
|
||||||
|
className="primary-button"
|
||||||
|
onClick={handleGoogleLogin}
|
||||||
>
|
>
|
||||||
{passwordVisible ? (
|
{pending ? "正在连接 Google…" : "使用 Google 登录"}
|
||||||
<EyeOff aria-hidden size={18} />
|
|
||||||
) : (
|
|
||||||
<Eye aria-hidden size={18} />
|
|
||||||
)}
|
|
||||||
</button>
|
</button>
|
||||||
|
{error ? <p className="form-error" role="alert">{error}</p> : null}
|
||||||
</div>
|
</div>
|
||||||
</label>
|
|
||||||
{error ? <p className="form-error">{error}</p> : null}
|
|
||||||
<button className="primary-button" disabled={pending} type="submit">
|
|
||||||
{pending ? "登录中..." : "登录"}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { LogOut } from "lucide-react";
|
|
||||||
import { useState } from "react";
|
|
||||||
|
|
||||||
export function LogoutButton() {
|
|
||||||
const router = useRouter();
|
|
||||||
const [pending, setPending] = useState(false);
|
|
||||||
|
|
||||||
async function logout() {
|
|
||||||
setPending(true);
|
|
||||||
await fetch("/api/auth/logout", { method: "POST" });
|
|
||||||
router.replace("/login");
|
|
||||||
router.refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<button className="secondary-button danger" disabled={pending} onClick={logout} type="button">
|
|
||||||
<LogOut aria-hidden size={18} />
|
|
||||||
{pending ? "退出中..." : "退出登录"}
|
|
||||||
</button>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,15 +0,0 @@
|
|||||||
type PageHeaderProps = {
|
|
||||||
eyebrow?: string;
|
|
||||||
title: string;
|
|
||||||
description?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export function PageHeader({ eyebrow, title, description }: PageHeaderProps) {
|
|
||||||
return (
|
|
||||||
<header className="page-header">
|
|
||||||
{eyebrow ? <p className="eyebrow">{eyebrow}</p> : null}
|
|
||||||
<h1>{title}</h1>
|
|
||||||
{description ? <p>{description}</p> : null}
|
|
||||||
</header>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { KeyRound } from "lucide-react";
|
|
||||||
import { FormEvent, useState } from "react";
|
|
||||||
|
|
||||||
import type { ApiEnvelope } from "@/lib/types";
|
|
||||||
|
|
||||||
async function readError(response: Response) {
|
|
||||||
const payload = (await response.json().catch(() => null)) as Partial<ApiEnvelope<unknown>> | null;
|
|
||||||
return payload?.message || "修改密码失败";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function PasswordChangeForm() {
|
|
||||||
const [pending, setPending] = useState(false);
|
|
||||||
const [error, setError] = useState("");
|
|
||||||
const [message, setMessage] = useState("");
|
|
||||||
|
|
||||||
async function handleSubmit(event: FormEvent<HTMLFormElement>) {
|
|
||||||
event.preventDefault();
|
|
||||||
setError("");
|
|
||||||
setMessage("");
|
|
||||||
setPending(true);
|
|
||||||
|
|
||||||
const form = event.currentTarget;
|
|
||||||
const formData = new FormData(form);
|
|
||||||
const oldPassword = String(formData.get("oldPassword") || "");
|
|
||||||
const newPassword = String(formData.get("newPassword") || "");
|
|
||||||
const confirmPassword = String(formData.get("confirmPassword") || "");
|
|
||||||
|
|
||||||
if (newPassword !== confirmPassword) {
|
|
||||||
setError("两次输入的新密码不一致");
|
|
||||||
setPending(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch("/api/auth/me/password", {
|
|
||||||
method: "PATCH",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ oldPassword, newPassword })
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
setError(await readError(response));
|
|
||||||
setPending(false);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
form.reset();
|
|
||||||
setMessage("密码已修改");
|
|
||||||
setPending(false);
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<form className="form-stack" onSubmit={handleSubmit}>
|
|
||||||
<label>
|
|
||||||
<span>旧密码</span>
|
|
||||||
<div className="input-wrap">
|
|
||||||
<KeyRound aria-hidden size={18} />
|
|
||||||
<input autoComplete="current-password" minLength={8} name="oldPassword" required type="password" />
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<span>新密码</span>
|
|
||||||
<div className="input-wrap">
|
|
||||||
<KeyRound aria-hidden size={18} />
|
|
||||||
<input autoComplete="new-password" minLength={8} name="newPassword" required type="password" />
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
<label>
|
|
||||||
<span>确认新密码</span>
|
|
||||||
<div className="input-wrap">
|
|
||||||
<KeyRound aria-hidden size={18} />
|
|
||||||
<input autoComplete="new-password" minLength={8} name="confirmPassword" required type="password" />
|
|
||||||
</div>
|
|
||||||
</label>
|
|
||||||
{error ? <p className="form-error">{error}</p> : null}
|
|
||||||
{message ? <p className="form-success">{message}</p> : null}
|
|
||||||
<button className="primary-button" disabled={pending} type="submit">
|
|
||||||
<KeyRound aria-hidden size={18} />
|
|
||||||
{pending ? "修改中..." : "修改密码"}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,8 +0,0 @@
|
|||||||
type StatusPillProps = {
|
|
||||||
children: React.ReactNode;
|
|
||||||
tone?: "default" | "success" | "warning" | "danger";
|
|
||||||
};
|
|
||||||
|
|
||||||
export function StatusPill({ children, tone = "default" }: StatusPillProps) {
|
|
||||||
return <span className={`status-pill status-pill--${tone}`}>{children}</span>;
|
|
||||||
}
|
|
||||||
@@ -1,145 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { CheckCircle2, MessageSquarePlus, PlayCircle } from "lucide-react";
|
|
||||||
import { FormEvent, useState } from "react";
|
|
||||||
|
|
||||||
import type { ApiEnvelope, TaskDetail, TaskStatus } from "@/lib/types";
|
|
||||||
|
|
||||||
type TaskActionPanelProps = {
|
|
||||||
taskId: string;
|
|
||||||
initialStatus: TaskStatus;
|
|
||||||
};
|
|
||||||
|
|
||||||
type TaskAction = "start" | "complete" | "comment";
|
|
||||||
|
|
||||||
function normalizeStatus(value: unknown): TaskStatus | null {
|
|
||||||
switch (value) {
|
|
||||||
case "PENDING":
|
|
||||||
case "pending":
|
|
||||||
return "pending";
|
|
||||||
case "IN_PROGRESS":
|
|
||||||
case "in_progress":
|
|
||||||
return "in_progress";
|
|
||||||
case "COMPLETED":
|
|
||||||
case "completed":
|
|
||||||
return "completed";
|
|
||||||
case "CANCELLED":
|
|
||||||
case "cancelled":
|
|
||||||
return "cancelled";
|
|
||||||
default:
|
|
||||||
return null;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function readMessage(response: Response) {
|
|
||||||
const payload = (await response.json().catch(() => null)) as Partial<ApiEnvelope<unknown>> | null;
|
|
||||||
return payload?.message || "操作失败";
|
|
||||||
}
|
|
||||||
|
|
||||||
export function TaskActionPanel({ taskId, initialStatus }: TaskActionPanelProps) {
|
|
||||||
const router = useRouter();
|
|
||||||
const [status, setStatus] = useState(initialStatus);
|
|
||||||
const [pendingAction, setPendingAction] = useState<TaskAction | null>(null);
|
|
||||||
const [message, setMessage] = useState("");
|
|
||||||
const [error, setError] = useState("");
|
|
||||||
|
|
||||||
async function runAction(action: Exclude<TaskAction, "comment">) {
|
|
||||||
setError("");
|
|
||||||
setMessage("");
|
|
||||||
setPendingAction(action);
|
|
||||||
|
|
||||||
const response = await fetch(`/api/mobile/tasks/${encodeURIComponent(taskId)}/${action}`, { method: "POST" });
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
setError(await readMessage(response));
|
|
||||||
setPendingAction(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const payload = (await response.json().catch(() => null)) as ApiEnvelope<TaskDetail> | null;
|
|
||||||
const nextStatus = normalizeStatus(payload?.data?.status);
|
|
||||||
if (nextStatus) setStatus(nextStatus);
|
|
||||||
|
|
||||||
setMessage(action === "start" ? "任务已开始处理" : "任务已完成");
|
|
||||||
setPendingAction(null);
|
|
||||||
router.refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
async function submitComment(event: FormEvent<HTMLFormElement>) {
|
|
||||||
event.preventDefault();
|
|
||||||
setError("");
|
|
||||||
setMessage("");
|
|
||||||
setPendingAction("comment");
|
|
||||||
|
|
||||||
const form = event.currentTarget;
|
|
||||||
const formData = new FormData(form);
|
|
||||||
const comment = String(formData.get("comment") || "").trim();
|
|
||||||
|
|
||||||
if (!comment) {
|
|
||||||
setError("请填写备注内容");
|
|
||||||
setPendingAction(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const response = await fetch(`/api/mobile/tasks/${encodeURIComponent(taskId)}/comment`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "Content-Type": "application/json" },
|
|
||||||
body: JSON.stringify({ comment })
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!response.ok) {
|
|
||||||
setError(await readMessage(response));
|
|
||||||
setPendingAction(null);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
form.reset();
|
|
||||||
setMessage("备注已追加");
|
|
||||||
setPendingAction(null);
|
|
||||||
router.refresh();
|
|
||||||
}
|
|
||||||
|
|
||||||
const canStart = status === "pending";
|
|
||||||
const canComplete = status === "pending" || status === "in_progress";
|
|
||||||
|
|
||||||
return (
|
|
||||||
<section className="section-block">
|
|
||||||
<div className="section-title">
|
|
||||||
<h2>处理任务</h2>
|
|
||||||
</div>
|
|
||||||
<div className="button-row">
|
|
||||||
<button
|
|
||||||
className="secondary-button"
|
|
||||||
disabled={!canStart || pendingAction !== null}
|
|
||||||
onClick={() => void runAction("start")}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
<PlayCircle aria-hidden size={18} />
|
|
||||||
{pendingAction === "start" ? "开始中..." : "开始处理"}
|
|
||||||
</button>
|
|
||||||
<button
|
|
||||||
className="primary-button"
|
|
||||||
disabled={!canComplete || pendingAction !== null}
|
|
||||||
onClick={() => void runAction("complete")}
|
|
||||||
type="button"
|
|
||||||
>
|
|
||||||
<CheckCircle2 aria-hidden size={18} />
|
|
||||||
{pendingAction === "complete" ? "完成中..." : "完成任务"}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
<form className="form-stack" onSubmit={submitComment}>
|
|
||||||
<label>
|
|
||||||
<span>处理备注</span>
|
|
||||||
<textarea className="text-area" maxLength={1000} name="comment" placeholder="填写交接、处理进展或完成说明" />
|
|
||||||
</label>
|
|
||||||
<button className="secondary-button" disabled={pendingAction !== null} type="submit">
|
|
||||||
<MessageSquarePlus aria-hidden size={18} />
|
|
||||||
{pendingAction === "comment" ? "提交中..." : "追加备注"}
|
|
||||||
</button>
|
|
||||||
</form>
|
|
||||||
{error ? <p className="form-error">{error}</p> : null}
|
|
||||||
{message ? <p className="form-success">{message}</p> : null}
|
|
||||||
</section>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,144 @@
|
|||||||
|
"use client";
|
||||||
|
/** 会话阅读位置按标签页保存;上翻时新回复只提示,不改变用户正在阅读的位置。 */
|
||||||
|
import { useEffect, useRef, useState, type RefObject } from "react";
|
||||||
|
|
||||||
|
type Position = {
|
||||||
|
anchor?: string;
|
||||||
|
offset: number;
|
||||||
|
top: number;
|
||||||
|
bottom: boolean;
|
||||||
|
revision: string;
|
||||||
|
unread: boolean;
|
||||||
|
};
|
||||||
|
/** 保存消息锚点而非只保存像素,消息排版或窗口高度变化后仍尽量回到同一条。 */
|
||||||
|
export function useChatReading(
|
||||||
|
id: string | undefined,
|
||||||
|
viewportRef: RefObject<HTMLDivElement | null>,
|
||||||
|
contentRef: RefObject<HTMLDivElement | null>,
|
||||||
|
atBottomRef: RefObject<boolean>,
|
||||||
|
draggingRef: RefObject<boolean>,
|
||||||
|
onJump: (value: boolean) => void,
|
||||||
|
) {
|
||||||
|
const [unread, setUnread] = useState(false);
|
||||||
|
const unreadRef = useRef(false);
|
||||||
|
useEffect(() => {
|
||||||
|
const view = viewportRef.current,
|
||||||
|
body = contentRef.current;
|
||||||
|
if (!id || !view || !body) return;
|
||||||
|
let frame = 0,
|
||||||
|
saveFrame = 0,
|
||||||
|
restored = false,
|
||||||
|
previousRevision = "";
|
||||||
|
const elements = () =>
|
||||||
|
Array.from(body.querySelectorAll<HTMLElement>("[data-message-id]"));
|
||||||
|
const revision = () => {
|
||||||
|
const last = elements().at(-1);
|
||||||
|
return last
|
||||||
|
? `${last.dataset.messageId}:${last.dataset.messageLength}`
|
||||||
|
: "";
|
||||||
|
};
|
||||||
|
const mark = (value: boolean) => {
|
||||||
|
unreadRef.current = value;
|
||||||
|
setUnread(value);
|
||||||
|
};
|
||||||
|
let lastPosition: Position | undefined;
|
||||||
|
const save = () => {
|
||||||
|
if (!restored) return;
|
||||||
|
// App Router 隐藏或卸载页面后 DOM 尺寸可能归零,不能用它覆盖最后一次有效阅读位置。
|
||||||
|
if (view.isConnected && body.isConnected && view.clientHeight > 0) {
|
||||||
|
const top = view.getBoundingClientRect().top;
|
||||||
|
const anchor = elements().find(
|
||||||
|
(el) => el.getBoundingClientRect().bottom > top,
|
||||||
|
);
|
||||||
|
lastPosition = {
|
||||||
|
anchor: anchor?.dataset.messageId,
|
||||||
|
offset: (anchor?.getBoundingClientRect().top ?? top) - top,
|
||||||
|
top: view.scrollTop,
|
||||||
|
bottom: atBottomRef.current,
|
||||||
|
revision: revision(),
|
||||||
|
unread: unreadRef.current,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
if (!lastPosition) return;
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(`dh-reading:${id}`, JSON.stringify(lastPosition));
|
||||||
|
} catch {}
|
||||||
|
};
|
||||||
|
let saved: Position | undefined;
|
||||||
|
try {
|
||||||
|
const value = JSON.parse(
|
||||||
|
sessionStorage.getItem(`dh-reading:${id}`) ?? "null",
|
||||||
|
);
|
||||||
|
if (value && Number.isFinite(value.top) && Number.isFinite(value.offset))
|
||||||
|
saved = value;
|
||||||
|
} catch {}
|
||||||
|
atBottomRef.current = saved?.bottom ?? true;
|
||||||
|
const follow = () => {
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
frame = requestAnimationFrame(() => {
|
||||||
|
if (!restored) {
|
||||||
|
let hash = "";
|
||||||
|
try {
|
||||||
|
hash = decodeURIComponent(window.location.hash.slice(1));
|
||||||
|
} catch {}
|
||||||
|
const target = hash
|
||||||
|
? elements().find((el) => el.id === hash)
|
||||||
|
: !saved?.bottom && saved?.anchor
|
||||||
|
? elements().find((el) => el.dataset.messageId === saved?.anchor)
|
||||||
|
: undefined;
|
||||||
|
if (target) {
|
||||||
|
view.scrollTop +=
|
||||||
|
target.getBoundingClientRect().top -
|
||||||
|
view.getBoundingClientRect().top -
|
||||||
|
(hash ? 12 : (saved?.offset ?? 0));
|
||||||
|
atBottomRef.current = false;
|
||||||
|
} else
|
||||||
|
view.scrollTop = atBottomRef.current
|
||||||
|
? view.scrollHeight
|
||||||
|
: (saved?.top ?? 0);
|
||||||
|
previousRevision = saved?.revision ?? revision();
|
||||||
|
mark(!!saved?.unread);
|
||||||
|
restored = true;
|
||||||
|
}
|
||||||
|
const next = revision();
|
||||||
|
if (atBottomRef.current) {
|
||||||
|
view.scrollTo({ top: view.scrollHeight, behavior: "instant" });
|
||||||
|
onJump(false);
|
||||||
|
mark(false);
|
||||||
|
} else {
|
||||||
|
if (next !== previousRevision) mark(true);
|
||||||
|
onJump(view.scrollHeight - view.scrollTop - view.clientHeight > 80);
|
||||||
|
}
|
||||||
|
previousRevision = next;
|
||||||
|
save();
|
||||||
|
});
|
||||||
|
};
|
||||||
|
const scroll = () => {
|
||||||
|
if (!restored || !view.isConnected || view.clientHeight <= 0) return;
|
||||||
|
if (view.scrollHeight - view.scrollTop - view.clientHeight <= 2)
|
||||||
|
mark(false);
|
||||||
|
cancelAnimationFrame(saveFrame);
|
||||||
|
saveFrame = requestAnimationFrame(save);
|
||||||
|
};
|
||||||
|
const endDrag = () => {
|
||||||
|
draggingRef.current = false;
|
||||||
|
};
|
||||||
|
const observer = new ResizeObserver(follow);
|
||||||
|
observer.observe(body);
|
||||||
|
observer.observe(view);
|
||||||
|
view.addEventListener("scroll", scroll);
|
||||||
|
window.addEventListener("pointerup", endDrag);
|
||||||
|
window.addEventListener("pointercancel", endDrag);
|
||||||
|
follow();
|
||||||
|
return () => {
|
||||||
|
save();
|
||||||
|
observer.disconnect();
|
||||||
|
cancelAnimationFrame(frame);
|
||||||
|
cancelAnimationFrame(saveFrame);
|
||||||
|
view.removeEventListener("scroll", scroll);
|
||||||
|
window.removeEventListener("pointerup", endDrag);
|
||||||
|
window.removeEventListener("pointercancel", endDrag);
|
||||||
|
};
|
||||||
|
}, [id, viewportRef, contentRef, atBottomRef, draggingRef, onJump]);
|
||||||
|
return unread;
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
/** 登录入口在解析JSON之前限制字节数,防止公开入口先无界缓存再交给后端校验。 */
|
||||||
|
export async function readLoginInput(
|
||||||
|
request: Request,
|
||||||
|
): Promise<Record<string, unknown>> {
|
||||||
|
if (!request.body) throw new SyntaxError("登录内容不合法");
|
||||||
|
const reader = request.body.getReader(),
|
||||||
|
decoder = new TextDecoder();
|
||||||
|
let bytes = 0,
|
||||||
|
text = "";
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const { done, value } = await reader.read();
|
||||||
|
if (done) break;
|
||||||
|
bytes += value.byteLength;
|
||||||
|
if (bytes > 8192) {
|
||||||
|
await reader.cancel();
|
||||||
|
throw new RangeError("登录内容过长");
|
||||||
|
}
|
||||||
|
text += decoder.decode(value, { stream: true });
|
||||||
|
}
|
||||||
|
text += decoder.decode();
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
const body: unknown = JSON.parse(text);
|
||||||
|
if (!body || typeof body !== "object" || Array.isArray(body))
|
||||||
|
throw new SyntaxError("登录内容不合法");
|
||||||
|
return body as Record<string, unknown>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
/** 同源写入校验使用代理保留的Host,避免服务端监听地址与公网域名不一致导致登录失败。 */
|
||||||
|
export function sameOriginRequest(request: Request) {
|
||||||
|
try {
|
||||||
|
const origin = request.headers.get("origin");
|
||||||
|
if (!origin) return false;
|
||||||
|
const parsed = new URL(origin);
|
||||||
|
return (
|
||||||
|
["https:", "http:"].includes(parsed.protocol) &&
|
||||||
|
parsed.origin === origin &&
|
||||||
|
parsed.host === request.headers.get("host")
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
+2
-31
@@ -4,8 +4,7 @@ import "server-only";
|
|||||||
import { redirect } from "next/navigation";
|
import { redirect } from "next/navigation";
|
||||||
import { expiredDigitalSessionPath } from "@/lib/digital-routes";
|
import { expiredDigitalSessionPath } from "@/lib/digital-routes";
|
||||||
|
|
||||||
import { clearSessionToken, getSessionToken } from "@/lib/session";
|
import { getSessionToken } from "@/lib/session";
|
||||||
import type { ApiEnvelope } from "@/lib/types";
|
|
||||||
|
|
||||||
/** 保留后端状态以便 BFF 清理失效会话。 */
|
/** 保留后端状态以便 BFF 清理失效会话。 */
|
||||||
export class BackendError extends Error {
|
export class BackendError extends Error {
|
||||||
@@ -55,7 +54,7 @@ async function parseBackendResponse<T>(response: Response): Promise<T> {
|
|||||||
/** 为服务端请求附加 HttpOnly 会话并禁止缓存私有数据。 */
|
/** 为服务端请求附加 HttpOnly 会话并禁止缓存私有数据。 */
|
||||||
export async function backendRequest<T>(
|
export async function backendRequest<T>(
|
||||||
path: string,
|
path: string,
|
||||||
init: RequestInit & { token?: string; allowUnauthorized?: boolean } = {},
|
init: RequestInit & { token?: string } = {},
|
||||||
) {
|
) {
|
||||||
const token = init.token ?? (await getSessionToken());
|
const token = init.token ?? (await getSessionToken());
|
||||||
const headers = new Headers(init.headers);
|
const headers = new Headers(init.headers);
|
||||||
@@ -93,31 +92,3 @@ export async function requireBackendData<T>(path: string, returnTo?: string) {
|
|||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/** 包装普通 JSON 业务接口,流式对话使用专用 BFF。 */
|
|
||||||
export async function proxyBackendJson<T>(
|
|
||||||
path: string,
|
|
||||||
init: RequestInit = {},
|
|
||||||
) {
|
|
||||||
try {
|
|
||||||
const data = await backendRequest<T>(path, init);
|
|
||||||
return Response.json({ success: true, data } satisfies ApiEnvelope<T>);
|
|
||||||
} catch (error) {
|
|
||||||
return backendErrorResponse(error);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 对浏览器返回统一错误,401 时同步清理 Cookie。 */
|
|
||||||
export async function backendErrorResponse(
|
|
||||||
error: unknown,
|
|
||||||
fallbackMessage = "请求失败",
|
|
||||||
) {
|
|
||||||
const status = error instanceof BackendError ? error.status : 500;
|
|
||||||
const message = error instanceof Error ? error.message : fallbackMessage;
|
|
||||||
|
|
||||||
if (status === 401) {
|
|
||||||
await clearSessionToken();
|
|
||||||
}
|
|
||||||
|
|
||||||
return Response.json({ success: false, data: null, message }, { status });
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -0,0 +1,25 @@
|
|||||||
|
/** 服务端生成中快照可能尚未落入增量正文;同步时保留浏览器已经收到的部分回复。 */
|
||||||
|
import type { Conversation } from "./digital";
|
||||||
|
|
||||||
|
/** 已结束的服务端记录为最终依据;仅在仍生成时保留同一消息较长的本地正文。 */
|
||||||
|
export function mergeConversationSnapshot(
|
||||||
|
current: Conversation | null,
|
||||||
|
saved: Conversation,
|
||||||
|
): Conversation {
|
||||||
|
if (!current || current.id !== saved.id || !saved.busy) return saved;
|
||||||
|
const known = new Map(
|
||||||
|
current.messages.map((message) => [message.id, message]),
|
||||||
|
);
|
||||||
|
return {
|
||||||
|
...saved,
|
||||||
|
messages: saved.messages.map((message) => {
|
||||||
|
const local = known.get(message.id);
|
||||||
|
return message.role === "assistant" &&
|
||||||
|
message.status === "generating" &&
|
||||||
|
local &&
|
||||||
|
local.content.length > message.content.length
|
||||||
|
? { ...message, content: local.content }
|
||||||
|
: message;
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
import type { Route } from "next";
|
import type { Route } from "next";
|
||||||
|
|
||||||
/** 顶部和底部导航共享同一份页面映射,保留旧工作台 /me 的兼容入口。 */
|
/** 顶部和底部导航共享同一份页面映射。 */
|
||||||
export const digitalTabs = {
|
export const digitalTabs = {
|
||||||
discover: "/discover",
|
discover: "/discover",
|
||||||
chats: "/chats",
|
chats: "/chats",
|
||||||
|
|||||||
@@ -0,0 +1,48 @@
|
|||||||
|
/** 独立 SSE 解码器,流关闭不代表回复成功,必须收到服务端 done 事件。 */
|
||||||
|
/** 网络分片可跨多个 SSE 事件,最后不完整事件不会被误解析。 */
|
||||||
|
export async function readDigitalStream(
|
||||||
|
response: Response,
|
||||||
|
onEvent: (event: string, data: Record<string, unknown>) => void,
|
||||||
|
) {
|
||||||
|
if (!response.ok) {
|
||||||
|
const p = await response.json();
|
||||||
|
throw new Error(p.error?.message ?? p.message ?? "发送失败");
|
||||||
|
}
|
||||||
|
if (!response.body) throw new Error("浏览器不支持流式连接");
|
||||||
|
const reader = response.body.getReader(),
|
||||||
|
decoder = new TextDecoder();
|
||||||
|
let buffer = "",
|
||||||
|
completed = false;
|
||||||
|
try {
|
||||||
|
for (;;) {
|
||||||
|
const { value, done } = await reader.read();
|
||||||
|
buffer += (
|
||||||
|
done ? decoder.decode() : decoder.decode(value, { stream: true })
|
||||||
|
).replaceAll("\r\n", "\n");
|
||||||
|
let end: number;
|
||||||
|
while ((end = buffer.indexOf("\n\n")) >= 0) {
|
||||||
|
const block = buffer.slice(0, end);
|
||||||
|
buffer = buffer.slice(end + 2);
|
||||||
|
const event = block
|
||||||
|
.split("\n")
|
||||||
|
.find((s) => s.startsWith("event:"))
|
||||||
|
?.slice(6)
|
||||||
|
.trim();
|
||||||
|
const data = block
|
||||||
|
.split("\n")
|
||||||
|
.filter((s) => s.startsWith("data:"))
|
||||||
|
.map((s) => s.slice(5).trim())
|
||||||
|
.join("\n");
|
||||||
|
if (event && data) {
|
||||||
|
if (event === "done") completed = true;
|
||||||
|
onEvent(event, JSON.parse(data));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (done) break;
|
||||||
|
}
|
||||||
|
if (!completed)
|
||||||
|
throw new Error("连接在回复结束前中断,请同步聊天记录后继续");
|
||||||
|
} finally {
|
||||||
|
reader.releaseLock();
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
-41
@@ -33,6 +33,7 @@ export type Message = {
|
|||||||
status: string;
|
status: string;
|
||||||
pinned: boolean;
|
pinned: boolean;
|
||||||
sequenceId?: number;
|
sequenceId?: number;
|
||||||
|
requestId?: string | null;
|
||||||
};
|
};
|
||||||
/** 不含实验配置的会话偏好。 */
|
/** 不含实验配置的会话偏好。 */
|
||||||
export type Settings = {
|
export type Settings = {
|
||||||
@@ -50,6 +51,13 @@ export type Conversation = {
|
|||||||
settings: Settings;
|
settings: Settings;
|
||||||
busy: boolean;
|
busy: boolean;
|
||||||
messages: Message[];
|
messages: Message[];
|
||||||
|
pinned?: boolean;
|
||||||
|
parent?: {
|
||||||
|
conversationId: string;
|
||||||
|
messageId: string;
|
||||||
|
title: string;
|
||||||
|
available: boolean;
|
||||||
|
} | null;
|
||||||
};
|
};
|
||||||
/** 通用请求保留服务端错误文本,401 自动返回登录。 */
|
/** 通用请求保留服务端错误文本,401 自动返回登录。 */
|
||||||
export async function digital<T>(
|
export async function digital<T>(
|
||||||
@@ -77,47 +85,8 @@ export async function digital<T>(
|
|||||||
throw new Error(data.error?.message ?? data.message ?? "请求失败");
|
throw new Error(data.error?.message ?? data.message ?? "请求失败");
|
||||||
return data.data as T;
|
return data.data as T;
|
||||||
}
|
}
|
||||||
/** 网络分片可跨多个 SSE 事件,最后不完整事件不会被误解析。 */
|
/** 严格检查终止事件,避免断网被当作回复完成。 */
|
||||||
export async function readStream(
|
export { readDigitalStream as readStream } from "./digital-stream";
|
||||||
response: Response,
|
|
||||||
onEvent: (event: string, data: Record<string, unknown>) => void,
|
|
||||||
) {
|
|
||||||
if (!response.ok) {
|
|
||||||
const p = await response.json();
|
|
||||||
throw new Error(p.error?.message ?? p.message ?? "发送失败");
|
|
||||||
}
|
|
||||||
if (!response.body) throw new Error("浏览器不支持流式连接");
|
|
||||||
const reader = response.body.getReader(),
|
|
||||||
decoder = new TextDecoder();
|
|
||||||
let buffer = "";
|
|
||||||
try {
|
|
||||||
for (;;) {
|
|
||||||
const { value, done } = await reader.read();
|
|
||||||
buffer += (
|
|
||||||
done ? decoder.decode() : decoder.decode(value, { stream: true })
|
|
||||||
).replaceAll("\r\n", "\n");
|
|
||||||
let end: number;
|
|
||||||
while ((end = buffer.indexOf("\n\n")) >= 0) {
|
|
||||||
const block = buffer.slice(0, end);
|
|
||||||
buffer = buffer.slice(end + 2);
|
|
||||||
const event = block
|
|
||||||
.split("\n")
|
|
||||||
.find((s) => s.startsWith("event:"))
|
|
||||||
?.slice(6)
|
|
||||||
.trim();
|
|
||||||
const data = block
|
|
||||||
.split("\n")
|
|
||||||
.filter((s) => s.startsWith("data:"))
|
|
||||||
.map((s) => s.slice(5).trim())
|
|
||||||
.join("\n");
|
|
||||||
if (event && data) onEvent(event, JSON.parse(data));
|
|
||||||
}
|
|
||||||
if (done) break;
|
|
||||||
}
|
|
||||||
} finally {
|
|
||||||
reader.releaseLock();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/** 会话列表摘要。 */
|
/** 会话列表摘要。 */
|
||||||
export type Summary = {
|
export type Summary = {
|
||||||
@@ -125,9 +94,12 @@ export type Summary = {
|
|||||||
characterId: string;
|
characterId: string;
|
||||||
title: string;
|
title: string;
|
||||||
updatedAt: string;
|
updatedAt: string;
|
||||||
|
pinned?: boolean;
|
||||||
|
lastMessage?: string | null;
|
||||||
};
|
};
|
||||||
/** 服务端首屏数据,仅包含可公开的内容摘要和当前账号决策。 */
|
/** 服务端首屏数据,仅包含可公开的内容摘要和当前账号决策。 */
|
||||||
export type Bootstrap = {
|
export type Bootstrap = {
|
||||||
|
account: string;
|
||||||
catalog: Card[];
|
catalog: Card[];
|
||||||
profile: Profile;
|
profile: Profile;
|
||||||
decision: {
|
decision: {
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
/** 使用内存中的 Firebase 凭据换取 Web 业务会话。 */
|
||||||
|
import { FirebaseError, getApps, initializeApp } from "firebase/app";
|
||||||
|
import {
|
||||||
|
browserPopupRedirectResolver,
|
||||||
|
GoogleAuthProvider,
|
||||||
|
initializeAuth,
|
||||||
|
inMemoryPersistence,
|
||||||
|
signInWithPopup,
|
||||||
|
signOut,
|
||||||
|
} from "firebase/auth";
|
||||||
|
|
||||||
|
const appName = "personal-digital-human-web";
|
||||||
|
const firebaseConfig = {
|
||||||
|
apiKey: "AIzaSyDNcdGylsWjL0Rt0rrEaPND7El7MuTYy2A",
|
||||||
|
authDomain: "personal-digital-human.firebaseapp.com",
|
||||||
|
projectId: "personal-digital-human",
|
||||||
|
storageBucket: "personal-digital-human.firebasestorage.app",
|
||||||
|
messagingSenderId: "699954559893",
|
||||||
|
appId: "1:699954559893:web:562e2218ccbae49476149c",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** 通过 Google 弹窗取得 ID token,业务会话由同源接口管理。 */
|
||||||
|
export async function signInWithGoogle() {
|
||||||
|
const app = getApps().find(({ name }) => name === appName)
|
||||||
|
?? initializeApp(firebaseConfig, appName);
|
||||||
|
const auth = initializeAuth(app, {
|
||||||
|
persistence: inMemoryPersistence,
|
||||||
|
popupRedirectResolver: browserPopupRedirectResolver,
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
const { user } = await signInWithPopup(auth, new GoogleAuthProvider());
|
||||||
|
const response = await fetch("/api/auth/firebase", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({ idToken: await user.getIdToken() }),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const result = await response.json().catch(() => null);
|
||||||
|
throw new Error(result?.message || "Google 登录暂不可用");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof FirebaseError)) throw error;
|
||||||
|
if (error.code === "auth/popup-closed-by-user") throw new Error("Google 登录已取消");
|
||||||
|
if (error.code === "auth/popup-blocked") throw new Error("请允许浏览器打开 Google 登录弹窗后重试");
|
||||||
|
if (error.code === "auth/unauthorized-domain") throw new Error("当前域名尚未启用 Google 登录");
|
||||||
|
throw new Error("Google 登录失败,请重试");
|
||||||
|
} finally {
|
||||||
|
// 页面只维持业务 Cookie 会话,清除 SDK 中的临时身份。
|
||||||
|
await signOut(auth).catch(() => undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,14 +0,0 @@
|
|||||||
export function formatDateTime(value?: string | null) {
|
|
||||||
if (!value) return "暂未设置";
|
|
||||||
|
|
||||||
return new Intl.DateTimeFormat("zh-CN", {
|
|
||||||
month: "2-digit",
|
|
||||||
day: "2-digit",
|
|
||||||
hour: "2-digit",
|
|
||||||
minute: "2-digit"
|
|
||||||
}).format(new Date(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
export function roleNames(roles: { name: string }[]) {
|
|
||||||
return roles.map((role) => role.name).join("、") || "未分配角色";
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
/** 无依赖的前台增长队列与推荐回执,便于验证重试幂等和账号隔离。 */
|
||||||
|
type EventName =
|
||||||
|
| "page_view"
|
||||||
|
| "card_impression"
|
||||||
|
| "card_open"
|
||||||
|
| "card_skip"
|
||||||
|
| "recommendation_exposure";
|
||||||
|
type Event = {
|
||||||
|
id: string;
|
||||||
|
event: EventName;
|
||||||
|
entity?: string;
|
||||||
|
receiptId?: string;
|
||||||
|
queuedAt: number;
|
||||||
|
};
|
||||||
|
const flushing = new Set<string>();
|
||||||
|
/** 队列按账号隔离;失败保留同一UUID重试,服务端以UUID幂等写入。 */
|
||||||
|
export function trackGrowth(
|
||||||
|
account: string,
|
||||||
|
event: EventName,
|
||||||
|
entity?: string,
|
||||||
|
receiptId?: string,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const key = `dh-events:${account}`,
|
||||||
|
queue = JSON.parse(sessionStorage.getItem(key) ?? "[]") as Event[];
|
||||||
|
queue.push({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
event,
|
||||||
|
entity,
|
||||||
|
receiptId,
|
||||||
|
queuedAt: Date.now(),
|
||||||
|
});
|
||||||
|
sessionStorage.setItem(key, JSON.stringify(queue.slice(-200)));
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
|
/** 单批20条,过期回执不再补报;400/404代表无效事件,其他失败保留待重试。 */
|
||||||
|
export async function flushGrowth(account: string) {
|
||||||
|
if (flushing.has(account)) return;
|
||||||
|
flushing.add(account);
|
||||||
|
try {
|
||||||
|
const key = `dh-events:${account}`,
|
||||||
|
queue = (
|
||||||
|
JSON.parse(sessionStorage.getItem(key) ?? "[]") as Event[]
|
||||||
|
).filter((e) => Date.now() - e.queuedAt < 23 * 3600000),
|
||||||
|
batch = queue.slice(0, 20);
|
||||||
|
if (!batch.length) return;
|
||||||
|
const response = await fetch("/api/digital/growth/events", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "Content-Type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
account,
|
||||||
|
events: batch.map(({ queuedAt, ...event }) => {
|
||||||
|
return { ...event, occurredAt: queuedAt };
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
keepalive: true,
|
||||||
|
});
|
||||||
|
if (response.ok || response.status === 400 || response.status === 404) {
|
||||||
|
const sent = new Set(batch.map((e) => e.id)),
|
||||||
|
current = JSON.parse(sessionStorage.getItem(key) ?? "[]") as Event[];
|
||||||
|
sessionStorage.setItem(
|
||||||
|
key,
|
||||||
|
JSON.stringify(current.filter((e) => !sent.has(e.id))),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
} finally {
|
||||||
|
flushing.delete(account);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** 推荐来源有24小时有效期,只用于服务端再次验证的归因回执。 */
|
||||||
|
export function recommendationReceipt(account: string, card: string) {
|
||||||
|
try {
|
||||||
|
const r = JSON.parse(
|
||||||
|
sessionStorage.getItem(`dh-recommendation:${account}:${card}`) ?? "null",
|
||||||
|
);
|
||||||
|
return r && r.until > Date.now() ? (r.id as string) : undefined;
|
||||||
|
} catch {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/** 推荐打开后跨独立路由承接回执;跳过后立即移除该项。 */
|
||||||
|
export function rememberRecommendation(
|
||||||
|
account: string,
|
||||||
|
card: string,
|
||||||
|
id: string,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
sessionStorage.setItem(
|
||||||
|
`dh-recommendation:${account}:${card}`,
|
||||||
|
JSON.stringify({ id, until: Date.now() + 23 * 3600000 }),
|
||||||
|
);
|
||||||
|
} catch {}
|
||||||
|
}
|
||||||
@@ -0,0 +1,50 @@
|
|||||||
|
/** C端增长事件队列只包含事件名、内容ID与回执;不采集正文、密码、设备指纹。 */
|
||||||
|
import { digital } from "./digital";
|
||||||
|
export {
|
||||||
|
trackGrowth,
|
||||||
|
flushGrowth,
|
||||||
|
recommendationReceipt,
|
||||||
|
rememberRecommendation,
|
||||||
|
} from "./growth-analytics";
|
||||||
|
/** 前台权益与运营卡片不包含后台策略和全站预算。 */
|
||||||
|
export type GrowthState = {
|
||||||
|
entitlement: {
|
||||||
|
tier: "guest" | "free" | "member";
|
||||||
|
limit: number;
|
||||||
|
remaining: number;
|
||||||
|
used: number;
|
||||||
|
reserved: number;
|
||||||
|
memberUntil: string | null;
|
||||||
|
};
|
||||||
|
interests: string[];
|
||||||
|
autoMemory: boolean;
|
||||||
|
segment: string;
|
||||||
|
inbox: { id: string; title: string; content: string }[];
|
||||||
|
};
|
||||||
|
/** 已保存评价按会话合并加载,避免每条消息各请求一次。 */
|
||||||
|
const feedbackCache = new Map<
|
||||||
|
string,
|
||||||
|
{
|
||||||
|
until: number;
|
||||||
|
value: Promise<
|
||||||
|
{ messageId: string; rating: "up" | "down"; reason: string }[]
|
||||||
|
>;
|
||||||
|
}
|
||||||
|
>();
|
||||||
|
export function feedbackFor(account: string, conversation: string) {
|
||||||
|
const key = `${account}:${conversation}`,
|
||||||
|
hit = feedbackCache.get(key);
|
||||||
|
if (hit && hit.until > Date.now()) return hit.value;
|
||||||
|
if (feedbackCache.size >= 100)
|
||||||
|
feedbackCache.delete(feedbackCache.keys().next().value!);
|
||||||
|
const value = digital<
|
||||||
|
{ messageId: string; rating: "up" | "down"; reason: string }[]
|
||||||
|
>(`conversations/${conversation}/feedback`);
|
||||||
|
feedbackCache.set(key, { until: Date.now() + 30000, value });
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 本人提交评价后失效会话缓存,下次进入从后端还原最新选择。 */
|
||||||
|
export function invalidateFeedback(account: string, conversation: string) {
|
||||||
|
feedbackCache.delete(`${account}:${conversation}`);
|
||||||
|
}
|
||||||
@@ -1,512 +0,0 @@
|
|||||||
import "server-only";
|
|
||||||
|
|
||||||
import { BackendError, backendRequest, requireBackendData } from "@/lib/backend";
|
|
||||||
import type {
|
|
||||||
AnnouncementDetail,
|
|
||||||
AnnouncementSummary,
|
|
||||||
AuthUser,
|
|
||||||
MobileBootstrap,
|
|
||||||
PermissionPayload,
|
|
||||||
ShiftSummary,
|
|
||||||
StoreDetail,
|
|
||||||
StoreEmployee,
|
|
||||||
TaskAssignee,
|
|
||||||
TaskDetail,
|
|
||||||
TaskEvent,
|
|
||||||
TaskSummary
|
|
||||||
} from "@/lib/types";
|
|
||||||
|
|
||||||
const EMPTY_TASKS: TaskSummary[] = [];
|
|
||||||
const EMPTY_ANNOUNCEMENTS: AnnouncementSummary[] = [];
|
|
||||||
const EMPTY_SHIFTS: ShiftSummary[] = [];
|
|
||||||
const OPTIONAL_MOBILE_FALLBACK_STATUSES = [404, 500, 501, 502, 503];
|
|
||||||
const OPTIONAL_STORE_FALLBACK_STATUSES = [403, 404, 500, 501, 502, 503];
|
|
||||||
|
|
||||||
type UnknownRecord = Record<string, unknown>;
|
|
||||||
|
|
||||||
export type TaskListFilter = {
|
|
||||||
status?: TaskSummary["status"];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ShiftListFilter = {
|
|
||||||
startDate?: string;
|
|
||||||
endDate?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
function isRecord(value: unknown): value is UnknownRecord {
|
|
||||||
return Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function stringOrUndefined(value: unknown) {
|
|
||||||
return typeof value === "string" && value.length > 0 ? value : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function numberOrUndefined(value: unknown) {
|
|
||||||
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function numericIdOrUndefined(value: unknown) {
|
|
||||||
if (typeof value === "number" && Number.isInteger(value)) return value;
|
|
||||||
if (typeof value === "string" && /^\d+$/.test(value)) return Number(value);
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
|
|
||||||
function toList<T>(value: unknown, normalize: (item: unknown) => T | null): T[] {
|
|
||||||
const source = Array.isArray(value) ? value : isRecord(value) && Array.isArray(value.items) ? value.items : [];
|
|
||||||
return source.map(normalize).filter((item): item is T => item !== null);
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTaskStatus(value: unknown): TaskSummary["status"] {
|
|
||||||
switch (value) {
|
|
||||||
case "PENDING":
|
|
||||||
case "pending":
|
|
||||||
return "pending";
|
|
||||||
case "IN_PROGRESS":
|
|
||||||
case "in_progress":
|
|
||||||
return "in_progress";
|
|
||||||
case "COMPLETED":
|
|
||||||
case "completed":
|
|
||||||
return "completed";
|
|
||||||
case "CANCELLED":
|
|
||||||
case "cancelled":
|
|
||||||
return "cancelled";
|
|
||||||
default:
|
|
||||||
return "pending";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTaskPriority(value: unknown): TaskSummary["priority"] {
|
|
||||||
switch (value) {
|
|
||||||
case "LOW":
|
|
||||||
case "low":
|
|
||||||
return "low";
|
|
||||||
case "HIGH":
|
|
||||||
case "high":
|
|
||||||
return "high";
|
|
||||||
case "URGENT":
|
|
||||||
case "urgent":
|
|
||||||
return "urgent";
|
|
||||||
default:
|
|
||||||
return "normal";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeAnnouncementLevel(value: unknown): AnnouncementSummary["level"] {
|
|
||||||
switch (value) {
|
|
||||||
case "IMPORTANT":
|
|
||||||
case "important":
|
|
||||||
return "important";
|
|
||||||
case "URGENT":
|
|
||||||
case "urgent":
|
|
||||||
return "urgent";
|
|
||||||
default:
|
|
||||||
return "normal";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeShiftStatus(value: unknown): ShiftSummary["status"] {
|
|
||||||
switch (value) {
|
|
||||||
case "CANCELLED":
|
|
||||||
case "cancelled":
|
|
||||||
return "cancelled";
|
|
||||||
case "COMPLETED":
|
|
||||||
case "completed":
|
|
||||||
return "completed";
|
|
||||||
default:
|
|
||||||
return "scheduled";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function summaryFromContent(value: unknown) {
|
|
||||||
const content = stringOrUndefined(value);
|
|
||||||
if (!content) return undefined;
|
|
||||||
|
|
||||||
const text = content.replace(/\s+/g, " ").trim();
|
|
||||||
return text.length > 48 ? `${text.slice(0, 48)}...` : text;
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTask(value: unknown): TaskSummary | null {
|
|
||||||
if (!isRecord(value)) return null;
|
|
||||||
|
|
||||||
const title = stringOrUndefined(value.title) ?? "未命名任务";
|
|
||||||
const assignees = toList(value.assignees, normalizeTaskAssignee);
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: String(value.id ?? title),
|
|
||||||
title,
|
|
||||||
description: stringOrUndefined(value.description),
|
|
||||||
status: normalizeTaskStatus(value.status),
|
|
||||||
priority: normalizeTaskPriority(value.priority),
|
|
||||||
dueAt: stringOrUndefined(value.dueAt) ?? null,
|
|
||||||
assigneeName: stringOrUndefined(value.assigneeName) ?? assignees[0]?.name,
|
|
||||||
storeName: stringOrUndefined(value.storeName)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTaskAssignee(value: unknown): TaskAssignee | null {
|
|
||||||
if (!isRecord(value)) return null;
|
|
||||||
|
|
||||||
const id = numericIdOrUndefined(value.id);
|
|
||||||
const name = stringOrUndefined(value.name) ?? stringOrUndefined(value.displayName);
|
|
||||||
if (id === undefined || !name) return null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
phone: stringOrUndefined(value.phone) ?? stringOrUndefined(value.username)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTaskEvent(value: unknown): TaskEvent | null {
|
|
||||||
if (!isRecord(value)) return null;
|
|
||||||
|
|
||||||
const id = numericIdOrUndefined(value.id);
|
|
||||||
const eventType = stringOrUndefined(value.eventType);
|
|
||||||
if (id === undefined || !eventType) return null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
taskId: numericIdOrUndefined(value.taskId),
|
|
||||||
eventType,
|
|
||||||
fromStatus: stringOrUndefined(value.fromStatus) ?? null,
|
|
||||||
toStatus: stringOrUndefined(value.toStatus) ?? null,
|
|
||||||
comment: stringOrUndefined(value.comment) ?? null,
|
|
||||||
createdAt: stringOrUndefined(value.createdAt) ?? null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeTaskDetail(value: unknown): TaskDetail {
|
|
||||||
if (!isRecord(value)) {
|
|
||||||
throw new BackendError("任务详情数据格式不正确", 502);
|
|
||||||
}
|
|
||||||
|
|
||||||
const summary = normalizeTask(value);
|
|
||||||
if (!summary) {
|
|
||||||
throw new BackendError("任务详情数据格式不正确", 502);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...summary,
|
|
||||||
assignees: toList(value.assignees, normalizeTaskAssignee),
|
|
||||||
events: toList(value.events, normalizeTaskEvent),
|
|
||||||
createdAt: stringOrUndefined(value.createdAt) ?? null,
|
|
||||||
updatedAt: stringOrUndefined(value.updatedAt) ?? null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeAnnouncement(value: unknown): AnnouncementSummary | null {
|
|
||||||
if (!isRecord(value)) return null;
|
|
||||||
|
|
||||||
const title = stringOrUndefined(value.title) ?? "未命名公告";
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: String(value.id ?? title),
|
|
||||||
title,
|
|
||||||
summary: stringOrUndefined(value.summary) ?? summaryFromContent(value.content),
|
|
||||||
level: normalizeAnnouncementLevel(value.level),
|
|
||||||
publishedAt: stringOrUndefined(value.publishedAt) ?? null,
|
|
||||||
read: typeof value.read === "boolean" ? value.read : Boolean(value.readAt)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeAnnouncementDetail(value: unknown): AnnouncementDetail {
|
|
||||||
if (!isRecord(value)) {
|
|
||||||
throw new BackendError("公告详情数据格式不正确", 502);
|
|
||||||
}
|
|
||||||
|
|
||||||
const summary = normalizeAnnouncement(value);
|
|
||||||
if (!summary) {
|
|
||||||
throw new BackendError("公告详情数据格式不正确", 502);
|
|
||||||
}
|
|
||||||
|
|
||||||
return {
|
|
||||||
...summary,
|
|
||||||
content: stringOrUndefined(value.content) ?? summary.summary ?? "",
|
|
||||||
readAt: stringOrUndefined(value.readAt) ?? null,
|
|
||||||
createdAt: stringOrUndefined(value.createdAt) ?? null,
|
|
||||||
updatedAt: stringOrUndefined(value.updatedAt) ?? null
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeShift(value: unknown): ShiftSummary | null {
|
|
||||||
if (!isRecord(value)) return null;
|
|
||||||
|
|
||||||
const startAt = stringOrUndefined(value.startAt) ?? "";
|
|
||||||
const endAt = stringOrUndefined(value.endAt) ?? "";
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: String(value.id ?? startAt),
|
|
||||||
date: stringOrUndefined(value.date) ?? startAt.slice(0, 10),
|
|
||||||
position: stringOrUndefined(value.position) ?? stringOrUndefined(value.roleName) ?? "班次",
|
|
||||||
startAt,
|
|
||||||
endAt,
|
|
||||||
status: normalizeShiftStatus(value.status)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function firstShift(value: unknown) {
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
return normalizeShift(value[0]);
|
|
||||||
}
|
|
||||||
|
|
||||||
return normalizeShift(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
function shiftList(value: unknown) {
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
return value.map(normalizeShift).filter((item): item is ShiftSummary => item !== null);
|
|
||||||
}
|
|
||||||
|
|
||||||
const shift = normalizeShift(value);
|
|
||||||
return shift ? [shift] : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
function permissionsFromBootstrap(value: unknown) {
|
|
||||||
if (Array.isArray(value)) {
|
|
||||||
return value.filter((item): item is string => typeof item === "string");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isRecord(value)) {
|
|
||||||
const codes = Array.isArray(value.codes) ? value.codes : value.permissions;
|
|
||||||
return Array.isArray(codes) ? codes.filter((item): item is string => typeof item === "string") : [];
|
|
||||||
}
|
|
||||||
|
|
||||||
return [];
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeRole(value: unknown) {
|
|
||||||
if (!isRecord(value)) return null;
|
|
||||||
|
|
||||||
const id = numericIdOrUndefined(value.id);
|
|
||||||
const code = stringOrUndefined(value.code);
|
|
||||||
const name = stringOrUndefined(value.name);
|
|
||||||
|
|
||||||
if (id === undefined || !code || !name) return null;
|
|
||||||
|
|
||||||
return { id, code, name };
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeStoreEmployee(value: unknown): StoreEmployee | null {
|
|
||||||
if (!isRecord(value)) return null;
|
|
||||||
|
|
||||||
const id = numericIdOrUndefined(value.id);
|
|
||||||
const name = stringOrUndefined(value.name) ?? stringOrUndefined(value.displayName);
|
|
||||||
if (id === undefined || !name) return null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
phone: stringOrUndefined(value.phone) ?? stringOrUndefined(value.username),
|
|
||||||
status: stringOrUndefined(value.status),
|
|
||||||
roles: toList(value.roles, normalizeRole)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeStoreDetail(value: unknown, fallbackUser?: AuthUser): StoreDetail | null {
|
|
||||||
if (!isRecord(value)) {
|
|
||||||
if (!fallbackUser?.storeId) return null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
id: fallbackUser.storeId,
|
|
||||||
name: fallbackUser.storeName ?? "当前门店",
|
|
||||||
address: null,
|
|
||||||
phone: null,
|
|
||||||
status: undefined,
|
|
||||||
employees: []
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
const id = numericIdOrUndefined(value.id) ?? fallbackUser?.storeId;
|
|
||||||
const name = stringOrUndefined(value.name) ?? fallbackUser?.storeName;
|
|
||||||
if (id === undefined || !name) return null;
|
|
||||||
|
|
||||||
return {
|
|
||||||
id,
|
|
||||||
name,
|
|
||||||
address: stringOrUndefined(value.address) ?? null,
|
|
||||||
phone: stringOrUndefined(value.phone) ?? null,
|
|
||||||
status: stringOrUndefined(value.status),
|
|
||||||
employees: toList(value.employees, normalizeStoreEmployee)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
function normalizeBootstrap(data: unknown): MobileBootstrap {
|
|
||||||
if (!isRecord(data) || !isRecord(data.user)) {
|
|
||||||
throw new BackendError("员工端首屏数据格式不正确", 502);
|
|
||||||
}
|
|
||||||
|
|
||||||
const counters = isRecord(data.counters) ? data.counters : {};
|
|
||||||
const tasks = toList(data.tasks, normalizeTask).slice(0, 5);
|
|
||||||
const latestAnnouncements = toList(data.latestAnnouncements, normalizeAnnouncement).slice(0, 3);
|
|
||||||
const todayShifts = shiftList(data.todayShifts ?? data.todayShift);
|
|
||||||
const todayShift = firstShift(data.todayShift) ?? todayShifts[0] ?? null;
|
|
||||||
const pendingTasks = tasks.filter((task) => task.status === "pending" || task.status === "in_progress");
|
|
||||||
const now = Date.now();
|
|
||||||
|
|
||||||
return {
|
|
||||||
user: data.user as AuthUser,
|
|
||||||
permissions: permissionsFromBootstrap(data.permissions),
|
|
||||||
unreadAnnouncementCount:
|
|
||||||
numberOrUndefined(data.unreadAnnouncementCount ?? counters.unreadAnnouncementCount) ??
|
|
||||||
latestAnnouncements.filter((item) => !item.read).length,
|
|
||||||
pendingTaskCount: numberOrUndefined(data.pendingTaskCount ?? counters.pendingTaskCount) ?? pendingTasks.length,
|
|
||||||
overdueTaskCount:
|
|
||||||
numberOrUndefined(data.overdueTaskCount ?? counters.overdueTaskCount) ??
|
|
||||||
pendingTasks.filter((task) => task.dueAt && new Date(task.dueAt).getTime() < now).length,
|
|
||||||
todayShift,
|
|
||||||
todayShifts,
|
|
||||||
latestAnnouncements,
|
|
||||||
tasks
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
async function optionalBackendData<T>(path: string, fallback: T, fallbackStatuses = [404]) {
|
|
||||||
try {
|
|
||||||
return await backendRequest<T>(path);
|
|
||||||
} catch (error) {
|
|
||||||
if (error instanceof BackendError && fallbackStatuses.includes(error.status)) {
|
|
||||||
return fallback;
|
|
||||||
}
|
|
||||||
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function withSearch(path: string, entries: Record<string, string | undefined>) {
|
|
||||||
const search = new URLSearchParams();
|
|
||||||
|
|
||||||
for (const [key, value] of Object.entries(entries)) {
|
|
||||||
if (value) {
|
|
||||||
search.set(key, value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const query = search.toString();
|
|
||||||
return query ? `${path}?${query}` : path;
|
|
||||||
}
|
|
||||||
|
|
||||||
function taskStatusToBackend(status?: TaskSummary["status"]) {
|
|
||||||
switch (status) {
|
|
||||||
case "pending":
|
|
||||||
return "PENDING";
|
|
||||||
case "in_progress":
|
|
||||||
return "IN_PROGRESS";
|
|
||||||
case "completed":
|
|
||||||
return "COMPLETED";
|
|
||||||
case "cancelled":
|
|
||||||
return "CANCELLED";
|
|
||||||
default:
|
|
||||||
return undefined;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getBootstrapData(): Promise<MobileBootstrap> {
|
|
||||||
try {
|
|
||||||
return normalizeBootstrap(await requireBackendData<unknown>("/mobile/bootstrap"));
|
|
||||||
} catch (error) {
|
|
||||||
if (!(error instanceof BackendError && OPTIONAL_MOBILE_FALLBACK_STATUSES.includes(error.status))) {
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
const [user, permissionPayload, tasks, announcements, todayShift] = await Promise.all([
|
|
||||||
requireBackendData<AuthUser>("/auth/me"),
|
|
||||||
requireBackendData<PermissionPayload>("/permissions/me"),
|
|
||||||
optionalBackendData<unknown>("/mobile/tasks", EMPTY_TASKS, OPTIONAL_MOBILE_FALLBACK_STATUSES),
|
|
||||||
optionalBackendData<unknown>("/mobile/announcements", EMPTY_ANNOUNCEMENTS, OPTIONAL_MOBILE_FALLBACK_STATUSES),
|
|
||||||
optionalBackendData<unknown>("/mobile/shifts/today", null, OPTIONAL_MOBILE_FALLBACK_STATUSES)
|
|
||||||
]);
|
|
||||||
|
|
||||||
const now = Date.now();
|
|
||||||
const normalizedTasks = toList(tasks, normalizeTask);
|
|
||||||
const normalizedAnnouncements = toList(announcements, normalizeAnnouncement);
|
|
||||||
const todayShifts = shiftList(todayShift);
|
|
||||||
const pendingTasks = normalizedTasks.filter((task) => task.status === "pending" || task.status === "in_progress");
|
|
||||||
|
|
||||||
return {
|
|
||||||
user,
|
|
||||||
permissions: permissionPayload.permissions,
|
|
||||||
unreadAnnouncementCount: normalizedAnnouncements.filter((item) => !item.read).length,
|
|
||||||
pendingTaskCount: pendingTasks.length,
|
|
||||||
overdueTaskCount: pendingTasks.filter((task) => task.dueAt && new Date(task.dueAt).getTime() < now).length,
|
|
||||||
todayShift: todayShifts[0] ?? null,
|
|
||||||
todayShifts,
|
|
||||||
latestAnnouncements: normalizedAnnouncements.slice(0, 3),
|
|
||||||
tasks: normalizedTasks.slice(0, 5)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getCurrentUser() {
|
|
||||||
return requireBackendData<AuthUser>("/auth/me");
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getPermissionPayload() {
|
|
||||||
return requireBackendData<PermissionPayload>("/permissions/me");
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getTasks(filter: TaskListFilter = {}) {
|
|
||||||
const path = withSearch("/mobile/tasks", {
|
|
||||||
status: taskStatusToBackend(filter.status)
|
|
||||||
});
|
|
||||||
|
|
||||||
return toList(
|
|
||||||
await optionalBackendData<unknown>(path, EMPTY_TASKS, OPTIONAL_MOBILE_FALLBACK_STATUSES),
|
|
||||||
normalizeTask
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getTaskDetail(id: string) {
|
|
||||||
return normalizeTaskDetail(await requireBackendData<unknown>(`/mobile/tasks/${encodeURIComponent(id)}`));
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAnnouncements() {
|
|
||||||
return toList(
|
|
||||||
await optionalBackendData<unknown>("/mobile/announcements", EMPTY_ANNOUNCEMENTS, OPTIONAL_MOBILE_FALLBACK_STATUSES),
|
|
||||||
normalizeAnnouncement
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getAnnouncementDetail(id: string) {
|
|
||||||
return normalizeAnnouncementDetail(
|
|
||||||
await requireBackendData<unknown>(`/mobile/announcements/${encodeURIComponent(id)}`)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getShifts(filter: ShiftListFilter = {}) {
|
|
||||||
const path = withSearch("/mobile/shifts", {
|
|
||||||
startDate: filter.startDate,
|
|
||||||
endDate: filter.endDate
|
|
||||||
});
|
|
||||||
|
|
||||||
return toList(
|
|
||||||
await optionalBackendData<unknown>(path, EMPTY_SHIFTS, OPTIONAL_MOBILE_FALLBACK_STATUSES),
|
|
||||||
normalizeShift
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getCurrentStore(user?: AuthUser) {
|
|
||||||
const currentUser = user ?? (await getCurrentUser());
|
|
||||||
if (!currentUser.storeId) return null;
|
|
||||||
|
|
||||||
const fallback = normalizeStoreDetail(null, currentUser);
|
|
||||||
return normalizeStoreDetail(
|
|
||||||
await optionalBackendData<unknown>(`/stores/${currentUser.storeId}`, fallback, OPTIONAL_STORE_FALLBACK_STATUSES),
|
|
||||||
currentUser
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function getCurrentStoreEmployees(user?: AuthUser) {
|
|
||||||
const currentUser = user ?? (await getCurrentUser());
|
|
||||||
if (!currentUser.storeId) return [];
|
|
||||||
|
|
||||||
const search = new URLSearchParams({
|
|
||||||
storeId: String(currentUser.storeId),
|
|
||||||
page: "1",
|
|
||||||
pageSize: "100"
|
|
||||||
});
|
|
||||||
|
|
||||||
return toList(
|
|
||||||
await optionalBackendData<unknown>(`/employees?${search.toString()}`, [], OPTIONAL_STORE_FALLBACK_STATUSES),
|
|
||||||
normalizeStoreEmployee
|
|
||||||
);
|
|
||||||
}
|
|
||||||
+10
-4
@@ -1,3 +1,4 @@
|
|||||||
|
/** 会话令牌仅保存在HttpOnly Cookie,Google 会话使用独立 Cookie 名。 */
|
||||||
import "server-only";
|
import "server-only";
|
||||||
|
|
||||||
import { cookies } from "next/headers";
|
import { cookies } from "next/headers";
|
||||||
@@ -6,14 +7,17 @@ import { getAppEnv } from "@/lib/environment";
|
|||||||
|
|
||||||
const DEFAULT_COOKIE_NAME = "role_user_session";
|
const DEFAULT_COOKIE_NAME = "role_user_session";
|
||||||
|
|
||||||
export function getSessionCookieName() {
|
/** 使用独立命名,避免读取旧密码和游客会话。 */
|
||||||
return process.env.ROLE_USER_SESSION_COOKIE || DEFAULT_COOKIE_NAME;
|
function getSessionCookieName() {
|
||||||
|
return `${process.env.ROLE_USER_SESSION_COOKIE || DEFAULT_COOKIE_NAME}_google`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 读取当前 Google 业务会话。 */
|
||||||
export async function getSessionToken() {
|
export async function getSessionToken() {
|
||||||
return (await cookies()).get(getSessionCookieName())?.value;
|
return (await cookies()).get(getSessionCookieName())?.value;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 写入仅服务端可读的业务会话。 */
|
||||||
export async function setSessionToken(token: string) {
|
export async function setSessionToken(token: string) {
|
||||||
const cookieStore = await cookies();
|
const cookieStore = await cookies();
|
||||||
|
|
||||||
@@ -22,10 +26,12 @@ export async function setSessionToken(token: string) {
|
|||||||
secure: getAppEnv() === "production",
|
secure: getAppEnv() === "production",
|
||||||
sameSite: "lax",
|
sameSite: "lax",
|
||||||
path: "/",
|
path: "/",
|
||||||
maxAge: 60 * 60 * 8
|
maxAge: 60 * 60 * 8,
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** 清理当前业务会话。 */
|
||||||
export async function clearSessionToken() {
|
export async function clearSessionToken() {
|
||||||
(await cookies()).delete(getSessionCookieName());
|
const store = await cookies();
|
||||||
|
store.delete(getSessionCookieName());
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,137 +0,0 @@
|
|||||||
/** 前台身份与业务协议,数字人账号使用独立 DIGITAL_USER 类型。 */
|
|
||||||
export type AccountType = "SUPER_ADMIN" | "EMPLOYEE" | "DIGITAL_USER";
|
|
||||||
|
|
||||||
export type Role = {
|
|
||||||
id: number;
|
|
||||||
code: string;
|
|
||||||
name: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type AuthUser = {
|
|
||||||
id: number;
|
|
||||||
username: string;
|
|
||||||
displayName: string;
|
|
||||||
accountType: AccountType;
|
|
||||||
storeId?: number;
|
|
||||||
storeName?: string;
|
|
||||||
roles: Role[];
|
|
||||||
permissions: string[];
|
|
||||||
canManage: boolean;
|
|
||||||
lastLoginAt?: string | null;
|
|
||||||
mustChangePassword?: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PermissionMenu = {
|
|
||||||
key: string;
|
|
||||||
title: string;
|
|
||||||
permission: string;
|
|
||||||
actions: string[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type PermissionPayload = {
|
|
||||||
permissions: string[];
|
|
||||||
menus: PermissionMenu[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ApiEnvelope<T> = {
|
|
||||||
success: boolean;
|
|
||||||
data: T;
|
|
||||||
message?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type LoginResponse = {
|
|
||||||
token: string;
|
|
||||||
tokenType: "Bearer";
|
|
||||||
expiresIn: string;
|
|
||||||
user: AuthUser;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type TaskStatus = "pending" | "in_progress" | "completed" | "cancelled";
|
|
||||||
|
|
||||||
export type TaskSummary = {
|
|
||||||
id: string;
|
|
||||||
title: string;
|
|
||||||
description?: string;
|
|
||||||
status: TaskStatus;
|
|
||||||
priority: "low" | "normal" | "high" | "urgent";
|
|
||||||
dueAt?: string | null;
|
|
||||||
assigneeName?: string;
|
|
||||||
storeName?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type TaskAssignee = {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
phone?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type TaskEvent = {
|
|
||||||
id: number;
|
|
||||||
taskId?: number;
|
|
||||||
eventType: "CREATED" | "UPDATED" | "STARTED" | "COMPLETED" | "CANCELLED" | "COMMENTED" | string;
|
|
||||||
fromStatus?: string | null;
|
|
||||||
toStatus?: string | null;
|
|
||||||
comment?: string | null;
|
|
||||||
createdAt?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type TaskDetail = TaskSummary & {
|
|
||||||
assignees: TaskAssignee[];
|
|
||||||
events: TaskEvent[];
|
|
||||||
createdAt?: string | null;
|
|
||||||
updatedAt?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type AnnouncementSummary = {
|
|
||||||
id: string;
|
|
||||||
title: string;
|
|
||||||
summary?: string;
|
|
||||||
level: "normal" | "important" | "urgent";
|
|
||||||
publishedAt?: string | null;
|
|
||||||
read: boolean;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type AnnouncementDetail = AnnouncementSummary & {
|
|
||||||
content: string;
|
|
||||||
readAt?: string | null;
|
|
||||||
createdAt?: string | null;
|
|
||||||
updatedAt?: string | null;
|
|
||||||
};
|
|
||||||
|
|
||||||
export type ShiftSummary = {
|
|
||||||
id: string;
|
|
||||||
date: string;
|
|
||||||
position: string;
|
|
||||||
startAt: string;
|
|
||||||
endAt: string;
|
|
||||||
status: "scheduled" | "cancelled" | "completed";
|
|
||||||
};
|
|
||||||
|
|
||||||
export type StoreEmployee = {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
phone?: string;
|
|
||||||
status?: string;
|
|
||||||
roles: Role[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type StoreDetail = {
|
|
||||||
id: number;
|
|
||||||
name: string;
|
|
||||||
address?: string | null;
|
|
||||||
phone?: string | null;
|
|
||||||
status?: string;
|
|
||||||
employees: StoreEmployee[];
|
|
||||||
};
|
|
||||||
|
|
||||||
export type MobileBootstrap = {
|
|
||||||
user: AuthUser;
|
|
||||||
permissions: string[];
|
|
||||||
unreadAnnouncementCount: number;
|
|
||||||
pendingTaskCount: number;
|
|
||||||
overdueTaskCount: number;
|
|
||||||
todayShift: ShiftSummary | null;
|
|
||||||
todayShifts: ShiftSummary[];
|
|
||||||
latestAnnouncements: AnnouncementSummary[];
|
|
||||||
tasks: TaskSummary[];
|
|
||||||
};
|
|
||||||
+1
-7
@@ -8,15 +8,9 @@ const protectedRoutes = [
|
|||||||
"/characters",
|
"/characters",
|
||||||
"/library",
|
"/library",
|
||||||
"/profile",
|
"/profile",
|
||||||
"/dashboard",
|
|
||||||
"/tasks",
|
|
||||||
"/schedule",
|
|
||||||
"/announcements",
|
|
||||||
"/store",
|
|
||||||
"/me",
|
|
||||||
];
|
];
|
||||||
const publicRoutes = ["/", "/login"];
|
const publicRoutes = ["/", "/login"];
|
||||||
const cookieName = process.env.ROLE_USER_SESSION_COOKIE || "role_user_session";
|
const cookieName = `${process.env.ROLE_USER_SESSION_COOKIE || "role_user_session"}_google`;
|
||||||
|
|
||||||
/** 路由级登录保护;深链携带站内回跳目标,不丢失具体聊天地址。 */
|
/** 路由级登录保护;深链携带站内回跳目标,不丢失具体聊天地址。 */
|
||||||
export function proxy(request: NextRequest) {
|
export function proxy(request: NextRequest) {
|
||||||
|
|||||||
@@ -0,0 +1,83 @@
|
|||||||
|
/** SSE 的真正终止、网络中断与跨分片 Unicode 解码回归。 */
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { readDigitalStream } from "../src/lib/digital-stream.ts";
|
||||||
|
|
||||||
|
test("只收到部分内容就断流时保留事件,并报告中断", async () => {
|
||||||
|
const events = [];
|
||||||
|
await assert.rejects(
|
||||||
|
readDigitalStream(
|
||||||
|
new Response('event: delta\ndata: {"text":"已有内容"}\n\n'),
|
||||||
|
(event, data) => events.push([event, data]),
|
||||||
|
),
|
||||||
|
/中断/,
|
||||||
|
);
|
||||||
|
assert.equal(events[0][1].text, "已有内容");
|
||||||
|
});
|
||||||
|
test("结束事件跨字节分片且包含中文时只解析一次", async () => {
|
||||||
|
const bytes = new TextEncoder().encode(
|
||||||
|
'event: delta\ndata: {"text":"中文"}\n\nevent: done\ndata: {"status":"complete"}\n\n',
|
||||||
|
);
|
||||||
|
const events = [];
|
||||||
|
await readDigitalStream(
|
||||||
|
new Response(
|
||||||
|
new ReadableStream({
|
||||||
|
start(controller) {
|
||||||
|
for (const byte of bytes) controller.enqueue(new Uint8Array([byte]));
|
||||||
|
controller.close();
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
),
|
||||||
|
(event, data) => events.push([event, data]),
|
||||||
|
);
|
||||||
|
assert.deepEqual(events, [
|
||||||
|
["delta", { text: "中文" }],
|
||||||
|
["done", { status: "complete" }],
|
||||||
|
]);
|
||||||
|
});
|
||||||
|
test("空连接不能被当作完成,服务端拒绝保持原错误", async () => {
|
||||||
|
await assert.rejects(
|
||||||
|
readDigitalStream(new Response(""), () => {}),
|
||||||
|
/中断/,
|
||||||
|
);
|
||||||
|
await assert.rejects(
|
||||||
|
readDigitalStream(
|
||||||
|
new Response('{"message":"上一条仍在生成"}', { status: 409 }),
|
||||||
|
() => {},
|
||||||
|
),
|
||||||
|
/仍在生成/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("同步生成中快照不会清空已收到的部分回复,完成后以服务端记录为准", async () => {
|
||||||
|
const { mergeConversationSnapshot } = await import(
|
||||||
|
"../src/lib/digital-recovery.ts"
|
||||||
|
);
|
||||||
|
const local = {
|
||||||
|
id: "chat",
|
||||||
|
busy: true,
|
||||||
|
messages: [
|
||||||
|
{
|
||||||
|
id: "reply",
|
||||||
|
role: "assistant",
|
||||||
|
status: "generating",
|
||||||
|
content: "已经显示的正文",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
};
|
||||||
|
const saved = { ...local, messages: [{ ...local.messages[0], content: "" }] };
|
||||||
|
assert.equal(
|
||||||
|
mergeConversationSnapshot(local, saved).messages[0].content,
|
||||||
|
"已经显示的正文",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
mergeConversationSnapshot(local, { ...saved, busy: false }).messages[0]
|
||||||
|
.content,
|
||||||
|
"",
|
||||||
|
);
|
||||||
|
assert.equal(
|
||||||
|
mergeConversationSnapshot({ ...local, id: "other" }, saved).messages[0]
|
||||||
|
.content,
|
||||||
|
"",
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
/** 事件队列使用可控浏览器存储与HTTP夹具,验证批次边界、重试和账号切换。 */
|
||||||
|
import test from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import {
|
||||||
|
trackGrowth,
|
||||||
|
flushGrowth,
|
||||||
|
rememberRecommendation,
|
||||||
|
recommendationReceipt,
|
||||||
|
} from "../src/lib/growth-analytics.ts";
|
||||||
|
function storage(t) {
|
||||||
|
const values = new Map();
|
||||||
|
if (!("sessionStorage" in globalThis))
|
||||||
|
Object.defineProperty(globalThis, "sessionStorage", {
|
||||||
|
value: undefined,
|
||||||
|
writable: true,
|
||||||
|
configurable: true,
|
||||||
|
});
|
||||||
|
t.mock.property(globalThis, "sessionStorage", {
|
||||||
|
getItem: (key) => values.get(key) ?? null,
|
||||||
|
setItem: (key, value) => values.set(key, value),
|
||||||
|
});
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
test("账号队列隔离,并将账号绑定到上报批次供服务端核验", async (t) => {
|
||||||
|
storage(t);
|
||||||
|
const sent = [];
|
||||||
|
t.mock.method(globalThis, "fetch", async (_url, init) => {
|
||||||
|
sent.push(JSON.parse(init.body));
|
||||||
|
return new Response("{}");
|
||||||
|
});
|
||||||
|
trackGrowth("user:1", "page_view", "discover");
|
||||||
|
trackGrowth("user:2", "card_open", "role");
|
||||||
|
await flushGrowth("user:1");
|
||||||
|
assert.equal(sent[0].account, "user:1");
|
||||||
|
assert.equal(sent[0].events.length, 1);
|
||||||
|
assert.equal(sent[0].events[0].event, "page_view");
|
||||||
|
await flushGrowth("user:2");
|
||||||
|
assert.equal(sent[1].account, "user:2");
|
||||||
|
});
|
||||||
|
test("失败重试保留同一个事件UUID,不重新记一次曝光", async (t) => {
|
||||||
|
storage(t);
|
||||||
|
const sent = [];
|
||||||
|
t.mock.method(globalThis, "fetch", async (_url, init) => {
|
||||||
|
sent.push(JSON.parse(init.body));
|
||||||
|
return new Response("{}", { status: sent.length === 1 ? 503 : 200 });
|
||||||
|
});
|
||||||
|
trackGrowth("user:retry", "card_impression", "role");
|
||||||
|
await flushGrowth("user:retry");
|
||||||
|
await flushGrowth("user:retry");
|
||||||
|
assert.equal(sent.length, 2);
|
||||||
|
assert.equal(sent[0].events[0].id, sent[1].events[0].id);
|
||||||
|
await flushGrowth("user:retry");
|
||||||
|
assert.equal(sent.length, 2);
|
||||||
|
});
|
||||||
|
test("一批最多20条,成功响应不丢失请求期间新入队的事件", async (t) => {
|
||||||
|
const values = storage(t);
|
||||||
|
const sent = [];
|
||||||
|
t.mock.method(globalThis, "fetch", async (_url, init) => {
|
||||||
|
sent.push(JSON.parse(init.body));
|
||||||
|
trackGrowth("user:batch", "card_open", "new");
|
||||||
|
return new Response("{}");
|
||||||
|
});
|
||||||
|
for (let i = 0; i < 25; i++)
|
||||||
|
trackGrowth("user:batch", "card_impression", `role-${i}`);
|
||||||
|
await flushGrowth("user:batch");
|
||||||
|
assert.equal(sent[0].events.length, 20);
|
||||||
|
const left = JSON.parse(values.get("dh-events:user:batch"));
|
||||||
|
assert.equal(left.length, 6);
|
||||||
|
assert.equal(left.at(-1).entity, "new");
|
||||||
|
});
|
||||||
|
test("无效批次停止重试,未授权与暂时失败不直接丢弃", async (t) => {
|
||||||
|
const values = storage(t);
|
||||||
|
let code = 401;
|
||||||
|
t.mock.method(
|
||||||
|
globalThis,
|
||||||
|
"fetch",
|
||||||
|
async () => new Response("{}", { status: code }),
|
||||||
|
);
|
||||||
|
trackGrowth("user:invalid", "page_view", "discover");
|
||||||
|
await flushGrowth("user:invalid");
|
||||||
|
assert.equal(JSON.parse(values.get("dh-events:user:invalid")).length, 1);
|
||||||
|
code = 400;
|
||||||
|
await flushGrowth("user:invalid");
|
||||||
|
assert.equal(JSON.parse(values.get("dh-events:user:invalid")).length, 0);
|
||||||
|
});
|
||||||
|
test("推荐回执按账号角色隔离,过期后不再用于新故事归因", (t) => {
|
||||||
|
const values = storage(t);
|
||||||
|
rememberRecommendation("u", "card", "receipt");
|
||||||
|
assert.equal(recommendationReceipt("u", "card"), "receipt");
|
||||||
|
assert.equal(recommendationReceipt("other", "card"), undefined);
|
||||||
|
values.set(
|
||||||
|
"dh-recommendation:u:card",
|
||||||
|
JSON.stringify({ id: "expired", until: Date.now() - 100 }),
|
||||||
|
);
|
||||||
|
assert.equal(recommendationReceipt("u", "card"), undefined);
|
||||||
|
});
|
||||||
|
|
||||||
|
import { sameOriginRequest } from "../src/lib/auth-origin.ts";
|
||||||
|
test("代理下公网Host可登录,跨站Origin和缺失Origin被拒绝", () => {
|
||||||
|
const make = (origin, host = "mrzhan.top") =>
|
||||||
|
new Request("http://127.0.0.1:3210/api/auth/login", {
|
||||||
|
headers: { host, ...(origin ? { origin } : {}) },
|
||||||
|
});
|
||||||
|
assert.equal(sameOriginRequest(make("https://mrzhan.top")), true);
|
||||||
|
for (const origin of [
|
||||||
|
"https://evil.test",
|
||||||
|
"null",
|
||||||
|
"https://mrzhan.top/path",
|
||||||
|
"https://mrzhan.top.evil.test",
|
||||||
|
undefined,
|
||||||
|
])
|
||||||
|
assert.equal(sameOriginRequest(make(origin)), false);
|
||||||
|
});
|
||||||
|
|
||||||
|
import { readLoginInput } from "../src/lib/auth-input.ts";
|
||||||
|
test("登录公开入口限制真实字节数,不先无界解析JSON", async () => {
|
||||||
|
const request = (body) =>
|
||||||
|
new Request("http://localhost/api/auth/login", { method: "POST", body });
|
||||||
|
assert.deepEqual(
|
||||||
|
await readLoginInput(request('{"username":"user","password":"fixture"}')),
|
||||||
|
{ username: "user", password: "fixture" },
|
||||||
|
);
|
||||||
|
await assert.rejects(
|
||||||
|
readLoginInput(request(JSON.stringify({ username: "a".repeat(9000) }))),
|
||||||
|
RangeError,
|
||||||
|
);
|
||||||
|
for (const body of ["null", "[]", "invalid"])
|
||||||
|
await assert.rejects(readLoginInput(request(body)), SyntaxError);
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user